Skip to main content

alpha2_model/
easing_presets.rs

1//! Easings made from a name, a function or a spring. Each is an [`Easing`] the evaluator
2//! already knows, so no curve family adds arithmetic to it.
3
4use crate::{CubicBezier, Easing, EasingPoint, MAX_EASING_POINTS, StepPosition, Steps};
5use std::f64::consts::PI;
6
7/// How close a table made for a named easing stays to its function.
8pub const PRESET_TOLERANCE: f64 = 5e-4;
9
10/// The most points a table made for a named easing has; the longest is `ease-in-out-bounce`.
11pub const PRESET_POINTS: usize = 192;
12
13const NARROWEST_PIECE: f64 = 1.0 / 65_536.0;
14
15/// The ten families of [`named`], each with an `in`, an `out` and an `in-out` form.
16pub const EASING_FAMILIES: [&str; 10] = [
17    "sine", "quad", "cubic", "quart", "quint", "expo", "circ", "back", "elastic", "bounce",
18];
19
20/// Every name [`named`] knows, in a fixed order: the CSS names, the two step names, then each
21/// family's `ease-in-`, `ease-out-` and `ease-in-out-` form.
22#[must_use]
23pub fn easing_names() -> Vec<String> {
24    [
25        "linear",
26        "ease",
27        "ease-in",
28        "ease-out",
29        "ease-in-out",
30        "step-start",
31        "step-end",
32    ]
33    .into_iter()
34    .map(str::to_owned)
35    .chain(EASING_FAMILIES.iter().flat_map(|family| {
36        ["in", "out", "in-out"].map(|direction| format!("ease-{direction}-{family}"))
37    }))
38    .collect()
39}
40
41const BACK: f64 = 1.701_58;
42
43fn bounce_out(t: f64) -> f64 {
44    const STRENGTH: f64 = 7.5625;
45    const SPAN: f64 = 2.75;
46    if t < 1.0 / SPAN {
47        STRENGTH * t * t
48    } else if t < 2.0 / SPAN {
49        let t = t - 1.5 / SPAN;
50        STRENGTH * t * t + 0.75
51    } else if t < 2.5 / SPAN {
52        let t = t - 2.25 / SPAN;
53        STRENGTH * t * t + 0.9375
54    } else {
55        let t = t - 2.625 / SPAN;
56        STRENGTH * t * t + 0.984_375
57    }
58}
59
60fn penner(family: &str, direction: usize, t: f64) -> f64 {
61    let power = |exponent: f64| match direction {
62        0 => libm::pow(t, exponent),
63        1 => 1.0 - libm::pow(1.0 - t, exponent),
64        _ if t < 0.5 => libm::pow(2.0 * t, exponent) / 2.0,
65        _ => 1.0 - libm::pow(2.0 - 2.0 * t, exponent) / 2.0,
66    };
67    match (family, direction) {
68        ("sine", 0) => 1.0 - libm::cos(t * PI / 2.0),
69        ("sine", 1) => libm::sin(t * PI / 2.0),
70        ("sine", _) => -(libm::cos(PI * t) - 1.0) / 2.0,
71        ("quad", _) => power(2.0),
72        ("cubic", _) => power(3.0),
73        ("quart", _) => power(4.0),
74        ("quint", _) => power(5.0),
75        ("expo", 0) => libm::pow(2.0, 10.0 * t - 10.0),
76        ("expo", 1) => 1.0 - libm::pow(2.0, -10.0 * t),
77        ("expo", _) if t < 0.5 => libm::pow(2.0, 20.0 * t - 10.0) / 2.0,
78        ("expo", _) => (2.0 - libm::pow(2.0, 10.0 - 20.0 * t)) / 2.0,
79        ("circ", 0) => 1.0 - libm::sqrt(1.0 - t * t),
80        ("circ", 1) => libm::sqrt(1.0 - (t - 1.0) * (t - 1.0)),
81        ("circ", _) if t < 0.5 => (1.0 - libm::sqrt(1.0 - 4.0 * t * t)) / 2.0,
82        ("circ", _) => f64::midpoint(libm::sqrt(1.0 - (2.0 - 2.0 * t) * (2.0 - 2.0 * t)), 1.0),
83        ("back", 0) => (BACK + 1.0) * t * t * t - BACK * t * t,
84        ("back", 1) => {
85            let t = t - 1.0;
86            1.0 + (BACK + 1.0) * t * t * t + BACK * t * t
87        }
88        ("back", _) => {
89            let overshoot = BACK * 1.525;
90            if t < 0.5 {
91                let t = 2.0 * t;
92                t * t * ((overshoot + 1.0) * t - overshoot) / 2.0
93            } else {
94                let t = 2.0 * t - 2.0;
95                f64::midpoint(t * t * ((overshoot + 1.0) * t + overshoot), 2.0)
96            }
97        }
98        ("elastic", 0) => {
99            -libm::pow(2.0, 10.0 * t - 10.0) * libm::sin((10.0 * t - 10.75) * (2.0 * PI / 3.0))
100        }
101        ("elastic", 1) => {
102            libm::pow(2.0, -10.0 * t) * libm::sin((10.0 * t - 0.75) * (2.0 * PI / 3.0)) + 1.0
103        }
104        ("elastic", _) => {
105            let wave = libm::sin((20.0 * t - 11.125) * (2.0 * PI / 4.5));
106            if t < 0.5 {
107                -(libm::pow(2.0, 20.0 * t - 10.0) * wave) / 2.0
108            } else {
109                libm::pow(2.0, 10.0 - 20.0 * t) * wave / 2.0 + 1.0
110            }
111        }
112        ("bounce", 0) => 1.0 - bounce_out(1.0 - t),
113        ("bounce", 1) => bounce_out(t),
114        ("bounce", _) if t < 0.5 => (1.0 - bounce_out(1.0 - 2.0 * t)) / 2.0,
115        ("bounce", _) => f64::midpoint(1.0, bounce_out(2.0 * t - 1.0)),
116        _ => t,
117    }
118}
119
120/// Penner's easing equation for a family name of [`named`], such as `ease-out-bounce`, at
121/// `progress` (clamped to `0..=1`): what the name's curve or table follows. `None` for any
122/// other name.
123#[must_use]
124pub fn easing_equation(name: &str, progress: f64) -> Option<f64> {
125    let (family, direction) = family_of(name)?;
126    Some(if progress <= 0.0 {
127        0.0
128    } else if progress >= 1.0 {
129        1.0
130    } else {
131        penner(family, direction, progress)
132    })
133}
134
135fn family_of(name: &str) -> Option<(&'static str, usize)> {
136    let rest = name.strip_prefix("ease-")?;
137    let (direction, family) = rest
138        .strip_prefix("in-out-")
139        .map(|family| (2, family))
140        .or_else(|| rest.strip_prefix("in-").map(|family| (0, family)))
141        .or_else(|| rest.strip_prefix("out-").map(|family| (1, family)))?;
142    EASING_FAMILIES
143        .iter()
144        .find(|known| **known == family)
145        .map(|known| (*known, direction))
146}
147
148/// The easing a name stands for: `linear`, the CSS names (`ease`, `ease-in`, `ease-out`,
149/// `ease-in-out`), `step-start`, `step-end`, and
150/// `ease-{in,out,in-out}-{sine,quad,cubic,quart,quint,expo,circ,back,elastic,bounce}`.
151///
152/// The in and out forms of `quad`, `cubic` and `back` are exact cubic Bezier curves. Every
153/// other family form is a table within [`PRESET_TOLERANCE`] of Penner's equation, of at most
154/// [`PRESET_POINTS`] points, the same on every platform.
155#[must_use]
156pub fn named(name: &str) -> Option<Easing> {
157    const THIRD: f32 = 1.0 / 3.0;
158    let bezier = |y1: f64, y2: f64| {
159        #[expect(
160            clippy::cast_possible_truncation,
161            reason = "handles are stored as `f32`"
162        )]
163        Easing::CubicBezier(CubicBezier::new(THIRD, y1 as f32, 2.0 * THIRD, y2 as f32))
164    };
165    let css = |x1, y1, x2, y2| Easing::CubicBezier(CubicBezier::new(x1, y1, x2, y2));
166    let step = |position| Easing::Steps(Steps { count: 1, position });
167    Some(match name {
168        "linear" => Easing::Linear,
169        "ease" => css(0.25, 0.1, 0.25, 1.0),
170        "ease-in" => css(0.42, 0.0, 1.0, 1.0),
171        "ease-out" => css(0.0, 0.0, 0.58, 1.0),
172        "ease-in-out" => css(0.42, 0.0, 0.58, 1.0),
173        "step-start" => step(StepPosition::Start),
174        "step-end" => step(StepPosition::End),
175        "ease-in-quad" => bezier(0.0, 1.0 / 3.0),
176        "ease-out-quad" => bezier(2.0 / 3.0, 1.0),
177        "ease-in-cubic" => bezier(0.0, 0.0),
178        "ease-out-cubic" => bezier(1.0, 1.0),
179        "ease-in-back" => bezier(0.0, -BACK / 3.0),
180        "ease-out-back" => bezier(1.0 + BACK / 3.0, 1.0),
181        other => {
182            family_of(other)?;
183            sampled(
184                |progress| easing_equation(other, progress).unwrap_or(progress),
185                0.9 * PRESET_TOLERANCE,
186                PRESET_POINTS,
187            )
188        }
189    })
190}
191
192fn piece_error(function: &impl Fn(f64) -> f64, a: f64, b: f64) -> f64 {
193    let (ya, yb) = (function(a), function(b));
194    [0.25, 0.5, 0.75]
195        .into_iter()
196        .map(|part| {
197            let x = a + (b - a) * part;
198            (function(x) - (ya + (yb - ya) * part)).abs()
199        })
200        .fold(0.0, f64::max)
201}
202
203/// `function`, which runs from 0 at 0 to 1 at 1, as a `points` easing: straight lines within
204/// `tolerance` of it at the quarter points of every piece, through at most `max_points` points
205/// (and at most [`MAX_EASING_POINTS`]).
206///
207/// The piece furthest from the function is halved, the earliest on a tie, until every piece is
208/// within `tolerance` or narrower than 1/65536, or the points run out. The order is fixed and
209/// every point's `x` is a dyadic fraction, so the table is the same wherever `function` gives
210/// the same values.
211#[must_use]
212pub fn sampled(function: impl Fn(f64) -> f64, tolerance: f64, max_points: usize) -> Easing {
213    let mut xs = vec![0.0, 1.0];
214    let mut errors = vec![piece_error(&function, 0.0, 1.0)];
215    while xs.len() - 2 < max_points.min(MAX_EASING_POINTS) {
216        let (worst, error) = errors.iter().copied().enumerate().fold(
217            (0, f64::NEG_INFINITY),
218            |best, (index, error)| {
219                if error > best.1 { (index, error) } else { best }
220            },
221        );
222        let (a, b) = (xs[worst], xs[worst + 1]);
223        let middle = f64::midpoint(a, b);
224        if error.partial_cmp(&tolerance) != Some(std::cmp::Ordering::Greater) {
225            break;
226        }
227        let measure = |a: f64, b: f64| {
228            if b - a > NARROWEST_PIECE {
229                piece_error(&function, a, b)
230            } else {
231                0.0
232            }
233        };
234        xs.insert(worst + 1, middle);
235        errors[worst] = measure(a, middle);
236        errors.insert(worst + 1, measure(middle, b));
237    }
238    #[expect(
239        clippy::cast_possible_truncation,
240        reason = "easing points are stored as `f32`"
241    )]
242    let points = xs[1..xs.len() - 1]
243        .iter()
244        .map(|x| EasingPoint {
245            x: *x as f32,
246            y: function(*x).clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32,
247        })
248        .filter(|point| point.y.is_finite())
249        .collect();
250    Easing::Points { points }
251}
252
253/// A mass on a damped spring, released at rest position 0 toward 1.
254#[derive(Copy, Clone, Debug, PartialEq)]
255pub struct Spring {
256    /// The mass, positive.
257    pub mass: f64,
258    /// The spring constant, positive.
259    pub stiffness: f64,
260    /// The damping coefficient, positive.
261    pub damping: f64,
262    /// The velocity at the start, in distances to the target per second.
263    pub velocity: f64,
264}
265
266/// A spring's motion as an easing, and how long it lasts.
267#[derive(Clone, Debug, PartialEq)]
268pub struct SpringEasing {
269    /// The motion from 0 to 1 over `settle_seconds`, as a table.
270    pub easing: Easing,
271    /// When the spring last is 0.001 or more from 1.
272    pub settle_seconds: f64,
273}
274
275/// How long a spring may take to settle.
276pub const MAX_SPRING_SECONDS: f64 = 60.0;
277
278const SETTLED: f64 = 0.001;
279const SETTLE_STEPS: u32 = 1000;
280
281impl Spring {
282    fn is_valid(self) -> bool {
283        [self.mass, self.stiffness, self.damping]
284            .iter()
285            .all(|value| value.is_finite() && *value > 0.0)
286            && self.velocity.is_finite()
287    }
288
289    fn shape(self) -> (f64, f64) {
290        (
291            libm::sqrt(self.stiffness / self.mass),
292            self.damping / (2.0 * libm::sqrt(self.stiffness * self.mass)),
293        )
294    }
295
296    fn decay(self) -> f64 {
297        let (frequency, ratio) = self.shape();
298        if ratio > 1.0 {
299            frequency * (ratio - libm::sqrt(ratio * ratio - 1.0))
300        } else {
301            frequency * ratio
302        }
303    }
304
305    /// The position at `seconds`: the response of a damped harmonic oscillator to a unit step,
306    /// from position 0 with the spring's velocity.
307    #[must_use]
308    pub fn position(self, seconds: f64) -> f64 {
309        let (frequency, ratio) = self.shape();
310        let t = seconds.max(0.0);
311        let left = if ratio < 1.0 {
312            let damped = frequency * libm::sqrt(1.0 - ratio * ratio);
313            libm::exp(-ratio * frequency * t)
314                * (libm::cos(damped * t)
315                    + (ratio * frequency - self.velocity) / damped * libm::sin(damped * t))
316        } else if ratio > 1.0 {
317            let root = libm::sqrt(ratio * ratio - 1.0);
318            let (slow, fast) = (-frequency * (ratio - root), -frequency * (ratio + root));
319            let first = (-self.velocity - fast) / (slow - fast);
320            first * libm::exp(slow * t) + (1.0 - first) * libm::exp(fast * t)
321        } else {
322            libm::exp(-frequency * t) * (1.0 + (frequency - self.velocity) * t)
323        };
324        1.0 - left
325    }
326
327    fn settle_seconds(self) -> Option<f64> {
328        let horizon = 16.0 / self.decay();
329        if !(horizon.is_finite() && horizon > 0.0) {
330            return None;
331        }
332        let step = horizon / f64::from(SETTLE_STEPS);
333        let away = |index: u32| (self.position(f64::from(index) * step) - 1.0).abs() >= SETTLED;
334        if away(SETTLE_STEPS) {
335            return None;
336        }
337        let last = (0..SETTLE_STEPS).rev().find(|index| away(*index))?;
338        let seconds = f64::from(last + 1) * step;
339        (seconds <= MAX_SPRING_SECONDS).then_some(seconds)
340    }
341}
342
343/// A spring's motion from 0 to 1 over the time it takes to stay within 0.001 of 1, as a table
344/// within `tolerance` of it of at most `max_points` points ([`sampled`]).
345///
346/// `None` for a mass, stiffness or damping that is not positive and finite, a velocity that is
347/// not finite, or a spring that takes more than [`MAX_SPRING_SECONDS`] to settle.
348#[must_use]
349pub fn spring(spring: Spring, tolerance: f64, max_points: usize) -> Option<SpringEasing> {
350    if !spring.is_valid() {
351        return None;
352    }
353    let settle_seconds = spring.settle_seconds()?;
354    let easing = sampled(
355        |progress| {
356            if progress >= 1.0 {
357                1.0
358            } else {
359                spring.position(progress * settle_seconds)
360            }
361        },
362        tolerance,
363        max_points,
364    );
365    Some(SpringEasing {
366        easing,
367        settle_seconds,
368    })
369}
370
371#[cfg(test)]
372#[path = "easing_presets_tests.rs"]
373mod tests;