alpha2-model 0.10.0

Versioned project and timeline model for alpha2.
Documentation
//! Easings made from a name, a function or a spring. Each is an [`Easing`] the evaluator
//! already knows, so no curve family adds arithmetic to it.

use crate::{CubicBezier, Easing, EasingPoint, MAX_EASING_POINTS, StepPosition, Steps};
use std::f64::consts::PI;

/// How close a table made for a named easing stays to its function.
pub const PRESET_TOLERANCE: f64 = 5e-4;

/// The most points a table made for a named easing has; the longest is `ease-in-out-bounce`.
pub const PRESET_POINTS: usize = 192;

const NARROWEST_PIECE: f64 = 1.0 / 65_536.0;

/// The ten families of [`named`], each with an `in`, an `out` and an `in-out` form.
pub const EASING_FAMILIES: [&str; 10] = [
    "sine", "quad", "cubic", "quart", "quint", "expo", "circ", "back", "elastic", "bounce",
];

/// Every name [`named`] knows, in a fixed order: the CSS names, the two step names, then each
/// family's `ease-in-`, `ease-out-` and `ease-in-out-` form.
#[must_use]
pub fn easing_names() -> Vec<String> {
    [
        "linear",
        "ease",
        "ease-in",
        "ease-out",
        "ease-in-out",
        "step-start",
        "step-end",
    ]
    .into_iter()
    .map(str::to_owned)
    .chain(EASING_FAMILIES.iter().flat_map(|family| {
        ["in", "out", "in-out"].map(|direction| format!("ease-{direction}-{family}"))
    }))
    .collect()
}

const BACK: f64 = 1.701_58;

fn bounce_out(t: f64) -> f64 {
    const STRENGTH: f64 = 7.5625;
    const SPAN: f64 = 2.75;
    if t < 1.0 / SPAN {
        STRENGTH * t * t
    } else if t < 2.0 / SPAN {
        let t = t - 1.5 / SPAN;
        STRENGTH * t * t + 0.75
    } else if t < 2.5 / SPAN {
        let t = t - 2.25 / SPAN;
        STRENGTH * t * t + 0.9375
    } else {
        let t = t - 2.625 / SPAN;
        STRENGTH * t * t + 0.984_375
    }
}

