alpha2-eval 0.10.0

Pure alpha2 timeline evaluation.
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
//! What an editor needs of a keyed number besides its value: control points to draw, speed,
//! range, and edits that keep the curve it already shows.

use crate::{SampleContext, sample_scalar};
use alpha2_model::{
    Animated, AnimatedPoint, CubicBezier, Extrapolation, Interpolation, Keyframe, MAX_KEYFRAMES,
    PointKeyframe, ValueBezier, Vec2,
};
use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};

mod materialize;
mod motion;
mod tangents;
mod wide;
mod within;

pub use materialize::materialize;
pub use motion::path_to_keys;
pub(crate) use tangents::tangents_of;
pub use tangents::{
    AutoTangent, auto_tangents, contain, from_handle_points, from_slopes, from_speed_influence,
};
pub(crate) use wide::{WideKey, as_value_curve, part_keys, split_at, stepped};
pub(crate) use within::keys_within;

/// Why a curve service did not do what was asked.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum CurveError {
    /// The value has no keyframes.
    Empty,
    /// The value is constant, split or bound to data.
    NotKeyed,
    /// The time lies outside the keyframes.
    OutsideKeys,
    /// A keyframe already lies at the time.
    OnAKey,
    /// A part of the segment has no timing curve: its amount is the same at both ends, or the
    /// segment is a value curve or a staircase.
    LevelSegment,
    /// The result would hold more than [`MAX_KEYFRAMES`] keyframes.
    TooManyKeys,
    /// The timing curve overshoots at the time, so the value is off the path between the two
    /// keyframes.
    OffThePath,
}

impl std::fmt::Display for CurveError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Empty => "the value has no keyframes",
            Self::NotKeyed => "the value is not keyframed",
            Self::OutsideKeys => "the time lies outside the keyframes",
            Self::OnAKey => "a keyframe already lies at the time",
            Self::LevelSegment => "a part of the segment has no timing curve",
            Self::TooManyKeys => "the result would hold too many keyframes",
            Self::OffThePath => "the value is off the path between the keyframes at the time",
        })
    }
}

impl std::error::Error for CurveError {}

/// What draws a segment.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum SegmentKind {
    /// The left keyframe's value, then a step.
    Hold,
    /// A straight line.
    Linear,
    /// A `cubic_bezier` timing curve.
    Timing,
    /// A `value_bezier` value curve.
    Value,
    /// A `steps` staircase.
    Steps,
    /// A `points` table of straight lines.
    Points,
}

/// One segment in (ticks, value): its two ends and, for a Bezier kind, its two control points.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ControlSegment {
    /// The left keyframe.
    pub start: (i64, f64),
    /// The right keyframe.
    pub end: (i64, f64),
    /// The two inner control points of a Bezier kind, the same for a timing curve and for the
    /// value curve that draws the same line.
    pub controls: Option<[(f64, f64); 2]>,
    /// What draws the segment.
    pub kind: SegmentKind,
}

/// A keyed number at one time.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CurveSample {
    /// The value the evaluator gives, before any property's range is applied.
    pub value: f32,
    /// The value's change per second, from the left where the curve has a corner. Finite: a
    /// vertical tangent gives the largest finite `f64` with its sign.
    pub velocity: f64,
}

#[expect(clippy::cast_precision_loss, reason = "a span of ticks as a length")]
fn span(left: MediaTime, right: MediaTime) -> f64 {
    (i128::from(right.ticks()) - i128::from(left.ticks())) as f64
}

#[expect(clippy::cast_precision_loss, reason = "a tick as a coordinate")]
const fn coordinate(time: MediaTime) -> f64 {
    time.ticks() as f64
}

#[expect(
    clippy::cast_possible_truncation,
    reason = "clamped to the range of f32"
)]
pub(crate) fn narrow(value: f64) -> f32 {
    if value.is_nan() {
        0.0
    } else {
        value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
    }
}

struct Cubic {
    x1: f64,
    x2: f64,
    from: f64,
    leave: f64,
    arrive: f64,
    to: f64,
}

