alpha2-model 0.10.0

Versioned project and timeline model for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
use crate::{CubicBezier, DataBinding, Easing, EasingPoint, Steps, ValueBezier};
use serde::{Deserialize, Serialize};

/// A two-dimensional value in normalized output coordinates.
#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Vec2 {
    /// Horizontal component.
    pub x: f32,
    /// Vertical component.
    pub y: f32,
}

impl Vec2 {
    /// Creates a two-dimensional value.
    #[must_use]
    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }

    fn is_finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite()
    }

    /// Whether both components are zero (either sign).
    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.x == 0.0 && self.y == 0.0
    }
}

/// Most keyframes of one animated value.
pub const MAX_KEYFRAMES: usize = 100_000;

/// What a keyframed value does before its first keyframe or after its last.
///
/// With one keyframe every choice holds its value.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Extrapolation {
    /// Keeps the nearest keyframe's value.
    #[default]
    Hold,
    /// Continues at the slope the curve has at that end. Not for values that only hold.
    Linear,
    /// Repeats the keyed range. After the last keyframe the range is an exact period: the last
    /// keyframe's own time already shows the first keyframe's value.
    Repeat,
    /// Repeats the keyed range, each pass starting where the last ended. Numbers and vectors
    /// only.
    RepeatOffset,
    /// Repeats the keyed range forward and backward in turn.
    PingPong,
}

impl Extrapolation {
    /// Whether this is `hold`, the default.
    #[must_use]
    pub const fn is_hold(&self) -> bool {
        matches!(self, Self::Hold)
    }

    const fn word(self) -> &'static str {
        match self {
            Self::Hold => "hold",
            Self::Linear => "linear",
            Self::Repeat => "repeat",
            Self::RepeatOffset => "repeat_offset",
            Self::PingPong => "ping_pong",
        }
    }
}

/// A value that is constant, controlled by sorted keyframes, split into one animated number
/// per component, or following a data set.
///
/// Only value types whose [`AnimatedValue::ACCEPTS_DATA`] is true (`f32`, [`Vec2`] and
/// [`crate::EffectValue`]) read or offer the `data` mode, and only those with an
/// [`AnimatedValue::SPLIT`] ([`Vec2`] and [`crate::EffectValue`]) the `split` mode; for the
/// others the mode fails to deserialize and the schema leaves it out.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Animated<T> {
    /// A value without animation.
    Constant {
        /// Value used at every timestamp.
        value: T,
    },
    /// Values evaluated from their keyframe sequence.
    Keyframes {
        /// Strictly ascending keyframes.
        keyframes: Vec<Keyframe<T>>,
        /// What the value does before the first keyframe.
        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
        before: Extrapolation,
        /// What the value does after the last keyframe.
        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
        after: Extrapolation,
    },
    /// One animated number per component, each with its own keyframes, curves and
    /// extrapolation, or its own data binding.
    Split {
        /// The components in order: `x` then `y`, or an effect vector's components.
        channels: Vec<Animated<f32>>,
    },
    /// A channel of a data set, followed at render time.
    Data(Box<DataBinding>),
}

const MAX_SPLIT_CHANNELS: usize = 4;

mod sealed {
    pub trait Sealed {}
}

/// A type an [`Animated`] value can hold. Sealed: implemented for the model's animatable types.
pub trait AnimatedValue: sealed::Sealed {
    /// Whether the type takes the `data` value mode.
    const ACCEPTS_DATA: bool;
    /// Whether a keyframe of the type can start a value curve ([`ValueBezier`]).
    const VALUE_CURVES: bool = false;
    /// Whether keyframes of the type can interpolate; those of the others only hold.
    const INTERPOLATES: bool;
    /// Whether two values of the type have a difference to add: what `repeat_offset` needs.
    const OFFSETS: bool;
    /// The fewest and the most channels the type's `split` mode takes, or `None` for a type
    /// without the mode.
    const SPLIT: Option<(usize, usize)> = None;

    /// Whether a keyframe holding this value may start or end a value curve.
    fn takes_value_curve(&self) -> bool {
        Self::VALUE_CURVES
    }

    /// Whether keyframes holding this value may extrapolate by `extrapolation`.
    fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
        match extrapolation {
            Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
            Extrapolation::Linear => Self::INTERPOLATES,
            Extrapolation::RepeatOffset => Self::OFFSETS,
        }
    }
}

macro_rules! animated_value {
    (data: $data:literal, interpolates: $interpolates:literal, offsets: $offsets:literal;
     $($type:ty),+) => {
        $(
            impl sealed::Sealed for $type {}
            impl AnimatedValue for $type {
                const ACCEPTS_DATA: bool = $data;
                const INTERPOLATES: bool = $interpolates;
                const OFFSETS: bool = $offsets;
            }
        )+
    };
}

impl sealed::Sealed for f32 {}
impl AnimatedValue for f32 {
    const ACCEPTS_DATA: bool = true;
    const VALUE_CURVES: bool = true;
    const INTERPOLATES: bool = true;
    const OFFSETS: bool = true;
}

