use std::time::{Duration, Instant};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Curve {
Ease([f32; 4]),
Spring { stiffness: f32, damping: f32 },
}
impl Default for Curve {
fn default() -> Self {
Curve::Ease([0.2, 0.0, 0.0, 1.0])
}
}
impl Curve {
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),
}
}
}
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),
]
}
}
#[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> {
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
}
pub fn target(&self) -> T {
self.to
}
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
}
pub fn value(&self) -> T {
self.current
}
pub fn settled(&self, now: Instant) -> bool {
self.duration.is_zero() || now.saturating_duration_since(self.start) >= self.duration
}
pub fn ends_at(&self) -> Instant {
self.start + self.duration
}
pub fn settle(&mut self) {
self.current = self.to;
}
}
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
}
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)
}
fn spring_progress(linear: f32, elapsed: Duration, duration: Duration) -> f32 {
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 {
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));
}
}