Skip to main content

alpha2_model/
easing.rs

1//! Timing curves shared by keyframe interpolation and transitions, and value curves of numbers.
2//!
3//! The timing curve is CSS Easing Functions Level 1 `cubic-bezier(x1, y1, x2, y2)`, the same
4//! definition web animation, Lottie and motion tools use, with `x1` and `x2` widened to every
5//! pair that never runs time backwards. Named presets (`ease`, `ease-in`, ...) are values of it
6//! kept by hosts, not the model.
7//!
8//! Evaluation uses only `f64` add, subtract, multiply and divide (no transcendental
9//! functions, no fused multiply-add) with a fixed iteration budget, so wasm and native
10//! produce identical bits.
11
12use serde::{Deserialize, Serialize};
13
14/// A CSS `cubic-bezier(x1, y1, x2, y2)` timing curve.
15///
16/// `x1` and `x2` may be any pair for which the curve never runs backwards in time, which holds
17/// the CSS range `0..=1` and reaches 4/3 and -1/3; a host exporting to CSS keeps both in
18/// `0..=1`. `y1` and `y2` are unbounded, so a curve may overshoot.
19#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21#[serde(deny_unknown_fields)]
22pub struct CubicBezier {
23    /// Horizontal coordinate of the first control point.
24    pub x1: f32,
25    /// Vertical coordinate of the first control point.
26    pub y1: f32,
27    /// Horizontal coordinate of the second control point.
28    pub x2: f32,
29    /// Vertical coordinate of the second control point.
30    pub y2: f32,
31}
32
33/// Newton steps tried before bisection takes over.
34const NEWTON_STEPS: usize = 8;
35/// Bisection halvings; 2^-64 is far below the tolerance.
36const BISECTION_STEPS: usize = 64;
37/// Accepted distance between the curve's `x` and the requested progress.
38const TOLERANCE: f64 = 1e-12;
39/// A slope this flat would send a Newton step far outside the curve.
40const MIN_SLOPE: f64 = 1e-9;
41
42impl CubicBezier {
43    /// Creates a curve from its two inner control points.
44    #[must_use]
45    pub const fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
46        Self { x1, y1, x2, y2 }
47    }
48
49    /// Whether every coordinate is finite and the curve never runs backwards in time
50    /// ([`time_handles_valid`]).
51    #[must_use]
52    pub fn is_valid(self) -> bool {
53        self.y1.is_finite() && self.y2.is_finite() && time_handles_valid(self.x1, self.x2)
54    }
55
56    /// The curve's output at linear `progress`, which is clamped to `0..=1`.
57    ///
58    /// 0 maps exactly to 0 and 1 to 1. Between them the output may leave `0..=1` when `y1` or
59    /// `y2` does.
60    #[must_use]
61    pub fn apply(self, progress: f64) -> f64 {
62        let x = progress.clamp(0.0, 1.0);
63        if x <= 0.0 {
64            return 0.0;
65        }
66        if x >= 1.0 {
67            return 1.0;
68        }
69        let parameter = self.time().parameter_at(x);
70        component(parameter, f64::from(self.y1), f64::from(self.y2))
71    }
72
73    /// The part of the curve between linear progress `from` and `to`, rescaled to the unit
74    /// square, so that it shows the same output over that part of a segment. `None` when the
75    /// output is equal at both ends (or the part is empty), which no rescaled curve can show.
76    /// The part's time coordinates may leave `0..=1`, as far as a curve that never runs
77    /// backwards allows.
78    ///
79    /// Uses only the operations of [`Self::apply`], so every platform gets the same bits.
80    #[must_use]
81    #[allow(clippy::cast_possible_truncation)]
82    pub fn between(self, from: f64, to: f64) -> Option<Self> {
83        let parameter = |progress: f64| {
84            if progress <= 0.0 {
85                0.0
86            } else if progress >= 1.0 {
87                1.0
88            } else {
89                self.time().parameter_at(progress)
90            }
91        };
92        let (u, v) = (parameter(from), parameter(to));
93        let part = |p1: f32, p2: f32| {
94            let points = [0.0, f64::from(p1), f64::from(p2), 1.0];
95            [
96                blossom(points, u, u, u),
97                blossom(points, u, u, v),
98                blossom(points, u, v, v),
99                blossom(points, v, v, v),
100            ]
101        };
102        let (x, y) = (part(self.x1, self.x2), part(self.y1, self.y2));
103        let (width, height) = (x[3] - x[0], y[3] - y[0]);
104        if width <= 0.0 || height == 0.0 {
105            return None;
106        }
107        let (x1, x2) = settle_time_handles((x[1] - x[0]) / width, (x[2] - x[0]) / width);
108        let curve = Self::new(
109            x1,
110            ((y[1] - y[0]) / height) as f32,
111            x2,
112            ((y[2] - y[0]) / height) as f32,
113        );
114        curve.is_valid().then_some(curve)
115    }
116
117    /// The curve played backwards: its output at `progress` is one minus this curve's at
118    /// `1 - progress`.
119    #[must_use]
120    pub fn reversed(self) -> Self {
121        let (x1, x2) = settle_time_handles(1.0 - f64::from(self.x2), 1.0 - f64::from(self.x1));
122        Self::new(x1, 1.0 - self.y2, x2, 1.0 - self.y1)
123    }
124
125    /// The slope of the output at linear `progress` (clamped to `0..=1`), in output per
126    /// progress. Always finite: a vertical tangent gives the largest finite `f64` with the
127    /// slope's sign.
128    #[must_use]
129    pub fn slope(self, progress: f64) -> f64 {
130        let time = self.time();
131        let u = time.parameter_within(progress);
132        rise_over_run(
133            slope(u, f64::from(self.y1), f64::from(self.y2)),
134            slope(u, time.x1, time.x2),
135        )
136    }
137
138    /// The slope of the output where the curve starts (`at_end` false) or ends: that of the
139    /// control polygon's first leg from that end that has a time extent, 1 when none has.
140    #[must_use]
141    pub fn end_slope(self, at_end: bool) -> f64 {
142        let (x1, y1) = (f64::from(self.x1), f64::from(self.y1));
143        let (x2, y2) = (f64::from(self.x2), f64::from(self.y2));
144        let legs = if at_end {
145            [(1.0 - x2, 1.0 - y2), (1.0 - x1, 1.0 - y1)]
146        } else {
147            [(x1, y1), (x2, y2)]
148        };
149        first_leg_slope(legs).unwrap_or(1.0)
150    }
151
152    /// The linear progresses strictly inside `0..1` at which the output stops rising or
153    /// falling, in no order.
154    #[must_use]
155    pub fn turns(self) -> [Option<f64>; 2] {
156        let time = self.time();
157        let (y1, y2) = (f64::from(self.y1), f64::from(self.y2));
158        let c = 3.0 * y1;
159        let b = 3.0 * (y2 - y1) - c;
160        let a = 1.0 - c - b;
161        quadratic_roots(3.0 * a, 2.0 * b, c)
162            .map(|turn| turn.filter(|u| *u > 0.0 && *u < 1.0))
163            .map(|turn| turn.map(|u| component(u, time.x1, time.x2)))
164    }
165
166    fn time(self) -> TimeCurve {
167        TimeCurve::new(self.x1, self.x2)
168    }
169}
170
171fn quadratic_roots(qa: f64, qb: f64, qc: f64) -> [Option<f64>; 2] {
172    if qa.abs() <= f64::EPSILON {
173        return [(qb.abs() > f64::EPSILON).then(|| -qc / qb), None];
174    }
175    let discriminant = qb * qb - 4.0 * qa * qc;
176    if discriminant < 0.0 {
177        return [None, None];
178    }
179    let root = discriminant.sqrt();
180    [
181        Some((-qb + root) / (2.0 * qa)),
182        Some((-qb - root) / (2.0 * qa)),
183    ]
184}
185
186fn rise_over_run(rise: f64, run: f64) -> f64 {
187    if run >= MIN_RUN {
188        rise / run
189    } else if rise > 0.0 {
190        VERTICAL_SLOPE
191    } else if rise < 0.0 {
192        -VERTICAL_SLOPE
193    } else {
194        0.0
195    }
196}
197
198const SETTLE_STEPS: usize = 32;
199
200#[expect(
201    clippy::cast_possible_truncation,
202    reason = "time handles are stored as `f32`"
203)]
204fn settle_time_handles(x1: f64, x2: f64) -> (f32, f32) {
205    let step = |value: f32, direction: f64| {
206        if direction > 0.0 {
207            value.next_up()
208        } else if direction < 0.0 {
209            value.next_down()
210        } else {
211            value
212        }
213    };
214    let rounded = (
215        if x1 > 0.0 { x1 } else { 0.0 } as f32,
216        if x2 < 1.0 { x2 } else { 1.0 } as f32,
217    );
218    let (mut first, mut second) = rounded;
219    for _ in 0..SETTLE_STEPS {
220        if time_handles_valid(first, second) {
221            return (first, second);
222        }
223        // x1 (1 - x2) - (x1 - x2)^2 is concave and not negative exactly on the valid pairs
224        // with x1 > x2; its gradient is ((1 - x2) - 2 (x1 - x2), 2 (x1 - x2) - x1).
225        let apart = 2.0 * (f64::from(first) - f64::from(second));
226        (first, second) = (
227            step(first, (1.0 - f64::from(second)) - apart),
228            step(second, apart - f64::from(first)),
229        );
230    }
231    if time_handles_valid(first, second) {
232        return (first, second);
233    }
234    (rounded.0.clamp(0.0, 1.0), rounded.1.clamp(0.0, 1.0))
235}
236
237fn first_leg_slope(legs: [(f64, f64); 2]) -> Option<f64> {
238    legs.into_iter()
239        .find(|(run, _)| *run > 0.0)
240        .map(|(run, rise)| rise / run)
241}
242
243/// Whether a cubic from time 0 to 1 with inner time coordinates `x1`, `x2` never runs backwards.
244///
245/// That is `x1 >= 0`, `x2 <= 1`, and `x2 >= x1` or `(x1 - x2)^2 <= x1 * (1 - x2)`.
246#[must_use]
247pub fn time_handles_valid(x1: f32, x2: f32) -> bool {
248    if !(x1.is_finite() && x2.is_finite()) {
249        return false;
250    }
251    let (first, last) = (f64::from(x1), 1.0 - f64::from(x2));
252    let middle = f64::from(x2) - f64::from(x1);
253    first >= 0.0 && last >= 0.0 && (middle >= 0.0 || middle * middle <= first * last)
254}
255
256#[derive(Copy, Clone)]
257struct TimeCurve {
258    x1: f64,
259    x2: f64,
260}
261
262impl TimeCurve {
263    fn new(x1: f32, x2: f32) -> Self {
264        Self {
265            x1: f64::from(x1),
266            x2: f64::from(x2),
267        }
268    }
269
270    fn parameter_within(self, progress: f64) -> f64 {
271        if progress <= 0.0 {
272            0.0
273        } else if progress >= 1.0 {
274            1.0
275        } else {
276            self.parameter_at(progress)
277        }
278    }
279
280    /// The Bezier parameter whose `x` equals `x`, for `x` in `(0, 1)`.
281    fn parameter_at(self, x: f64) -> f64 {
282        self.newton(x).unwrap_or_else(|| self.bisection(x))
283    }
284
285    /// Newton's method from `t = x`, if it lands within `NEWTON_STEPS` without leaving `0..=1`.
286    fn newton(self, x: f64) -> Option<f64> {
287        let Self { x1, x2 } = self;
288        let mut parameter = x;
289        for _ in 0..NEWTON_STEPS {
290            let error = component(parameter, x1, x2) - x;
291            if error.abs() < TOLERANCE {
292                return (0.0..=1.0).contains(&parameter).then_some(parameter);
293            }
294            let slope = slope(parameter, x1, x2);
295            if slope.abs() < MIN_SLOPE {
296                return None;
297            }
298            parameter -= error / slope;
299        }
300        None
301    }
302
303    /// Bisection on `0..=1`, where `x(t)` is non-decreasing because the time handles are valid.
304    /// It converges where Newton fails on flat parts.
305    fn bisection(self, x: f64) -> f64 {
306        let Self { x1, x2 } = self;
307        let (mut low, mut high) = (0.0_f64, 1.0_f64);
308        let mut parameter = x;
309        for _ in 0..BISECTION_STEPS {
310            let value = component(parameter, x1, x2);
311            if (value - x).abs() < TOLERANCE {
312                break;
313            }
314            if value < x {
315                low = parameter;
316            } else {
317                high = parameter;
318            }
319            parameter = low + (high - low) * 0.5;
320        }
321        parameter
322    }
323}
324
325/// One coordinate of the curve at parameter `t` for inner control coordinates `p1`, `p2`:
326/// `3 (1-t)^2 t p1 + 3 (1-t) t^2 p2 + t^3`, in Horner form.
327fn component(t: f64, p1: f64, p2: f64) -> f64 {
328    let c = 3.0 * p1;
329    let b = 3.0 * (p2 - p1) - c;
330    let a = 1.0 - c - b;
331    ((a * t + b) * t + c) * t
332}
333
334/// The blossom of a cubic with control values `points` at `(u, v, w)`: de Casteljau with one
335/// parameter per level. `(u, u, v)` and `(u, v, v)` are the inner controls of the part `u..=v`.
336fn blossom(points: [f64; 4], u: f64, v: f64, w: f64) -> f64 {
337    let lerp = |a: f64, b: f64, t: f64| a + (b - a) * t;
338    let first = [
339        lerp(points[0], points[1], u),
340        lerp(points[1], points[2], u),
341        lerp(points[2], points[3], u),
342    ];
343    let second = [lerp(first[0], first[1], v), lerp(first[1], first[2], v)];
344    lerp(second[0], second[1], w)
345}
346
347/// The derivative of [`component`] with respect to `t`.
348fn slope(t: f64, p1: f64, p2: f64) -> f64 {
349    let c = 3.0 * p1;
350    let b = 3.0 * (p2 - p1) - c;
351    let a = 1.0 - c - b;
352    (3.0 * a * t + 2.0 * b) * t + c
353}
354
355/// A cubic Bezier in (time, value) between two keys of a number.
356///
357/// The control points are `leave` above this key's value and `arrive` above the next key's, at
358/// `x1` and `x2` of the segment's length. Without `x1` and `x2` they sit at one third and two
359/// thirds, and the segment is a cubic Hermite curve.
360#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
361#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
362#[serde(deny_unknown_fields)]
363pub struct ValueBezier {
364    /// Time of the first control point as a fraction of the segment. Given with `x2` or not at
365    /// all; the pair is any for which the curve never runs backwards in time.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub x1: Option<f32>,
368    /// The first control point's value minus this keyframe's value.
369    pub leave: f32,
370    /// Time of the second control point as a fraction of the segment. Given with `x1` or not at
371    /// all.
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub x2: Option<f32>,
374    /// The second control point's value minus the next keyframe's value.
375    pub arrive: f32,
376}
377
378const VERTICAL_SLOPE: f64 = f64::MAX;
379const MIN_RUN: f64 = 1e-12;
380
381impl ValueBezier {
382    /// Creates a curve with control points at one third and two thirds of the segment.
383    #[must_use]
384    pub const fn unweighted(leave: f32, arrive: f32) -> Self {
385        Self {
386            x1: None,
387            leave,
388            x2: None,
389            arrive,
390        }
391    }
392
393    /// Creates a curve with control points at `x1` and `x2` of the segment.
394    #[must_use]
395    pub const fn weighted(x1: f32, leave: f32, x2: f32, arrive: f32) -> Self {
396        Self {
397            x1: Some(x1),
398            leave,
399            x2: Some(x2),
400            arrive,
401        }
402    }
403
404    /// Whether the offsets are finite, and the time coordinates are given together and never
405    /// run backwards ([`time_handles_valid`]).
406    #[must_use]
407    pub fn is_valid(self) -> bool {
408        self.leave.is_finite()
409            && self.arrive.is_finite()
410            && match (self.x1, self.x2) {
411                (None, None) => true,
412                (Some(x1), Some(x2)) => time_handles_valid(x1, x2),
413                _ => false,
414            }
415    }
416
417    /// The time coordinates, or `None` for the unweighted form.
418    #[must_use]
419    pub fn weights(self) -> Option<(f32, f32)> {
420        self.x1.zip(self.x2)
421    }
422
423    /// The value at `progress` of the segment from `from` to `to`: `from` at 0 and before,
424    /// `to` at 1 and after. Between them it may leave the range of the two.
425    ///
426    /// Uses only the operations of [`CubicBezier::apply`], so every platform gets the same bits.
427    #[must_use]
428    pub fn value(self, from: f32, to: f32, progress: f64) -> f64 {
429        self.value_between(f64::from(from), f64::from(to), progress)
430    }
431
432    /// [`Self::value`] between ends of any size, such as times in ticks: with `u` the curve's
433    /// parameter at `progress` and `a`, `b`, `c` its polynomial, `from + ((a u + b) u + c) u`
434    /// in that order of operations.
435    #[must_use]
436    pub fn value_between(self, from: f64, to: f64, progress: f64) -> f64 {
437        if progress <= 0.0 {
438            return from;
439        }
440        if progress >= 1.0 {
441            return to;
442        }
443        let u = match self.weights() {
444            None => progress,
445            Some((x1, x2)) => TimeCurve::new(x1, x2).parameter_at(progress),
446        };
447        let [a, b, c] = self.polynomial(from, to);
448        from + ((a * u + b) * u + c) * u
449    }
450
451    /// The slope at `progress` (clamped to `0..=1`), in value per segment length. Always
452    /// finite: a vertical tangent gives the largest finite `f64` with the slope's sign.
453    #[must_use]
454    pub fn slope(self, from: f32, to: f32, progress: f64) -> f64 {
455        self.slope_between(f64::from(from), f64::from(to), progress)
456    }
457
458    /// [`Self::slope`] between ends of any size.
459    #[must_use]
460    pub fn slope_between(self, from: f64, to: f64, progress: f64) -> f64 {
461        let progress = progress.clamp(0.0, 1.0);
462        let [a, b, c] = self.polynomial(from, to);
463        let rise = |u: f64| (3.0 * a * u + 2.0 * b) * u + c;
464        let Some((x1, x2)) = self.weights() else {
465            return rise(progress);
466        };
467        let time = TimeCurve::new(x1, x2);
468        let u = time.parameter_within(progress);
469        rise_over_run(rise(u), slope(u, time.x1, time.x2))
470    }
471
472    /// The part of the segment from `from` to `to` between linear progress `start` and `end`:
473    /// the values at its two ends ([`Self::value`] rounded to `f32`) and the curve between
474    /// them. An unweighted curve gives an unweighted part.
475    ///
476    /// Uses only the operations of [`CubicBezier::apply`], so every platform gets the same bits.
477    #[must_use]
478    #[expect(
479        clippy::cast_possible_truncation,
480        reason = "values and handles are stored as `f32`"
481    )]
482    pub fn between(self, from: f32, to: f32, start: f64, end: f64) -> (f32, f32, Self) {
483        let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
484        let (low, high) = (
485            narrow(self.value(from, to, start)),
486            narrow(self.value(from, to, end)),
487        );
488        let part = self.part_between(
489            (f64::from(from), f64::from(to)),
490            (start, end),
491            (f64::from(low), f64::from(high)),
492        );
493        (low, high, part)
494    }
495
496    /// The curve of the part of the segment between `ends` from linear progress `span.0` to
497    /// `span.1`, for a segment between `part_ends`: the values a keyframe at each end of the
498    /// part holds. The part's two inner control points stay where they are.
499    #[must_use]
500    #[expect(
501        clippy::cast_possible_truncation,
502        reason = "handles are stored as `f32`"
503    )]
504    pub fn part_between(self, ends: (f64, f64), span: (f64, f64), part_ends: (f64, f64)) -> Self {
505        let time = self.weights().map(|(x1, x2)| TimeCurve::new(x1, x2));
506        let parameter = |progress: f64| {
507            time.map_or(progress.clamp(0.0, 1.0), |time| {
508                time.parameter_within(progress)
509            })
510        };
511        let (u, v) = (parameter(span.0), parameter(span.1));
512        let part = |points: [f64; 4]| {
513            [
514                blossom(points, u, u, u),
515                blossom(points, u, u, v),
516                blossom(points, u, v, v),
517                blossom(points, v, v, v),
518            ]
519        };
520        let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
521        let (from, to) = ends;
522        let y = part([
523            from,
524            from + f64::from(self.leave),
525            to + f64::from(self.arrive),
526            to,
527        ]);
528        let weights = time.and_then(|time| {
529            let x = part([0.0, time.x1, time.x2, 1.0]);
530            let width = x[3] - x[0];
531            (width > 0.0).then(|| settle_time_handles((x[1] - x[0]) / width, (x[2] - x[0]) / width))
532        });
533        Self {
534            x1: weights.map(|(x1, _)| x1),
535            leave: narrow(y[1] - part_ends.0),
536            x2: weights.map(|(_, x2)| x2),
537            arrive: narrow(y[2] - part_ends.1),
538        }
539    }
540
541    /// The curve of the same segment played backwards, from its right keyframe to its left.
542    #[must_use]
543    pub fn reversed(self) -> Self {
544        let weights = self
545            .weights()
546            .map(|(x1, x2)| settle_time_handles(1.0 - f64::from(x2), 1.0 - f64::from(x1)));
547        Self {
548            x1: weights.map(|(x1, _)| x1),
549            leave: self.arrive,
550            x2: weights.map(|(_, x2)| x2),
551            arrive: self.leave,
552        }
553    }
554
555    /// The same curve between other end values: its control points stay where they are while
556    /// the segment's ends move from `from`, `to` to `new_from`, `new_to`.
557    #[must_use]
558    pub fn rebased(self, from: f32, to: f32, new_from: f32, new_to: f32) -> Self {
559        self.rebased_between(
560            (f64::from(from), f64::from(to)),
561            (f64::from(new_from), f64::from(new_to)),
562        )
563    }
564
565    /// [`Self::rebased`] between ends of any size.
566    #[must_use]
567    #[expect(
568        clippy::cast_possible_truncation,
569        reason = "clamped to the `f32` range first"
570    )]
571    pub fn rebased_between(self, ends: (f64, f64), new_ends: (f64, f64)) -> Self {
572        let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
573        Self {
574            leave: narrow(ends.0 + f64::from(self.leave) - new_ends.0),
575            arrive: narrow(ends.1 + f64::from(self.arrive) - new_ends.1),
576            ..self
577        }
578    }
579
580    /// The least and greatest value over the segment from `from` to `to`.
581    #[must_use]
582    pub fn range(self, from: f32, to: f32) -> [f64; 2] {
583        let (from, to) = (f64::from(from), f64::from(to));
584        let [a, b, c] = self.polynomial(from, to);
585        let value = |u: f64| from + ((a * u + b) * u + c) * u;
586        quadratic_roots(3.0 * a, 2.0 * b, c)
587            .into_iter()
588            .flatten()
589            .filter(|u| *u > 0.0 && *u < 1.0)
590            .map(value)
591            .fold([from.min(to), from.max(to)], |[low, high], value| {
592                [low.min(value), high.max(value)]
593            })
594    }
595
596    /// The slope where the segment from `from` to `to` starts (`at_end` false) or ends, in value
597    /// per segment length: that of the control polygon's first leg from that end that has a
598    /// time extent, the chord's when none has.
599    #[must_use]
600    pub fn end_slope(self, from: f32, to: f32, at_end: bool) -> f64 {
601        self.end_slope_between(f64::from(from), f64::from(to), at_end)
602    }
603
604    /// [`Self::end_slope`] between ends of any size.
605    #[must_use]
606    pub fn end_slope_between(self, from: f64, to: f64, at_end: bool) -> f64 {
607        let (x1, x2) = self.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
608            (f64::from(x1), f64::from(x2))
609        });
610        let change = to - from;
611        let (leave, arrive) = (f64::from(self.leave), f64::from(self.arrive));
612        let legs = if at_end {
613            [(1.0 - x2, -arrive), (1.0 - x1, change - leave)]
614        } else {
615            [(x1, leave), (x2, change + arrive)]
616        };
617        first_leg_slope(legs).unwrap_or(change)
618    }
619
620    /// The linear progresses strictly inside `0..1` at which the value between `from` and `to`
621    /// stops rising or falling, in no order.
622    #[must_use]
623    pub fn turns_between(self, from: f64, to: f64) -> [Option<f64>; 2] {
624        let [a, b, c] = self.polynomial(from, to);
625        let time = self.weights().map(|(x1, x2)| TimeCurve::new(x1, x2));
626        quadratic_roots(3.0 * a, 2.0 * b, c)
627            .map(|turn| turn.filter(|u| *u > 0.0 && *u < 1.0))
628            .map(|turn| turn.map(|u| time.map_or(u, |time| component(u, time.x1, time.x2))))
629    }
630
631    fn polynomial(self, from: f64, to: f64) -> [f64; 3] {
632        let change = to - from;
633        let c = 3.0 * f64::from(self.leave);
634        let b = 3.0 * (change + f64::from(self.arrive) - f64::from(self.leave)) - c;
635        let a = change - c - b;
636        [a, b, c]
637    }
638}
639
640/// The most steps a `steps` curve has.
641pub const MAX_EASING_STEPS: u32 = 65_536;
642
643/// The most points a `points` curve lists.
644pub const MAX_EASING_POINTS: usize = 256;
645
646/// Where a `steps` curve rises, as the CSS `steps()` positions.
647#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
648#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
649#[serde(rename_all = "snake_case")]
650pub enum StepPosition {
651    /// The first rise is at the start, so the curve never shows 0 (`jump-start`).
652    Start,
653    /// The last rise is at the end, so the curve never shows 1 before it (`jump-end`).
654    #[default]
655    End,
656    /// No rise at either end: the first step shows 0 and the last shows 1 (`jump-none`).
657    None,
658    /// A rise at both ends: the curve shows neither 0 nor 1 (`jump-both`).
659    Both,
660}
661
662impl StepPosition {
663    #[expect(
664        clippy::trivially_copy_pass_by_ref,
665        reason = "serde passes a field by reference"
666    )]
667    fn is_end(&self) -> bool {
668        *self == Self::End
669    }
670}
671
672/// A staircase of equal steps, as CSS `steps()`.
673#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
674#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
675#[serde(deny_unknown_fields)]
676pub struct Steps {
677    /// How many steps: 1 to [`MAX_EASING_STEPS`], and at least 2 where `position` is `none`.
678    #[serde(deserialize_with = "step_count")]
679    #[cfg_attr(
680        feature = "schema",
681        schemars(range(min = 1, max = MAX_EASING_STEPS))
682    )]
683    pub count: u32,
684    /// Where the curve rises.
685    #[serde(default, skip_serializing_if = "StepPosition::is_end")]
686    pub position: StepPosition,
687}
688
689fn step_count<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
690    let count = u32::deserialize(deserializer)?;
691    if (1..=MAX_EASING_STEPS).contains(&count) {
692        Ok(count)
693    } else {
694        Err(serde::de::Error::custom(format!(
695            "a steps count is 1 to {MAX_EASING_STEPS}, not {count}"
696        )))
697    }
698}
699
700impl Steps {
701    /// Whether the count is one the position can have.
702    #[must_use]
703    pub const fn is_valid(self) -> bool {
704        let least = if matches!(self.position, StepPosition::None) {
705            2
706        } else {
707            1
708        };
709        self.count >= least && self.count <= MAX_EASING_STEPS
710    }
711
712    /// The step that `elapsed` of `length` falls on, from 0. Both are in the same unit and
713    /// `length` is positive; with whole ticks a step starts on the first tick at or after its
714    /// exact time.
715    #[must_use]
716    pub const fn index(self, elapsed: i128, length: i128) -> i128 {
717        let last = self.count as i128 - 1;
718        let index = (elapsed * self.count as i128).div_euclid(length);
719        if index < 0 {
720            0
721        } else if index > last {
722            last
723        } else {
724            index
725        }
726    }
727
728    /// The output on step `index`.
729    #[must_use]
730    #[expect(clippy::cast_precision_loss, reason = "counts of at most 65,537")]
731    pub const fn amount(self, index: i128) -> f64 {
732        let (rises, of) = self.fraction(index);
733        rises as f64 / of as f64
734    }
735
736    /// The output on step `index` as an exact fraction: the rises made, over how many the
737    /// curve has.
738    #[must_use]
739    pub const fn fraction(self, index: i128) -> (i128, i128) {
740        let count = self.count as i128;
741        match self.position {
742            StepPosition::End => (index, count),
743            StepPosition::Start => (index + 1, count),
744            StepPosition::None => (index, count - 1),
745            StepPosition::Both => (index + 1, count + 1),
746        }
747    }
748
749    /// The output at linear `progress`: the step it falls on, 0 before the curve and 1 from
750    /// its end.
751    #[must_use]
752    pub fn apply(self, progress: f64) -> f64 {
753        if progress >= 1.0 {
754            return 1.0;
755        }
756        if progress < 0.0 || progress.is_nan() {
757            return 0.0;
758        }
759        #[expect(
760            clippy::cast_possible_truncation,
761            reason = "a progress below 1 times a count of at most 65,536"
762        )]
763        let index = (progress * f64::from(self.count)).floor() as i128;
764        self.amount(index.clamp(0, i128::from(self.count) - 1))
765    }
766}
767
768/// One point of a `points` curve.
769#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
770#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
771#[serde(deny_unknown_fields)]
772pub struct EasingPoint {
773    /// Linear progress, strictly between 0 and 1.
774    pub x: f32,
775    /// The output there; it may leave `0..=1`.
776    pub y: f32,
777}
778
779/// Whether `points` rise strictly in `x` inside `(0, 1)`, have finite outputs, and number at
780/// most [`MAX_EASING_POINTS`].
781#[must_use]
782pub fn easing_points_valid(points: &[EasingPoint]) -> bool {
783    points.len() <= MAX_EASING_POINTS
784        && points
785            .iter()
786            .all(|point| point.x > 0.0 && point.x < 1.0 && point.y.is_finite())
787        && points.windows(2).all(|pair| pair[0].x < pair[1].x)
788}
789
790fn table_piece(points: &[EasingPoint], progress: f64) -> [(f64, f64); 2] {
791    let wide = |point: &EasingPoint| (f64::from(point.x), f64::from(point.y));
792    let next = points.partition_point(|point| f64::from(point.x) <= progress);
793    [
794        next.checked_sub(1)
795            .and_then(|index| points.get(index))
796            .map_or((0.0, 0.0), wide),
797        points.get(next).map_or((1.0, 1.0), wide),
798    ]
799}
800
801/// The output of a `points` curve at linear `progress` (clamped to `0..=1`): the straight line
802/// between its two neighbours among `(0, 0)`, the points and `(1, 1)`.
803#[must_use]
804pub fn easing_points_at(points: &[EasingPoint], progress: f64) -> f64 {
805    if progress <= 0.0 || progress.is_nan() {
806        return 0.0;
807    }
808    if progress >= 1.0 {
809        return 1.0;
810    }
811    let [(xa, ya), (xb, yb)] = table_piece(points, progress);
812    ya + (yb - ya) * ((progress - xa) / (xb - xa))
813}
814
815/// The slope of a `points` curve at linear `progress` (clamped to `0..=1`): that of the piece
816/// `progress` lies on, the later one at a point and the last at 1.
817#[must_use]
818pub fn easing_points_slope(points: &[EasingPoint], progress: f64) -> f64 {
819    let [(xa, ya), (xb, yb)] = table_piece(points, progress.clamp(0.0, 1.0));
820    (yb - ya) / (xb - xa)
821}
822
823/// The least and greatest output of a `points` curve.
824#[must_use]
825pub fn easing_points_range(points: &[EasingPoint]) -> [f64; 2] {
826    points.iter().fold([0.0, 1.0], |[low, high], point| {
827        [low.min(f64::from(point.y)), high.max(f64::from(point.y))]
828    })
829}
830
831#[expect(
832    clippy::cast_possible_truncation,
833    reason = "easing points are stored as `f32`"
834)]
835fn rising_points(points: impl Iterator<Item = (f64, f64)>) -> Vec<EasingPoint> {
836    let mut rising: Vec<EasingPoint> = Vec::new();
837    for (x, y) in points {
838        let point = EasingPoint {
839            x: x as f32,
840            y: y.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32,
841        };
842        if point.x > rising.last().map_or(0.0, |last| last.x) && point.x < 1.0 {
843            rising.push(point);
844        }
845    }
846    rising
847}
848
849/// The points of the same curve played backwards: its output at `progress` is one minus this
850/// curve's at `1 - progress`.
851#[must_use]
852pub fn easing_points_reversed(points: &[EasingPoint]) -> Vec<EasingPoint> {
853    rising_points(
854        points
855            .iter()
856            .rev()
857            .map(|point| (1.0 - f64::from(point.x), 1.0 - f64::from(point.y))),
858    )
859}
860
861/// The points of the curve strictly between linear progress `start` and `end`, with that part
862/// stretched over `0..1` and each output passed through `output`, which maps the part's first
863/// output to 0 and its last to 1. `None` when an output is then not finite.
864#[must_use]
865pub fn easing_points_between(
866    points: &[EasingPoint],
867    start: f64,
868    end: f64,
869    output: impl Fn(f64) -> f64,
870) -> Option<Vec<EasingPoint>> {
871    let inside: Vec<(f64, f64)> = points
872        .iter()
873        .map(|point| (f64::from(point.x), output(f64::from(point.y))))
874        .filter(|(x, _)| *x > start && *x < end)
875        .map(|(x, y)| ((x - start) / (end - start), y))
876        .collect();
877    inside
878        .iter()
879        .all(|(_, y)| y.is_finite())
880        .then(|| rising_points(inside.into_iter()))
881}
882
883/// A timing curve from linear progress to eased progress, without a hold.
884///
885/// Transitions use it directly; keyframe [`crate::Interpolation`] adds `hold`.
886#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
887#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
888#[serde(tag = "type", rename_all = "snake_case", from = "EasingWire")]
889pub enum Easing {
890    /// Progress advances at a constant rate.
891    Linear,
892    /// Progress follows a CSS `cubic-bezier()` curve.
893    CubicBezier(CubicBezier),
894    /// Progress rises in equal steps, as CSS `steps()`.
895    Steps(Steps),
896    /// Progress follows straight lines through a table of points, as CSS `linear()`: from
897    /// `(0, 0)` through each point to `(1, 1)`.
898    Points {
899        /// The points between the two ends, rising strictly in `x`; at most
900        /// [`MAX_EASING_POINTS`].
901        points: Vec<EasingPoint>,
902    },
903}
904
905/// The wire form of [`Easing`].
906///
907/// serde lets an internally tagged unit variant ignore extra fields even with
908/// `deny_unknown_fields`; empty struct variants reject them, as the published schema does.
909#[derive(Deserialize)]
910#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
911#[cfg_attr(feature = "schema", schemars(rename = "Easing"))]
912#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
913pub(crate) enum EasingWire {
914    /// Progress advances at a constant rate.
915    Linear {},
916    /// Progress follows a CSS `cubic-bezier()` curve.
917    CubicBezier(CubicBezier),
918    /// Progress rises in equal steps, as CSS `steps()`.
919    Steps(Steps),
920    /// Progress follows straight lines through a table of points, as CSS `linear()`: from
921    /// `(0, 0)` through each point to `(1, 1)`.
922    Points {
923        /// The points between the two ends, rising strictly in `x`; at most
924        /// `MAX_EASING_POINTS`.
925        #[serde(deserialize_with = "crate::bounded::seq::<_, _, MAX_EASING_POINTS>")]
926        #[cfg_attr(feature = "schema", schemars(length(max = MAX_EASING_POINTS)))]
927        points: Vec<EasingPoint>,
928    },
929}
930
931impl From<EasingWire> for Easing {
932    fn from(wire: EasingWire) -> Self {
933        match wire {
934            EasingWire::Linear {} => Self::Linear,
935            EasingWire::CubicBezier(curve) => Self::CubicBezier(curve),
936            EasingWire::Steps(steps) => Self::Steps(steps),
937            EasingWire::Points { points } => Self::Points { points },
938        }
939    }
940}
941
942impl Easing {
943    /// Whether the curve's parameters are usable.
944    #[must_use]
945    pub fn is_valid(&self) -> bool {
946        match self {
947            Self::Linear => true,
948            Self::CubicBezier(curve) => curve.is_valid(),
949            Self::Steps(steps) => steps.is_valid(),
950            Self::Points { points } => easing_points_valid(points),
951        }
952    }
953
954    /// Eased progress for linear `progress`, which is clamped to `0..=1`.
955    #[must_use]
956    pub fn apply(&self, progress: f64) -> f64 {
957        match self {
958            Self::Linear => progress.clamp(0.0, 1.0),
959            Self::CubicBezier(curve) => curve.apply(progress),
960            Self::Steps(steps) => steps.apply(progress),
961            Self::Points { points } => easing_points_at(points, progress),
962        }
963    }
964}
965
966#[cfg(test)]
967#[path = "easing_parts_tests.rs"]
968mod parts_tests;
969
970#[cfg(test)]
971#[path = "easing_steps_tests.rs"]
972mod steps_tests;
973
974#[cfg(test)]
975mod tests {
976    use super::{CubicBezier, Easing, ValueBezier, time_handles_valid};
977
978    const EASE: CubicBezier = CubicBezier::new(0.25, 0.1, 0.25, 1.0);
979
980    #[test]
981    fn css_ease_matches_its_reference_value() {
982        // CSS `ease` at x = 0.5 is 0.80240338758485699 at t = 0.69957243870638562, computed
983        // independently by 200-step bisection in 50-digit decimal arithmetic. The f32 control
984        // points move it by under 1e-9.
985        assert!((EASE.apply(0.5) - 0.802_403_387_584_857).abs() < 1e-9);
986        assert!((EASE.time().parameter_at(0.5) - 0.699_572_438_706_385_6).abs() < 1e-9);
987        let ease_in_out = CubicBezier::new(0.42, 0.0, 0.58, 1.0);
988        // 0.42 and 0.58 are not exact in f32, so the symmetry is to ~1e-8.
989        assert!((ease_in_out.apply(0.5) - 0.5).abs() < 1e-7);
990        for x in [0.1, 0.25, 0.4] {
991            let mirrored = 1.0 - ease_in_out.apply(1.0 - x);
992            assert!((ease_in_out.apply(x) - mirrored).abs() < 1e-7);
993        }
994    }
995
996    #[test]
997    fn ends_are_exact_and_input_is_clamped() {
998        for curve in [EASE, CubicBezier::new(0.0, -2.0, 1.0, 3.0)] {
999            assert_eq!(curve.apply(0.0).to_bits(), 0.0_f64.to_bits());
1000            assert_eq!(curve.apply(1.0).to_bits(), 1.0_f64.to_bits());
1001            assert_eq!(curve.apply(-4.0).to_bits(), 0.0_f64.to_bits());
1002            assert_eq!(curve.apply(9.0).to_bits(), 1.0_f64.to_bits());
1003        }
1004    }
1005
1006    #[test]
1007    fn the_linear_curve_is_the_identity() {
1008        let linear = CubicBezier::new(0.0, 0.0, 1.0, 1.0);
1009        for index in 0..=64 {
1010            let x = f64::from(index) / 64.0;
1011            assert!((linear.apply(x) - x).abs() < 1e-12, "{x}");
1012            assert!((Easing::Linear.apply(x) - x).abs() < f64::EPSILON);
1013        }
1014    }
1015
1016    #[test]
1017    fn flat_curves_fall_back_to_bisection_and_stay_accurate() {
1018        // x(t) = t^3 is flat at t = 0 and x(t) = 1 - (1 - t)^3 at t = 1, so Newton from t = x
1019        // overshoots on the first and has no slope on the second.
1020        let cases = [
1021            (CubicBezier::new(0.0, 0.0, 0.0, 0.0), 0.001, 0.1),
1022            (CubicBezier::new(1.0, 1.0, 1.0, 1.0), 0.999, 0.9),
1023        ];
1024        for (curve, x, parameter) in cases {
1025            assert_eq!(
1026                curve.time().newton(x),
1027                None,
1028                "Newton must give up on {curve:?}"
1029            );
1030            let found = curve.time().parameter_at(x);
1031            assert!((found - parameter).abs() < 1e-9, "{curve:?}: {found}");
1032            let x_back = super::component(found, f64::from(curve.x1), f64::from(curve.x2));
1033            assert!((x_back - x).abs() < 1e-12);
1034        }
1035    }
1036
1037    #[test]
1038    fn a_part_of_a_curve_rescaled_shows_the_same_output() {
1039        let curves = [
1040            EASE,
1041            CubicBezier::new(0.42, 0.0, 0.58, 1.0),
1042            CubicBezier::new(0.3, -0.5, 0.7, 1.5),
1043            CubicBezier::new(0.0, 0.0, 1.0, 1.0),
1044        ];
1045        for curve in curves {
1046            for (from, to) in [
1047                (0.0, 0.37),
1048                (0.37, 1.0),
1049                (0.1, 0.9),
1050                (0.5, 0.55),
1051                (0.0, 1.0),
1052            ] {
1053                let part = curve.between(from, to).expect("a curve that moves");
1054                assert!(part.is_valid(), "{curve:?} {from} {to}");
1055                let (low, high) = (curve.apply(from), curve.apply(to));
1056                for step in 0..=1000 {
1057                    let x = from + (to - from) * f64::from(step) / 1000.0;
1058                    let local = (x - from) / (to - from);
1059                    let shown = low + (high - low) * part.apply(local);
1060                    // The part's controls are `f32`, as every curve of a document is.
1061                    assert!(
1062                        (shown - curve.apply(x)).abs() < 1e-6,
1063                        "{curve:?} {from}..{to} at {x}: {shown} {}",
1064                        curve.apply(x)
1065                    );
1066                }
1067            }
1068        }
1069    }
1070
1071    #[test]
1072    fn an_empty_part_has_no_curve() {
1073        assert_eq!(EASE.between(0.4, 0.4), None);
1074    }
1075
1076    #[test]
1077    fn overshooting_curves_leave_the_unit_interval_between_the_ends() {
1078        let back = CubicBezier::new(0.34, 1.56, 0.64, 1.0);
1079        let peak = (1..100)
1080            .map(|index| back.apply(f64::from(index) / 100.0))
1081            .fold(f64::MIN, f64::max);
1082        assert!(peak > 1.05, "ease-out-back overshoots: {peak}");
1083        assert!((Easing::CubicBezier(back).apply(1.0) - 1.0).abs() < f64::EPSILON);
1084    }
1085
1086    #[test]
1087    fn only_time_coordinates_that_run_backwards_are_rejected() {
1088        assert!(CubicBezier::new(0.0, -5.0, 1.0, 5.0).is_valid());
1089        assert!(CubicBezier::new(1.136, 0.0, 0.909, 1.0).is_valid());
1090        assert!(!CubicBezier::new(-0.1, 0.0, 1.0, 1.0).is_valid());
1091        assert!(!CubicBezier::new(0.0, 0.0, 1.1, 1.0).is_valid());
1092        assert!(!CubicBezier::new(1.2, 0.0, 0.2, 1.0).is_valid());
1093        assert!(!CubicBezier::new(0.0, f32::NAN, 1.0, 1.0).is_valid());
1094        assert!(!CubicBezier::new(f32::NAN, 0.0, 1.0, 1.0).is_valid());
1095        assert!(!CubicBezier::new(0.0, 0.0, f32::INFINITY, 1.0).is_valid());
1096        assert!(!Easing::CubicBezier(CubicBezier::new(0.0, 0.0, 2.0, 1.0)).is_valid());
1097    }
1098
1099    fn least_time_speed(x1: f32, x2: f32) -> f64 {
1100        let (first, last) = (f64::from(x1), 1.0 - f64::from(x2));
1101        let middle = f64::from(x2) - f64::from(x1);
1102        (0..=4096)
1103            .map(|step| {
1104                let u = f64::from(step) / 4096.0;
1105                let rest = 1.0 - u;
1106                rest * rest * first + 2.0 * rest * u * middle + u * u * last
1107            })
1108            .fold(f64::INFINITY, f64::min)
1109    }
1110
1111    #[test]
1112    fn time_handles_are_valid_exactly_where_time_never_runs_backwards() {
1113        let coordinate = |index: u16| f32::from(index) / 64.0 - 0.5;
1114        let mut valid = 0;
1115        for x1 in (0..=128).map(coordinate) {
1116            for x2 in (0..=128).map(coordinate) {
1117                let least = least_time_speed(x1, x2);
1118                let verdict = time_handles_valid(x1, x2);
1119                valid += u32::from(verdict);
1120                assert!(
1121                    verdict == (least >= -1e-12) || least.abs() < 1e-6,
1122                    "({x1}, {x2}): {verdict}, least speed {least}"
1123                );
1124            }
1125        }
1126        assert!(valid > 65 * 65, "more than the CSS box: {valid}");
1127        assert!(!time_handles_valid(f32::NAN, 0.5));
1128        assert!(!time_handles_valid(0.5, f32::INFINITY));
1129    }
1130
1131    #[test]
1132    fn the_css_box_is_inside_the_valid_time_handles() {
1133        let coordinate = |index: u16| f32::from(index) / 64.0;
1134        for x1 in (0..=64).map(coordinate) {
1135            for x2 in (0..=64).map(coordinate) {
1136                assert!(time_handles_valid(x1, x2), "({x1}, {x2})");
1137            }
1138        }
1139    }
1140
1141    #[test]
1142    fn the_widest_valid_handles_are_near_four_thirds_and_minus_one_third() {
1143        assert!(time_handles_valid(1.333, 2.0 / 3.0));
1144        assert!(time_handles_valid(1.0 / 3.0, -0.333));
1145        let partners = || (0..=2048_u16).map(|index| f32::from(index) / 1024.0 - 0.5);
1146        for partner in partners() {
1147            assert!(!time_handles_valid(1.34, partner), "x2 = {partner}");
1148            assert!(!time_handles_valid(partner, -0.34), "x1 = {partner}");
1149        }
1150    }
1151
1152    #[test]
1153    fn a_curve_outside_the_css_box_still_reaches_every_progress() {
1154        let curve = CubicBezier::new(1.136, 0.0, 0.909, 1.0);
1155        let mut previous = 0.0;
1156        for step in 1..1000 {
1157            let x = f64::from(step) / 1000.0;
1158            let parameter = curve.time().parameter_at(x);
1159            let back = super::component(parameter, f64::from(curve.x1), f64::from(curve.x2));
1160            assert!((back - x).abs() < 1e-9, "{x}: {back}");
1161            assert!(parameter >= previous, "{x}: {parameter} after {previous}");
1162            previous = parameter;
1163        }
1164    }
1165
1166    #[test]
1167    fn an_unweighted_value_curve_has_its_control_points_at_the_thirds() {
1168        let curve = ValueBezier::unweighted(0.75, -0.25);
1169        let thirds = ValueBezier::weighted(1.0 / 3.0, 0.75, 2.0 / 3.0, -0.25);
1170        assert_eq!(curve.weights(), None);
1171        assert_eq!(thirds.weights(), Some((1.0 / 3.0, 2.0 / 3.0)));
1172        for step in 0..=64 {
1173            let progress = f64::from(step) / 64.0;
1174            let (plain, solved) = (
1175                curve.value(-1.0, 2.5, progress),
1176                thirds.value(-1.0, 2.5, progress),
1177            );
1178            assert!(
1179                (plain - solved).abs() < 1e-6,
1180                "{progress}: {plain} {solved}"
1181            );
1182        }
1183    }
1184
1185    #[test]
1186    fn the_ends_of_a_value_curve_are_its_two_values_exactly() {
1187        for curve in [
1188            ValueBezier::unweighted(3.0, -7.0),
1189            ValueBezier::weighted(0.0, 5.0, 1.0, 5.0),
1190            ValueBezier::weighted(1.136, -2.0, 0.909, 0.5),
1191        ] {
1192            for progress in [-4.0, 0.0] {
1193                assert_eq!(
1194                    curve.value(0.1, 0.7, progress).to_bits(),
1195                    f64::from(0.1_f32).to_bits()
1196                );
1197            }
1198            for progress in [1.0, 9.0] {
1199                assert_eq!(
1200                    curve.value(0.1, 0.7, progress).to_bits(),
1201                    f64::from(0.7_f32).to_bits()
1202                );
1203            }
1204        }
1205    }
1206
1207    #[test]
1208    fn a_value_curves_slope_is_its_rise_over_its_run() {
1209        let straight = ValueBezier::unweighted(1.0, -1.0);
1210        for progress in [0.0, 0.3, 1.0] {
1211            assert!((straight.slope(2.0, 5.0, progress) - 3.0).abs() < 1e-12);
1212        }
1213        let weighted = ValueBezier::weighted(0.25, 0.5, 0.5, -1.0);
1214        assert!((weighted.slope(0.0, 1.0, 0.0) - 0.5 / 0.25).abs() < 1e-9);
1215        assert!((weighted.slope(0.0, 1.0, 1.0) - 1.0 / 0.5).abs() < 1e-9);
1216        for step in 1..64 {
1217            let progress = f64::from(step) / 64.0;
1218            let numeric = (weighted.value(0.0, 1.0, progress + 1e-6)
1219                - weighted.value(0.0, 1.0, progress - 1e-6))
1220                / 2e-6;
1221            let slope = weighted.slope(0.0, 1.0, progress);
1222            assert!(
1223                (slope - numeric).abs() < 1e-4,
1224                "{progress}: {slope} {numeric}"
1225            );
1226        }
1227        let vertical = ValueBezier::weighted(0.0, 0.5, 1.0, 0.5);
1228        assert_eq!(vertical.slope(0.0, 1.0, 0.0).to_bits(), f64::MAX.to_bits());
1229        assert_eq!(
1230            vertical.slope(0.0, 1.0, 1.0).to_bits(),
1231            (-f64::MAX).to_bits()
1232        );
1233        let level = ValueBezier::weighted(0.0, 0.0, 1.0, 0.0);
1234        assert_eq!(level.slope(1.0, 1.0, 0.0).to_bits(), 0.0_f64.to_bits());
1235    }
1236
1237    #[test]
1238    fn a_value_curves_range_holds_every_value_and_is_reached() {
1239        let curves = [
1240            ValueBezier::unweighted(0.6, 0.6),
1241            ValueBezier::unweighted(-2.0, 3.0),
1242            ValueBezier::weighted(0.1, 4.0, 0.2, -3.0),
1243            ValueBezier::weighted(1.136, 0.0, 0.909, 0.0),
1244            ValueBezier::unweighted(0.0, 0.0),
1245        ];
1246        for curve in curves {
1247            for (from, to) in [(1.0, 1.0), (0.0, 1.0), (2.25, -3.5)] {
1248                let [low, high] = curve.range(from, to);
1249                let (mut least, mut greatest) = (f64::INFINITY, f64::NEG_INFINITY);
1250                for step in 0..=4096 {
1251                    let value = curve.value(from, to, f64::from(step) / 4096.0);
1252                    least = least.min(value);
1253                    greatest = greatest.max(value);
1254                }
1255                assert!(low <= least + 1e-9 && greatest <= high + 1e-9, "{curve:?}");
1256                assert!(
1257                    (low - least).abs() < 1e-5 && (high - greatest).abs() < 1e-5,
1258                    "{curve:?} {from}..{to}: {low}..{high} sampled {least}..{greatest}"
1259                );
1260            }
1261        }
1262    }
1263
1264    #[test]
1265    fn an_end_slope_is_the_first_control_leg_with_a_time_extent() {
1266        let near = |slope: f64, expected: f64| (slope - expected).abs() < 1e-12;
1267        let timing = CubicBezier::new(0.25, 0.5, 0.5, 0.75);
1268        assert!(near(timing.end_slope(false), 2.0));
1269        assert!(near(timing.end_slope(true), 0.5));
1270        let upright = CubicBezier::new(0.0, 0.5, 1.0, 0.25);
1271        assert!(near(upright.end_slope(false), 0.25));
1272        assert!(near(upright.end_slope(true), 0.5));
1273        assert!(near(
1274            CubicBezier::new(0.0, 0.5, 0.0, 0.25).end_slope(false),
1275            1.0
1276        ));
1277        assert!(near(
1278            CubicBezier::new(1.0, 0.5, 1.0, 0.25).end_slope(true),
1279            1.0
1280        ));
1281        assert!(near(
1282            CubicBezier::new(0.0, 0.0, 1.0, 1.0).end_slope(false),
1283            1.0
1284        ));
1285
1286        let value = ValueBezier::weighted(0.25, 1.5, 0.5, -3.0);
1287        assert!(near(value.end_slope(1.0, 3.0, false), 6.0));
1288        assert!(near(value.end_slope(1.0, 3.0, true), 6.0));
1289        let thirds = ValueBezier::unweighted(1.5, -3.0);
1290        assert!((thirds.end_slope(1.0, 3.0, false) - 4.5).abs() < 1e-9);
1291        assert!((thirds.end_slope(1.0, 3.0, true) - 9.0).abs() < 1e-9);
1292        assert!((thirds.end_slope(1.0, 3.0, false) - thirds.slope(1.0, 3.0, 0.0)).abs() < 1e-9);
1293        assert!((thirds.end_slope(1.0, 3.0, true) - thirds.slope(1.0, 3.0, 1.0)).abs() < 1e-9);
1294        let upright = ValueBezier::weighted(0.0, 1.5, 1.0, -3.0);
1295        assert!(near(upright.end_slope(1.0, 3.0, false), 2.0 - 3.0));
1296        assert!(near(upright.end_slope(1.0, 3.0, true), 2.0 - 1.5));
1297        let chord = ValueBezier::weighted(0.0, 1.5, 0.0, -3.0);
1298        assert!(near(chord.end_slope(1.0, 3.0, false), 2.0));
1299        assert!(near(
1300            ValueBezier::weighted(1.0, 1.5, 1.0, -3.0).end_slope(1.0, 3.0, true),
1301            2.0
1302        ));
1303    }
1304
1305    #[test]
1306    fn a_value_curve_needs_finite_offsets_and_both_time_coordinates() {
1307        assert!(ValueBezier::unweighted(1e30, -1e30).is_valid());
1308        assert!(ValueBezier::weighted(1.2, 0.0, 0.9, 0.0).is_valid());
1309        assert!(!ValueBezier::unweighted(f32::NAN, 0.0).is_valid());
1310        assert!(!ValueBezier::unweighted(0.0, f32::INFINITY).is_valid());
1311        assert!(!ValueBezier::weighted(1.2, 0.0, 0.2, 0.0).is_valid());
1312        let half = ValueBezier {
1313            x1: Some(0.5),
1314            ..ValueBezier::unweighted(0.0, 0.0)
1315        };
1316        assert!(!half.is_valid());
1317    }
1318
1319    #[test]
1320    fn the_wire_form_is_a_tagged_object() {
1321        let easing: Easing =
1322            serde_json::from_str(r#"{"type":"cubic_bezier","x1":0.42,"y1":0,"x2":0.58,"y2":1}"#)
1323                .expect("cubic bezier easing");
1324        assert_eq!(
1325            easing,
1326            Easing::CubicBezier(CubicBezier::new(0.42, 0.0, 0.58, 1.0))
1327        );
1328        let linear: Easing = serde_json::from_str(r#"{"type":"linear"}"#).expect("linear");
1329        assert_eq!(linear, Easing::Linear);
1330        assert!(serde_json::from_str::<Easing>(r#""linear""#).is_err());
1331        assert!(serde_json::from_str::<Easing>(r#"{"type":"linear","x1":0}"#).is_err());
1332    }
1333}