impl Cubic {
    fn of(left: &Keyframe<f32>, right: &Keyframe<f32>) -> Option<Self> {
        let (from, to) = (f64::from(left.value), f64::from(right.value));
        match left.interpolation {
            Interpolation::Hold
            | Interpolation::Linear
            | Interpolation::Steps(_)
            | Interpolation::Points { .. } => None,
            Interpolation::CubicBezier(curve) => Some(Self {
                x1: f64::from(curve.x1),
                x2: f64::from(curve.x2),
                from,
                leave: f64::from(curve.y1) * (to - from),
                arrive: (f64::from(curve.y2) - 1.0) * (to - from),
                to,
            }),
            Interpolation::ValueBezier(curve) => {
                let (x1, x2) = curve.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
                    (f64::from(x1), f64::from(x2))
                });
                Some(Self {
                    x1,
                    x2,
                    from,
                    leave: f64::from(curve.leave),
                    arrive: f64::from(curve.arrive),
                    to,
                })
            }
        }
    }

    fn progress_at(&self, u: f64) -> f64 {
        let c = 3.0 * self.x1;
        let b = 3.0 * (self.x2 - self.x1) - c;
        let a = 1.0 - c - b;
        ((a * u + b) * u + c) * u
    }

    fn polynomial(&self) -> [f64; 3] {
        let change = self.to - self.from;
        let c = 3.0 * self.leave;
        let b = 3.0 * (change + self.arrive - self.leave) - c;
        [change - c - b, b, c]
    }

    fn value_at(&self, u: f64) -> f64 {
        let [a, b, c] = self.polynomial();
        self.from + ((a * u + b) * u + c) * u
    }

    fn turns(&self) -> impl Iterator<Item = f64> {
        let [a, b, c] = self.polynomial();
        let (qa, qb, qc) = (3.0 * a, 2.0 * b, c);
        let mut roots = [None, None];
        if qa.abs() <= f64::EPSILON {
            if qb.abs() > f64::EPSILON {
                roots[0] = Some(-qc / qb);
            }
        } else {
            let discriminant = qb * qb - 4.0 * qa * qc;
            if discriminant >= 0.0 {
                let root = discriminant.sqrt();
                roots = [
                    Some((-qb + root) / (2.0 * qa)),
                    Some((-qb - root) / (2.0 * qa)),
                ];
            }
        }
        roots.into_iter().flatten().filter(|u| *u > 0.0 && *u < 1.0)
    }
}

/// The segments of a keyed number, for drawing its curve and handles. Empty for a value that
/// is not keyed.
#[must_use]
pub fn segments(animation: &Animated<f32>) -> Vec<ControlSegment> {
    let Animated::Keyframes { keyframes, .. } = animation else {
        return Vec::new();
    };
    keyframes
        .windows(2)
        .map(|pair| {
            let (left, right) = (&pair[0], &pair[1]);
            let length = span(left.time, right.time);
            let controls = Cubic::of(left, right).map(|cubic| {
                [
                    (
                        coordinate(left.time) + cubic.x1 * length,
                        cubic.from + cubic.leave,
                    ),
                    (
                        coordinate(left.time) + cubic.x2 * length,
                        cubic.to + cubic.arrive,
                    ),
                ]
            });
            ControlSegment {
                start: (left.time.ticks(), f64::from(left.value)),
                end: (right.time.ticks(), f64::from(right.value)),
                controls,
                kind: match left.interpolation {
                    Interpolation::Hold => SegmentKind::Hold,
                    Interpolation::Linear => SegmentKind::Linear,
                    Interpolation::CubicBezier(_) => SegmentKind::Timing,
                    Interpolation::ValueBezier(_) => SegmentKind::Value,
                    Interpolation::Steps(_) => SegmentKind::Steps,
                    Interpolation::Points { .. } => SegmentKind::Points,
                },
            }
        })
        .collect()
}

/// The value and velocity of a number at each of `times`, with its extrapolation. On a
/// keyframe, at a wrap and at a turn of `ping_pong` the velocity is the one the curve arrives
/// with. A value that is not keyed has no velocity.
#[must_use]
pub fn sample(animation: &Animated<f32>, times: &[MediaTime]) -> Vec<CurveSample> {
    times
        .iter()
        .map(|time| CurveSample {
            value: sample_scalar(animation, *time, &SampleContext::NONE),
            velocity: match animation {
                Animated::Keyframes {
                    keyframes,
                    before,
                    after,
                } => velocity(keyframes, *before, *after, *time),
                _ => 0.0,
            },
        })
        .collect()
}

fn per_second(slope: f64, left: &Keyframe<f32>, right: &Keyframe<f32>) -> f64 {
    let seconds = span(left.time, right.time) / span(MediaTime(0), MediaTime(TICKS_PER_SECOND));
    let velocity = slope / seconds;
    if velocity.is_nan() {
        0.0
    } else {
        velocity.clamp(-f64::MAX, f64::MAX)
    }
}

