Skip to main content

alpha2_eval/
text_animation.rs

1//! Text animators sampled at a time: the plain numbers each animator applies.
2
3use alpha2_geometry::StableHash;
4use alpha2_model::{
5    Animated, Extrapolation, Interpolation, Keyframe, RangeShape, RangeUnits, RunState,
6    TextAnimator, TextRun, TextSelector, TextUnit,
7};
8use alpha2_time::MediaTime;
9
10use crate::{SampleContext, sample_rgba, sample_scalar, sample_vec2};
11
12/// An animator's selector and properties at one time.
13#[derive(Clone, Debug, PartialEq)]
14pub struct SampledAnimator {
15    /// What it selects.
16    pub selector: SampledSelector,
17    /// Offset in font sizes, +y down.
18    pub offset: Option<[f32; 2]>,
19    /// Scale about each character's centre.
20    pub scale: Option<[f32; 2]>,
21    /// Clockwise degrees about each character's centre.
22    pub rotation_degrees: Option<f32>,
23    /// Target opacity.
24    pub opacity: Option<f32>,
25    /// Target fill color, straight sRGB.
26    pub fill: Option<[f32; 4]>,
27    /// Target stroke color, straight sRGB.
28    pub stroke: Option<[f32; 4]>,
29    /// Extra space after each character, font sizes.
30    pub tracking: Option<f32>,
31    /// Whether the advance follows the horizontal scale.
32    pub advance_follows_scale: bool,
33    /// The reveal's edge, its values held to their ranges.
34    pub reveal: Option<SampledReveal>,
35}
36
37/// A text reveal at one time.
38#[derive(Copy, Clone, Debug, PartialEq)]
39pub struct SampledReveal {
40    /// How much of a fully selected unit shows, in `[0, 1]`.
41    pub progress: f32,
42    /// The direction the edge travels, clockwise degrees.
43    pub angle_degrees: f32,
44    /// The edge's softness, font sizes in `[0, MAX_REVEAL_FEATHER]`.
45    pub feather: f32,
46}
47
48/// A selector at one time.
49#[derive(Clone, Debug, PartialEq)]
50pub enum SampledSelector {
51    /// A Range selector's values.
52    Range {
53        /// What it counts.
54        based_on: TextUnit,
55        /// Percents or indices.
56        units: RangeUnits,
57        /// Start, with the offset not added.
58        start: f32,
59        /// End, with the offset not added.
60        end: f32,
61        /// Added to start and end.
62        offset: f32,
63        /// How selection rises and falls.
64        shape: RangeShape,
65        /// Selection scale.
66        amount: f32,
67    },
68    /// A Timing selector (its values are not animated).
69    Timing {
70        /// Which runs.
71        state: RunState,
72        /// Fade length.
73        ramp: MediaTime,
74        /// Sweep each run's characters in order.
75        sweep: bool,
76    },
77    /// A Class selector.
78    Class {
79        /// The class name.
80        class: String,
81    },
82}
83
84/// `animators` sampled at `time`, in order.
85#[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
163/// Feeds every value of `animators` to `hash`.
164pub 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/// The largest factor any cluster's advance can be widened by under `animators` over a text of
225/// `runs`: per animator whose advance follows its scale, `1 + w (s - 1)` with `s` its largest
226/// horizontal scale and `w` its largest selection, at least 1; their product, at most the
227/// largest animator scale, which also bounds a cluster's. 1 when none pushes.
228///
229/// Keyframes count every value and each eased segment's extremes, so an overshooting curve
230/// reserves its overshoot. A value bound to data, which text animators refuse, takes its range's
231/// bound.
232#[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 widest = *ANIMATOR_SCALE.end();
245        let largest_scale = match scale {
246            Animated::Split { channels } => channels
247                .first()
248                .map_or(f64::from(widest), |x| largest(x, |value| *value, widest)),
249            scale => largest(scale, |value| value.x, widest),
250        }
251        .max(0.0);
252        let selection = match &animator.selector {
253            TextSelector::Range { amount, .. } => {
254                largest(amount, |value| *value, 1.0).clamp(0.0, 1.0)
255            }
256            TextSelector::Timing { .. } => {
257                if runs.iter().any(|run| run.time.is_some()) {
258                    1.0
259                } else {
260                    0.0
261                }
262            }
263            TextSelector::Class { class } => {
264                if runs.iter().any(|run| run.class.contains(class)) {
265                    1.0
266                } else {
267                    0.0
268                }
269            }
270        };
271        headroom *= (1.0 + selection * (largest_scale - 1.0)).max(1.0);
272    }
273    #[expect(
274        clippy::cast_possible_truncation,
275        reason = "at most the cluster scale limit"
276    )]
277    let headroom = headroom.min(f64::from(*ANIMATOR_SCALE.end())) as f32;
278    headroom
279}
280
281const ANIMATOR_SCALE: std::ops::RangeInclusive<f32> = alpha2_model::ANIMATOR_SCALE_RANGE;
282
283/// The largest `component` an animated value takes, `bound` for one bound to data.
284fn largest<T>(animated: &Animated<T>, component: impl Fn(&T) -> f32, bound: f32) -> f64 {
285    match animated {
286        Animated::Constant { value } => f64::from(component(value)),
287        Animated::Keyframes { before, after, .. }
288            if [*before, *after].iter().any(|extrapolation| {
289                matches!(
290                    extrapolation,
291                    Extrapolation::Linear | Extrapolation::RepeatOffset
292                )
293            }) =>
294        {
295            f64::from(bound)
296        }
297        Animated::Keyframes { keyframes, .. } => keyframes
298            .iter()
299            .zip(keyframes.iter().skip(1).map(Some).chain([None]))
300            .map(|(left, right)| segment_largest(left, right, &component))
301            .fold(f64::NEG_INFINITY, f64::max),
302        Animated::Data(_) | Animated::Split { .. } => f64::from(bound),
303    }
304}
305
306/// The largest `component` from keyframe `left` to `right`, the left value alone for the last.
307fn segment_largest<T>(
308    left: &Keyframe<T>,
309    right: Option<&Keyframe<T>>,
310    component: &impl Fn(&T) -> f32,
311) -> f64 {
312    let from = f64::from(component(&left.value));
313    let Some(right) = right else {
314        return from;
315    };
316    let to = f64::from(component(&right.value));
317    let [low, high] = match left.interpolation {
318        Interpolation::Hold => return from,
319        Interpolation::ValueBezier(curve) => {
320            return curve.range(component(&left.value), component(&right.value))[1];
321        }
322        Interpolation::Linear | Interpolation::Steps(_) => [0.0, 1.0],
323        Interpolation::CubicBezier(curve) => {
324            bezier_output_range(f64::from(curve.y1), f64::from(curve.y2))
325        }
326        Interpolation::Points { ref points } => alpha2_model::easing_points_range(points),
327    };
328    (from + (to - from) * low).max(from + (to - from) * high)
329}
330
331/// The least and largest output of a `cubic-bezier` with these `y1`, `y2` over its whole
332/// parameter range: its ends and where its derivative, a quadratic, is zero.
333fn bezier_output_range(y1: f64, y2: f64) -> [f64; 2] {
334    let output = |t: f64| {
335        let rest = 1.0 - t;
336        3.0 * rest * rest * t * y1 + 3.0 * rest * t * t * y2 + t * t * t
337    };
338    let (d0, d1, d2) = (y1, y2 - y1, 1.0 - y2);
339    let (a, b, c) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0);
340    let mut roots = [None, None];
341    if a.abs() <= f64::EPSILON {
342        if b.abs() > f64::EPSILON {
343            roots[0] = Some(-c / b);
344        }
345    } else {
346        let discriminant = b * b - 4.0 * a * c;
347        if discriminant >= 0.0 {
348            let root = discriminant.sqrt();
349            roots = [Some((-b + root) / (2.0 * a)), Some((-b - root) / (2.0 * a))];
350        }
351    }
352    roots
353        .into_iter()
354        .flatten()
355        .filter(|t| *t > 0.0 && *t < 1.0)
356        .map(output)
357        .fold([0.0, 1.0], |[low, high], value| {
358            [low.min(value), high.max(value)]
359        })
360}