1use crate::{CubicBezier, DataBinding, Easing, EasingPoint, Steps, ValueBezier};
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(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[serde(rename_all = "snake_case")]
42pub enum Extrapolation {
43 #[default]
45 Hold,
46 Linear,
48 Repeat,
51 RepeatOffset,
54 PingPong,
56}
57
58impl Extrapolation {
59 #[must_use]
61 pub const fn is_hold(&self) -> bool {
62 matches!(self, Self::Hold)
63 }
64
65 const fn word(self) -> &'static str {
66 match self {
67 Self::Hold => "hold",
68 Self::Linear => "linear",
69 Self::Repeat => "repeat",
70 Self::RepeatOffset => "repeat_offset",
71 Self::PingPong => "ping_pong",
72 }
73 }
74}
75
76#[derive(Clone, Debug, PartialEq, Serialize)]
84#[serde(tag = "mode", rename_all = "snake_case")]
85pub enum Animated<T> {
86 Constant {
88 value: T,
90 },
91 Keyframes {
93 keyframes: Vec<Keyframe<T>>,
95 #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
97 before: Extrapolation,
98 #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
100 after: Extrapolation,
101 },
102 Split {
105 channels: Vec<Animated<f32>>,
107 },
108 Data(Box<DataBinding>),
110}
111
112const MAX_SPLIT_CHANNELS: usize = 4;
113
114mod sealed {
115 pub trait Sealed {}
116}
117
118pub trait AnimatedValue: sealed::Sealed {
120 const ACCEPTS_DATA: bool;
122 const VALUE_CURVES: bool = false;
124 const INTERPOLATES: bool;
126 const OFFSETS: bool;
128 const SPLIT: Option<(usize, usize)> = None;
131
132 fn takes_value_curve(&self) -> bool {
134 Self::VALUE_CURVES
135 }
136
137 fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
139 match extrapolation {
140 Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
141 Extrapolation::Linear => Self::INTERPOLATES,
142 Extrapolation::RepeatOffset => Self::OFFSETS,
143 }
144 }
145}
146
147macro_rules! animated_value {
148 (data: $data:literal, interpolates: $interpolates:literal, offsets: $offsets:literal;
149 $($type:ty),+) => {
150 $(
151 impl sealed::Sealed for $type {}
152 impl AnimatedValue for $type {
153 const ACCEPTS_DATA: bool = $data;
154 const INTERPOLATES: bool = $interpolates;
155 const OFFSETS: bool = $offsets;
156 }
157 )+
158 };
159}
160
161impl sealed::Sealed for f32 {}
162impl AnimatedValue for f32 {
163 const ACCEPTS_DATA: bool = true;
164 const VALUE_CURVES: bool = true;
165 const INTERPOLATES: bool = true;
166 const OFFSETS: bool = true;
167}
168
169impl sealed::Sealed for crate::EffectValue {}
170impl AnimatedValue for crate::EffectValue {
171 const ACCEPTS_DATA: bool = true;
172 const VALUE_CURVES: bool = true;
173 const INTERPOLATES: bool = true;
174 const OFFSETS: bool = true;
175 const SPLIT: Option<(usize, usize)> = Some((2, MAX_SPLIT_CHANNELS));
176
177 fn takes_value_curve(&self) -> bool {
178 matches!(self, Self::Float(_))
179 }
180
181 fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
182 match extrapolation {
183 Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
184 Extrapolation::Linear => self.interpolates(),
185 Extrapolation::RepeatOffset => {
186 matches!(self, Self::Float(_) | Self::Vec2(_) | Self::Vec4(_))
187 }
188 }
189 }
190}
191
192impl sealed::Sealed for Vec2 {}
193impl AnimatedValue for Vec2 {
194 const ACCEPTS_DATA: bool = true;
195 const INTERPOLATES: bool = true;
196 const OFFSETS: bool = true;
197 const SPLIT: Option<(usize, usize)> = Some((2, 2));
198}
199
200animated_value!(data: false, interpolates: false, offsets: false; String, crate::TextContent);
201animated_value!(
202 data: false, interpolates: true, offsets: false;
203 crate::Paint,
204 crate::Rgba,
205 crate::Path,
206 crate::LayoutLength,
207 crate::LayoutSize,
208 crate::LayoutOffset,
209 crate::Insets
210);
211
212#[derive(Deserialize)]
217#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
218#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
219#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
220#[cfg_attr(
221 feature = "schema",
222 schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
223)]
224enum AnimatedWire<T> {
225 Constant {
227 value: T,
229 },
230 Keyframes {
232 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
234 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
235 keyframes: Vec<Keyframe<T>>,
236 #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
238 #[cfg_attr(
239 feature = "schema",
240 schemars(schema_with = "extrapolation_schema::<T>")
241 )]
242 before: Extrapolation,
243 #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
245 #[cfg_attr(
246 feature = "schema",
247 schemars(schema_with = "extrapolation_schema::<T>")
248 )]
249 after: Extrapolation,
250 },
251 Split {
254 #[serde(deserialize_with = "crate::bounded::seq::<_, _, MAX_SPLIT_CHANNELS>")]
256 channels: Vec<Animated<f32>>,
257 },
258 Data(DataBinding),
260}
261
262#[cfg(feature = "schema")]
263fn extrapolation_schema<T: AnimatedValue>(
264 generator: &mut schemars::SchemaGenerator,
265) -> schemars::Schema {
266 match (T::INTERPOLATES, T::OFFSETS) {
267 (true, true) => generator.subschema_for::<Extrapolation>(),
268 (true, false) => generator.subschema_for::<ExtrapolationWithoutOffset>(),
269 (false, _) => generator.subschema_for::<HoldExtrapolation>(),
270 }
271}
272
273#[cfg(feature = "schema")]
274struct ExtrapolationWithoutOffset;
275
276#[cfg(feature = "schema")]
277impl schemars::JsonSchema for ExtrapolationWithoutOffset {
278 fn schema_name() -> std::borrow::Cow<'static, str> {
279 "ExtrapolationWithoutOffset".into()
280 }
281
282 fn schema_id() -> std::borrow::Cow<'static, str> {
283 "alpha2_model::ExtrapolationWithoutOffset".into()
284 }
285
286 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
287 let mut schema = Extrapolation::json_schema(generator);
288 crate::schema::drop_word(&mut schema, Extrapolation::RepeatOffset.word());
289 schema.insert(
290 "description".to_owned(),
291 "What a keyframed value that has no difference to add does before its first \
292 keyframe or after its\nlast: every choice but `repeat_offset`."
293 .into(),
294 );
295 schema
296 }
297}
298
299#[cfg(feature = "schema")]
300struct HoldExtrapolation;
301
302#[cfg(feature = "schema")]
303impl schemars::JsonSchema for HoldExtrapolation {
304 fn schema_name() -> std::borrow::Cow<'static, str> {
305 "HoldExtrapolation".into()
306 }
307
308 fn schema_id() -> std::borrow::Cow<'static, str> {
309 "alpha2_model::HoldExtrapolation".into()
310 }
311
312 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
313 let mut schema = Extrapolation::json_schema(generator);
314 for extrapolation in [Extrapolation::Linear, Extrapolation::RepeatOffset] {
315 crate::schema::drop_word(&mut schema, extrapolation.word());
316 }
317 schema.insert(
318 "description".to_owned(),
319 "What a keyframed value that only holds does before its first keyframe or after \
320 its last: `hold`,\n`repeat` or `ping_pong`."
321 .into(),
322 );
323 schema
324 }
325}
326
327impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
328 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
329 Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
330 AnimatedWire::Constant { value } => Self::Constant { value },
331 AnimatedWire::Keyframes {
332 keyframes,
333 before,
334 after,
335 } => {
336 if keyframes.iter().any(|keyframe| {
337 matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
338 && !keyframe.value.takes_value_curve()
339 }) {
340 return Err(serde::de::Error::custom(if T::SPLIT.is_some() {
341 "this value takes no `value_bezier`; split it or use a timing curve"
342 } else {
343 "this value takes no `value_bezier`; use a timing curve"
344 }));
345 }
346 if let Some(refused) = [before, after].into_iter().find(|extrapolation| {
347 !keyframes
348 .iter()
349 .all(|keyframe| keyframe.value.extrapolates(*extrapolation))
350 }) {
351 return Err(serde::de::Error::custom(format_args!(
352 "this value takes no `{}` extrapolation",
353 refused.word()
354 )));
355 }
356 Self::Keyframes {
357 keyframes,
358 before,
359 after,
360 }
361 }
362 AnimatedWire::Split { channels } => match T::SPLIT {
363 Some((least, most)) if (least..=most).contains(&channels.len()) => {
364 Self::Split { channels }
365 }
366 Some((least, most)) => {
367 return Err(serde::de::Error::custom(format_args!(
368 "a `split` of this value has {least} to {most} channels, not {}",
369 channels.len()
370 )));
371 }
372 None => {
373 return Err(serde::de::Error::custom("this value takes no `split` mode"));
374 }
375 },
376 AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
377 AnimatedWire::Data(_) => {
378 return Err(serde::de::Error::custom(
379 "this value takes no `data` mode; use `constant` or `keyframes`",
380 ));
381 }
382 })
383 }
384}
385
386#[cfg(feature = "schema")]
387impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
388 fn schema_name() -> std::borrow::Cow<'static, str> {
390 if T::ACCEPTS_DATA {
391 AnimatedWire::<T>::schema_name()
392 } else {
393 format!("Keyframed_{}", T::schema_name()).into()
394 }
395 }
396
397 fn schema_id() -> std::borrow::Cow<'static, str> {
398 if T::ACCEPTS_DATA {
399 AnimatedWire::<T>::schema_id()
400 } else {
401 format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
402 }
403 }
404
405 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
406 let mut schema = AnimatedWire::<T>::json_schema(generator);
407 match T::SPLIT {
408 Some((least, most)) => crate::schema::bound_split_channels(&mut schema, least, most),
409 None => crate::schema::drop_variant(&mut schema, "mode", "split"),
410 }
411 if !T::ACCEPTS_DATA {
412 crate::schema::drop_data_mode(&mut schema);
413 schema.insert(
414 "description".to_owned(),
415 "A value that is constant or controlled by sorted keyframes.".into(),
416 );
417 }
418 schema
419 }
420}
421
422impl<T> Animated<T> {
423 #[must_use]
425 pub const fn keyed(keyframes: Vec<Keyframe<T>>) -> Self {
426 Self::Keyframes {
427 keyframes,
428 before: Extrapolation::Hold,
429 after: Extrapolation::Hold,
430 }
431 }
432
433 #[must_use]
436 pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
437 match self {
438 Self::Constant { value } => Animated::Constant { value: map(value) },
439 Self::Keyframes {
440 keyframes,
441 before,
442 after,
443 } => Animated::Keyframes {
444 keyframes: keyframes
445 .iter()
446 .map(|keyframe| Keyframe {
447 time: keyframe.time,
448 value: map(&keyframe.value),
449 interpolation: keyframe.interpolation.clone(),
450 })
451 .collect(),
452 before: *before,
453 after: *after,
454 },
455 Self::Split { channels } => Animated::Split {
456 channels: channels.clone(),
457 },
458 Self::Data(binding) => Animated::Data(binding.clone()),
459 }
460 }
461
462 #[must_use]
465 pub const fn data(&self) -> Option<&DataBinding> {
466 match self {
467 Self::Data(binding) => Some(binding),
468 Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } => None,
469 }
470 }
471
472 #[must_use]
474 pub const fn varies(&self) -> bool {
475 !matches!(self, Self::Constant { .. })
476 }
477}
478
479pub(crate) fn bindings_of<'a, T: Placed>(
480 at: &str,
481 animated: &'a Animated<T>,
482 visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
483) {
484 match animated {
485 Animated::Data(binding) => visit(at, binding, T::PLACE),
486 Animated::Split { channels } => channel_bindings(channels, at, visit),
487 Animated::Constant { .. } | Animated::Keyframes { .. } => {}
488 }
489}
490
491pub(crate) fn point_bindings_of<'a>(
492 at: &str,
493 animated: &'a AnimatedPoint,
494 visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
495) {
496 match animated {
497 AnimatedPoint::Data(binding) => visit(at, binding, PlaceType::Point),
498 AnimatedPoint::Split { channels } => channel_bindings(channels, at, visit),
499 AnimatedPoint::Path(motion) => {
500 bindings_of(&format!("{at}.distance"), &motion.distance, visit);
501 }
502 AnimatedPoint::Constant { .. } | AnimatedPoint::Keyframes { .. } => {}
503 }
504}
505
506fn channel_bindings<'a>(
507 channels: &'a [Animated<f32>],
508 at: &str,
509 visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
510) {
511 for (index, channel) in channels.iter().enumerate() {
512 if let Animated::Data(binding) = channel {
513 visit(&channel_path(at, index), binding, PlaceType::Scalar);
514 }
515 }
516}
517
518pub(crate) fn channel_path(at: &str, index: usize) -> String {
519 format!("{at}.channels[{index}]")
520}
521
522pub(crate) fn valid_channels(
523 channels: &[Animated<f32>],
524 count: std::ops::RangeInclusive<usize>,
525 check: impl Fn(f32) -> bool,
526) -> bool {
527 count.contains(&channels.len())
528 && channels
529 .iter()
530 .all(|channel| valid_scalar_values(channel, &check))
531}
532
533#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
540#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
541#[serde(deny_unknown_fields)]
542#[serde(tag = "mode", rename_all = "snake_case")]
543pub enum AnimatedPoint {
544 Constant {
546 value: Vec2,
548 },
549 Keyframes {
551 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
553 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
554 keyframes: Vec<PointKeyframe>,
555 #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
558 before: Extrapolation,
559 #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
562 after: Extrapolation,
563 },
564 Split {
568 #[serde(deserialize_with = "two_channels")]
570 #[cfg_attr(feature = "schema", schemars(length(min = 2, max = 2)))]
571 channels: Vec<Animated<f32>>,
572 },
573 Path(Box<MotionPath>),
575 Data(Box<DataBinding>),
577}
578
579pub const MAX_MOTION_PATH_VERTICES: usize = 256;
581
582#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
584#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
585#[serde(deny_unknown_fields)]
586pub struct MotionPath {
587 #[serde(deserialize_with = "motion_path")]
590 #[cfg_attr(feature = "schema", schemars(schema_with = "motion_path_schema"))]
591 pub path: crate::Path,
592 pub distance: Animated<f32>,
596}
597
598fn motion_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<crate::Path, D::Error> {
599 let path = crate::Path::deserialize(deserializer)?;
600 let vertices = match path.subpaths.as_slice() {
601 [subpath] => subpath.vertices.len(),
602 subpaths => {
603 return Err(serde::de::Error::custom(format_args!(
604 "the path of a position has 1 subpath, not {}",
605 subpaths.len()
606 )));
607 }
608 };
609 if !(2..=MAX_MOTION_PATH_VERTICES).contains(&vertices) {
610 return Err(serde::de::Error::custom(format_args!(
611 "the path of a position has 2 to {MAX_MOTION_PATH_VERTICES} vertices, not {vertices}"
612 )));
613 }
614 Ok(path)
615}
616
617#[cfg(feature = "schema")]
618fn motion_path_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
619 let vertex = generator.subschema_for::<crate::PathVertex>();
620 schemars::json_schema!({
621 "description": "One subpath of 2 to `MAX_MOTION_PATH_VERTICES` vertices.",
622 "type": "object",
623 "properties": {
624 "subpaths": {
625 "description": "The one subpath.",
626 "type": "array",
627 "minItems": 1,
628 "maxItems": 1,
629 "items": {
630 "type": "object",
631 "properties": {
632 "closed": {
633 "description": "Whether a segment joins the last vertex back to the first.",
634 "type": "boolean",
635 "default": false
636 },
637 "vertices": {
638 "description": "The vertices, in order.",
639 "type": "array",
640 "minItems": 2,
641 "maxItems": MAX_MOTION_PATH_VERTICES,
642 "items": vertex
643 }
644 },
645 "required": ["vertices"],
646 "additionalProperties": false
647 }
648 }
649 },
650 "required": ["subpaths"],
651 "additionalProperties": false
652 })
653}
654
655#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
657#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
658#[serde(rename_all = "snake_case")]
659pub enum Orient {
660 #[default]
662 None,
663 Path,
667}
668
669impl Orient {
670 #[expect(
671 clippy::trivially_copy_pass_by_ref,
672 reason = "serde passes a field by reference"
673 )]
674 fn is_none(&self) -> bool {
675 *self == Self::None
676 }
677}
678
679fn two_channels<'de, D: serde::Deserializer<'de>>(
680 deserializer: D,
681) -> Result<Vec<Animated<f32>>, D::Error> {
682 let channels = crate::bounded::seq::<_, Animated<f32>, 2>(deserializer)?;
683 if channels.len() != 2 {
684 return Err(serde::de::Error::custom(format_args!(
685 "a `split` position has 2 channels, not {}",
686 channels.len()
687 )));
688 }
689 Ok(channels)
690}
691
692impl Default for AnimatedPoint {
693 fn default() -> Self {
694 Self::Constant {
695 value: Vec2::default(),
696 }
697 }
698}
699
700impl From<Animated<Vec2>> for AnimatedPoint {
701 fn from(animation: Animated<Vec2>) -> Self {
702 match animation {
703 Animated::Constant { value } => Self::Constant { value },
704 Animated::Keyframes {
705 keyframes,
706 before,
707 after,
708 } => Self::Keyframes {
709 keyframes: keyframes
710 .into_iter()
711 .map(|keyframe| PointKeyframe {
712 time: keyframe.time,
713 value: keyframe.value,
714 interpolation: keyframe.interpolation,
715 out_tangent: Vec2::default(),
716 in_tangent: Vec2::default(),
717 })
718 .collect(),
719 before,
720 after,
721 },
722 Animated::Split { channels } => Self::Split { channels },
723 Animated::Data(binding) => Self::Data(binding),
724 }
725 }
726}
727
728impl Animated<f32> {
729 #[must_use]
732 pub fn is_valid(&self) -> bool {
733 valid_scalar_values(self, |_| true)
734 }
735}
736
737impl AnimatedPoint {
738 #[must_use]
741 pub fn is_valid(&self) -> bool {
742 valid_point_animation(self)
743 }
744
745 #[must_use]
747 pub const fn keyed(keyframes: Vec<PointKeyframe>) -> Self {
748 Self::Keyframes {
749 keyframes,
750 before: Extrapolation::Hold,
751 after: Extrapolation::Hold,
752 }
753 }
754
755 #[must_use]
757 pub const fn is_animated(&self) -> bool {
758 !matches!(self, Self::Constant { .. })
759 }
760
761 #[must_use]
764 pub const fn data(&self) -> Option<&DataBinding> {
765 match self {
766 Self::Data(binding) => Some(binding),
767 Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } | Self::Path(_) => {
768 None
769 }
770 }
771 }
772}
773
774#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
776#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
777#[serde(deny_unknown_fields)]
778pub struct PointKeyframe {
779 pub time: alpha2_time::MediaTime,
781 pub value: Vec2,
783 #[serde(deserialize_with = "timing_interpolation")]
786 #[cfg_attr(feature = "schema", schemars(with = "TimingInterpolation"))]
787 pub interpolation: Interpolation,
788 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
790 pub out_tangent: Vec2,
791 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
793 pub in_tangent: Vec2,
794}
795
796#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
798#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
799#[serde(deny_unknown_fields)]
800#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
801#[cfg_attr(
802 feature = "schema",
803 schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
804)]
805pub struct Keyframe<T> {
806 pub time: alpha2_time::MediaTime,
809 pub value: T,
811 #[cfg_attr(
813 feature = "schema",
814 schemars(schema_with = "interpolation_schema::<T>")
815 )]
816 pub interpolation: Interpolation,
817}
818
819#[cfg(feature = "schema")]
820fn interpolation_schema<T: AnimatedValue>(
821 generator: &mut schemars::SchemaGenerator,
822) -> schemars::Schema {
823 if T::VALUE_CURVES {
824 generator.subschema_for::<Interpolation>()
825 } else {
826 generator.subschema_for::<TimingInterpolation>()
827 }
828}
829
830fn timing_interpolation<'de, D: serde::Deserializer<'de>>(
831 deserializer: D,
832) -> Result<Interpolation, D::Error> {
833 let interpolation = Interpolation::deserialize(deserializer)?;
834 if matches!(interpolation, Interpolation::ValueBezier(_)) {
835 return Err(serde::de::Error::custom(
836 "a position takes no `value_bezier`; split it or use a timing curve",
837 ));
838 }
839 Ok(interpolation)
840}
841
842#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
847#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
848#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
849pub enum Interpolation {
850 Hold,
852 Linear,
854 CubicBezier(CubicBezier),
856 ValueBezier(ValueBezier),
859 Steps(Steps),
862 Points {
865 points: Vec<EasingPoint>,
868 },
869}
870
871#[cfg(feature = "schema")]
872pub(crate) struct TimingInterpolation;
873
874#[cfg(feature = "schema")]
875impl schemars::JsonSchema for TimingInterpolation {
876 fn schema_name() -> std::borrow::Cow<'static, str> {
877 "TimingInterpolation".into()
878 }
879
880 fn schema_id() -> std::borrow::Cow<'static, str> {
881 "alpha2_model::TimingInterpolation".into()
882 }
883
884 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
885 let mut schema = InterpolationWire::json_schema(generator);
886 crate::schema::drop_variant(&mut schema, "type", "value_bezier");
887 schema.insert(
888 "description".to_owned(),
889 "Interpolation from one keyframe to the next for a value that is not a number: every \
890 kind but\nthe value curve."
891 .into(),
892 );
893 schema
894 }
895}
896
897#[derive(Deserialize)]
900#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
901#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
902#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
903pub(crate) enum InterpolationWire {
904 Hold {},
906 Linear {},
908 CubicBezier(CubicBezier),
910 ValueBezier(ValueBezier),
913 Steps(Steps),
916 Points {
919 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EASING_POINTS }>")]
922 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EASING_POINTS)))]
923 points: Vec<EasingPoint>,
924 },
925}
926
927impl From<InterpolationWire> for Interpolation {
928 fn from(wire: InterpolationWire) -> Self {
929 match wire {
930 InterpolationWire::Hold {} => Self::Hold,
931 InterpolationWire::Linear {} => Self::Linear,
932 InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
933 InterpolationWire::ValueBezier(curve) => Self::ValueBezier(curve),
934 InterpolationWire::Steps(steps) => Self::Steps(steps),
935 InterpolationWire::Points { points } => Self::Points { points },
936 }
937 }
938}
939
940impl From<Easing> for Interpolation {
941 fn from(easing: Easing) -> Self {
942 match easing {
943 Easing::Linear => Self::Linear,
944 Easing::CubicBezier(curve) => Self::CubicBezier(curve),
945 Easing::Steps(steps) => Self::Steps(steps),
946 Easing::Points { points } => Self::Points { points },
947 }
948 }
949}
950
951#[derive(Copy, Clone, Debug, PartialEq)]
953pub enum SegmentShape {
954 Hold,
956 Amount(f64),
958 Value(ValueBezier),
960}
961
962impl Interpolation {
963 #[must_use]
966 #[inline]
967 pub fn shape(&self, progress: f64) -> SegmentShape {
968 match self {
969 Self::Hold => SegmentShape::Hold,
970 Self::Linear => SegmentShape::Amount(progress.clamp(0.0, 1.0)),
971 Self::CubicBezier(curve) => SegmentShape::Amount(curve.apply(progress)),
972 Self::ValueBezier(curve) => SegmentShape::Value(*curve),
973 Self::Steps(steps) => SegmentShape::Amount(steps.apply(progress)),
974 Self::Points { points } => {
975 SegmentShape::Amount(crate::easing_points_at(points, progress))
976 }
977 }
978 }
979
980 #[must_use]
984 pub fn end_slope(&self, at_end: bool) -> Option<f64> {
985 match self {
986 Self::Hold | Self::Steps(_) => Some(0.0),
987 Self::Linear => Some(1.0),
988 Self::CubicBezier(curve) => Some(curve.end_slope(at_end)),
989 Self::ValueBezier(_) => None,
990 Self::Points { points } => Some(crate::easing_points_slope(
991 points,
992 if at_end { 1.0 } else { 0.0 },
993 )),
994 }
995 }
996
997 #[must_use]
999 pub fn is_valid(&self) -> bool {
1000 match self {
1001 Self::Hold | Self::Linear => true,
1002 Self::CubicBezier(curve) => curve.is_valid(),
1003 Self::ValueBezier(curve) => curve.is_valid(),
1004 Self::Steps(steps) => steps.is_valid(),
1005 Self::Points { points } => crate::easing_points_valid(points),
1006 }
1007 }
1008}
1009
1010#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1012#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1013#[serde(deny_unknown_fields)]
1014pub struct VisualProperties {
1017 #[serde(default = "centre_point")]
1020 pub position: AnimatedPoint,
1021 #[serde(default = "centre")]
1023 pub anchor: Vec2,
1024 #[serde(default = "unit_scale")]
1026 pub scale: Animated<Vec2>,
1027 #[serde(default = "no_rotation")]
1029 pub rotation_degrees: Animated<f32>,
1030 #[serde(default = "opaque")]
1032 pub opacity: Animated<f32>,
1033 #[serde(default, skip_serializing_if = "Option::is_none")]
1036 pub correction: Option<crate::CorrectionRef>,
1037 #[serde(default, skip_serializing_if = "Orient::is_none")]
1039 pub orient: Orient,
1040}
1041
1042impl Default for VisualProperties {
1043 fn default() -> Self {
1044 Self {
1045 position: centre_point(),
1046 anchor: centre(),
1047 scale: unit_scale(),
1048 rotation_degrees: no_rotation(),
1049 opacity: opaque(),
1050 correction: None,
1051 orient: Orient::None,
1052 }
1053 }
1054}
1055
1056const fn centre() -> Vec2 {
1057 Vec2::new(0.5, 0.5)
1058}
1059
1060const fn centre_point() -> AnimatedPoint {
1061 AnimatedPoint::Constant { value: centre() }
1062}
1063
1064pub(crate) const fn unit_scale() -> Animated<Vec2> {
1065 Animated::Constant {
1066 value: Vec2::new(1.0, 1.0),
1067 }
1068}
1069
1070const fn no_rotation() -> Animated<f32> {
1071 Animated::Constant { value: 0.0 }
1072}
1073
1074pub(crate) const fn opaque() -> Animated<f32> {
1075 Animated::Constant { value: 1.0 }
1076}
1077
1078pub(crate) enum Keyed<'a> {
1080 Times(&'a [alpha2_time::MediaTime], Extrapolation, Extrapolation),
1082 Data(&'a DataBinding, PlaceType),
1084}
1085
1086#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1088pub(crate) enum PlaceType {
1089 Point,
1091 Vec2,
1093 Scalar,
1095 Effect,
1097 Other,
1099}
1100
1101pub(crate) trait Placed {
1103 const PLACE: PlaceType;
1104}
1105
1106macro_rules! placed {
1107 ($place:ident: $($type:ty),+) => {
1108 $(impl Placed for $type {
1109 const PLACE: PlaceType = PlaceType::$place;
1110 })+
1111 };
1112}
1113
1114placed!(Scalar: f32);
1115placed!(Vec2: Vec2);
1116placed!(Effect: crate::EffectValue);
1117placed!(
1118 Other: String,
1119 crate::TextContent,
1120 crate::Paint,
1121 crate::Rgba,
1122 crate::Path,
1123 crate::LayoutLength,
1124 crate::LayoutSize,
1125 crate::LayoutOffset,
1126 crate::Insets
1127);
1128
1129pub(crate) fn visit_keyed<T: Placed>(
1131 at: &str,
1132 animated: &Animated<T>,
1133 visit: &mut impl FnMut(&str, Keyed<'_>),
1134) {
1135 match animated {
1136 Animated::Keyframes {
1137 keyframes,
1138 before,
1139 after,
1140 } => {
1141 let times = keyframes
1142 .iter()
1143 .map(|keyframe| keyframe.time)
1144 .collect::<Vec<_>>();
1145 visit(at, Keyed::Times(×, *before, *after));
1146 }
1147 Animated::Split { channels } => visit_keyed_channels(at, channels, visit),
1148 Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
1149 Animated::Constant { .. } => {}
1150 }
1151}
1152
1153fn visit_keyed_channels(
1154 at: &str,
1155 channels: &[Animated<f32>],
1156 visit: &mut impl FnMut(&str, Keyed<'_>),
1157) {
1158 for (index, channel) in channels.iter().enumerate() {
1159 match channel {
1160 Animated::Keyframes {
1161 keyframes,
1162 before,
1163 after,
1164 } => {
1165 let times = keyframes
1166 .iter()
1167 .map(|keyframe| keyframe.time)
1168 .collect::<Vec<_>>();
1169 visit(
1170 &channel_path(at, index),
1171 Keyed::Times(×, *before, *after),
1172 );
1173 }
1174 Animated::Data(binding) => visit(
1175 &channel_path(at, index),
1176 Keyed::Data(binding, PlaceType::Scalar),
1177 ),
1178 Animated::Constant { .. } | Animated::Split { .. } => {}
1179 }
1180 }
1181}
1182
1183pub(crate) fn visit_keyed_point(
1185 at: &str,
1186 animated: &AnimatedPoint,
1187 visit: &mut impl FnMut(&str, Keyed<'_>),
1188) {
1189 match animated {
1190 AnimatedPoint::Keyframes {
1191 keyframes,
1192 before,
1193 after,
1194 } => {
1195 let times = keyframes
1196 .iter()
1197 .map(|keyframe| keyframe.time)
1198 .collect::<Vec<_>>();
1199 visit(at, Keyed::Times(×, *before, *after));
1200 }
1201 AnimatedPoint::Split { channels } => visit_keyed_channels(at, channels, visit),
1202 AnimatedPoint::Path(motion) => {
1203 visit_keyed(&format!("{at}.distance"), &motion.distance, visit);
1204 }
1205 AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
1206 AnimatedPoint::Constant { .. } => {}
1207 }
1208}
1209
1210impl VisualProperties {
1211 pub(crate) fn validate(&self) -> bool {
1212 self.anchor.is_finite()
1213 && valid_point_animation(&self.position)
1214 && valid_vec2_animation(&self.scale)
1215 && valid_scalar_animation(&self.rotation_degrees, false)
1216 && valid_scalar_animation(&self.opacity, true)
1217 }
1218}
1219
1220fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
1221 match animation {
1222 Animated::Constant { value } => value.is_finite(),
1223 Animated::Keyframes {
1224 keyframes,
1225 before,
1226 after,
1227 } => {
1228 valid_keyframes(keyframes, *before, *after)
1229 && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
1230 }
1231 Animated::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1232 Animated::Data(_) => true,
1233 }
1234}
1235
1236pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
1238 match animation {
1239 AnimatedPoint::Constant { value } => value.is_finite(),
1240 AnimatedPoint::Data(_) => true,
1241 AnimatedPoint::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1242 AnimatedPoint::Path(motion) => {
1243 let vertices = match motion.path.subpaths.as_slice() {
1244 [subpath] => subpath.vertices.as_slice(),
1245 _ => &[],
1246 };
1247 (2..=MAX_MOTION_PATH_VERTICES).contains(&vertices.len())
1248 && vertices.iter().all(|vertex| {
1249 vertex.point.is_finite()
1250 && vertex.in_tangent.is_finite()
1251 && vertex.out_tangent.is_finite()
1252 })
1253 && valid_scalar_values(&motion.distance, |_| true)
1254 }
1255 AnimatedPoint::Keyframes { keyframes, .. } => {
1256 !keyframes.is_empty()
1257 && keyframes.len() <= MAX_KEYFRAMES
1258 && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1259 && keyframes.iter().all(|keyframe| {
1260 keyframe.interpolation.is_valid()
1261 && !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1262 && keyframe.value.is_finite()
1263 && keyframe.out_tangent.is_finite()
1264 && keyframe.in_tangent.is_finite()
1265 })
1266 }
1267 }
1268}
1269
1270fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
1271 let domain = if unit_interval {
1272 crate::Domain::UNIT
1273 } else {
1274 crate::Domain::ANY
1275 };
1276 let valid_value = |value: f32| domain.contains(value);
1277 match animation {
1278 Animated::Constant { value } => valid_value(*value),
1279 Animated::Keyframes {
1280 keyframes,
1281 before,
1282 after,
1283 } => {
1284 valid_keyframes(keyframes, *before, *after)
1285 && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
1286 }
1287 Animated::Split { .. } => false,
1288 Animated::Data(_) => true,
1289 }
1290}
1291
1292pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
1294 let valid = |value: f32| value.is_finite() && check(value);
1295 match animation {
1296 Animated::Constant { value } => valid(*value),
1297 Animated::Keyframes {
1298 keyframes,
1299 before,
1300 after,
1301 } => {
1302 valid_keyframes(keyframes, *before, *after)
1303 && keyframes.iter().all(|keyframe| valid(keyframe.value))
1304 }
1305 Animated::Split { .. } => false,
1306 Animated::Data(_) => true,
1307 }
1308}
1309
1310pub(crate) fn valid_keyframes<T: AnimatedValue>(
1312 keyframes: &[Keyframe<T>],
1313 before: Extrapolation,
1314 after: Extrapolation,
1315) -> bool {
1316 !keyframes.is_empty()
1317 && keyframes.iter().all(|keyframe| {
1318 keyframe.value.extrapolates(before) && keyframe.value.extrapolates(after)
1319 })
1320 && keyframes.len() <= MAX_KEYFRAMES
1321 && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1322 && keyframes
1323 .iter()
1324 .all(|keyframe| keyframe.interpolation.is_valid())
1325 && keyframes
1326 .iter()
1327 .zip(keyframes.iter().skip(1).map(Some).chain([None]))
1328 .all(|(keyframe, next)| {
1329 !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1330 || (keyframe.value.takes_value_curve()
1331 && next.is_none_or(|next| next.value.takes_value_curve()))
1332 })
1333}