fn slope_at(left: &Keyframe<f32>, right: &Keyframe<f32>, progress: f64) -> f64 {
    let change = f64::from(right.value) - f64::from(left.value);
    let slope = match left.interpolation {
        Interpolation::Hold | Interpolation::Steps(_) => 0.0,
        Interpolation::Points { ref points } => {
            alpha2_model::easing_points_slope(points, progress) * change
        }
        Interpolation::Linear => change,
        Interpolation::CubicBezier(curve) => {
            let slope = curve.slope(progress) * change;
            if slope.is_nan() { 0.0 } else { slope }
        }
        Interpolation::ValueBezier(curve) => curve.slope(left.value, right.value, progress),
    };
    per_second(slope, left, right)
}

fn continued_slope(left: &Keyframe<f32>, right: &Keyframe<f32>, at_end: bool) -> f64 {
    let change = f64::from(right.value) - f64::from(left.value);
    let slope = match left.interpolation {
        Interpolation::ValueBezier(curve) => curve.end_slope(left.value, right.value, at_end),
        ref timing => timing.end_slope(at_end).unwrap_or(0.0) * change,
    };
    per_second(slope, left, right)
}

fn slope_before(keyframes: &[Keyframe<f32>], at: i128) -> f64 {
    let right = keyframes.partition_point(|keyframe| i128::from(keyframe.time.ticks()) < at);
    slope_in(&keyframes[right - 1], &keyframes[right], at)
}

fn slope_after(keyframes: &[Keyframe<f32>], at: i128) -> f64 {
    let right = keyframes.partition_point(|keyframe| i128::from(keyframe.time.ticks()) <= at);
    slope_in(&keyframes[right - 1], &keyframes[right], at)
}

#[expect(
    clippy::cast_precision_loss,
    reason = "ticks as a fraction of a segment"
)]
fn slope_in(left: &Keyframe<f32>, right: &Keyframe<f32>, at: i128) -> f64 {
    let start = i128::from(left.time.ticks());
    let progress = (at - start) as f64 / (i128::from(right.time.ticks()) - start) as f64;
    slope_at(left, right, progress)
}

fn velocity(
    keyframes: &[Keyframe<f32>],
    before: Extrapolation,
    after: Extrapolation,
    time: MediaTime,
) -> f64 {
    let [first, .., last] = keyframes else {
        return 0.0;
    };
    let (start, end, at) = (
        i128::from(first.time.ticks()),
        i128::from(last.time.ticks()),
        i128::from(time.ticks()),
    );
    let period = end - start;
    let side = if at <= start {
        before
    } else if at > end {
        after
    } else {
        return slope_before(keyframes, at);
    };
    match side {
        Extrapolation::Hold => 0.0,
        Extrapolation::Linear if at > end => {
            continued_slope(&keyframes[keyframes.len() - 2], last, true)
        }
        Extrapolation::Linear => continued_slope(first, &keyframes[1], false),
        Extrapolation::Repeat | Extrapolation::RepeatOffset => {
            let offset = (at - start).rem_euclid(period);
            slope_before(keyframes, start + if offset == 0 { period } else { offset })
        }
        Extrapolation::PingPong => {
            let offset = (at - start).rem_euclid(2 * period);
            if offset == 0 {
                0.0 - slope_after(keyframes, start)
            } else if offset <= period {
                slope_before(keyframes, start + offset)
            } else {
                0.0 - slope_after(keyframes, start + 2 * period - offset)
            }
        }
    }
}

struct Bounds([f64; 2]);

impl Bounds {
    fn add(&mut self, value: f64) {
        self.0 = [self.0[0].min(value), self.0[1].max(value)];
    }
}