fn penner(family: &str, direction: usize, t: f64) -> f64 {
    let power = |exponent: f64| match direction {
        0 => libm::pow(t, exponent),
        1 => 1.0 - libm::pow(1.0 - t, exponent),
        _ if t < 0.5 => libm::pow(2.0 * t, exponent) / 2.0,
        _ => 1.0 - libm::pow(2.0 - 2.0 * t, exponent) / 2.0,
    };
    match (family, direction) {
        ("sine", 0) => 1.0 - libm::cos(t * PI / 2.0),
        ("sine", 1) => libm::sin(t * PI / 2.0),
        ("sine", _) => -(libm::cos(PI * t) - 1.0) / 2.0,
        ("quad", _) => power(2.0),
        ("cubic", _) => power(3.0),
        ("quart", _) => power(4.0),
        ("quint", _) => power(5.0),
        ("expo", 0) => libm::pow(2.0, 10.0 * t - 10.0),
        ("expo", 1) => 1.0 - libm::pow(2.0, -10.0 * t),
        ("expo", _) if t < 0.5 => libm::pow(2.0, 20.0 * t - 10.0) / 2.0,
        ("expo", _) => (2.0 - libm::pow(2.0, 10.0 - 20.0 * t)) / 2.0,
        ("circ", 0) => 1.0 - libm::sqrt(1.0 - t * t),
        ("circ", 1) => libm::sqrt(1.0 - (t - 1.0) * (t - 1.0)),
        ("circ", _) if t < 0.5 => (1.0 - libm::sqrt(1.0 - 4.0 * t * t)) / 2.0,
        ("circ", _) => f64::midpoint(libm::sqrt(1.0 - (2.0 - 2.0 * t) * (2.0 - 2.0 * t)), 1.0),
        ("back", 0) => (BACK + 1.0) * t * t * t - BACK * t * t,
        ("back", 1) => {
            let t = t - 1.0;
            1.0 + (BACK + 1.0) * t * t * t + BACK * t * t
        }
        ("back", _) => {
            let overshoot = BACK * 1.525;
            if t < 0.5 {
                let t = 2.0 * t;
                t * t * ((overshoot + 1.0) * t - overshoot) / 2.0
            } else {
                let t = 2.0 * t - 2.0;
                f64::midpoint(t * t * ((overshoot + 1.0) * t + overshoot), 2.0)
            }
        }
        ("elastic", 0) => {
            -libm::pow(2.0, 10.0 * t - 10.0) * libm::sin((10.0 * t - 10.75) * (2.0 * PI / 3.0))
        }
        ("elastic", 1) => {
            libm::pow(2.0, -10.0 * t) * libm::sin((10.0 * t - 0.75) * (2.0 * PI / 3.0)) + 1.0
        }
        ("elastic", _) => {
            let wave = libm::sin((20.0 * t - 11.125) * (2.0 * PI / 4.5));
            if t < 0.5 {
                -(libm::pow(2.0, 20.0 * t - 10.0) * wave) / 2.0
            } else {
                libm::pow(2.0, 10.0 - 20.0 * t) * wave / 2.0 + 1.0
            }
        }
        ("bounce", 0) => 1.0 - bounce_out(1.0 - t),
        ("bounce", 1) => bounce_out(t),
        ("bounce", _) if t < 0.5 => (1.0 - bounce_out(1.0 - 2.0 * t)) / 2.0,
        ("bounce", _) => f64::midpoint(1.0, bounce_out(2.0 * t - 1.0)),
        _ => t,
    }
}

/// Penner's easing equation for a family name of [`named`], such as `ease-out-bounce`, at
/// `progress` (clamped to `0..=1`): what the name's curve or table follows. `None` for any
/// other name.
#[must_use]
pub fn easing_equation(name: &str, progress: f64) -> Option<f64> {
    let (family, direction) = family_of(name)?;
    Some(if progress <= 0.0 {
        0.0
    } else if progress >= 1.0 {
        1.0
    } else {
        penner(family, direction, progress)
    })
}

fn family_of(name: &str) -> Option<(&'static str, usize)> {
    let rest = name.strip_prefix("ease-")?;
    let (direction, family) = rest
        .strip_prefix("in-out-")
        .map(|family| (2, family))
        .or_else(|| rest.strip_prefix("in-").map(|family| (0, family)))
        .or_else(|| rest.strip_prefix("out-").map(|family| (1, family)))?;
    EASING_FAMILIES
        .iter()
        .find(|known| **known == family)
        .map(|known| (*known, direction))
}

