use crate::{CubicBezier, Easing, EasingPoint, MAX_EASING_POINTS, StepPosition, Steps};
use std::f64::consts::PI;
pub const PRESET_TOLERANCE: f64 = 5e-4;
pub const PRESET_POINTS: usize = 192;
const NARROWEST_PIECE: f64 = 1.0 / 65_536.0;
pub const EASING_FAMILIES: [&str; 10] = [
"sine", "quad", "cubic", "quart", "quint", "expo", "circ", "back", "elastic", "bounce",
];
#[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,
}
}
#[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))
}
#[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)
}
#[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 }
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Spring {
pub mass: f64,
pub stiffness: f64,
pub damping: f64,
pub velocity: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SpringEasing {
pub easing: Easing,
pub settle_seconds: f64,
}
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
}
}
#[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)
}
}
#[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;