fn keyed_bounds(keyframes: &[Keyframe<f32>], from: i64, to: i64, bounds: &mut Bounds) {
    for (index, left) in keyframes.iter().enumerate() {
        let start = left.time.ticks();
        if start > to {
            break;
        }
        let Some(right) = keyframes.get(index + 1) else {
            if start >= from {
                bounds.add(f64::from(left.value));
            }
            break;
        };
        let end = right.time.ticks();
        if end < from {
            continue;
        }
        let held = matches!(left.interpolation, Interpolation::Hold);
        if start >= from || (held && end > from) {
            bounds.add(f64::from(left.value));
        }
        let length = span(left.time, right.time);
        #[expect(clippy::cast_precision_loss, reason = "ticks as coordinates")]
        let (low, high) = (from as f64, to as f64);
        if let Interpolation::Points { points } = &left.interpolation {
            let change = f64::from(right.value) - f64::from(left.value);
            for point in points {
                let time = coordinate(left.time) + f64::from(point.x) * length;
                if time >= low && time <= high {
                    bounds.add(f64::from(left.value) + change * f64::from(point.y));
                }
            }
        }
        let Some(cubic) = Cubic::of(left, right) else {
            continue;
        };
        for u in cubic.turns() {
            let time = coordinate(left.time) + cubic.progress_at(u) * length;
            if time >= low && time <= high {
                bounds.add(cubic.value_at(u));
            }
        }
    }
}

/// The least and greatest value of a number over `range`, overshoot between keyframes
/// included, with its extrapolation.
///
/// Exact, except where the range holds more passes of a `repeat_offset` value than keyframes
/// can spell: there the two outermost passes count whole.
#[must_use]
pub fn range(animation: &Animated<f32>, range: TimeRange) -> [f64; 2] {
    let from = range.start().ticks();
    let to = range.end().ticks().saturating_sub(1).max(from);
    let value = |tick: i64| {
        f64::from(sample_scalar(
            animation,
            MediaTime(tick),
            &SampleContext::NONE,
        ))
    };
    let mut bounds = Bounds([value(from); 2]);
    bounds.add(value(to));
    let Animated::Keyframes {
        keyframes,
        before,
        after,
    } = animation
    else {
        return bounds.0;
    };
    let [first, .., last] = keyframes.as_slice() else {
        return bounds.0;
    };
    let mut spelled = animation.clone();
    if materialize(&mut spelled, range).is_ok() {
        if let Animated::Keyframes { keyframes, .. } = &spelled {
            keyed_bounds(keyframes, from, to, &mut bounds);
        }
        return bounds.0;
    }
    let (start, end) = (first.time.ticks(), last.time.ticks());
    if from <= end && to >= start {
        keyed_bounds(keyframes, from.max(start), to.min(end), &mut bounds);
    }
    let mut whole = Bounds([f64::from(first.value); 2]);
    keyed_bounds(keyframes, start, end, &mut whole);
    let travel = f64::from(last.value) - f64::from(first.value);
    let period = i128::from(end) - i128::from(start);
    let pass = |tick: i64| (i128::from(tick) - i128::from(start)).div_euclid(period);
    for (reached, side, passes) in [
        (from < start, *before, [pass(from), -1]),
        (to >= end, *after, [1, pass(to)]),
    ] {
        if !reached {
            continue;
        }
        match side {
            Extrapolation::Hold | Extrapolation::Linear => {}
            Extrapolation::Repeat | Extrapolation::PingPong => {
                bounds.add(whole.0[0]);
                bounds.add(whole.0[1]);
            }
            Extrapolation::RepeatOffset => {
                for pass in passes {
                    #[expect(clippy::cast_precision_loss, reason = "a count of passes")]
                    let offset = pass as f64 * travel;
                    bounds.add(whole.0[0] + offset);
                    bounds.add(whole.0[1] + offset);
                }
            }
        }
    }
    bounds.0
}

pub(crate) fn segment_value(left: &Keyframe<f32>, right: &Keyframe<f32>, tick: i64) -> f32 {
    narrow(wide::curve_value(left, right, tick))
}

pub(crate) fn between_keys(
    times: impl ExactSizeIterator<Item = MediaTime> + Clone,
    time: MediaTime,
) -> Result<(usize, f64), CurveError> {
    let count = times.len();
    let (Some(first), Some(last)) = (times.clone().next(), times.clone().last()) else {
        return Err(CurveError::Empty);
    };
    if time < first || time > last {
        return Err(CurveError::OutsideKeys);
    }
    if count >= MAX_KEYFRAMES {
        return Err(CurveError::TooManyKeys);
    }
    let mut left = 0;
    let mut bounds = (first, last);
    for (index, key) in times.enumerate() {
        if key == time {
            return Err(CurveError::OnAKey);
        }
        if key < time {
            left = index;
            bounds.0 = key;
        } else {
            bounds.1 = key;
            break;
        }
    }
    Ok((left, span(bounds.0, time) / span(bounds.0, bounds.1)))
}

