Skip to main content

alpha2_model/
animation.rs

1use crate::{CubicBezier, DataBinding, Easing};
2use serde::{Deserialize, Serialize};
3
4/// A two-dimensional value in normalized output coordinates.
5#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
6#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
7#[serde(deny_unknown_fields)]
8pub struct Vec2 {
9    /// Horizontal component.
10    pub x: f32,
11    /// Vertical component.
12    pub y: f32,
13}
14
15impl Vec2 {
16    /// Creates a two-dimensional value.
17    #[must_use]
18    pub const fn new(x: f32, y: f32) -> Self {
19        Self { x, y }
20    }
21
22    fn is_finite(self) -> bool {
23        self.x.is_finite() && self.y.is_finite()
24    }
25
26    /// Whether both components are zero (either sign).
27    #[must_use]
28    pub fn is_zero(&self) -> bool {
29        self.x == 0.0 && self.y == 0.0
30    }
31}
32
33/// Most keyframes of one animated value.
34pub const MAX_KEYFRAMES: usize = 100_000;
35
36/// A value that is constant, controlled by sorted keyframes, or following a data set.
37///
38/// Only value types whose [`AnimatedValue::ACCEPTS_DATA`] is true (`f32`, [`Vec2`] and
39/// [`crate::EffectValue`]) read or offer the `data` mode; for the others it fails to
40/// deserialize and the schema leaves it out.
41#[derive(Clone, Debug, PartialEq, Serialize)]
42#[serde(tag = "mode", rename_all = "snake_case")]
43pub enum Animated<T> {
44    /// A value without animation.
45    Constant {
46        /// Value used at every timestamp.
47        value: T,
48    },
49    /// Values evaluated from their keyframe sequence.
50    Keyframes {
51        /// Strictly ascending keyframes. The evaluator clamps outside the sequence.
52        keyframes: Vec<Keyframe<T>>,
53    },
54    /// A channel of a data set, followed at render time.
55    Data(Box<DataBinding>),
56}
57
58mod sealed {
59    pub trait Sealed {}
60}
61
62/// A type an [`Animated`] value can hold. Sealed: implemented for the model's animatable types.
63pub trait AnimatedValue: sealed::Sealed {
64    /// Whether the type takes the `data` value mode.
65    const ACCEPTS_DATA: bool;
66}
67
68macro_rules! animated_value {
69    ($accepts:literal: $($type:ty),+) => {
70        $(
71            impl sealed::Sealed for $type {}
72            impl AnimatedValue for $type {
73                const ACCEPTS_DATA: bool = $accepts;
74            }
75        )+
76    };
77}
78
79animated_value!(true: f32, Vec2, crate::EffectValue);
80animated_value!(
81    false: String,
82    crate::Paint,
83    crate::Rgba,
84    crate::Path,
85    crate::LayoutLength,
86    crate::LayoutSize,
87    crate::LayoutOffset,
88    crate::Insets
89);
90
91// The wire form of `Animated`, before the value type decides whether it takes data. Its doc
92// comment is the schema's description.
93/// A value that is constant, controlled by sorted keyframes, or following a data set.
94#[derive(Deserialize)]
95#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
96#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
97#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
98enum AnimatedWire<T> {
99    /// A value without animation.
100    Constant {
101        /// Value used at every timestamp.
102        value: T,
103    },
104    /// Values evaluated from their keyframe sequence.
105    Keyframes {
106        /// Strictly ascending keyframes. The evaluator clamps outside the sequence.
107        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
108        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
109        keyframes: Vec<Keyframe<T>>,
110    },
111    /// A channel of a data set, followed at render time.
112    Data(DataBinding),
113}
114
115impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
116    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
117        Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
118            AnimatedWire::Constant { value } => Self::Constant { value },
119            AnimatedWire::Keyframes { keyframes } => Self::Keyframes { keyframes },
120            AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
121            AnimatedWire::Data(_) => {
122                return Err(serde::de::Error::custom(
123                    "this value takes no `data` mode; use `constant` or `keyframes`",
124                ));
125            }
126        })
127    }
128}
129
130#[cfg(feature = "schema")]
131impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
132    // Types without the data mode are a separate generic, `Keyframed_{T}`, for one shape each.
133    fn schema_name() -> std::borrow::Cow<'static, str> {
134        if T::ACCEPTS_DATA {
135            AnimatedWire::<T>::schema_name()
136        } else {
137            format!("Keyframed_{}", T::schema_name()).into()
138        }
139    }
140
141    fn schema_id() -> std::borrow::Cow<'static, str> {
142        if T::ACCEPTS_DATA {
143            AnimatedWire::<T>::schema_id()
144        } else {
145            format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
146        }
147    }
148
149    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
150        let mut schema = AnimatedWire::<T>::json_schema(generator);
151        if !T::ACCEPTS_DATA {
152            crate::schema::drop_data_mode(&mut schema);
153            schema.insert(
154                "description".to_owned(),
155                "A value that is constant or controlled by sorted keyframes.".into(),
156            );
157        }
158        schema
159    }
160}
161
162impl<T> Animated<T> {
163    /// The same animation with each value mapped by `map`, keeping times and interpolations.
164    #[must_use]
165    pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
166        match self {
167            Self::Constant { value } => Animated::Constant { value: map(value) },
168            Self::Keyframes { keyframes } => Animated::Keyframes {
169                keyframes: keyframes
170                    .iter()
171                    .map(|keyframe| Keyframe {
172                        time: keyframe.time,
173                        value: map(&keyframe.value),
174                        interpolation: keyframe.interpolation,
175                    })
176                    .collect(),
177            },
178            Self::Data(binding) => Animated::Data(binding.clone()),
179        }
180    }
181
182    /// The data binding, when the value follows a data set.
183    #[must_use]
184    pub const fn data(&self) -> Option<&DataBinding> {
185        match self {
186            Self::Data(binding) => Some(binding),
187            Self::Constant { .. } | Self::Keyframes { .. } => None,
188        }
189    }
190
191    /// Whether the value can change over time: keyframes or data.
192    #[must_use]
193    pub const fn varies(&self) -> bool {
194        !matches!(self, Self::Constant { .. })
195    }
196}
197
198/// A position that can move along curves between its keyframes.
199///
200/// Its JSON is an `Animated<Vec2>` plus optional spatial tangents per keyframe. With them,
201/// the value travels the cubic Bezier through this keyframe's `out_tangent` and the next's
202/// `in_tangent`, at the speed its timing curve sets along the arc length. Without them it
203/// moves in a straight line.
204#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
205#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
206#[serde(deny_unknown_fields)]
207#[serde(tag = "mode", rename_all = "snake_case")]
208pub enum AnimatedPoint {
209    /// A value without animation.
210    Constant {
211        /// Value used at every timestamp.
212        value: Vec2,
213    },
214    /// Values evaluated from their keyframe sequence.
215    Keyframes {
216        /// Strictly ascending keyframes. The evaluator clamps outside the sequence.
217        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
218        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
219        keyframes: Vec<PointKeyframe>,
220    },
221    /// A channel of a data set, followed at render time.
222    Data(Box<DataBinding>),
223}
224
225impl Default for AnimatedPoint {
226    fn default() -> Self {
227        Self::Constant {
228            value: Vec2::default(),
229        }
230    }
231}
232
233impl From<Animated<Vec2>> for AnimatedPoint {
234    fn from(animation: Animated<Vec2>) -> Self {
235        match animation {
236            Animated::Constant { value } => Self::Constant { value },
237            Animated::Keyframes { keyframes } => Self::Keyframes {
238                keyframes: keyframes
239                    .into_iter()
240                    .map(|keyframe| PointKeyframe {
241                        time: keyframe.time,
242                        value: keyframe.value,
243                        interpolation: keyframe.interpolation,
244                        out_tangent: Vec2::default(),
245                        in_tangent: Vec2::default(),
246                    })
247                    .collect(),
248            },
249            Animated::Data(binding) => Self::Data(binding),
250        }
251    }
252}
253
254impl AnimatedPoint {
255    /// Whether the value changes over time: keyframes or data.
256    #[must_use]
257    pub const fn is_animated(&self) -> bool {
258        !matches!(self, Self::Constant { .. })
259    }
260
261    /// The data binding, when the value follows a data set.
262    #[must_use]
263    pub const fn data(&self) -> Option<&DataBinding> {
264        match self {
265            Self::Data(binding) => Some(binding),
266            Self::Constant { .. } | Self::Keyframes { .. } => None,
267        }
268    }
269}
270
271/// One keyframe of an [`AnimatedPoint`].
272#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
273#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
274#[serde(deny_unknown_fields)]
275pub struct PointKeyframe {
276    /// Timestamp of this value, as a [`Keyframe`]'s.
277    pub time: alpha2_time::MediaTime,
278    /// Value at `time`.
279    pub value: Vec2,
280    /// Interpolation from this keyframe to its successor: how fast the value travels along the
281    /// way.
282    pub interpolation: Interpolation,
283    /// The curve's first control point toward the next keyframe, relative to this value.
284    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
285    pub out_tangent: Vec2,
286    /// The curve's second control point from the previous keyframe, relative to this value.
287    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
288    pub in_tangent: Vec2,
289}
290
291/// One timestamped control value.
292#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
293#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
294#[serde(deny_unknown_fields)]
295#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
296pub struct Keyframe<T> {
297    /// Timestamp of this value. Timeline time, except composition time in a composition node's
298    /// settings and picture time in a shapes or layout generator's tree.
299    pub time: alpha2_time::MediaTime,
300    /// Value at `time`.
301    pub value: T,
302    /// Interpolation from this keyframe to its successor.
303    pub interpolation: Interpolation,
304}
305
306/// Interpolation from one keyframe to the next.
307///
308/// Values interpolate numerically: a rotation from 0 to 720 degrees turns twice. A host that
309/// wants the shortest path normalizes its keyframe values.
310#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
311#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
312#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
313pub enum Interpolation {
314    /// Keep this keyframe's value until the next keyframe.
315    Hold,
316    /// Move to the next value at a constant rate.
317    Linear,
318    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
319    CubicBezier(CubicBezier),
320}
321
322/// The wire form of [`Interpolation`]; see `EasingWire` for why unit variants are empty
323/// structs.
324#[derive(Deserialize)]
325#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
326#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
327#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
328pub(crate) enum InterpolationWire {
329    /// Keep this keyframe's value until the next keyframe.
330    Hold {},
331    /// Move to the next value at a constant rate.
332    Linear {},
333    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
334    CubicBezier(CubicBezier),
335}
336
337impl From<InterpolationWire> for Interpolation {
338    fn from(wire: InterpolationWire) -> Self {
339        match wire {
340            InterpolationWire::Hold {} => Self::Hold,
341            InterpolationWire::Linear {} => Self::Linear,
342            InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
343        }
344    }
345}
346
347impl Interpolation {
348    /// The fraction of the way to the next value at linear segment `progress` (clamped to
349    /// `0..=1`), or `None` while holding. A cubic Bezier may overshoot `0..=1`.
350    #[must_use]
351    pub fn amount(self, progress: f64) -> Option<f64> {
352        match self {
353            Self::Hold => None,
354            Self::Linear => Some(Easing::Linear.apply(progress)),
355            Self::CubicBezier(curve) => Some(curve.apply(progress)),
356        }
357    }
358
359    /// Whether the interpolation's parameters are usable.
360    #[must_use]
361    pub fn is_valid(self) -> bool {
362        match self {
363            Self::Hold | Self::Linear => true,
364            Self::CubicBezier(curve) => curve.is_valid(),
365        }
366    }
367}
368
369/// Resolution-independent visual presentation controls for a clip.
370#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
371#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
372#[serde(deny_unknown_fields)]
373///
374/// Omitted fields default to the source centred on the canvas, unscaled, unrotated and opaque.
375pub struct VisualProperties {
376    /// Animated normalized canvas translation, along spatial curves where keyframes have
377    /// tangents.
378    #[serde(default = "centre_point")]
379    pub position: AnimatedPoint,
380    /// Unanimated normalized point within the source rectangle.
381    #[serde(default = "centre")]
382    pub anchor: Vec2,
383    /// Animated per-axis scale.
384    #[serde(default = "unit_scale")]
385    pub scale: Animated<Vec2>,
386    /// Animated clockwise rotation in degrees.
387    #[serde(default = "no_rotation")]
388    pub rotation_degrees: Animated<f32>,
389    /// Animated opacity constrained to `0..=1`.
390    #[serde(default = "opaque")]
391    pub opacity: Animated<f32>,
392    /// A `similarity` data set moving the clip's own picture, applied before this transform.
393    /// Clip visuals only.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub correction: Option<crate::CorrectionRef>,
396}
397
398impl Default for VisualProperties {
399    fn default() -> Self {
400        Self {
401            position: centre_point(),
402            anchor: centre(),
403            scale: unit_scale(),
404            rotation_degrees: no_rotation(),
405            opacity: opaque(),
406            correction: None,
407        }
408    }
409}
410
411const fn centre() -> Vec2 {
412    Vec2::new(0.5, 0.5)
413}
414
415const fn centre_point() -> AnimatedPoint {
416    AnimatedPoint::Constant { value: centre() }
417}
418
419pub(crate) const fn unit_scale() -> Animated<Vec2> {
420    Animated::Constant {
421        value: Vec2::new(1.0, 1.0),
422    }
423}
424
425const fn no_rotation() -> Animated<f32> {
426    Animated::Constant { value: 0.0 }
427}
428
429pub(crate) const fn opaque() -> Animated<f32> {
430    Animated::Constant { value: 1.0 }
431}
432
433/// What a walk over animated values meets at one value that is not constant.
434pub(crate) enum Keyed<'a> {
435    /// The times of its keyframes.
436    Times(&'a [alpha2_time::MediaTime]),
437    /// Its data binding, with the type of the value bound.
438    Data(&'a DataBinding, PlaceType),
439}
440
441/// The value type a data binding sits on, which decides the kinds it can follow.
442#[derive(Copy, Clone, Debug, Eq, PartialEq)]
443pub(crate) enum PlaceType {
444    /// A point along spatial curves.
445    Point,
446    /// A two-component value.
447    Vec2,
448    /// A number.
449    Scalar,
450    /// An effect parameter, whose type its definition gives.
451    Effect,
452    /// A type that takes no data.
453    Other,
454}
455
456/// The [`PlaceType`] of each animatable type.
457pub(crate) trait Placed {
458    const PLACE: PlaceType;
459}
460
461macro_rules! placed {
462    ($place:ident: $($type:ty),+) => {
463        $(impl Placed for $type {
464            const PLACE: PlaceType = PlaceType::$place;
465        })+
466    };
467}
468
469placed!(Scalar: f32);
470placed!(Vec2: Vec2);
471placed!(Effect: crate::EffectValue);
472placed!(
473    Other: String,
474    crate::Paint,
475    crate::Rgba,
476    crate::Path,
477    crate::LayoutLength,
478    crate::LayoutSize,
479    crate::LayoutOffset,
480    crate::Insets
481);
482
483/// Calls `visit` with `at` and the times of `animated`'s keyframes, or its data binding.
484pub(crate) fn visit_keyed<T: Placed>(
485    at: &str,
486    animated: &Animated<T>,
487    visit: &mut impl FnMut(&str, Keyed<'_>),
488) {
489    match animated {
490        Animated::Keyframes { keyframes } => {
491            let times = keyframes
492                .iter()
493                .map(|keyframe| keyframe.time)
494                .collect::<Vec<_>>();
495            visit(at, Keyed::Times(&times));
496        }
497        Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
498        Animated::Constant { .. } => {}
499    }
500}
501
502/// [`visit_keyed`] for a point along a spatial curve.
503pub(crate) fn visit_keyed_point(
504    at: &str,
505    animated: &AnimatedPoint,
506    visit: &mut impl FnMut(&str, Keyed<'_>),
507) {
508    match animated {
509        AnimatedPoint::Keyframes { keyframes } => {
510            let times = keyframes
511                .iter()
512                .map(|keyframe| keyframe.time)
513                .collect::<Vec<_>>();
514            visit(at, Keyed::Times(&times));
515        }
516        AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
517        AnimatedPoint::Constant { .. } => {}
518    }
519}
520
521impl VisualProperties {
522    pub(crate) fn validate(&self) -> bool {
523        self.anchor.is_finite()
524            && valid_point_animation(&self.position)
525            && valid_vec2_animation(&self.scale)
526            && valid_scalar_animation(&self.rotation_degrees, false)
527            && valid_scalar_animation(&self.opacity, true)
528    }
529}
530
531fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
532    match animation {
533        Animated::Constant { value } => value.is_finite(),
534        Animated::Keyframes { keyframes } => {
535            valid_keyframes(keyframes)
536                && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
537        }
538        Animated::Data(_) => true,
539    }
540}
541
542/// Valid keyframes (or a constant) whose values and tangents are finite.
543pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
544    match animation {
545        AnimatedPoint::Constant { value } => value.is_finite(),
546        AnimatedPoint::Data(_) => true,
547        AnimatedPoint::Keyframes { keyframes } => {
548            !keyframes.is_empty()
549                && keyframes.len() <= MAX_KEYFRAMES
550                && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
551                && keyframes.iter().all(|keyframe| {
552                    keyframe.interpolation.is_valid()
553                        && keyframe.value.is_finite()
554                        && keyframe.out_tangent.is_finite()
555                        && keyframe.in_tangent.is_finite()
556                })
557        }
558    }
559}
560
561fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
562    let domain = if unit_interval {
563        crate::Domain::UNIT
564    } else {
565        crate::Domain::ANY
566    };
567    let valid_value = |value: f32| domain.contains(value);
568    match animation {
569        Animated::Constant { value } => valid_value(*value),
570        Animated::Keyframes { keyframes } => {
571            valid_keyframes(keyframes)
572                && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
573        }
574        Animated::Data(_) => true,
575    }
576}
577
578/// Valid keyframes (or a constant) whose every finite value passes `check`.
579pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
580    let valid = |value: f32| value.is_finite() && check(value);
581    match animation {
582        Animated::Constant { value } => valid(*value),
583        Animated::Keyframes { keyframes } => {
584            valid_keyframes(keyframes) && keyframes.iter().all(|keyframe| valid(keyframe.value))
585        }
586        Animated::Data(_) => true,
587    }
588}
589
590/// A non-empty, strictly ascending run of at most [`MAX_KEYFRAMES`] with usable interpolations.
591pub(crate) fn valid_keyframes<T>(keyframes: &[Keyframe<T>]) -> bool {
592    !keyframes.is_empty()
593        && keyframes.len() <= MAX_KEYFRAMES
594        && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
595        && keyframes
596            .iter()
597            .all(|keyframe| keyframe.interpolation.is_valid())
598}