impl sealed::Sealed for crate::EffectValue {}
impl AnimatedValue for crate::EffectValue {
    const ACCEPTS_DATA: bool = true;
    const VALUE_CURVES: bool = true;
    const INTERPOLATES: bool = true;
    const OFFSETS: bool = true;
    const SPLIT: Option<(usize, usize)> = Some((2, MAX_SPLIT_CHANNELS));

    fn takes_value_curve(&self) -> bool {
        matches!(self, Self::Float(_))
    }

    fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
        match extrapolation {
            Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
            Extrapolation::Linear => self.interpolates(),
            Extrapolation::RepeatOffset => {
                matches!(self, Self::Float(_) | Self::Vec2(_) | Self::Vec4(_))
            }
        }
    }
}

impl sealed::Sealed for Vec2 {}
impl AnimatedValue for Vec2 {
    const ACCEPTS_DATA: bool = true;
    const INTERPOLATES: bool = true;
    const OFFSETS: bool = true;
    const SPLIT: Option<(usize, usize)> = Some((2, 2));
}

animated_value!(data: false, interpolates: false, offsets: false; String, crate::TextContent);
animated_value!(
    data: false, interpolates: true, offsets: false;
    crate::Paint,
    crate::Rgba,
    crate::Path,
    crate::LayoutLength,
    crate::LayoutSize,
    crate::LayoutOffset,
    crate::Insets
);

// The wire form of `Animated`, before the value type decides whether it takes data. Its doc
// comment is the schema's description.
/// A value that is constant, controlled by sorted keyframes, split into one animated number per
/// component, or following a data set.
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
)]
enum AnimatedWire<T> {
    /// A value without animation.
    Constant {
        /// Value used at every timestamp.
        value: T,
    },
    /// Values evaluated from their keyframe sequence.
    Keyframes {
        /// Strictly ascending keyframes.
        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
        keyframes: Vec<Keyframe<T>>,
        /// What the value does before the first keyframe.
        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
        #[cfg_attr(
            feature = "schema",
            schemars(schema_with = "extrapolation_schema::<T>")
        )]
        before: Extrapolation,
        /// What the value does after the last keyframe.
        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
        #[cfg_attr(
            feature = "schema",
            schemars(schema_with = "extrapolation_schema::<T>")
        )]
        after: Extrapolation,
    },
    /// One animated number per component, each with its own keyframes, curves and
    /// extrapolation, or its own data binding.
    Split {
        /// The components in order: `x` then `y`, or an effect vector's components.
        #[serde(deserialize_with = "crate::bounded::seq::<_, _, MAX_SPLIT_CHANNELS>")]
        channels: Vec<Animated<f32>>,
    },
    /// A channel of a data set, followed at render time.
    Data(DataBinding),
}

#[cfg(feature = "schema")]
fn extrapolation_schema<T: AnimatedValue>(
    generator: &mut schemars::SchemaGenerator,
) -> schemars::Schema {
    match (T::INTERPOLATES, T::OFFSETS) {
        (true, true) => generator.subschema_for::<Extrapolation>(),
        (true, false) => generator.subschema_for::<ExtrapolationWithoutOffset>(),
        (false, _) => generator.subschema_for::<HoldExtrapolation>(),
    }
}

#[cfg(feature = "schema")]
struct ExtrapolationWithoutOffset;

#[cfg(feature = "schema")]
impl schemars::JsonSchema for ExtrapolationWithoutOffset {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "ExtrapolationWithoutOffset".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        "alpha2_model::ExtrapolationWithoutOffset".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let mut schema = Extrapolation::json_schema(generator);
        crate::schema::drop_word(&mut schema, Extrapolation::RepeatOffset.word());
        schema.insert(
            "description".to_owned(),
            "What a keyframed value that has no difference to add does before its first \
             keyframe or after its\nlast: every choice but `repeat_offset`."
                .into(),
        );
        schema
    }
}

#[cfg(feature = "schema")]
struct HoldExtrapolation;

#[cfg(feature = "schema")]
impl schemars::JsonSchema for HoldExtrapolation {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "HoldExtrapolation".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        "alpha2_model::HoldExtrapolation".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let mut schema = Extrapolation::json_schema(generator);
        for extrapolation in [Extrapolation::Linear, Extrapolation::RepeatOffset] {
            crate::schema::drop_word(&mut schema, extrapolation.word());
        }
        schema.insert(
            "description".to_owned(),
            "What a keyframed value that only holds does before its first keyframe or after \
             its last: `hold`,\n`repeat` or `ping_pong`."
                .into(),
        );
        schema
    }
}

impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
            AnimatedWire::Constant { value } => Self::Constant { value },
            AnimatedWire::Keyframes {
                keyframes,
                before,
                after,
            } => {
                if keyframes.iter().any(|keyframe| {
                    matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
                        && !keyframe.value.takes_value_curve()
                }) {
                    return Err(serde::de::Error::custom(if T::SPLIT.is_some() {
                        "this value takes no `value_bezier`; split it or use a timing curve"
                    } else {
                        "this value takes no `value_bezier`; use a timing curve"
                    }));
                }
                if let Some(refused) = [before, after].into_iter().find(|extrapolation| {
                    !keyframes
                        .iter()
                        .all(|keyframe| keyframe.value.extrapolates(*extrapolation))
                }) {
                    return Err(serde::de::Error::custom(format_args!(
                        "this value takes no `{}` extrapolation",
                        refused.word()
                    )));
                }
                Self::Keyframes {
                    keyframes,
                    before,
                    after,
                }
            }
            AnimatedWire::Split { channels } => match T::SPLIT {
                Some((least, most)) if (least..=most).contains(&channels.len()) => {
                    Self::Split { channels }
                }
                Some((least, most)) => {
                    return Err(serde::de::Error::custom(format_args!(
                        "a `split` of this value has {least} to {most} channels, not {}",
                        channels.len()
                    )));
                }
                None => {
                    return Err(serde::de::Error::custom("this value takes no `split` mode"));
                }
            },
            AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
            AnimatedWire::Data(_) => {
                return Err(serde::de::Error::custom(
                    "this value takes no `data` mode; use `constant` or `keyframes`",
                ));
            }
        })
    }
}

#[cfg(feature = "schema")]
impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
    // Types without the data mode are a separate generic, `Keyframed_{T}`, for one shape each.
    fn schema_name() -> std::borrow::Cow<'static, str> {
        if T::ACCEPTS_DATA {
            AnimatedWire::<T>::schema_name()
        } else {
            format!("Keyframed_{}", T::schema_name()).into()
        }
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        if T::ACCEPTS_DATA {
            AnimatedWire::<T>::schema_id()
        } else {
            format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
        }
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let mut schema = AnimatedWire::<T>::json_schema(generator);
        match T::SPLIT {
            Some((least, most)) => crate::schema::bound_split_channels(&mut schema, least, most),
            None => crate::schema::drop_variant(&mut schema, "mode", "split"),
        }
        if !T::ACCEPTS_DATA {
            crate::schema::drop_data_mode(&mut schema);
            schema.insert(
                "description".to_owned(),
                "A value that is constant or controlled by sorted keyframes.".into(),
            );
        }
        schema
    }
}

impl<T> Animated<T> {
    /// A value controlled by `keyframes`, holding before the first and after the last.
    #[must_use]
    pub const fn keyed(keyframes: Vec<Keyframe<T>>) -> Self {
        Self::Keyframes {
            keyframes,
            before: Extrapolation::Hold,
            after: Extrapolation::Hold,
        }
    }

    /// The same animation with each value mapped by `map`, keeping times, interpolations and
    /// extrapolation.
    #[must_use]
    pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
        match self {
            Self::Constant { value } => Animated::Constant { value: map(value) },
            Self::Keyframes {
                keyframes,
                before,
                after,
            } => Animated::Keyframes {
                keyframes: keyframes
                    .iter()
                    .map(|keyframe| Keyframe {
                        time: keyframe.time,
                        value: map(&keyframe.value),
                        interpolation: keyframe.interpolation.clone(),
                    })
                    .collect(),
                before: *before,
                after: *after,
            },
            Self::Split { channels } => Animated::Split {
                channels: channels.clone(),
            },
            Self::Data(binding) => Animated::Data(binding.clone()),
        }
    }

    /// The data binding, when the whole value follows a data set. A `split` value's channels
    /// hold their own.
    #[must_use]
    pub const fn data(&self) -> Option<&DataBinding> {
        match self {
            Self::Data(binding) => Some(binding),
            Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } => None,
        }
    }

    /// Whether the value can change over time: keyframes, split channels or data.
    #[must_use]
    pub const fn varies(&self) -> bool {
        !matches!(self, Self::Constant { .. })
    }
}

pub(crate) fn bindings_of<'a, T: Placed>(
    at: &str,
    animated: &'a Animated<T>,
    visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
) {
    match animated {
        Animated::Data(binding) => visit(at, binding, T::PLACE),
        Animated::Split { channels } => channel_bindings(channels, at, visit),
        Animated::Constant { .. } | Animated::Keyframes { .. } => {}
    }
}

pub(crate) fn point_bindings_of<'a>(
    at: &str,
    animated: &'a AnimatedPoint,
    visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
) {
    match animated {
        AnimatedPoint::Data(binding) => visit(at, binding, PlaceType::Point),
        AnimatedPoint::Split { channels } => channel_bindings(channels, at, visit),
        AnimatedPoint::Path(motion) => {
            bindings_of(&format!("{at}.distance"), &motion.distance, visit);
        }
        AnimatedPoint::Constant { .. } | AnimatedPoint::Keyframes { .. } => {}
    }
}