/// Adds a keyframe at `time` without changing the curve: the segment it falls in is cut by de
/// Casteljau subdivision and the new keyframe takes the curve's value there, rounded to `f32`.
/// A `steps` segment becomes held keyframes, one where each value starts, and a `points`
/// segment two tables, or straight lines between keyframes where a part ends level.
///
/// # Errors
///
/// [`CurveError::NotKeyed`], [`CurveError::Empty`], [`CurveError::OutsideKeys`] (a time past an
/// end needs a keyframe of its own, not a cut), [`CurveError::OnAKey`], or
/// [`CurveError::TooManyKeys`].
pub fn insert_key(animation: &mut Animated<f32>, time: MediaTime) -> Result<(), CurveError> {
    let Animated::Keyframes { keyframes, .. } = animation else {
        return Err(CurveError::NotKeyed);
    };
    let (index, _) = between_keys(keyframes.iter().map(|key| key.time), time)?;
    wide::split_at(keyframes, index, time)
}

fn timing_parts(
    interpolation: &Interpolation,
    progress: f64,
) -> Result<(Interpolation, Interpolation), CurveError> {
    match interpolation {
        Interpolation::Hold => Ok((Interpolation::Hold, Interpolation::Hold)),
        Interpolation::Linear => Ok((Interpolation::Linear, Interpolation::Linear)),
        Interpolation::CubicBezier(curve) => curve
            .between(0.0, progress)
            .zip(curve.between(progress, 1.0))
            .map(|(leading, trailing)| {
                (
                    Interpolation::CubicBezier(leading),
                    Interpolation::CubicBezier(trailing),
                )
            })
            .ok_or(CurveError::LevelSegment),
        Interpolation::Points { points } => {
            let cut = alpha2_model::easing_points_at(points, progress);
            let part = |start: f64, end: f64, low: f64, high: f64| {
                let rise = high - low;
                (rise != 0.0)
                    .then(|| {
                        alpha2_model::easing_points_between(points, start, end, |y| {
                            (y - low) / rise
                        })
                    })
                    .flatten()
                    .map(|points| Interpolation::Points { points })
            };
            part(0.0, progress, 0.0, cut)
                .zip(part(progress, 1.0, cut, 1.0))
                .ok_or(CurveError::LevelSegment)
        }
        Interpolation::ValueBezier(_) | Interpolation::Steps(_) => Err(CurveError::LevelSegment),
    }
}

/// Adds a keyframe holding `value` at `time` to a value that has no value axis (a colour, a
/// paint, a path), cutting the segment's timing curve so both parts keep their shape. `value`
/// is the caller's sample of the animation at `time`.
///
/// # Errors
///
/// As [`insert_key`], and [`CurveError::LevelSegment`] where a part of the timing curve has no
/// rescaled form.
pub fn insert_eased_key<T>(
    animation: &mut Animated<T>,
    time: MediaTime,
    value: T,
) -> Result<(), CurveError> {
    let Animated::Keyframes { keyframes, .. } = animation else {
        return Err(CurveError::NotKeyed);
    };
    let (index, progress) = between_keys(keyframes.iter().map(|key| key.time), time)?;
    let (leading, trailing) = timing_parts(&keyframes[index].interpolation, progress)?;
    keyframes[index].interpolation = leading;
    keyframes.insert(
        index + 1,
        Keyframe {
            time,
            value,
            interpolation: trailing,
        },
    );
    Ok(())
}

