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 "type": "array",
626 "minItems": 1,
627 "maxItems": 1,
628 "items": {
629 "type": "object",
630 "properties": {
631 "closed": {
632 "description": "Whether a segment joins the last vertex back to the first.",
633 "type": "boolean",
634 "default": false
635 },
636 "vertices": {
637 "description": "The vertices, in order.",
638 "type": "array",
639 "minItems": 2,
640 "maxItems": MAX_MOTION_PATH_VERTICES,
641 "items": vertex
642 }
643 },
644 "required": ["vertices"],
645 "additionalProperties": false
646 }
647 }
648 },
649 "required": ["subpaths"],
650 "additionalProperties": false
651 })
652}
653
654#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
656#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
657#[serde(rename_all = "snake_case")]
658pub enum Orient {
659 #[default]
661 None,
662 Path,
666}
667
668impl Orient {
669 #[expect(
670 clippy::trivially_copy_pass_by_ref,
671 reason = "serde passes a field by reference"
672 )]
673 fn is_none(&self) -> bool {
674 *self == Self::None
675 }
676}
677
678fn two_channels<'de, D: serde::Deserializer<'de>>(
679 deserializer: D,
680) -> Result<Vec<Animated<f32>>, D::Error> {
681 let channels = crate::bounded::seq::<_, Animated<f32>, 2>(deserializer)?;
682 if channels.len() != 2 {
683 return Err(serde::de::Error::custom(format_args!(
684 "a `split` position has 2 channels, not {}",
685 channels.len()
686 )));
687 }
688 Ok(channels)
689}
690
691impl Default for AnimatedPoint {
692 fn default() -> Self {
693 Self::Constant {
694 value: Vec2::default(),
695 }
696 }
697}
698
699impl From<Animated<Vec2>> for AnimatedPoint {
700 fn from(animation: Animated<Vec2>) -> Self {
701 match animation {
702 Animated::Constant { value } => Self::Constant { value },
703 Animated::Keyframes {
704 keyframes,
705 before,
706 after,
707 } => Self::Keyframes {
708 keyframes: keyframes
709 .into_iter()
710 .map(|keyframe| PointKeyframe {
711 time: keyframe.time,
712 value: keyframe.value,
713 interpolation: keyframe.interpolation,
714 out_tangent: Vec2::default(),
715 in_tangent: Vec2::default(),
716 })
717 .collect(),
718 before,
719 after,
720 },
721 Animated::Split { channels } => Self::Split { channels },
722 Animated::Data(binding) => Self::Data(binding),
723 }
724 }
725}
726
727impl Animated<f32> {
728 #[must_use]
731 pub fn is_valid(&self) -> bool {
732 valid_scalar_values(self, |_| true)
733 }
734}
735
736impl AnimatedPoint {
737 #[must_use]
740 pub fn is_valid(&self) -> bool {
741 valid_point_animation(self)
742 }
743
744 #[must_use]
746 pub const fn keyed(keyframes: Vec<PointKeyframe>) -> Self {
747 Self::Keyframes {
748 keyframes,
749 before: Extrapolation::Hold,
750 after: Extrapolation::Hold,
751 }
752 }
753
754 #[must_use]
756 pub const fn is_animated(&self) -> bool {
757 !matches!(self, Self::Constant { .. })
758 }
759
760 #[must_use]
763 pub const fn data(&self) -> Option<&DataBinding> {
764 match self {
765 Self::Data(binding) => Some(binding),
766 Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } | Self::Path(_) => {
767 None
768 }
769 }
770 }
771}
772
773#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
775#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
776#[serde(deny_unknown_fields)]
777pub struct PointKeyframe {
778 pub time: alpha2_time::MediaTime,
780 pub value: Vec2,
782 #[serde(deserialize_with = "timing_interpolation")]
785 #[cfg_attr(feature = "schema", schemars(with = "TimingInterpolation"))]
786 pub interpolation: Interpolation,
787 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
789 pub out_tangent: Vec2,
790 #[serde(default, skip_serializing_if = "Vec2::is_zero")]
792 pub in_tangent: Vec2,
793}
794
795#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
797#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
798#[serde(deny_unknown_fields)]
799#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
800#[cfg_attr(
801 feature = "schema",
802 schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
803)]
804pub struct Keyframe<T> {
805 pub time: alpha2_time::MediaTime,
808 pub value: T,
810 #[cfg_attr(
812 feature = "schema",
813 schemars(schema_with = "interpolation_schema::<T>")
814 )]
815 pub interpolation: Interpolation,
816}
817
818#[cfg(feature = "schema")]
819fn interpolation_schema<T: AnimatedValue>(
820 generator: &mut schemars::SchemaGenerator,
821) -> schemars::Schema {
822 if T::VALUE_CURVES {
823 generator.subschema_for::<Interpolation>()
824 } else {
825 generator.subschema_for::<TimingInterpolation>()
826 }
827}
828
829fn timing_interpolation<'de, D: serde::Deserializer<'de>>(
830 deserializer: D,
831) -> Result<Interpolation, D::Error> {
832 let interpolation = Interpolation::deserialize(deserializer)?;
833 if matches!(interpolation, Interpolation::ValueBezier(_)) {
834 return Err(serde::de::Error::custom(
835 "a position takes no `value_bezier`; split it or use a timing curve",
836 ));
837 }
838 Ok(interpolation)
839}
840
841#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
846#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
847#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
848pub enum Interpolation {
849 Hold,
851 Linear,
853 CubicBezier(CubicBezier),
855 ValueBezier(ValueBezier),
858 Steps(Steps),
861 Points {
864 points: Vec<EasingPoint>,
867 },
868}
869
870#[cfg(feature = "schema")]
871pub(crate) struct TimingInterpolation;
872
873#[cfg(feature = "schema")]
874impl schemars::JsonSchema for TimingInterpolation {
875 fn schema_name() -> std::borrow::Cow<'static, str> {
876 "TimingInterpolation".into()
877 }
878
879 fn schema_id() -> std::borrow::Cow<'static, str> {
880 "alpha2_model::TimingInterpolation".into()
881 }
882
883 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
884 let mut schema = InterpolationWire::json_schema(generator);
885 crate::schema::drop_variant(&mut schema, "type", "value_bezier");
886 schema.insert(
887 "description".to_owned(),
888 "Interpolation from one keyframe to the next for a value that is not a number: every \
889 kind but\nthe value curve."
890 .into(),
891 );
892 schema
893 }
894}
895
896#[derive(Deserialize)]
899#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
900#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
901#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
902pub(crate) enum InterpolationWire {
903 Hold {},
905 Linear {},
907 CubicBezier(CubicBezier),
909 ValueBezier(ValueBezier),
912 Steps(Steps),
915 Points {
918 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EASING_POINTS }>")]
921 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EASING_POINTS)))]
922 points: Vec<EasingPoint>,
923 },
924}
925
926impl From<InterpolationWire> for Interpolation {
927 fn from(wire: InterpolationWire) -> Self {
928 match wire {
929 InterpolationWire::Hold {} => Self::Hold,
930 InterpolationWire::Linear {} => Self::Linear,
931 InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
932 InterpolationWire::ValueBezier(curve) => Self::ValueBezier(curve),
933 InterpolationWire::Steps(steps) => Self::Steps(steps),
934 InterpolationWire::Points { points } => Self::Points { points },
935 }
936 }
937}
938
939impl From<Easing> for Interpolation {
940 fn from(easing: Easing) -> Self {
941 match easing {
942 Easing::Linear => Self::Linear,
943 Easing::CubicBezier(curve) => Self::CubicBezier(curve),
944 Easing::Steps(steps) => Self::Steps(steps),
945 Easing::Points { points } => Self::Points { points },
946 }
947 }
948}
949
950#[derive(Copy, Clone, Debug, PartialEq)]
952pub enum SegmentShape {
953 Hold,
955 Amount(f64),
957 Value(ValueBezier),
959}
960
961impl Interpolation {
962 #[must_use]
965 #[inline]
966 pub fn shape(&self, progress: f64) -> SegmentShape {
967 match self {
968 Self::Hold => SegmentShape::Hold,
969 Self::Linear => SegmentShape::Amount(progress.clamp(0.0, 1.0)),
970 Self::CubicBezier(curve) => SegmentShape::Amount(curve.apply(progress)),
971 Self::ValueBezier(curve) => SegmentShape::Value(*curve),
972 Self::Steps(steps) => SegmentShape::Amount(steps.apply(progress)),
973 Self::Points { points } => {
974 SegmentShape::Amount(crate::easing_points_at(points, progress))
975 }
976 }
977 }
978
979 #[must_use]
983 pub fn end_slope(&self, at_end: bool) -> Option<f64> {
984 match self {
985 Self::Hold | Self::Steps(_) => Some(0.0),
986 Self::Linear => Some(1.0),
987 Self::CubicBezier(curve) => Some(curve.end_slope(at_end)),
988 Self::ValueBezier(_) => None,
989 Self::Points { points } => Some(crate::easing_points_slope(
990 points,
991 if at_end { 1.0 } else { 0.0 },
992 )),
993 }
994 }
995
996 #[must_use]
998 pub fn is_valid(&self) -> bool {
999 match self {
1000 Self::Hold | Self::Linear => true,
1001 Self::CubicBezier(curve) => curve.is_valid(),
1002 Self::ValueBezier(curve) => curve.is_valid(),
1003 Self::Steps(steps) => steps.is_valid(),
1004 Self::Points { points } => crate::easing_points_valid(points),
1005 }
1006 }
1007}
1008
1009#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1011#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1012#[serde(deny_unknown_fields)]
1013pub struct VisualProperties {
1016 #[serde(default = "centre_point")]
1019 pub position: AnimatedPoint,
1020 #[serde(default = "centre")]
1022 pub anchor: Vec2,
1023 #[serde(default = "unit_scale")]
1025 pub scale: Animated<Vec2>,
1026 #[serde(default = "no_rotation")]
1028 pub rotation_degrees: Animated<f32>,
1029 #[serde(default = "opaque")]
1031 pub opacity: Animated<f32>,
1032 #[serde(default, skip_serializing_if = "Option::is_none")]
1035 pub correction: Option<crate::CorrectionRef>,
1036 #[serde(default, skip_serializing_if = "Orient::is_none")]
1038 pub orient: Orient,
1039}
1040
1041impl Default for VisualProperties {
1042 fn default() -> Self {
1043 Self {
1044 position: centre_point(),
1045 anchor: centre(),
1046 scale: unit_scale(),
1047 rotation_degrees: no_rotation(),
1048 opacity: opaque(),
1049 correction: None,
1050 orient: Orient::None,
1051 }
1052 }
1053}
1054
1055const fn centre() -> Vec2 {
1056 Vec2::new(0.5, 0.5)
1057}
1058
1059const fn centre_point() -> AnimatedPoint {
1060 AnimatedPoint::Constant { value: centre() }
1061}
1062
1063pub(crate) const fn unit_scale() -> Animated<Vec2> {
1064 Animated::Constant {
1065 value: Vec2::new(1.0, 1.0),
1066 }
1067}
1068
1069const fn no_rotation() -> Animated<f32> {
1070 Animated::Constant { value: 0.0 }
1071}
1072
1073pub(crate) const fn opaque() -> Animated<f32> {
1074 Animated::Constant { value: 1.0 }
1075}
1076
1077pub(crate) enum Keyed<'a> {
1079 Times(&'a [alpha2_time::MediaTime], Extrapolation, Extrapolation),
1081 Data(&'a DataBinding, PlaceType),
1083}
1084
1085#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1087pub(crate) enum PlaceType {
1088 Point,
1090 Vec2,
1092 Scalar,
1094 Effect,
1096 Other,
1098}
1099
1100pub(crate) trait Placed {
1102 const PLACE: PlaceType;
1103}
1104
1105macro_rules! placed {
1106 ($place:ident: $($type:ty),+) => {
1107 $(impl Placed for $type {
1108 const PLACE: PlaceType = PlaceType::$place;
1109 })+
1110 };
1111}
1112
1113placed!(Scalar: f32);
1114placed!(Vec2: Vec2);
1115placed!(Effect: crate::EffectValue);
1116placed!(
1117 Other: String,
1118 crate::TextContent,
1119 crate::Paint,
1120 crate::Rgba,
1121 crate::Path,
1122 crate::LayoutLength,
1123 crate::LayoutSize,
1124 crate::LayoutOffset,
1125 crate::Insets
1126);
1127
1128pub(crate) fn visit_keyed<T: Placed>(
1130 at: &str,
1131 animated: &Animated<T>,
1132 visit: &mut impl FnMut(&str, Keyed<'_>),
1133) {
1134 match animated {
1135 Animated::Keyframes {
1136 keyframes,
1137 before,
1138 after,
1139 } => {
1140 let times = keyframes
1141 .iter()
1142 .map(|keyframe| keyframe.time)
1143 .collect::<Vec<_>>();
1144 visit(at, Keyed::Times(×, *before, *after));
1145 }
1146 Animated::Split { channels } => visit_keyed_channels(at, channels, visit),
1147 Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
1148 Animated::Constant { .. } => {}
1149 }
1150}
1151
1152fn visit_keyed_channels(
1153 at: &str,
1154 channels: &[Animated<f32>],
1155 visit: &mut impl FnMut(&str, Keyed<'_>),
1156) {
1157 for (index, channel) in channels.iter().enumerate() {
1158 match channel {
1159 Animated::Keyframes {
1160 keyframes,
1161 before,
1162 after,
1163 } => {
1164 let times = keyframes
1165 .iter()
1166 .map(|keyframe| keyframe.time)
1167 .collect::<Vec<_>>();
1168 visit(
1169 &channel_path(at, index),
1170 Keyed::Times(×, *before, *after),
1171 );
1172 }
1173 Animated::Data(binding) => visit(
1174 &channel_path(at, index),
1175 Keyed::Data(binding, PlaceType::Scalar),
1176 ),
1177 Animated::Constant { .. } | Animated::Split { .. } => {}
1178 }
1179 }
1180}
1181
1182pub(crate) fn visit_keyed_point(
1184 at: &str,
1185 animated: &AnimatedPoint,
1186 visit: &mut impl FnMut(&str, Keyed<'_>),
1187) {
1188 match animated {
1189 AnimatedPoint::Keyframes {
1190 keyframes,
1191 before,
1192 after,
1193 } => {
1194 let times = keyframes
1195 .iter()
1196 .map(|keyframe| keyframe.time)
1197 .collect::<Vec<_>>();
1198 visit(at, Keyed::Times(×, *before, *after));
1199 }
1200 AnimatedPoint::Split { channels } => visit_keyed_channels(at, channels, visit),
1201 AnimatedPoint::Path(motion) => {
1202 visit_keyed(&format!("{at}.distance"), &motion.distance, visit);
1203 }
1204 AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
1205 AnimatedPoint::Constant { .. } => {}
1206 }
1207}
1208
1209impl VisualProperties {
1210 pub(crate) fn validate(&self) -> bool {
1211 self.anchor.is_finite()
1212 && valid_point_animation(&self.position)
1213 && valid_vec2_animation(&self.scale)
1214 && valid_scalar_animation(&self.rotation_degrees, false)
1215 && valid_scalar_animation(&self.opacity, true)
1216 }
1217}
1218
1219fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
1220 match animation {
1221 Animated::Constant { value } => value.is_finite(),
1222 Animated::Keyframes {
1223 keyframes,
1224 before,
1225 after,
1226 } => {
1227 valid_keyframes(keyframes, *before, *after)
1228 && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
1229 }
1230 Animated::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1231 Animated::Data(_) => true,
1232 }
1233}
1234
1235pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
1237 match animation {
1238 AnimatedPoint::Constant { value } => value.is_finite(),
1239 AnimatedPoint::Data(_) => true,
1240 AnimatedPoint::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1241 AnimatedPoint::Path(motion) => {
1242 let vertices = match motion.path.subpaths.as_slice() {
1243 [subpath] => subpath.vertices.as_slice(),
1244 _ => &[],
1245 };
1246 (2..=MAX_MOTION_PATH_VERTICES).contains(&vertices.len())
1247 && vertices.iter().all(|vertex| {
1248 vertex.point.is_finite()
1249 && vertex.in_tangent.is_finite()
1250 && vertex.out_tangent.is_finite()
1251 })
1252 && valid_scalar_values(&motion.distance, |_| true)
1253 }
1254 AnimatedPoint::Keyframes { keyframes, .. } => {
1255 !keyframes.is_empty()
1256 && keyframes.len() <= MAX_KEYFRAMES
1257 && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1258 && keyframes.iter().all(|keyframe| {
1259 keyframe.interpolation.is_valid()
1260 && !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1261 && keyframe.value.is_finite()
1262 && keyframe.out_tangent.is_finite()
1263 && keyframe.in_tangent.is_finite()
1264 })
1265 }
1266 }
1267}
1268
1269fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
1270 let domain = if unit_interval {
1271 crate::Domain::UNIT
1272 } else {
1273 crate::Domain::ANY
1274 };
1275 let valid_value = |value: f32| domain.contains(value);
1276 match animation {
1277 Animated::Constant { value } => valid_value(*value),
1278 Animated::Keyframes {
1279 keyframes,
1280 before,
1281 after,
1282 } => {
1283 valid_keyframes(keyframes, *before, *after)
1284 && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
1285 }
1286 Animated::Split { .. } => false,
1287 Animated::Data(_) => true,
1288 }
1289}
1290
1291pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
1293 let valid = |value: f32| value.is_finite() && check(value);
1294 match animation {
1295 Animated::Constant { value } => valid(*value),
1296 Animated::Keyframes {
1297 keyframes,
1298 before,
1299 after,
1300 } => {
1301 valid_keyframes(keyframes, *before, *after)
1302 && keyframes.iter().all(|keyframe| valid(keyframe.value))
1303 }
1304 Animated::Split { .. } => false,
1305 Animated::Data(_) => true,
1306 }
1307}
1308
1309pub(crate) fn valid_keyframes<T: AnimatedValue>(
1311 keyframes: &[Keyframe<T>],
1312 before: Extrapolation,
1313 after: Extrapolation,
1314) -> bool {
1315 !keyframes.is_empty()
1316 && keyframes.iter().all(|keyframe| {
1317 keyframe.value.extrapolates(before) && keyframe.value.extrapolates(after)
1318 })
1319 && keyframes.len() <= MAX_KEYFRAMES
1320 && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1321 && keyframes
1322 .iter()
1323 .all(|keyframe| keyframe.interpolation.is_valid())
1324 && keyframes
1325 .iter()
1326 .zip(keyframes.iter().skip(1).map(Some).chain([None]))
1327 .all(|(keyframe, next)| {
1328 !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1329 || (keyframe.value.takes_value_curve()
1330 && next.is_none_or(|next| next.value.takes_value_curve()))
1331 })
1332}