rcus-core 0.2.0

Core types for rcus: retained view tree, style, input, and the host bridge protocol
Documentation
//! Values that move between two points over a curve.
//!
//! There is no animation graph here and no registry: a host holds `Animated`
//! values the same way it holds any other state, reads them once per frame, and
//! tells the window how long it should keep waking. That keeps the arithmetic
//! testable without a window and keeps the render loop from needing to know what
//! is animating.

use std::time::{Duration, Instant};

/// How a value gets from one end to the other.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Curve {
    /// A cubic bezier easing curve, as `cubic-bezier(x1, y1, x2, y2)` in CSS.
    /// Used for anything that changes state.
    Ease([f32; 4]),
    /// A damped spring, integrated at a fixed rate. Used for anything a finger
    /// moved, because it settles rather than arriving.
    Spring { stiffness: f32, damping: f32 },
}

impl Default for Curve {
    fn default() -> Self {
        Curve::Ease([0.2, 0.0, 0.0, 1.0])
    }
}

impl Curve {
    /// Progress in `0.0..=1.0` for linear time in `0.0..=1.0`.
    pub fn sample(&self, t: f32, elapsed: Duration, duration: Duration) -> f32 {
        let t = t.clamp(0.0, 1.0);
        match self {
            Curve::Ease(control) => ease(*control, t),
            Curve::Spring { .. } => spring_progress(t, elapsed, duration),
        }
    }
}

/// Values a curve can interpolate. f32 covers geometry, u8 a step, and a colour
/// quadruple a tint.
pub trait Lerp: Copy {
    fn lerp(from: Self, to: Self, t: f32) -> Self;
}

impl Lerp for f32 {
    fn lerp(from: f32, to: f32, t: f32) -> f32 {
        from + (to - from) * t
    }
}

impl Lerp for u8 {
    fn lerp(from: u8, to: u8, t: f32) -> u8 {
        let value = f32::lerp(from as f32, to as f32, t);
        value.round().clamp(0.0, 255.0) as u8
    }
}

impl Lerp for [f32; 4] {
    fn lerp(from: [f32; 4], to: [f32; 4], t: f32) -> Self {
        [
            f32::lerp(from[0], to[0], t),
            f32::lerp(from[1], to[1], t),
            f32::lerp(from[2], to[2], t),
            f32::lerp(from[3], to[3], t),
        ]
    }
}

/// A value moving from `from` to `to` over `duration`, shaped by `curve`.
#[derive(Clone, Copy, Debug)]
pub struct Animated<T: Lerp + PartialEq> {
    from: T,
    to: T,
    current: T,
    start: Instant,
    duration: Duration,
    curve: Curve,
}

impl<T: Lerp + PartialEq + std::fmt::Debug> Animated<T> {
    /// Starts at `from` and moves to `to`. A zero duration jumps, which is what
    /// reduced motion wants: the end state, with no travel.
    pub fn new(from: T, to: T, start: Instant, duration: Duration, curve: Curve) -> Self {
        let mut animated = Self {
            from,
            to,
            current: from,
            start,
            duration,
            curve,
        };
        animated.current = animated.value_at(start);
        animated
    }

    pub fn curve(&self) -> Curve {
        self.curve
    }

    pub fn duration(&self) -> Duration {
        self.duration
    }

    /// Where the value ends up.
    pub fn target(&self) -> T {
        self.to
    }

    /// Recomputes and returns the value at `now`.
    pub fn value_at(&mut self, now: Instant) -> T {
        self.current = if self.duration.is_zero() {
            self.to
        } else {
            let elapsed = now.saturating_duration_since(self.start);
            let linear = (elapsed.as_secs_f32() / self.duration.as_secs_f32()).clamp(0.0, 1.0);
            let eased = self.curve.sample(linear, elapsed, self.duration);
            T::lerp(self.from, self.to, eased.clamp(0.0, 1.0))
        };
        self.current
    }

    /// The value as of the last `value_at`.
    pub fn value(&self) -> T {
        self.current
    }

    /// True once the value has stopped moving, at which point a host can stop
    /// asking for frames.
    pub fn settled(&self, now: Instant) -> bool {
        self.duration.is_zero() || now.saturating_duration_since(self.start) >= self.duration
    }

