1use crate::{CubicBezier, DataBinding, Easing};
2use serde::{Deserialize, Serialize};
3
4#[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 pub x: f32,
11 pub y: f32,
13}
14
15impl Vec2 {
16 #[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 #[must_use]
28 pub fn is_zero(&self) -> bool {
29 self.x == 0.0 && self.y == 0.0
30 }
31}
32
33pub const MAX_KEYFRAMES: usize = 100_000;
35
36#[derive(Clone, Debug, PartialEq, Serialize)]
42#[serde(tag = "mode", rename_all = "snake_case")]
43pub enum Animated<T> {
44 Constant {
46 value: T,
48 },
49 Keyframes {
51 keyframes: Vec<Keyframe<T>>,
53 },
54 Data(Box<DataBinding>),
56}
57
58mod sealed {
59 pub trait Sealed {}
60}
61
62pub trait AnimatedValue: sealed::Sealed {
64 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#[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 Constant {
101 value: T,
103 },
104 Keyframes {
106 #[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 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 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 #[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 #[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 #[must_use]
193 pub const fn varies(&self) -> bool {
194 !matches!(self, Self::Constant { .. })
195 }
196}
197
198#[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 Constant {
211 value: Vec2,
213 },
214 Keyframes {
216 #[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 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 #[must_use]
257 pub const fn is_animated(&self) -> bool {
258 !matches!(self, Self::Constant { .. })
259 }
260
261 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
273#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
274#[serde(deny_unknown_fields)]
275pub struct PointKeyframe {
276 pub time: alpha2_time::MediaTime,
278 pub value: Vec2,
280 pub interpolation: Interpolation,
283 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
285 pub out_tangent: Vec2,
286 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
288 pub in_tangent: Vec2,
289}
290
291#[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 pub time: alpha2_time::MediaTime,
300 pub value: T,
302 pub interpolation: Interpolation,
304}
305
306#[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 Hold,
316 Linear,
318 CubicBezier(CubicBezier),
320}
321
322#[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 Hold {},
331 Linear {},
333 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 #[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 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
371#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
372#[serde(deny_unknown_fields)]
373pub struct VisualProperties {
376 #[serde(default = "centre_point")]
379 pub position: AnimatedPoint,
380 #[serde(default = "centre")]
382 pub anchor: Vec2,
383 #[serde(default = "unit_scale")]
385 pub scale: Animated<Vec2>,
386 #[serde(default = "no_rotation")]
388 pub rotation_degrees: Animated<f32>,
389 #[serde(default = "opaque")]
391 pub opacity: Animated<f32>,
392 #[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
433pub(crate) enum Keyed<'a> {
435 Times(&'a [alpha2_time::MediaTime]),
437 Data(&'a DataBinding, PlaceType),
439}
440
441#[derive(Copy, Clone, Debug, Eq, PartialEq)]
443pub(crate) enum PlaceType {
444 Point,
446 Vec2,
448 Scalar,
450 Effect,
452 Other,
454}
455
456pub(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
483pub(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(×));
496 }
497 Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
498 Animated::Constant { .. } => {}
499 }
500}
501
502pub(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(×));
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
542pub(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
578pub(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
590pub(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}