/// The easing a name stands for: `linear`, the CSS names (`ease`, `ease-in`, `ease-out`,
/// `ease-in-out`), `step-start`, `step-end`, and
/// `ease-{in,out,in-out}-{sine,quad,cubic,quart,quint,expo,circ,back,elastic,bounce}`.
///
/// The in and out forms of `quad`, `cubic` and `back` are exact cubic Bezier curves. Every
/// other family form is a table within [`PRESET_TOLERANCE`] of Penner's equation, of at most
/// [`PRESET_POINTS`] points, the same on every platform.
#[must_use]
pub fn named(name: &str) -> Option<Easing> {
    const THIRD: f32 = 1.0 / 3.0;
    let bezier = |y1: f64, y2: f64| {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "handles are stored as `f32`"
        )]
        Easing::CubicBezier(CubicBezier::new(THIRD, y1 as f32, 2.0 * THIRD, y2 as f32))
    };
    let css = |x1, y1, x2, y2| Easing::CubicBezier(CubicBezier::new(x1, y1, x2, y2));
    let step = |position| Easing::Steps(Steps { count: 1, position });
    Some(match name {
        "linear" => Easing::Linear,
        "ease" => css(0.25, 0.1, 0.25, 1.0),
        "ease-in" => css(0.42, 0.0, 1.0, 1.0),
        "ease-out" => css(0.0, 0.0, 0.58, 1.0),
        "ease-in-out" => css(0.42, 0.0, 0.58, 1.0),
        "step-start" => step(StepPosition::Start),
        "step-end" => step(StepPosition::End),
        "ease-in-quad" => bezier(0.0, 1.0 / 3.0),
        "ease-out-quad" => bezier(2.0 / 3.0, 1.0),
        "ease-in-cubic" => bezier(0.0, 0.0),
        "ease-out-cubic" => bezier(1.0, 1.0),
        "ease-in-back" => bezier(0.0, -BACK / 3.0),
        "ease-out-back" => bezier(1.0 + BACK / 3.0, 1.0),
        other => {
            family_of(other)?;
            sampled(
                |progress| easing_equation(other, progress).unwrap_or(progress),
                0.9 * PRESET_TOLERANCE,
                PRESET_POINTS,
            )
        }
    })
}

fn piece_error(function: &impl Fn(f64) -> f64, a: f64, b: f64) -> f64 {
    let (ya, yb) = (function(a), function(b));
    [0.25, 0.5, 0.75]
        .into_iter()
        .map(|part| {
            let x = a + (b - a) * part;
            (function(x) - (ya + (yb - ya) * part)).abs()
        })
        .fold(0.0, f64::max)
}

/// `function`, which runs from 0 at 0 to 1 at 1, as a `points` easing: straight lines within
/// `tolerance` of it at the quarter points of every piece, through at most `max_points` points
/// (and at most [`MAX_EASING_POINTS`]).
///
/// The piece furthest from the function is halved, the earliest on a tie, until every piece is
/// within `tolerance` or narrower than 1/65536, or the points run out. The order is fixed and
/// every point's `x` is a dyadic fraction, so the table is the same wherever `function` gives
/// the same values.
#[must_use]
pub fn sampled(function: impl Fn(f64) -> f64, tolerance: f64, max_points: usize) -> Easing {
    let mut xs = vec![0.0, 1.0];
    let mut errors = vec![piece_error(&function, 0.0, 1.0)];
    while xs.len() - 2 < max_points.min(MAX_EASING_POINTS) {
        let (worst, error) = errors.iter().copied().enumerate().fold(
            (0, f64::NEG_INFINITY),
            |best, (index, error)| {
                if error > best.1 { (index, error) } else { best }
            },
        );
        let (a, b) = (xs[worst], xs[worst + 1]);
        let middle = f64::midpoint(a, b);
        if error.partial_cmp(&tolerance) != Some(std::cmp::Ordering::Greater) {
            break;
        }
        let measure = |a: f64, b: f64| {
            if b - a > NARROWEST_PIECE {
                piece_error(&function, a, b)
            } else {
                0.0
            }
        };
        xs.insert(worst + 1, middle);
        errors[worst] = measure(a, middle);
        errors.insert(worst + 1, measure(middle, b));
    }
    #[expect(
        clippy::cast_possible_truncation,
        reason = "easing points are stored as `f32`"
    )]
    let points = xs[1..xs.len() - 1]
        .iter()
        .map(|x| EasingPoint {
            x: *x as f32,
            y: function(*x).clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32,
        })
        .filter(|point| point.y.is_finite())
        .collect();
    Easing::Points { points }
}

/// A mass on a damped spring, released at rest position 0 toward 1.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Spring {
    /// The mass, positive.
    pub mass: f64,
    /// The spring constant, positive.
    pub stiffness: f64,
    /// The damping coefficient, positive.
    pub damping: f64,
    /// The velocity at the start, in distances to the target per second.
    pub velocity: f64,
}

