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::TextContent,
83 crate::Paint,
84 crate::Rgba,
85 crate::Path,
86 crate::LayoutLength,
87 crate::LayoutSize,
88 crate::LayoutOffset,
89 crate::Insets
90);
91
92#[derive(Deserialize)]
96#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
97#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
98#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
99enum AnimatedWire<T> {
100 Constant {
102 value: T,
104 },
105 Keyframes {
107 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
109 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
110 keyframes: Vec<Keyframe<T>>,
111 },
112 Data(DataBinding),
114}
115
116impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
117 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
118 Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
119 AnimatedWire::Constant { value } => Self::Constant { value },
120 AnimatedWire::Keyframes { keyframes } => Self::Keyframes { keyframes },
121 AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
122 AnimatedWire::Data(_) => {
123 return Err(serde::de::Error::custom(
124 "this value takes no `data` mode; use `constant` or `keyframes`",
125 ));
126 }
127 })
128 }
129}
130
131#[cfg(feature = "schema")]
132impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
133 fn schema_name() -> std::borrow::Cow<'static, str> {
135 if T::ACCEPTS_DATA {
136 AnimatedWire::<T>::schema_name()
137 } else {
138 format!("Keyframed_{}", T::schema_name()).into()
139 }
140 }
141
142 fn schema_id() -> std::borrow::Cow<'static, str> {
143 if T::ACCEPTS_DATA {
144 AnimatedWire::<T>::schema_id()
145 } else {
146 format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
147 }
148 }
149
150 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
151 let mut schema = AnimatedWire::<T>::json_schema(generator);
152 if !T::ACCEPTS_DATA {
153 crate::schema::drop_data_mode(&mut schema);
154 schema.insert(
155 "description".to_owned(),
156 "A value that is constant or controlled by sorted keyframes.".into(),
157 );
158 }
159 schema
160 }
161}
162
163impl<T> Animated<T> {
164 #[must_use]
166 pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
167 match self {
168 Self::Constant { value } => Animated::Constant { value: map(value) },
169 Self::Keyframes { keyframes } => Animated::Keyframes {
170 keyframes: keyframes
171 .iter()
172 .map(|keyframe| Keyframe {
173 time: keyframe.time,
174 value: map(&keyframe.value),
175 interpolation: keyframe.interpolation,
176 })
177 .collect(),
178 },
179 Self::Data(binding) => Animated::Data(binding.clone()),
180 }
181 }
182
183 #[must_use]
185 pub const fn data(&self) -> Option<&DataBinding> {
186 match self {
187 Self::Data(binding) => Some(binding),
188 Self::Constant { .. } | Self::Keyframes { .. } => None,
189 }
190 }
191
192 #[must_use]
194 pub const fn varies(&self) -> bool {
195 !matches!(self, Self::Constant { .. })
196 }
197}
198
199#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
206#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
207#[serde(deny_unknown_fields)]
208#[serde(tag = "mode", rename_all = "snake_case")]
209pub enum AnimatedPoint {
210 Constant {
212 value: Vec2,
214 },
215 Keyframes {
217 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
219 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
220 keyframes: Vec<PointKeyframe>,
221 },
222 Data(Box<DataBinding>),
224}
225
226impl Default for AnimatedPoint {
227 fn default() -> Self {
228 Self::Constant {
229 value: Vec2::default(),
230 }
231 }
232}
233
234impl From<Animated<Vec2>> for AnimatedPoint {
235 fn from(animation: Animated<Vec2>) -> Self {
236 match animation {
237 Animated::Constant { value } => Self::Constant { value },
238 Animated::Keyframes { keyframes } => Self::Keyframes {
239 keyframes: keyframes
240 .into_iter()
241 .map(|keyframe| PointKeyframe {
242 time: keyframe.time,
243 value: keyframe.value,
244 interpolation: keyframe.interpolation,
245 out_tangent: Vec2::default(),
246 in_tangent: Vec2::default(),
247 })
248 .collect(),
249 },
250 Animated::Data(binding) => Self::Data(binding),
251 }
252 }
253}
254
255impl AnimatedPoint {
256 #[must_use]
258 pub const fn is_animated(&self) -> bool {
259 !matches!(self, Self::Constant { .. })
260 }
261
262 #[must_use]
264 pub const fn data(&self) -> Option<&DataBinding> {
265 match self {
266 Self::Data(binding) => Some(binding),
267 Self::Constant { .. } | Self::Keyframes { .. } => None,
268 }
269 }
270}
271
272#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
274#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
275#[serde(deny_unknown_fields)]
276pub struct PointKeyframe {
277 pub time: alpha2_time::MediaTime,
279 pub value: Vec2,
281 pub interpolation: Interpolation,
284 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
286 pub out_tangent: Vec2,
287 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
289 pub in_tangent: Vec2,
290}
291
292#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
294#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
295#[serde(deny_unknown_fields)]
296#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
297pub struct Keyframe<T> {
298 pub time: alpha2_time::MediaTime,
301 pub value: T,
303 pub interpolation: Interpolation,
305}
306
307#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
312#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
313#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
314pub enum Interpolation {
315 Hold,
317 Linear,
319 CubicBezier(CubicBezier),
321}
322
323#[derive(Deserialize)]
326#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
327#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
328#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
329pub(crate) enum InterpolationWire {
330 Hold {},
332 Linear {},
334 CubicBezier(CubicBezier),
336}
337
338impl From<InterpolationWire> for Interpolation {
339 fn from(wire: InterpolationWire) -> Self {
340 match wire {
341 InterpolationWire::Hold {} => Self::Hold,
342 InterpolationWire::Linear {} => Self::Linear,
343 InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
344 }
345 }
346}
347
348impl Interpolation {
349 #[must_use]
352 pub fn amount(self, progress: f64) -> Option<f64> {
353 match self {
354 Self::Hold => None,
355 Self::Linear => Some(Easing::Linear.apply(progress)),
356 Self::CubicBezier(curve) => Some(curve.apply(progress)),
357 }
358 }
359
360 #[must_use]
362 pub fn is_valid(self) -> bool {
363 match self {
364 Self::Hold | Self::Linear => true,
365 Self::CubicBezier(curve) => curve.is_valid(),
366 }
367 }
368}
369
370#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
372#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
373#[serde(deny_unknown_fields)]
374pub struct VisualProperties {
377 #[serde(default = "centre_point")]
380 pub position: AnimatedPoint,
381 #[serde(default = "centre")]
383 pub anchor: Vec2,
384 #[serde(default = "unit_scale")]
386 pub scale: Animated<Vec2>,
387 #[serde(default = "no_rotation")]
389 pub rotation_degrees: Animated<f32>,
390 #[serde(default = "opaque")]
392 pub opacity: Animated<f32>,
393 #[serde(default, skip_serializing_if = "Option::is_none")]
396 pub correction: Option<crate::CorrectionRef>,
397}
398
399impl Default for VisualProperties {
400 fn default() -> Self {
401 Self {
402 position: centre_point(),
403 anchor: centre(),
404 scale: unit_scale(),
405 rotation_degrees: no_rotation(),
406 opacity: opaque(),
407 correction: None,
408 }
409 }
410}
411
412const fn centre() -> Vec2 {
413 Vec2::new(0.5, 0.5)
414}
415
416const fn centre_point() -> AnimatedPoint {
417 AnimatedPoint::Constant { value: centre() }
418}
419
420pub(crate) const fn unit_scale() -> Animated<Vec2> {
421 Animated::Constant {
422 value: Vec2::new(1.0, 1.0),
423 }
424}
425
426const fn no_rotation() -> Animated<f32> {
427 Animated::Constant { value: 0.0 }
428}
429
430pub(crate) const fn opaque() -> Animated<f32> {
431 Animated::Constant { value: 1.0 }
432}
433
434pub(crate) enum Keyed<'a> {
436 Times(&'a [alpha2_time::MediaTime]),
438 Data(&'a DataBinding, PlaceType),
440}
441
442#[derive(Copy, Clone, Debug, Eq, PartialEq)]
444pub(crate) enum PlaceType {
445 Point,
447 Vec2,
449 Scalar,
451 Effect,
453 Other,
455}
456
457pub(crate) trait Placed {
459 const PLACE: PlaceType;
460}
461
462macro_rules! placed {
463 ($place:ident: $($type:ty),+) => {
464 $(impl Placed for $type {
465 const PLACE: PlaceType = PlaceType::$place;
466 })+
467 };
468}
469
470placed!(Scalar: f32);
471placed!(Vec2: Vec2);
472placed!(Effect: crate::EffectValue);
473placed!(
474 Other: String,
475 crate::TextContent,
476 crate::Paint,
477 crate::Rgba,
478 crate::Path,
479 crate::LayoutLength,
480 crate::LayoutSize,
481 crate::LayoutOffset,
482 crate::Insets
483);
484
485pub(crate) fn visit_keyed<T: Placed>(
487 at: &str,
488 animated: &Animated<T>,
489 visit: &mut impl FnMut(&str, Keyed<'_>),
490) {
491 match animated {
492 Animated::Keyframes { keyframes } => {
493 let times = keyframes
494 .iter()
495 .map(|keyframe| keyframe.time)
496 .collect::<Vec<_>>();
497 visit(at, Keyed::Times(×));
498 }
499 Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
500 Animated::Constant { .. } => {}
501 }
502}
503
504pub(crate) fn visit_keyed_point(
506 at: &str,
507 animated: &AnimatedPoint,
508 visit: &mut impl FnMut(&str, Keyed<'_>),
509) {
510 match animated {
511 AnimatedPoint::Keyframes { keyframes } => {
512 let times = keyframes
513 .iter()
514 .map(|keyframe| keyframe.time)
515 .collect::<Vec<_>>();
516 visit(at, Keyed::Times(×));
517 }
518 AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
519 AnimatedPoint::Constant { .. } => {}
520 }
521}
522
523impl VisualProperties {
524 pub(crate) fn validate(&self) -> bool {
525 self.anchor.is_finite()
526 && valid_point_animation(&self.position)
527 && valid_vec2_animation(&self.scale)
528 && valid_scalar_animation(&self.rotation_degrees, false)
529 && valid_scalar_animation(&self.opacity, true)
530 }
531}
532
533fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
534 match animation {
535 Animated::Constant { value } => value.is_finite(),
536 Animated::Keyframes { keyframes } => {
537 valid_keyframes(keyframes)
538 && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
539 }
540 Animated::Data(_) => true,
541 }
542}
543
544pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
546 match animation {
547 AnimatedPoint::Constant { value } => value.is_finite(),
548 AnimatedPoint::Data(_) => true,
549 AnimatedPoint::Keyframes { keyframes } => {
550 !keyframes.is_empty()
551 && keyframes.len() <= MAX_KEYFRAMES
552 && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
553 && keyframes.iter().all(|keyframe| {
554 keyframe.interpolation.is_valid()
555 && keyframe.value.is_finite()
556 && keyframe.out_tangent.is_finite()
557 && keyframe.in_tangent.is_finite()
558 })
559 }
560 }
561}
562
563fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
564 let domain = if unit_interval {
565 crate::Domain::UNIT
566 } else {
567 crate::Domain::ANY
568 };
569 let valid_value = |value: f32| domain.contains(value);
570 match animation {
571 Animated::Constant { value } => valid_value(*value),
572 Animated::Keyframes { keyframes } => {
573 valid_keyframes(keyframes)
574 && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
575 }
576 Animated::Data(_) => true,
577 }
578}
579
580pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
582 let valid = |value: f32| value.is_finite() && check(value);
583 match animation {
584 Animated::Constant { value } => valid(*value),
585 Animated::Keyframes { keyframes } => {
586 valid_keyframes(keyframes) && keyframes.iter().all(|keyframe| valid(keyframe.value))
587 }
588 Animated::Data(_) => true,
589 }
590}
591
592pub(crate) fn valid_keyframes<T>(keyframes: &[Keyframe<T>]) -> bool {
594 !keyframes.is_empty()
595 && keyframes.len() <= MAX_KEYFRAMES
596 && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
597 && keyframes
598 .iter()
599 .all(|keyframe| keyframe.interpolation.is_valid())
600}