/// Adds a keyframe at `time` to a position without changing its path or its speed along it:
/// the timing curve is cut as by [`insert_eased_key`] and the spatial curve where that much of
/// its arc length lies, measured in a space `aspect` wide per unit high.
///
/// # Errors
///
/// As [`insert_eased_key`], and [`CurveError::OffThePath`] where the timing curve overshoots
/// at `time`.
pub fn insert_point_key(
    animation: &mut AnimatedPoint,
    time: MediaTime,
    aspect: f64,
) -> Result<(), CurveError> {
    let AnimatedPoint::Keyframes { keyframes, .. } = animation else {
        return Err(CurveError::NotKeyed);
    };
    let (index, progress) = between_keys(keyframes.iter().map(|key| key.time), time)?;
    let (left, right) = (&keyframes[index], &keyframes[index + 1]);
    let amount = match left.interpolation {
        Interpolation::Hold => {
            let held = PointKeyframe {
                time,
                value: left.value,
                interpolation: Interpolation::Hold,
                out_tangent: Vec2::default(),
                in_tangent: Vec2::default(),
            };
            keyframes.insert(index + 1, held);
            return Ok(());
        }
        Interpolation::Linear => progress,
        Interpolation::CubicBezier(curve) => curve.apply(progress),
        Interpolation::Points { ref points } => alpha2_model::easing_points_at(points, progress),
        Interpolation::ValueBezier(_) | Interpolation::Steps(_) => {
            return Err(CurveError::LevelSegment);
        }
    };
    if !(0.0..=1.0).contains(&amount) {
        return Err(CurveError::OffThePath);
    }
    let (leading, trailing) = timing_parts(&left.interpolation, progress)?;
    let straight = left.out_tangent.is_zero() && right.in_tangent.is_zero();
    let aspect = if aspect.is_finite() && aspect > 0.0 {
        aspect
    } else {
        1.0
    };
    let point = |value: Vec2| {
        alpha2_geometry::kurbo::Point::new(f64::from(value.x) * aspect, f64::from(value.y))
    };
    let vector = |value: Vec2| {
        alpha2_geometry::kurbo::Vec2::new(f64::from(value.x) * aspect, f64::from(value.y))
    };
    let cut = alpha2_geometry::spatial::cut_along(
        point(left.value),
        vector(left.out_tangent),
        vector(right.in_tangent),
        point(right.value),
        amount,
    );
    let back = |x: f64, y: f64| Vec2::new(narrow(x / aspect), narrow(y));
    let tangent = |tangent: alpha2_geometry::kurbo::Vec2| {
        if straight {
            Vec2::default()
        } else {
            back(tangent.x, tangent.y)
        }
    };
    let added = PointKeyframe {
        time,
        value: back(cut.point.x, cut.point.y),
        interpolation: trailing,
        out_tangent: tangent(cut.cut_out),
        in_tangent: tangent(cut.cut_in),
    };
    keyframes[index].interpolation = leading;
    keyframes[index].out_tangent = tangent(cut.from_out);
    keyframes[index + 1].in_tangent = tangent(cut.to_in);
    keyframes.insert(index + 1, added);
    Ok(())
}

/// Rewrites every timing curve and straight line of a keyed number as the value curve that
/// draws the same line. Held, stepped and table segments stay.
pub fn to_value_curves(animation: &mut Animated<f32>) {
    let Animated::Keyframes { keyframes, .. } = animation else {
        return;
    };
    for index in 0..keyframes.len().saturating_sub(1) {
        let (from, to) = (
            f64::from(keyframes[index].value),
            f64::from(keyframes[index + 1].value),
        );
        if let Some(curve) = as_value_curve(&keyframes[index].interpolation, from, to) {
            keyframes[index].interpolation = Interpolation::ValueBezier(curve);
        }
    }
}

/// Rewrites every value curve of a keyed number as the timing curve that draws the same line.
///
/// # Errors
///
/// [`CurveError::LevelSegment`] when a value curve lies between two equal keyframes, which no
/// timing curve can draw; the value is then left as it was.
pub fn to_timing_curves(animation: &mut Animated<f32>) -> Result<(), CurveError> {
    let Animated::Keyframes { keyframes, .. } = animation else {
        return Ok(());
    };
    let mut rewritten = Vec::new();
    for (index, pair) in keyframes.windows(2).enumerate() {
        let Interpolation::ValueBezier(curve) = pair[0].interpolation else {
            continue;
        };
        let change = f64::from(pair[1].value) - f64::from(pair[0].value);
        let timing = timing_curve(curve, change).ok_or(CurveError::LevelSegment)?;
        rewritten.push((index, Interpolation::CubicBezier(timing)));
    }
    for (index, interpolation) in rewritten {
        keyframes[index].interpolation = interpolation;
    }
    Ok(())
}

fn timing_curve(curve: ValueBezier, change: f64) -> Option<CubicBezier> {
    if change == 0.0 {
        return None;
    }
    let (x1, x2) = curve.weights().unwrap_or((1.0 / 3.0, 2.0 / 3.0));
    Some(CubicBezier::new(
        x1,
        narrow(f64::from(curve.leave) / change),
        x2,
        narrow(1.0 + f64::from(curve.arrive) / change),
    ))
}

#[cfg(test)]
#[path = "curves_tests.rs"]
mod tests;