1use alpha2_geometry::StableHash;
4use alpha2_model::{
5 Animated, Interpolation, Keyframe, RangeShape, RangeUnits, RunState, TextAnimator, TextRun,
6 TextSelector, TextUnit,
7};
8use alpha2_time::MediaTime;
9
10use crate::{SampleContext, sample_rgba, sample_scalar, sample_vec2};
11
12#[derive(Clone, Debug, PartialEq)]
14pub struct SampledAnimator {
15 pub selector: SampledSelector,
17 pub offset: Option<[f32; 2]>,
19 pub scale: Option<[f32; 2]>,
21 pub rotation_degrees: Option<f32>,
23 pub opacity: Option<f32>,
25 pub fill: Option<[f32; 4]>,
27 pub stroke: Option<[f32; 4]>,
29 pub tracking: Option<f32>,
31 pub advance_follows_scale: bool,
33 pub reveal: Option<SampledReveal>,
35}
36
37#[derive(Copy, Clone, Debug, PartialEq)]
39pub struct SampledReveal {
40 pub progress: f32,
42 pub angle_degrees: f32,
44 pub feather: f32,
46}
47
48#[derive(Clone, Debug, PartialEq)]
50pub enum SampledSelector {
51 Range {
53 based_on: TextUnit,
55 units: RangeUnits,
57 start: f32,
59 end: f32,
61 offset: f32,
63 shape: RangeShape,
65 amount: f32,
67 },
68 Timing {
70 state: RunState,
72 ramp: MediaTime,
74 sweep: bool,
76 },
77 Class {
79 class: String,
81 },
82}
83
84#[must_use]
86pub fn sample_text_animators(animators: &[TextAnimator], time: MediaTime) -> Vec<SampledAnimator> {
87 animators
88 .iter()
89 .map(|animator| {
90 let properties = &animator.properties;
91 let pair = |value: alpha2_model::Vec2| [value.x, value.y];
92 let color =
93 |value: alpha2_model::Rgba| [value.red, value.green, value.blue, value.alpha];
94 SampledAnimator {
95 selector: match &animator.selector {
96 TextSelector::Range {
97 based_on,
98 units,
99 start,
100 end,
101 offset,
102 shape,
103 amount,
104 } => SampledSelector::Range {
105 based_on: *based_on,
106 units: *units,
107 start: sample_scalar(start, time, &SampleContext::NONE),
108 end: sample_scalar(end, time, &SampleContext::NONE),
109 offset: sample_scalar(offset, time, &SampleContext::NONE),
110 shape: *shape,
111 amount: sample_scalar(amount, time, &SampleContext::NONE).clamp(0.0, 1.0),
112 },
113 TextSelector::Timing { state, ramp, sweep } => SampledSelector::Timing {
114 state: *state,
115 ramp: *ramp,
116 sweep: *sweep,
117 },
118 TextSelector::Class { class } => SampledSelector::Class {
119 class: class.clone(),
120 },
121 },
122 offset: properties.offset.as_ref().map(|value| {
123 let bound = alpha2_model::MAX_ANIMATOR_OFFSET;
124 pair(sample_vec2(value, time, &SampleContext::NONE))
125 .map(|axis| axis.clamp(-bound, bound))
126 }),
127 scale: properties.scale.as_ref().map(|value| {
128 pair(sample_vec2(value, time, &SampleContext::NONE)).map(|axis| axis.max(0.0))
129 }),
130 rotation_degrees: properties
131 .rotation_degrees
132 .as_ref()
133 .map(|value| sample_scalar(value, time, &SampleContext::NONE)),
134 opacity: properties
135 .opacity
136 .as_ref()
137 .map(|value| sample_scalar(value, time, &SampleContext::NONE).clamp(0.0, 1.0)),
138 fill: properties
139 .fill
140 .as_ref()
141 .map(|value| color(sample_rgba(value, time))),
142 stroke: properties
143 .stroke
144 .as_ref()
145 .map(|value| color(sample_rgba(value, time))),
146 tracking: properties
147 .tracking
148 .as_ref()
149 .map(|value| sample_scalar(value, time, &SampleContext::NONE)),
150 advance_follows_scale: properties.advance_follows_scale,
151 reveal: properties.reveal.as_ref().map(|reveal| SampledReveal {
152 progress: sample_scalar(&reveal.progress, time, &SampleContext::NONE)
153 .clamp(0.0, 1.0),
154 angle_degrees: sample_scalar(&reveal.angle_degrees, time, &SampleContext::NONE),
155 feather: sample_scalar(&reveal.feather, time, &SampleContext::NONE)
156 .clamp(0.0, alpha2_model::MAX_REVEAL_FEATHER),
157 }),
158 }
159 })
160 .collect()
161}
162
163pub fn hash_sampled_animators(hash: &mut StableHash, animators: &[SampledAnimator]) {
165 hash.u64(animators.len() as u64);
166 for animator in animators {
167 match &animator.selector {
168 SampledSelector::Range {
169 based_on,
170 units,
171 start,
172 end,
173 offset,
174 shape,
175 amount,
176 } => {
177 hash.u32(0);
178 hash.u32(*based_on as u32);
179 hash.u32(*units as u32);
180 hash.u32(*shape as u32);
181 for value in [start, end, offset, amount] {
182 hash.f32(*value);
183 }
184 }
185 SampledSelector::Timing { state, ramp, sweep } => {
186 hash.u32(1);
187 hash.u32(*state as u32);
188 hash.u64(ramp.ticks().cast_unsigned());
189 hash.u32(u32::from(*sweep));
190 }
191 SampledSelector::Class { class } => {
192 hash.u32(2);
193 hash.bytes(class.as_bytes());
194 }
195 }
196 let mut option = |values: Option<&[f32]>| match values {
197 None => hash.u32(0),
198 Some(values) => {
199 hash.u32(1);
200 for value in values {
201 hash.f32(*value);
202 }
203 }
204 };
205 option(animator.offset.as_ref().map(<[f32; 2]>::as_slice));
206 option(animator.scale.as_ref().map(<[f32; 2]>::as_slice));
207 option(animator.rotation_degrees.as_ref().map(std::slice::from_ref));
208 option(animator.opacity.as_ref().map(std::slice::from_ref));
209 option(animator.fill.as_ref().map(<[f32; 4]>::as_slice));
210 option(animator.stroke.as_ref().map(<[f32; 4]>::as_slice));
211 option(animator.tracking.as_ref().map(std::slice::from_ref));
212 if animator.advance_follows_scale {
213 hash.u32(0xadf5);
214 }
215 if let Some(reveal) = animator.reveal {
216 hash.u32(0x2e7e);
217 for value in [reveal.progress, reveal.angle_degrees, reveal.feather] {
218 hash.f32(value);
219 }
220 }
221 }
222}
223
224#[must_use]
233pub fn advance_headroom(animators: &[TextAnimator], runs: &[TextRun]) -> f32 {
234 let mut headroom = 1.0_f64;
235 for animator in animators {
236 let properties = &animator.properties;
237 let Some(scale) = properties
238 .scale
239 .as_ref()
240 .filter(|_| properties.advance_follows_scale)
241 else {
242 continue;
243 };
244 let largest_scale = largest(scale, |value| value.x, *ANIMATOR_SCALE.end()).max(0.0);
245 let selection = match &animator.selector {
246 TextSelector::Range { amount, .. } => {
247 largest(amount, |value| *value, 1.0).clamp(0.0, 1.0)
248 }
249 TextSelector::Timing { .. } => {
250 if runs.iter().any(|run| run.time.is_some()) {
251 1.0
252 } else {
253 0.0
254 }
255 }
256 TextSelector::Class { class } => {
257 if runs.iter().any(|run| run.class.contains(class)) {
258 1.0
259 } else {
260 0.0
261 }
262 }
263 };
264 headroom *= (1.0 + selection * (largest_scale - 1.0)).max(1.0);
265 }
266 #[expect(
267 clippy::cast_possible_truncation,
268 reason = "at most the cluster scale limit"
269 )]
270 let headroom = headroom.min(f64::from(*ANIMATOR_SCALE.end())) as f32;
271 headroom
272}
273
274const ANIMATOR_SCALE: std::ops::RangeInclusive<f32> = alpha2_model::ANIMATOR_SCALE_RANGE;
275
276fn largest<T>(animated: &Animated<T>, component: impl Fn(&T) -> f32, bound: f32) -> f64 {
278 match animated {
279 Animated::Constant { value } => f64::from(component(value)),
280 Animated::Keyframes { keyframes } => keyframes
281 .iter()
282 .zip(keyframes.iter().skip(1).map(Some).chain([None]))
283 .map(|(left, right)| segment_largest(left, right, &component))
284 .fold(f64::NEG_INFINITY, f64::max),
285 Animated::Data(_) => f64::from(bound),
286 }
287}
288
289fn segment_largest<T>(
291 left: &Keyframe<T>,
292 right: Option<&Keyframe<T>>,
293 component: &impl Fn(&T) -> f32,
294) -> f64 {
295 let from = f64::from(component(&left.value));
296 let Some(right) = right else {
297 return from;
298 };
299 let to = f64::from(component(&right.value));
300 let [low, high] = match left.interpolation {
301 Interpolation::Hold => return from,
302 Interpolation::Linear => [0.0, 1.0],
303 Interpolation::CubicBezier(curve) => {
304 bezier_output_range(f64::from(curve.y1), f64::from(curve.y2))
305 }
306 };
307 (from + (to - from) * low).max(from + (to - from) * high)
308}
309
310fn bezier_output_range(y1: f64, y2: f64) -> [f64; 2] {
313 let output = |t: f64| {
314 let rest = 1.0 - t;
315 3.0 * rest * rest * t * y1 + 3.0 * rest * t * t * y2 + t * t * t
316 };
317 let (d0, d1, d2) = (y1, y2 - y1, 1.0 - y2);
318 let (a, b, c) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0);
319 let mut roots = [None, None];
320 if a.abs() <= f64::EPSILON {
321 if b.abs() > f64::EPSILON {
322 roots[0] = Some(-c / b);
323 }
324 } else {
325 let discriminant = b * b - 4.0 * a * c;
326 if discriminant >= 0.0 {
327 let root = discriminant.sqrt();
328 roots = [Some((-b + root) / (2.0 * a)), Some((-b - root) / (2.0 * a))];
329 }
330 }
331 roots
332 .into_iter()
333 .flatten()
334 .filter(|t| *t > 0.0 && *t < 1.0)
335 .map(output)
336 .fold([0.0, 1.0], |[low, high], value| {
337 [low.min(value), high.max(value)]
338 })
339}