fn channel_bindings<'a>(
    channels: &'a [Animated<f32>],
    at: &str,
    visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
) {
    for (index, channel) in channels.iter().enumerate() {
        if let Animated::Data(binding) = channel {
            visit(&channel_path(at, index), binding, PlaceType::Scalar);
        }
    }
}

pub(crate) fn channel_path(at: &str, index: usize) -> String {
    format!("{at}.channels[{index}]")
}

pub(crate) fn valid_channels(
    channels: &[Animated<f32>],
    count: std::ops::RangeInclusive<usize>,
    check: impl Fn(f32) -> bool,
) -> bool {
    count.contains(&channels.len())
        && channels
            .iter()
            .all(|channel| valid_scalar_values(channel, &check))
}

/// A position that can move along curves between its keyframes.
///
/// Its JSON is an `Animated<Vec2>` plus optional spatial tangents per keyframe. With them,
/// the value travels the cubic Bezier through this keyframe's `out_tangent` and the next's
/// `in_tangent`, at the speed its timing curve sets along the arc length. Without them it
/// moves in a straight line.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum AnimatedPoint {
    /// A value without animation.
    Constant {
        /// Value used at every timestamp.
        value: Vec2,
    },
    /// Values evaluated from their keyframe sequence.
    Keyframes {
        /// Strictly ascending keyframes.
        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
        keyframes: Vec<PointKeyframe>,
        /// What the value does before the first keyframe. `linear` continues along the path's
        /// start tangent.
        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
        before: Extrapolation,
        /// What the value does after the last keyframe. `linear` continues along the path's end
        /// tangent.
        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
        after: Extrapolation,
    },
    /// One animated number per axis, each with its own keyframes, curves and extrapolation, or
    /// its own data binding. The value has no spatial path of its own: it is wherever the two
    /// numbers put it.
    Split {
        /// The `x` value, then the `y` value.
        #[serde(deserialize_with = "two_channels")]
        #[cfg_attr(feature = "schema", schemars(length(min = 2, max = 2)))]
        channels: Vec<Animated<f32>>,
    },
    /// A point a fraction of the way along a path.
    Path(Box<MotionPath>),
    /// A channel of a data set, followed at render time.
    Data(Box<DataBinding>),
}

/// The most vertices the path of a `path` position has.
pub const MAX_MOTION_PATH_VERTICES: usize = 256;

/// A path and how far along it a position is.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct MotionPath {
    /// The path, in the position's own space: one subpath of 2 to
    /// [`MAX_MOTION_PATH_VERTICES`] vertices.
    #[serde(deserialize_with = "motion_path")]
    #[cfg_attr(feature = "schema", schemars(schema_with = "motion_path_schema"))]
    pub path: crate::Path,
    /// The fraction of the path's length travelled, measured as it shows on screen. Clamped to
    /// `0..=1` on an open path; on a closed one it wraps, so 1.25 is a quarter of the way
    /// round again.
    pub distance: Animated<f32>,
}

fn motion_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<crate::Path, D::Error> {
    let path = crate::Path::deserialize(deserializer)?;
    let vertices = match path.subpaths.as_slice() {
        [subpath] => subpath.vertices.len(),
        subpaths => {
            return Err(serde::de::Error::custom(format_args!(
                "the path of a position has 1 subpath, not {}",
                subpaths.len()
            )));
        }
    };
    if !(2..=MAX_MOTION_PATH_VERTICES).contains(&vertices) {
        return Err(serde::de::Error::custom(format_args!(
            "the path of a position has 2 to {MAX_MOTION_PATH_VERTICES} vertices, not {vertices}"
        )));
    }
    Ok(path)
}

#[cfg(feature = "schema")]
fn motion_path_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
    let vertex = generator.subschema_for::<crate::PathVertex>();
    schemars::json_schema!({
        "description": "One subpath of 2 to `MAX_MOTION_PATH_VERTICES` vertices.",
        "type": "object",
        "properties": {
            "subpaths": {
                "description": "The one subpath.",
                "type": "array",
                "minItems": 1,
                "maxItems": 1,
                "items": {
                    "type": "object",
                    "properties": {
                        "closed": {
                            "description": "Whether a segment joins the last vertex back to the first.",
                            "type": "boolean",
                            "default": false
                        },
                        "vertices": {
                            "description": "The vertices, in order.",
                            "type": "array",
                            "minItems": 2,
                            "maxItems": MAX_MOTION_PATH_VERTICES,
                            "items": vertex
                        }
                    },
                    "required": ["vertices"],
                    "additionalProperties": false
                }
            }
        },
        "required": ["subpaths"],
        "additionalProperties": false
    })
}

/// How a transform turns with its position.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Orient {
    /// It does not.
    #[default]
    None,
    /// The direction of the position's path where the position is, is added to the rotation:
    /// that of its spatial curve between keyframes, or of the path of a `path` position. A
    /// position with no path adds nothing.
    Path,
}

impl Orient {
    #[expect(
        clippy::trivially_copy_pass_by_ref,
        reason = "serde passes a field by reference"
    )]
    fn is_none(&self) -> bool {
        *self == Self::None
    }
}

