| 1 | //! `KeyStretcher` and `MultiText`. |
| 2 | |
| 3 | use super::*; |
| 4 | use model::InputBinding; |
| 5 | |
| 6 | const MAX_TEXT_LAYERS: usize = 16; |
| 7 | |
| 8 | /// How the middle segment maps onto `[SourceStart, SourceEnd]`. |
| 9 | #[derive(Clone, Copy, PartialEq, Debug)] |
| 10 | enum StretchMode { |
| 11 | Hold, |
| 12 | Loop, |
| 13 | PingPong, |
| 14 | Scale, |
| 15 | } |
| 16 | |
| 17 | struct Stretch { |
| 18 | source: [f64; 2], |
| 19 | stretch: [f64; 2], |
| 20 | mode: StretchMode, |
| 21 | } |
| 22 | |
| 23 | impl Stretch { |
| 24 | /// Source time for output time `t`: the intro before `stretch[0]` and outro after `stretch[1]` play |
| 25 | /// unstretched, continuous with the middle segment's ends. |
| 26 | fn source_time(&self, t: f64) -> f64 { |
| 27 | let [src_start, src_end] = self.source; |
| 28 | let [st_start, st_end] = self.stretch; |
| 29 | if t < st_start { |
| 30 | return t + (src_start - st_start); |
| 31 | } |
| 32 | if t > st_end { |
| 33 | return src_end + (t - st_end); |
| 34 | } |
| 35 | let dt = t - st_start; |
| 36 | let src_span = src_end - src_start; |
| 37 | let out_span = st_end - st_start; |
| 38 | if src_span <= 0.0 { |
| 39 | return src_start; |
| 40 | } |
| 41 | src_start |
| 42 | + match self.mode { |
| 43 | StretchMode::Scale if out_span > 0.0 => dt / out_span * src_span, |
| 44 | StretchMode::Scale => 0.0, |
| 45 | StretchMode::Hold => dt.min(src_span), |
| 46 | StretchMode::Loop => dt.rem_euclid(src_span), |
| 47 | StretchMode::PingPong => { |
| 48 | let p = dt.rem_euclid(2.0 * src_span); |
| 49 | if p <= src_span { p } else { 2.0 * src_span - p } |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /// Re-keys `node`'s inputs for text layer `layer` (`0` = the shared inputs only): `Layer{n}Foo`, `Layer{n}.Foo` |
| 56 | /// and `Foo{n}` override `Foo`, then MultiText names map onto `TextPlus` inputs. |
| 57 | fn text_layer_inputs(node: &Node, layer: usize) -> HashMap<String, InputBinding> { |
| 58 | const ALIASES: [(&str, &str); 5] = |
| 59 | [("Text", "StyledText"), ("Red", "Red1"), ("Green", "Green1"), ("Blue", "Blue1"), ("Alpha", "Alpha1")]; |
| 60 | let alias = |name: &str| ALIASES.iter().find(|(from, _)| *from == name).map_or(name, |(_, to)| *to).to_owned(); |
| 61 | let layer_name = |key: &str| -> Option<String> { |
| 62 | let n = layer.to_string(); |
| 63 | let rest = key |
| 64 | .strip_prefix(&format!("Layer{n}")) |
| 65 | .filter(|r| !r.starts_with(|c: char| c.is_ascii_digit())) |
| 66 | .map(|r| r.trim_start_matches('.')); |
| 67 | let rest = rest.or_else(|| key.strip_suffix(&n).filter(|r| !r.is_empty() && !r.ends_with(|c: char| c.is_ascii_digit()))); |
| 68 | rest.map(|r| if r.is_empty() { "StyledText".to_owned() } else { alias(r) }) |
| 69 | }; |
| 70 | let shared = node |
| 71 | .inputs |
| 72 | .iter() |
| 73 | .filter(|(k, _)| !k.starts_with("Layer") && !k.ends_with(|c: char| c.is_ascii_digit())) |
| 74 | .map(|(k, b)| (alias(k), b.clone())); |
| 75 | let own = node.inputs.iter().filter_map(|(k, b)| Some((layer_name(k).filter(|_| layer > 0)?, b.clone()))); |
| 76 | shared.chain(own).collect() |
| 77 | } |
| 78 | |
| 79 | fn text_layers(node: &Node) -> Vec<usize> { |
| 80 | (1..=MAX_TEXT_LAYERS) |
| 81 | .filter(|&n| { |
| 82 | ["Layer{}", "Layer{}StyledText", "Layer{}.StyledText", "Layer{}Text", "Layer{}.Text", "StyledText{}", "Text{}"] |
| 83 | .iter() |
| 84 | .any(|pat| node.inputs.contains_key(&pat.replace("{}", &n.to_string()))) |
| 85 | }) |
| 86 | .collect() |
| 87 | } |
| 88 | |
| 89 | impl Engine { |
| 90 | /// `KeyStretcher` — retimes `Input` so the intro and outro play unstretched around a stretched middle segment. |
| 91 | #[allow(clippy::too_many_arguments)] |
| 92 | pub(in crate::eval) fn eval_key_stretcher( |
| 93 | &mut self, |
| 94 | comp: &Comp, |
| 95 | node: &Node, |
| 96 | time: f64, |
| 97 | frame_i: i64, |
| 98 | enc: &mut wgpu::CommandEncoder, |
| 99 | visiting: &mut HashSet<(NodeId, i64)>, |
| 100 | stats: &mut EvalStats, |
| 101 | ) -> CachedTexture { |
| 102 | let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { |
| 103 | return self.dummy.clone(); |
| 104 | }; |
| 105 | let [g_start, g_end] = comp.global_range.map(|f| f as f64); |
| 106 | let read = |keys: &[&str], default: f64| num_any(comp, node, keys, time, default, &self.expr); |
| 107 | let mode = match str_any(node, &["StretchMode", "Mode"]).map(squash).as_deref() { |
| 108 | Some("hold") => StretchMode::Hold, |
| 109 | Some("loop") => StretchMode::Loop, |
| 110 | Some("pingpong") => StretchMode::PingPong, |
| 111 | Some(_) => StretchMode::Scale, |
| 112 | None => match read(&["StretchMode", "Mode"], 3.0).round() as i32 { |
| 113 | 0 => StretchMode::Hold, |
| 114 | 1 => StretchMode::Loop, |
| 115 | 2 => StretchMode::PingPong, |
| 116 | _ => StretchMode::Scale, |
| 117 | }, |
| 118 | }; |
| 119 | let stretch = Stretch { |
| 120 | source: [read(&["SourceStart"], g_start), read(&["SourceEnd"], g_end)], |
| 121 | stretch: [read(&["StretchStart", "KeyFrames"], g_start), read(&["StretchEnd"], g_end)], |
| 122 | mode, |
| 123 | }; |
| 124 | let remapped = stretch.source_time(time).clamp(g_start, g_end.max(g_start)); |
| 125 | if (remapped - time).abs() < 1e-9 { |
| 126 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 127 | } |
| 128 | self.eval_time_remapped(comp, node, time, frame_i, remapped, enc, visiting, stats) |
| 129 | } |
| 130 | |
| 131 | /// `MultiText` — one `TextPlus` render per layer (`Layer{n}` / `Text{n}` / `StyledText{n}` with per-layer |
| 132 | /// overrides of the shared inputs), composited over each other in layer order on the shared canvas. |
| 133 | #[allow(clippy::too_many_arguments)] |
| 134 | pub(in crate::eval) fn eval_multi_text( |
| 135 | &mut self, |
| 136 | comp: &Comp, |
| 137 | node: &Node, |
| 138 | time: f64, |
| 139 | frame_i: i64, |
| 140 | comp_dims: [u32; 2], |
| 141 | enc: &mut wgpu::CommandEncoder, |
| 142 | stats: &mut EvalStats, |
| 143 | ) -> CachedTexture { |
| 144 | let layers = text_layers(node); |
| 145 | let mut acc: Option<CachedTexture> = None; |
| 146 | for layer in if layers.is_empty() { vec![0] } else { layers } { |
| 147 | let mut text_node = node.clone(); |
| 148 | text_node.kind = "TextPlus".to_owned(); |
| 149 | text_node.inputs = text_layer_inputs(node, layer); |
| 150 | let rendered = self.eval_text_plus(comp, &text_node, time, frame_i, comp_dims, enc, stats); |
| 151 | acc = Some(match acc { |
| 152 | None => rendered, |
| 153 | Some(bg) => { |
| 154 | let bg = self.crop_to_canvas(enc, bg); |
| 155 | let fg = self.crop_to_canvas(enc, rendered); |
| 156 | self.merge_text_layer(node, bg, fg, frame_i, enc, stats) |
| 157 | } |
| 158 | }); |
| 159 | } |
| 160 | acc.unwrap_or_else(|| self.dummy.clone()) |
| 161 | } |
| 162 | |
| 163 | /// Straight `Merge` of canvas-sized `fg` over `bg`. |
| 164 | fn merge_text_layer( |
| 165 | &mut self, |
| 166 | node: &Node, |
| 167 | bg: CachedTexture, |
| 168 | fg: CachedTexture, |
| 169 | frame_i: i64, |
| 170 | enc: &mut wgpu::CommandEncoder, |
| 171 | stats: &mut EvalStats, |
| 172 | ) -> CachedTexture { |
| 173 | let key = self.make_key(node, "MultiTextMerge", bg.size, &[bg.content_hash, fg.content_hash], &[]); |
| 174 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 175 | stats.cache_hits += 1; |
| 176 | return hit; |
| 177 | } |
| 178 | stats.cache_misses += 1; |
| 179 | stats.nodes_evaluated += 1; |
| 180 | let mut u = UniformParams::default(); |
| 181 | u.p[0] = [0.5, 0.5, 1.0, 0.0]; |
| 182 | u.p[1] = [1.0, 1.0, 0.0, 0.0]; |
| 183 | u.p[2] = [0.0, 0.0, 1.0, 0.0]; |
| 184 | u.p[3] = [0.0, 0.0, fg.size[0] as f32, fg.size[1] as f32]; |
| 185 | u.p[6] = [0.0, 1.0, 0.0, 0.0]; |
| 186 | let dst = self.alloc_tex_like(&bg, bg.depth.max(fg.depth), key); |
| 187 | self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &fg.view, &self.dummy.view, &dst, &u); |
| 188 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 189 | dst |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | #[cfg(test)] |
| 194 | mod tests { |
| 195 | use super::*; |
| 196 | |
| 197 | fn stretch(mode: StretchMode) -> Stretch { |
| 198 | Stretch { source: [10.0, 14.0], stretch: [10.0, 18.0], mode } |
| 199 | } |
| 200 | |
| 201 | #[test] |
| 202 | fn middle_modes_map_into_source_range() { |
| 203 | assert_eq!(stretch(StretchMode::Scale).source_time(14.0), 12.0); |
| 204 | assert_eq!(stretch(StretchMode::Hold).source_time(17.0), 14.0); |
| 205 | assert_eq!(stretch(StretchMode::Loop).source_time(15.0), 11.0); |
| 206 | assert_eq!(stretch(StretchMode::PingPong).source_time(15.0), 13.0); |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn intro_and_outro_stay_unstretched() { |
| 211 | let s = stretch(StretchMode::Loop); |
| 212 | assert_eq!(s.source_time(4.0), 4.0); |
| 213 | assert_eq!(s.source_time(20.0), 16.0); |
| 214 | } |
| 215 | } |