Skip to main content

rcus_core/
anim.rs

1//! Values that move between two points over a curve.
2//!
3//! There is no animation graph here and no registry: a host holds `Animated`
4//! values the same way it holds any other state, reads them once per frame, and
5//! tells the window how long it should keep waking. That keeps the arithmetic
6//! testable without a window and keeps the render loop from needing to know what
7//! is animating.
8
9use std::time::{Duration, Instant};
10
11/// How a value gets from one end to the other.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub enum Curve {
14    /// A cubic bezier easing curve, as `cubic-bezier(x1, y1, x2, y2)` in CSS.
15    /// Used for anything that changes state.
16    Ease([f32; 4]),
17    /// A damped spring, integrated at a fixed rate. Used for anything a finger
18    /// moved, because it settles rather than arriving.
19    Spring { stiffness: f32, damping: f32 },
20}
21
22impl Default for Curve {
23    fn default() -> Self {
24        Curve::Ease([0.2, 0.0, 0.0, 1.0])
25    }
26}
27
28impl Curve {
29    /// Progress in `0.0..=1.0` for linear time in `0.0..=1.0`.
30    pub fn sample(&self, t: f32, elapsed: Duration, duration: Duration) -> f32 {
31        let t = t.clamp(0.0, 1.0);
32        match self {
33            Curve::Ease(control) => ease(*control, t),
34            Curve::Spring { .. } => spring_progress(t, elapsed, duration),
35        }
36    }
37}
38
39/// Values a curve can interpolate. f32 covers geometry, u8 a step, and a colour
40/// quadruple a tint.
41pub trait Lerp: Copy {
42    fn lerp(from: Self, to: Self, t: f32) -> Self;
43}
44
45impl Lerp for f32 {
46    fn lerp(from: f32, to: f32, t: f32) -> f32 {
47        from + (to - from) * t
48    }
49}
50
51impl Lerp for u8 {
52    fn lerp(from: u8, to: u8, t: f32) -> u8 {
53        let value = f32::lerp(from as f32, to as f32, t);
54        value.round().clamp(0.0, 255.0) as u8
55    }
56}
57
58impl Lerp for [f32; 4] {
59    fn lerp(from: [f32; 4], to: [f32; 4], t: f32) -> Self {
60        [
61            f32::lerp(from[0], to[0], t),
62            f32::lerp(from[1], to[1], t),
63            f32::lerp(from[2], to[2], t),
64            f32::lerp(from[3], to[3], t),
65        ]
66    }
67}
68
69/// A value moving from `from` to `to` over `duration`, shaped by `curve`.
70#[derive(Clone, Copy, Debug)]
71pub struct Animated<T: Lerp + PartialEq> {
72    from: T,
73    to: T,
74    current: T,
75    start: Instant,
76    duration: Duration,
77    curve: Curve,
78}
79
80impl<T: Lerp + PartialEq + std::fmt::Debug> Animated<T> {
81    /// Starts at `from` and moves to `to`. A zero duration jumps, which is what
82    /// reduced motion wants: the end state, with no travel.
83    pub fn new(from: T, to: T, start: Instant, duration: Duration, curve: Curve) -> Self {
84        let mut animated = Self {
85            from,
86            to,
87            current: from,
88            start,
89            duration,
90            curve,
91        };
92        animated.current = animated.value_at(start);
93        animated
94    }
95
96    pub fn curve(&self) -> Curve {
97        self.curve
98    }
99
100    pub fn duration(&self) -> Duration {
101        self.duration
102    }
103
104    /// Where the value ends up.
105    pub fn target(&self) -> T {
106        self.to
107    }
108
109    /// Recomputes and returns the value at `now`.
110    pub fn value_at(&mut self, now: Instant) -> T {
111        self.current = if self.duration.is_zero() {
112            self.to
113        } else {
114            let elapsed = now.saturating_duration_since(self.start);
115            let linear = (elapsed.as_secs_f32() / self.duration.as_secs_f32()).clamp(0.0, 1.0);
116            let eased = self.curve.sample(linear, elapsed, self.duration);
117            T::lerp(self.from, self.to, eased.clamp(0.0, 1.0))
118        };
119        self.current
120    }
121
122    /// The value as of the last `value_at`.
123    pub fn value(&self) -> T {
124        self.current
125    }
126
127    /// True once the value has stopped moving, at which point a host can stop
128    /// asking for frames.
129    pub fn settled(&self, now: Instant) -> bool {
130        self.duration.is_zero() || now.saturating_duration_since(self.start) >= self.duration
131    }
132
133    /// When this value stops moving.
134    pub fn ends_at(&self) -> Instant {
135        self.start + self.duration
136    }
137
138    /// Jumps to the end, which is what switching on reduced motion mid-flight
139    /// has to do: the value must arrive, not finish.
140    pub fn settle(&mut self) {
141        self.current = self.to;
142    }
143}
144
145/// One axis of a cubic bezier with its endpoints pinned at 0 and 1, which is
146/// what makes these the same control points CSS calls `cubic-bezier`.
147fn bezier_axis(p1: f32, p2: f32, t: f32) -> f32 {
148    let t = t.clamp(0.0, 1.0);
149    let u = 1.0 - t;
150    3.0 * u * u * t * p1 + 3.0 * u * t * t * p2 + t * t * t
151}
152
153/// Eased progress for linear time, by bisecting the curve's x axis and reading
154/// y where it crosses.
155///
156/// Bisection rather than a closed form because a CSS easing curve may have two
157/// y values for one x, and the branch a designer sees in their browser is the
158/// one that is increasing.
159fn ease(control: [f32; 4], x: f32) -> f32 {
160    let x = x.clamp(0.0, 1.0);
161    let (mut low, mut high) = (0.0f32, 1.0f32);
162    for _ in 0..16 {
163        let mid = (low + high) * 0.5;
164        if bezier_axis(control[0], control[2], mid) < x {
165            low = mid;
166        } else {
167            high = mid;
168        }
169    }
170    bezier_axis(control[1], control[3], (low + high) * 0.5)
171}
172
173/// Integrates a damped spring at a fixed step so the result does not depend on
174/// the frame rate, and reports how far along it is.
175fn spring_progress(linear: f32, elapsed: Duration, duration: Duration) -> f32 {
176    // A critically damped spring approaches its target without overshooting, so
177    // progress is an exponential that starts fast and settles. Sampling it at a
178    // fixed rate keeps the answer independent of the frame rate: `elapsed` is
179    // quantised to the step before the exponential is evaluated.
180    const STEP: Duration = Duration::from_micros(4167);
181    let steps = elapsed.as_nanos() / STEP.as_nanos();
182    let seconds = (steps as f64 * STEP.as_secs_f64()) as f32;
183    let settle = (duration.as_secs_f32() / 4.0).max(f32::MIN_POSITIVE);
184    if linear >= 1.0 {
185        // A spring that has had its whole duration has arrived. Approaching 1
186        // asymptotically forever would leave a value a hair short at exactly the
187        // moment it is supposed to be done.
188        return 1.0;
189    }
190    (1.0 - (-seconds / settle).exp()).clamp(0.0, 1.0)
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    fn at(base: Instant, ms: u64) -> Instant {
198        base + Duration::from_millis(ms)
199    }
200
201    #[test]
202    fn a_value_starts_where_it_was_going_from() {
203        let now = Instant::now();
204        let mut animated = Animated::new(
205            10.0f32,
206            20.0,
207            now,
208            Duration::from_millis(100),
209            Curve::default(),
210        );
211        assert_eq!(animated.value_at(now), 10.0);
212    }
213
214    #[test]
215    fn a_value_arrives_exactly_at_the_end() {
216        let now = Instant::now();
217        let mut animated = Animated::new(
218            10.0f32,
219            20.0,
220            now,
221            Duration::from_millis(100),
222            Curve::default(),
223        );
224        assert_eq!(animated.value_at(at(now, 100)), 20.0);
225        assert_eq!(animated.value_at(at(now, 5000)), 20.0);
226    }
227
228    #[test]
229    fn a_value_half_way_through_is_half_way_between() {
230        let now = Instant::now();
231        let mut animated = Animated::new(
232            0.0f32,
233            100.0,
234            now,
235            Duration::from_millis(200),
236            Curve::Ease([0.0, 0.0, 1.0, 1.0]),
237        );
238        let half = animated.value_at(at(now, 100));
239        assert!((half - 50.0).abs() < 0.01, "got {half}");
240    }
241
242    #[test]
243    fn an_ease_out_runs_ahead_of_linear_and_an_ease_in_behind_it() {
244        let now = Instant::now();
245        let mut ease_out = Animated::new(
246            0.0f32,
247            1.0,
248            now,
249            Duration::from_millis(100),
250            Curve::Ease([0.2, 0.0, 0.0, 1.0]),
251        );
252        let mut linear = Animated::new(
253            0.0f32,
254            1.0,
255            now,
256            Duration::from_millis(100),
257            Curve::Ease([0.0, 0.0, 1.0, 1.0]),
258        );
259        let at_quarter = at(now, 25);
260        let ahead = ease_out.value_at(at_quarter);
261        let level = linear.value_at(at_quarter);
262        assert!(ahead > level, "an ease-out rises fast: {ahead} vs {level}");
263        assert!(ease([0.4, 0.0, 1.0, 1.0], 0.25) < 0.25, "an ease-in lags");
264        assert!(
265            (ease([0.0, 0.0, 1.0, 1.0], 0.25) - 0.25).abs() < 1e-3,
266            "the identity curve is linear, and bisection is approximate"
267        );
268    }
269
270    #[test]
271    fn a_curve_never_leaves_its_range() {
272        for control in [
273            [0.2f32, 0.0, 0.0, 1.0],
274            [0.4, 0.0, 1.0, 1.0],
275            [0.0, 0.0, 1.0, 1.0],
276            [0.9, 0.1, 0.1, 0.9],
277        ] {
278            for step in 0..=20 {
279                let value = ease(control, step as f32 / 20.0);
280                assert!(
281                    (0.0..=1.0).contains(&value),
282                    "curve {control:?} at {step} gave {value}"
283                );
284            }
285        }
286    }
287
288    #[test]
289    fn a_zero_duration_jumps_and_is_never_settled_later() {
290        let now = Instant::now();
291        let mut animated = Animated::new(0.0f32, 9.0, now, Duration::ZERO, Curve::default());
292        assert_eq!(animated.value_at(now), 9.0);
293        assert!(animated.settled(now));
294    }
295
296    #[test]
297    fn a_value_is_unsettled_until_it_arrives() {
298        let now = Instant::now();
299        let animated = Animated::new(
300            0.0f32,
301            1.0,
302            now,
303            Duration::from_millis(100),
304            Curve::default(),
305        );
306        assert!(!animated.settled(at(now, 50)));
307        assert!(animated.settled(at(now, 100)));
308    }
309
310    #[test]
311    fn a_spring_settles_inside_its_duration_and_never_overshoots() {
312        let now = Instant::now();
313        let mut animated = Animated::new(
314            0.0f32,
315            1.0,
316            now,
317            Duration::from_millis(600),
318            Curve::Spring {
319                stiffness: 220.0,
320                damping: 26.0,
321            },
322        );
323        let mut previous = 0.0;
324        for step in 0..60 {
325            let value = animated.value_at(at(now, step * 10));
326            assert!(
327                value <= 1.0,
328                "a critically damped spring does not overshoot, got {value}"
329            );
330            assert!(value >= previous - 0.001, "a spring does not go backwards");
331            previous = value;
332        }
333        assert!(animated.settled(at(now, 600)));
334        assert_eq!(animated.value_at(at(now, 600)), 1.0);
335    }
336
337    #[test]
338    fn settling_early_arrives_rather_than_finishing() {
339        let now = Instant::now();
340        let mut animated = Animated::new(
341            0.0f32,
342            1.0,
343            now,
344            Duration::from_millis(1000),
345            Curve::default(),
346        );
347        animated.value_at(at(now, 10));
348        animated.settle();
349        assert_eq!(animated.value(), 1.0, "reduce motion arriving mid-flight");
350    }
351
352    #[test]
353    fn a_colour_channel_interpolates_as_a_number() {
354        let mut animated = Animated::new(
355            [0.0f32, 0.0, 0.0, 1.0],
356            [1.0, 0.0, 0.0, 0.0],
357            Instant::now(),
358            Duration::from_millis(100),
359            Curve::default(),
360        );
361        let now = Instant::now();
362        let value = animated.value_at(now);
363        assert!((value[0]).abs() < 0.01, "got {}", value[0]);
364        assert!((value[3]).abs() > 0.99, "got {}", value[3]);
365    }
366
367    #[test]
368    fn an_unsigned_channel_never_leaves_its_range() {
369        let mut animated = Animated::new(
370            0u8,
371            255,
372            Instant::now(),
373            Duration::from_millis(100),
374            Curve::default(),
375        );
376        let now = Instant::now();
377        let mut previous = animated.value_at(now);
378        for step in 1..10 {
379            let value = animated.value_at(at(now, step * 10));
380            assert!(value >= previous, "a channel climbs towards its end");
381            previous = value;
382        }
383        assert_eq!(animated.value_at(at(now, 100)), 255);
384    }
385
386    #[test]
387    fn a_value_knows_when_it_ends() {
388        let now = Instant::now();
389        let animated = Animated::new(
390            0.0f32,
391            1.0,
392            now,
393            Duration::from_millis(250),
394            Curve::default(),
395        );
396        assert_eq!(animated.ends_at(), at(now, 250));
397    }
398}