fn two_channels<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Vec<Animated<f32>>, D::Error> {
    let channels = crate::bounded::seq::<_, Animated<f32>, 2>(deserializer)?;
    if channels.len() != 2 {
        return Err(serde::de::Error::custom(format_args!(
            "a `split` position has 2 channels, not {}",
            channels.len()
        )));
    }
    Ok(channels)
}

impl Default for AnimatedPoint {
    fn default() -> Self {
        Self::Constant {
            value: Vec2::default(),
        }
    }
}

impl From<Animated<Vec2>> for AnimatedPoint {
    fn from(animation: Animated<Vec2>) -> Self {
        match animation {
            Animated::Constant { value } => Self::Constant { value },
            Animated::Keyframes {
                keyframes,
                before,
                after,
            } => Self::Keyframes {
                keyframes: keyframes
                    .into_iter()
                    .map(|keyframe| PointKeyframe {
                        time: keyframe.time,
                        value: keyframe.value,
                        interpolation: keyframe.interpolation,
                        out_tangent: Vec2::default(),
                        in_tangent: Vec2::default(),
                    })
                    .collect(),
                before,
                after,
            },
            Animated::Split { channels } => Self::Split { channels },
            Animated::Data(binding) => Self::Data(binding),
        }
    }
}

impl Animated<f32> {
    /// Whether a project can hold this number: finite values, and keyframes that ascend, stay
    /// within [`MAX_KEYFRAMES`] and have valid interpolations. A `split` number is not valid.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        valid_scalar_values(self, |_| true)
    }
}

impl AnimatedPoint {
    /// Whether a project can hold this position: finite values and tangents, and keyframes that
    /// ascend, stay within [`MAX_KEYFRAMES`] and have valid interpolations.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        valid_point_animation(self)
    }

    /// A position controlled by `keyframes`, holding before the first and after the last.
    #[must_use]
    pub const fn keyed(keyframes: Vec<PointKeyframe>) -> Self {
        Self::Keyframes {
            keyframes,
            before: Extrapolation::Hold,
            after: Extrapolation::Hold,
        }
    }

    /// Whether the value changes over time: keyframes, split channels or data.
    #[must_use]
    pub const fn is_animated(&self) -> bool {
        !matches!(self, Self::Constant { .. })
    }

    /// The data binding, when the whole value follows a data set. A `split` value's channels
    /// hold their own.
    #[must_use]
    pub const fn data(&self) -> Option<&DataBinding> {
        match self {
            Self::Data(binding) => Some(binding),
            Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } | Self::Path(_) => {
                None
            }
        }
    }
}

/// One keyframe of an [`AnimatedPoint`].
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PointKeyframe {
    /// Timestamp of this value, as a [`Keyframe`]'s.
    pub time: alpha2_time::MediaTime,
    /// Value at `time`.
    pub value: Vec2,
    /// Interpolation from this keyframe to its successor: how fast the value travels along the
    /// way.
    #[serde(deserialize_with = "timing_interpolation")]
    #[cfg_attr(feature = "schema", schemars(with = "TimingInterpolation"))]
    pub interpolation: Interpolation,
    /// The curve's first control point toward the next keyframe, relative to this value.
    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
    pub out_tangent: Vec2,
    /// The curve's second control point from the previous keyframe, relative to this value.
    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
    pub in_tangent: Vec2,
}

/// One timestamped control value.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
)]
pub struct Keyframe<T> {
    /// Timestamp of this value. Timeline time, except composition time in a composition node's
    /// settings and picture time in a shapes or layout generator's tree.
    pub time: alpha2_time::MediaTime,
    /// Value at `time`.
    pub value: T,
    /// Interpolation from this keyframe to its successor.
    #[cfg_attr(
        feature = "schema",
        schemars(schema_with = "interpolation_schema::<T>")
    )]
    pub interpolation: Interpolation,
}

#[cfg(feature = "schema")]
fn interpolation_schema<T: AnimatedValue>(
    generator: &mut schemars::SchemaGenerator,
) -> schemars::Schema {
    if T::VALUE_CURVES {
        generator.subschema_for::<Interpolation>()
    } else {
        generator.subschema_for::<TimingInterpolation>()
    }
}

fn timing_interpolation<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Interpolation, D::Error> {
    let interpolation = Interpolation::deserialize(deserializer)?;
    if matches!(interpolation, Interpolation::ValueBezier(_)) {
        return Err(serde::de::Error::custom(
            "a position takes no `value_bezier`; split it or use a timing curve",
        ));
    }
    Ok(interpolation)
}