    /// When this value stops moving.
    pub fn ends_at(&self) -> Instant {
        self.start + self.duration
    }

    /// Jumps to the end, which is what switching on reduced motion mid-flight
    /// has to do: the value must arrive, not finish.
    pub fn settle(&mut self) {
        self.current = self.to;
    }
}

/// One axis of a cubic bezier with its endpoints pinned at 0 and 1, which is
/// what makes these the same control points CSS calls `cubic-bezier`.
fn bezier_axis(p1: f32, p2: f32, t: f32) -> f32 {
    let t = t.clamp(0.0, 1.0);
    let u = 1.0 - t;
    3.0 * u * u * t * p1 + 3.0 * u * t * t * p2 + t * t * t
}

/// Eased progress for linear time, by bisecting the curve's x axis and reading
/// y where it crosses.
///
/// Bisection rather than a closed form because a CSS easing curve may have two
/// y values for one x, and the branch a designer sees in their browser is the
/// one that is increasing.
fn ease(control: [f32; 4], x: f32) -> f32 {
    let x = x.clamp(0.0, 1.0);
    let (mut low, mut high) = (0.0f32, 1.0f32);
    for _ in 0..16 {
        let mid = (low + high) * 0.5;
        if bezier_axis(control[0], control[2], mid) < x {
            low = mid;
        } else {
            high = mid;
        }
    }
    bezier_axis(control[1], control[3], (low + high) * 0.5)
}