/// A spring's motion as an easing, and how long it lasts.
#[derive(Clone, Debug, PartialEq)]
pub struct SpringEasing {
    /// The motion from 0 to 1 over `settle_seconds`, as a table.
    pub easing: Easing,
    /// When the spring last is 0.001 or more from 1.
    pub settle_seconds: f64,
}

/// How long a spring may take to settle.
pub const MAX_SPRING_SECONDS: f64 = 60.0;

const SETTLED: f64 = 0.001;
const SETTLE_STEPS: u32 = 1000;

impl Spring {
    fn is_valid(self) -> bool {
        [self.mass, self.stiffness, self.damping]
            .iter()
            .all(|value| value.is_finite() && *value > 0.0)
            && self.velocity.is_finite()
    }

    fn shape(self) -> (f64, f64) {
        (
            libm::sqrt(self.stiffness / self.mass),
            self.damping / (2.0 * libm::sqrt(self.stiffness * self.mass)),
        )
    }

    fn decay(self) -> f64 {
        let (frequency, ratio) = self.shape();
        if ratio > 1.0 {
            frequency * (ratio - libm::sqrt(ratio * ratio - 1.0))
        } else {
            frequency * ratio
        }
    }

    /// The position at `seconds`: the response of a damped harmonic oscillator to a unit step,
    /// from position 0 with the spring's velocity.
    #[must_use]
    pub fn position(self, seconds: f64) -> f64 {
        let (frequency, ratio) = self.shape();
        let t = seconds.max(0.0);
        let left = if ratio < 1.0 {
            let damped = frequency * libm::sqrt(1.0 - ratio * ratio);
            libm::exp(-ratio * frequency * t)
                * (libm::cos(damped * t)
                    + (ratio * frequency - self.velocity) / damped * libm::sin(damped * t))
        } else if ratio > 1.0 {
            let root = libm::sqrt(ratio * ratio - 1.0);
            let (slow, fast) = (-frequency * (ratio - root), -frequency * (ratio + root));
            let first = (-self.velocity - fast) / (slow - fast);
            first * libm::exp(slow * t) + (1.0 - first) * libm::exp(fast * t)
        } else {
            libm::exp(-frequency * t) * (1.0 + (frequency - self.velocity) * t)
        };
        1.0 - left
    }

    fn settle_seconds(self) -> Option<f64> {
        let horizon = 16.0 / self.decay();
        if !(horizon.is_finite() && horizon > 0.0) {
            return None;
        }
        let step = horizon / f64::from(SETTLE_STEPS);
        let away = |index: u32| (self.position(f64::from(index) * step) - 1.0).abs() >= SETTLED;
        if away(SETTLE_STEPS) {
            return None;
        }
        let last = (0..SETTLE_STEPS).rev().find(|index| away(*index))?;
        let seconds = f64::from(last + 1) * step;
        (seconds <= MAX_SPRING_SECONDS).then_some(seconds)
    }
}

/// A spring's motion from 0 to 1 over the time it takes to stay within 0.001 of 1, as a table
/// within `tolerance` of it of at most `max_points` points ([`sampled`]).
///
/// `None` for a mass, stiffness or damping that is not positive and finite, a velocity that is
/// not finite, or a spring that takes more than [`MAX_SPRING_SECONDS`] to settle.
#[must_use]
pub fn spring(spring: Spring, tolerance: f64, max_points: usize) -> Option<SpringEasing> {
    if !spring.is_valid() {
        return None;
    }
    let settle_seconds = spring.settle_seconds()?;
    let easing = sampled(
        |progress| {
            if progress >= 1.0 {
                1.0
            } else {
                spring.position(progress * settle_seconds)
            }
        },
        tolerance,
        max_points,
    );
    Some(SpringEasing {
        easing,
        settle_seconds,
    })
}

#[cfg(test)]
#[path = "easing_presets_tests.rs"]
mod tests;