/// Interpolation from one keyframe to the next.
///
/// Values interpolate numerically: a rotation from 0 to 720 degrees turns twice. A host that
/// wants the shortest path normalizes its keyframe values.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
pub enum Interpolation {
    /// Keep this keyframe's value until the next keyframe.
    Hold,
    /// Move to the next value at a constant rate.
    Linear,
    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
    CubicBezier(CubicBezier),
    /// Move to the next value along a value curve, which can move between equal values. Numbers
    /// only: an animated number, or an effect parameter between `float` keyframes.
    ValueBezier(ValueBezier),
    /// Move to the next value in equal steps, as CSS `steps()`. A step starts on the first tick
    /// at or after its exact time.
    Steps(Steps),
    /// Move to the next value along straight lines through a table of points, as CSS
    /// `linear()`: from `(0, 0)` through each point to `(1, 1)`.
    Points {
        /// The points between the two ends, rising strictly in `x`; at most
        /// [`crate::MAX_EASING_POINTS`].
        points: Vec<EasingPoint>,
    },
}

#[cfg(feature = "schema")]
pub(crate) struct TimingInterpolation;

#[cfg(feature = "schema")]
impl schemars::JsonSchema for TimingInterpolation {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "TimingInterpolation".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        "alpha2_model::TimingInterpolation".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let mut schema = InterpolationWire::json_schema(generator);
        crate::schema::drop_variant(&mut schema, "type", "value_bezier");
        schema.insert(
            "description".to_owned(),
            "Interpolation from one keyframe to the next for a value that is not a number: every \
             kind but\nthe value curve."
                .into(),
        );
        schema
    }
}

/// The wire form of [`Interpolation`]; see `EasingWire` for why unit variants are empty
/// structs.
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum InterpolationWire {
    /// Keep this keyframe's value until the next keyframe.
    Hold {},
    /// Move to the next value at a constant rate.
    Linear {},
    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
    CubicBezier(CubicBezier),
    /// Move to the next value along a value curve, which can move between equal values. Numbers
    /// only: an animated number, or an effect parameter between `float` keyframes.
    ValueBezier(ValueBezier),
    /// Move to the next value in equal steps, as CSS `steps()`. A step starts on the first tick
    /// at or after its exact time.
    Steps(Steps),
    /// Move to the next value along straight lines through a table of points, as CSS
    /// `linear()`: from `(0, 0)` through each point to `(1, 1)`.
    Points {
        /// The points between the two ends, rising strictly in `x`; at most
        /// `MAX_EASING_POINTS`.
        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EASING_POINTS }>")]
        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EASING_POINTS)))]
        points: Vec<EasingPoint>,
    },
}

impl From<InterpolationWire> for Interpolation {
    fn from(wire: InterpolationWire) -> Self {
        match wire {
            InterpolationWire::Hold {} => Self::Hold,
            InterpolationWire::Linear {} => Self::Linear,
            InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
            InterpolationWire::ValueBezier(curve) => Self::ValueBezier(curve),
            InterpolationWire::Steps(steps) => Self::Steps(steps),
            InterpolationWire::Points { points } => Self::Points { points },
        }
    }
}

impl From<Easing> for Interpolation {
    fn from(easing: Easing) -> Self {
        match easing {
            Easing::Linear => Self::Linear,
            Easing::CubicBezier(curve) => Self::CubicBezier(curve),
            Easing::Steps(steps) => Self::Steps(steps),
            Easing::Points { points } => Self::Points { points },
        }
    }
}

/// What a keyframe segment does at one progress.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum SegmentShape {
    /// Keeps the left keyframe's value.
    Hold,
    /// This fraction of the way to the next value; may leave `0..=1`.
    Amount(f64),
    /// Follows a value curve between the two keyframes' values.
    Value(ValueBezier),
}

impl Interpolation {
    /// What the segment does at linear `progress` (clamped to `0..=1` for an amount). The
    /// keyframe sampler places `steps` by whole ticks instead ([`Steps::index`]).
    #[must_use]
    #[inline]
    pub fn shape(&self, progress: f64) -> SegmentShape {
        match self {
            Self::Hold => SegmentShape::Hold,
            Self::Linear => SegmentShape::Amount(progress.clamp(0.0, 1.0)),
            Self::CubicBezier(curve) => SegmentShape::Amount(curve.apply(progress)),
            Self::ValueBezier(curve) => SegmentShape::Value(*curve),
            Self::Steps(steps) => SegmentShape::Amount(steps.apply(progress)),
            Self::Points { points } => {
                SegmentShape::Amount(crate::easing_points_at(points, progress))
            }
        }
    }

    /// The slope of the amount where the segment starts (`at_end` false) or ends, which
    /// `linear` extrapolation continues: 0 for `hold`. `None` for a value curve, which has no
    /// amount; its slope is [`ValueBezier::end_slope`].
    #[must_use]
    pub fn end_slope(&self, at_end: bool) -> Option<f64> {
        match self {
            Self::Hold | Self::Steps(_) => Some(0.0),
            Self::Linear => Some(1.0),
            Self::CubicBezier(curve) => Some(curve.end_slope(at_end)),
            Self::ValueBezier(_) => None,
            Self::Points { points } => Some(crate::easing_points_slope(
                points,
                if at_end { 1.0 } else { 0.0 },
            )),
        }
    }