/// Integrates a damped spring at a fixed step so the result does not depend on
/// the frame rate, and reports how far along it is.
fn spring_progress(linear: f32, elapsed: Duration, duration: Duration) -> f32 {
    // A critically damped spring approaches its target without overshooting, so
    // progress is an exponential that starts fast and settles. Sampling it at a
    // fixed rate keeps the answer independent of the frame rate: `elapsed` is
    // quantised to the step before the exponential is evaluated.
    const STEP: Duration = Duration::from_micros(4167);
    let steps = elapsed.as_nanos() / STEP.as_nanos();
    let seconds = (steps as f64 * STEP.as_secs_f64()) as f32;
    let settle = (duration.as_secs_f32() / 4.0).max(f32::MIN_POSITIVE);
    if linear >= 1.0 {
        // A spring that has had its whole duration has arrived. Approaching 1
        // asymptotically forever would leave a value a hair short at exactly the
        // moment it is supposed to be done.
        return 1.0;
    }
    (1.0 - (-seconds / settle).exp()).clamp(0.0, 1.0)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at(base: Instant, ms: u64) -> Instant {
        base + Duration::from_millis(ms)
    }

    #[test]
    fn a_value_starts_where_it_was_going_from() {
        let now = Instant::now();
        let mut animated = Animated::new(
            10.0f32,
            20.0,
            now,
            Duration::from_millis(100),
            Curve::default(),
        );
        assert_eq!(animated.value_at(now), 10.0);
    }

    #[test]
    fn a_value_arrives_exactly_at_the_end() {
        let now = Instant::now();
        let mut animated = Animated::new(
            10.0f32,
            20.0,
            now,
            Duration::from_millis(100),
            Curve::default(),
        );
        assert_eq!(animated.value_at(at(now, 100)), 20.0);
        assert_eq!(animated.value_at(at(now, 5000)), 20.0);
    }

    #[test]
    fn a_value_half_way_through_is_half_way_between() {
        let now = Instant::now();
        let mut animated = Animated::new(
            0.0f32,
            100.0,
            now,
            Duration::from_millis(200),
            Curve::Ease([0.0, 0.0, 1.0, 1.0]),
        );
        let half = animated.value_at(at(now, 100));
        assert!((half - 50.0).abs() < 0.01, "got {half}");
    }

    #[test]
    fn an_ease_out_runs_ahead_of_linear_and_an_ease_in_behind_it() {
        let now = Instant::now();
        let mut ease_out = Animated::new(
            0.0f32,
            1.0,
            now,
            Duration::from_millis(100),
            Curve::Ease([0.2, 0.0, 0.0, 1.0]),
        );
        let mut linear = Animated::new(
            0.0f32,
            1.0,
            now,
            Duration::from_millis(100),
            Curve::Ease([0.0, 0.0, 1.0, 1.0]),
        );
        let at_quarter = at(now, 25);
        let ahead = ease_out.value_at(at_quarter);
        let level = linear.value_at(at_quarter);
        assert!(ahead > level, "an ease-out rises fast: {ahead} vs {level}");
        assert!(ease([0.4, 0.0, 1.0, 1.0], 0.25) < 0.25, "an ease-in lags");
        assert!(
            (ease([0.0, 0.0, 1.0, 1.0], 0.25) - 0.25).abs() < 1e-3,
            "the identity curve is linear, and bisection is approximate"
        );
    }

    #[test]
    fn a_curve_never_leaves_its_range() {
        for control in [
            [0.2f32, 0.0, 0.0, 1.0],
            [0.4, 0.0, 1.0, 1.0],
            [0.0, 0.0, 1.0, 1.0],
            [0.9, 0.1, 0.1, 0.9],
        ] {
            for step in 0..=20 {
                let value = ease(control, step as f32 / 20.0);
                assert!(
                    (0.0..=1.0).contains(&value),
                    "curve {control:?} at {step} gave {value}"
                );
            }
        }
    }

    #[test]
    fn a_zero_duration_jumps_and_is_never_settled_later() {
        let now = Instant::now();
        let mut animated = Animated::new(0.0f32, 9.0, now, Duration::ZERO, Curve::default());
        assert_eq!(animated.value_at(now), 9.0);
        assert!(animated.settled(now));
    }

    #[test]
    fn a_value_is_unsettled_until_it_arrives() {
        let now = Instant::now();
        let animated = Animated::new(
            0.0f32,
            1.0,
            now,
            Duration::from_millis(100),
            Curve::default(),
        );
        assert!(!animated.settled(at(now, 50)));
        assert!(animated.settled(at(now, 100)));
    }

    #[test]
    fn a_spring_settles_inside_its_duration_and_never_overshoots() {
        let now = Instant::now();
        let mut animated = Animated::new(
            0.0f32,
            1.0,
            now,
            Duration::from_millis(600),
            Curve::Spring {
                stiffness: 220.0,
                damping: 26.0,
            },
        );
        let mut previous = 0.0;
        for step in 0..60 {
            let value = animated.value_at(at(now, step * 10));
            assert!(
                value <= 1.0,
                "a critically damped spring does not overshoot, got {value}"
            );
            assert!(value >= previous - 0.001, "a spring does not go backwards");
            previous = value;
        }
        assert!(animated.settled(at(now, 600)));
        assert_eq!(animated.value_at(at(now, 600)), 1.0);
    }

    #[test]
    fn settling_early_arrives_rather_than_finishing() {
        let now = Instant::now();
        let mut animated = Animated::new(
            0.0f32,
            1.0,
            now,
            Duration::from_millis(1000),
            Curve::default(),
        );
        animated.value_at(at(now, 10));
        animated.settle();
        assert_eq!(animated.value(), 1.0, "reduce motion arriving mid-flight");
    }

    #[test]
    fn a_colour_channel_interpolates_as_a_number() {
        let mut animated = Animated::new(
            [0.0f32, 0.0, 0.0, 1.0],
            [1.0, 0.0, 0.0, 0.0],
            Instant::now(),
            Duration::from_millis(100),
            Curve::default(),
        );
        let now = Instant::now();
        let value = animated.value_at(now);
        assert!((value[0]).abs() < 0.01, "got {}", value[0]);
        assert!((value[3]).abs() > 0.99, "got {}", value[3]);
    }

    #[test]
    fn an_unsigned_channel_never_leaves_its_range() {
        let mut animated = Animated::new(
            0u8,
            255,
            Instant::now(),
            Duration::from_millis(100),
            Curve::default(),
        );
        let now = Instant::now();
        let mut previous = animated.value_at(now);
        for step in 1..10 {
            let value = animated.value_at(at(now, step * 10));
            assert!(value >= previous, "a channel climbs towards its end");
            previous = value;
        }
        assert_eq!(animated.value_at(at(now, 100)), 255);
    }

    #[test]
    fn a_value_knows_when_it_ends() {
        let now = Instant::now();
        let animated = Animated::new(
            0.0f32,
            1.0,
            now,
            Duration::from_millis(250),
            Curve::default(),
        );
        assert_eq!(animated.ends_at(), at(now, 250));
    }
}