    /// Whether the interpolation's parameters are usable.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        match self {
            Self::Hold | Self::Linear => true,
            Self::CubicBezier(curve) => curve.is_valid(),
            Self::ValueBezier(curve) => curve.is_valid(),
            Self::Steps(steps) => steps.is_valid(),
            Self::Points { points } => crate::easing_points_valid(points),
        }
    }
}

/// Resolution-independent visual presentation controls for a clip.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
///
/// Omitted fields default to the source centred on the canvas, unscaled, unrotated and opaque.
pub struct VisualProperties {
    /// Animated normalized canvas translation, along spatial curves where keyframes have
    /// tangents.
    #[serde(default = "centre_point")]
    pub position: AnimatedPoint,
    /// Unanimated normalized point within the source rectangle.
    #[serde(default = "centre")]
    pub anchor: Vec2,
    /// Animated per-axis scale.
    #[serde(default = "unit_scale")]
    pub scale: Animated<Vec2>,
    /// Animated clockwise rotation in degrees.
    #[serde(default = "no_rotation")]
    pub rotation_degrees: Animated<f32>,
    /// Animated opacity constrained to `0..=1`.
    #[serde(default = "opaque")]
    pub opacity: Animated<f32>,
    /// A `similarity` data set moving the clip's own picture, applied before this transform.
    /// Clip visuals only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub correction: Option<crate::CorrectionRef>,
    /// Whether the rotation follows the direction of the position's path.
    #[serde(default, skip_serializing_if = "Orient::is_none")]
    pub orient: Orient,
}

impl Default for VisualProperties {
    fn default() -> Self {
        Self {
            position: centre_point(),
            anchor: centre(),
            scale: unit_scale(),
            rotation_degrees: no_rotation(),
            opacity: opaque(),
            correction: None,
            orient: Orient::None,
        }
    }
}

const fn centre() -> Vec2 {
    Vec2::new(0.5, 0.5)
}

const fn centre_point() -> AnimatedPoint {
    AnimatedPoint::Constant { value: centre() }
}

pub(crate) const fn unit_scale() -> Animated<Vec2> {
    Animated::Constant {
        value: Vec2::new(1.0, 1.0),
    }
}

const fn no_rotation() -> Animated<f32> {
    Animated::Constant { value: 0.0 }
}

pub(crate) const fn opaque() -> Animated<f32> {
    Animated::Constant { value: 1.0 }
}

/// What a walk over animated values meets at one value that is not constant.
pub(crate) enum Keyed<'a> {
    /// The times of its keyframes.
    Times(&'a [alpha2_time::MediaTime], Extrapolation, Extrapolation),
    /// Its data binding, with the type of the value bound.
    Data(&'a DataBinding, PlaceType),
}

/// The value type a data binding sits on, which decides the kinds it can follow.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum PlaceType {
    /// A point along spatial curves.
    Point,
    /// A two-component value.
    Vec2,
    /// A number.
    Scalar,
    /// An effect parameter, whose type its definition gives.
    Effect,
    /// A type that takes no data.
    Other,
}

/// The [`PlaceType`] of each animatable type.
pub(crate) trait Placed {
    const PLACE: PlaceType;
}

macro_rules! placed {
    ($place:ident: $($type:ty),+) => {
        $(impl Placed for $type {
            const PLACE: PlaceType = PlaceType::$place;
        })+
    };
}

placed!(Scalar: f32);
placed!(Vec2: Vec2);
placed!(Effect: crate::EffectValue);
placed!(
    Other: String,
    crate::TextContent,
    crate::Paint,
    crate::Rgba,
    crate::Path,
    crate::LayoutLength,
    crate::LayoutSize,
    crate::LayoutOffset,
    crate::Insets
);

/// Calls `visit` with `at` and the times of `animated`'s keyframes, or its data binding.
pub(crate) fn visit_keyed<T: Placed>(
    at: &str,
    animated: &Animated<T>,
    visit: &mut impl FnMut(&str, Keyed<'_>),
) {
    match animated {
        Animated::Keyframes {
            keyframes,
            before,
            after,
        } => {
            let times = keyframes
                .iter()
                .map(|keyframe| keyframe.time)
                .collect::<Vec<_>>();
            visit(at, Keyed::Times(&times, *before, *after));
        }
        Animated::Split { channels } => visit_keyed_channels(at, channels, visit),
        Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
        Animated::Constant { .. } => {}
    }
}

fn visit_keyed_channels(
    at: &str,
    channels: &[Animated<f32>],
    visit: &mut impl FnMut(&str, Keyed<'_>),
) {
    for (index, channel) in channels.iter().enumerate() {
        match channel {
            Animated::Keyframes {
                keyframes,
                before,
                after,
            } => {
                let times = keyframes
                    .iter()
                    .map(|keyframe| keyframe.time)
                    .collect::<Vec<_>>();
                visit(
                    &channel_path(at, index),
                    Keyed::Times(&times, *before, *after),
                );
            }
            Animated::Data(binding) => visit(
                &channel_path(at, index),
                Keyed::Data(binding, PlaceType::Scalar),
            ),
            Animated::Constant { .. } | Animated::Split { .. } => {}
        }
    }
}

/// [`visit_keyed`] for a point along a spatial curve.
pub(crate) fn visit_keyed_point(
    at: &str,
    animated: &AnimatedPoint,
    visit: &mut impl FnMut(&str, Keyed<'_>),
) {
    match animated {
        AnimatedPoint::Keyframes {
            keyframes,
            before,
            after,
        } => {
            let times = keyframes
                .iter()
                .map(|keyframe| keyframe.time)
                .collect::<Vec<_>>();
            visit(at, Keyed::Times(&times, *before, *after));
        }
        AnimatedPoint::Split { channels } => visit_keyed_channels(at, channels, visit),
        AnimatedPoint::Path(motion) => {
            visit_keyed(&format!("{at}.distance"), &motion.distance, visit);
        }
        AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
        AnimatedPoint::Constant { .. } => {}
    }
}

impl VisualProperties {
    pub(crate) fn validate(&self) -> bool {
        self.anchor.is_finite()
            && valid_point_animation(&self.position)
            && valid_vec2_animation(&self.scale)
            && valid_scalar_animation(&self.rotation_degrees, false)
            && valid_scalar_animation(&self.opacity, true)
    }
}

fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
    match animation {
        Animated::Constant { value } => value.is_finite(),
        Animated::Keyframes {
            keyframes,
            before,
            after,
        } => {
            valid_keyframes(keyframes, *before, *after)
                && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
        }
        Animated::Split { channels } => valid_channels(channels, 2..=2, |_| true),
        Animated::Data(_) => true,
    }
}

/// Valid keyframes (or a constant) whose values and tangents are finite.
pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
    match animation {
        AnimatedPoint::Constant { value } => value.is_finite(),
        AnimatedPoint::Data(_) => true,
        AnimatedPoint::Split { channels } => valid_channels(channels, 2..=2, |_| true),
        AnimatedPoint::Path(motion) => {
            let vertices = match motion.path.subpaths.as_slice() {
                [subpath] => subpath.vertices.as_slice(),
                _ => &[],
            };
            (2..=MAX_MOTION_PATH_VERTICES).contains(&vertices.len())
                && vertices.iter().all(|vertex| {
                    vertex.point.is_finite()
                        && vertex.in_tangent.is_finite()
                        && vertex.out_tangent.is_finite()
                })
                && valid_scalar_values(&motion.distance, |_| true)
        }
        AnimatedPoint::Keyframes { keyframes, .. } => {
            !keyframes.is_empty()
                && keyframes.len() <= MAX_KEYFRAMES
                && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
                && keyframes.iter().all(|keyframe| {
                    keyframe.interpolation.is_valid()
                        && !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
                        && keyframe.value.is_finite()
                        && keyframe.out_tangent.is_finite()
                        && keyframe.in_tangent.is_finite()
                })
        }
    }
}

fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
    let domain = if unit_interval {
        crate::Domain::UNIT
    } else {
        crate::Domain::ANY
    };
    let valid_value = |value: f32| domain.contains(value);
    match animation {
        Animated::Constant { value } => valid_value(*value),
        Animated::Keyframes {
            keyframes,
            before,
            after,
        } => {
            valid_keyframes(keyframes, *before, *after)
                && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
        }
        Animated::Split { .. } => false,
        Animated::Data(_) => true,
    }
}

/// Valid keyframes (or a constant) whose every finite value passes `check`.
pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
    let valid = |value: f32| value.is_finite() && check(value);
    match animation {
        Animated::Constant { value } => valid(*value),
        Animated::Keyframes {
            keyframes,
            before,
            after,
        } => {
            valid_keyframes(keyframes, *before, *after)
                && keyframes.iter().all(|keyframe| valid(keyframe.value))
        }
        Animated::Split { .. } => false,
        Animated::Data(_) => true,
    }
}

/// A non-empty, strictly ascending run of at most [`MAX_KEYFRAMES`] with usable interpolations.
pub(crate) fn valid_keyframes<T: AnimatedValue>(
    keyframes: &[Keyframe<T>],
    before: Extrapolation,
    after: Extrapolation,
) -> bool {
    !keyframes.is_empty()
        && keyframes.iter().all(|keyframe| {
            keyframe.value.extrapolates(before) && keyframe.value.extrapolates(after)
        })
        && keyframes.len() <= MAX_KEYFRAMES
        && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
        && keyframes
            .iter()
            .all(|keyframe| keyframe.interpolation.is_valid())
        && keyframes
            .iter()
            .zip(keyframes.iter().skip(1).map(Some).chain([None]))
            .all(|(keyframe, next)| {
                !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
                    || (keyframe.value.takes_value_curve()
                        && next.is_none_or(|next| next.value.takes_value_curve()))
            })
}