Skip to main content

vibe/animation/
curves.rs

1//! Zero-heap mathematical easing curves and parametric interpolators.
2//!
3//! Provides standard CSS / Penner easings, cubic Bézier parametric solvers,
4//! and relativistic time-warp mappings without heap allocation.
5
6use std::f64::consts::PI;
7
8/// Standard animation curve types.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum EasingCurve {
11    Linear,
12    QuadIn,
13    QuadOut,
14    QuadInOut,
15    CubicIn,
16    CubicOut,
17    CubicInOut,
18    QuartIn,
19    QuartOut,
20    QuartInOut,
21    QuintIn,
22    QuintOut,
23    QuintInOut,
24    SineIn,
25    SineOut,
26    SineInOut,
27    ExpoIn,
28    ExpoOut,
29    ExpoInOut,
30    CircIn,
31    CircOut,
32    CircInOut,
33    ElasticIn,
34    ElasticOut,
35    ElasticInOut,
36    BackIn,
37    BackOut,
38    BackInOut,
39    BounceIn,
40    BounceOut,
41    BounceInOut,
42}
43
44impl EasingCurve {
45    /// Parse an easing curve from its canonical name (e.g., "ease-in-out", "cubic-in").
46    pub fn from_name(name: &str) -> Option<Self> {
47        match name.to_ascii_lowercase().replace('_', "-").as_str() {
48            "linear" => Some(Self::Linear),
49            "quad-in" | "ease-in-quad" => Some(Self::QuadIn),
50            "quad-out" | "ease-out-quad" => Some(Self::QuadOut),
51            "quad-in-out" | "ease-in-out-quad" => Some(Self::QuadInOut),
52            "cubic-in" | "ease-in" => Some(Self::CubicIn),
53            "cubic-out" | "ease-out" => Some(Self::CubicOut),
54            "cubic-in-out" | "ease-in-out" => Some(Self::CubicInOut),
55            "quart-in" | "ease-in-quart" => Some(Self::QuartIn),
56            "quart-out" | "ease-out-quart" => Some(Self::QuartOut),
57            "quart-in-out" | "ease-in-out-quart" => Some(Self::QuartInOut),
58            "quint-in" | "ease-in-quint" => Some(Self::QuintIn),
59            "quint-out" | "ease-out-quint" => Some(Self::QuintOut),
60            "quint-in-out" | "ease-in-out-quint" => Some(Self::QuintInOut),
61            "sine-in" | "ease-in-sine" => Some(Self::SineIn),
62            "sine-out" | "ease-out-sine" => Some(Self::SineOut),
63            "sine-in-out" | "ease-in-out-sine" => Some(Self::SineInOut),
64            "expo-in" | "ease-in-expo" => Some(Self::ExpoIn),
65            "expo-out" | "ease-out-expo" => Some(Self::ExpoOut),
66            "expo-in-out" | "ease-in-out-expo" => Some(Self::ExpoInOut),
67            "circ-in" | "ease-in-circ" => Some(Self::CircIn),
68            "circ-out" | "ease-out-circ" => Some(Self::CircOut),
69            "circ-in-out" | "ease-in-out-circ" => Some(Self::CircInOut),
70            "elastic-in" | "ease-in-elastic" => Some(Self::ElasticIn),
71            "elastic-out" | "ease-out-elastic" => Some(Self::ElasticOut),
72            "elastic-in-out" | "ease-in-out-elastic" => Some(Self::ElasticInOut),
73            "back-in" | "ease-in-back" => Some(Self::BackIn),
74            "back-out" | "ease-out-back" => Some(Self::BackOut),
75            "back-in-out" | "ease-in-out-back" => Some(Self::BackInOut),
76            "bounce-in" | "ease-in-bounce" => Some(Self::BounceIn),
77            "bounce-out" | "ease-out-bounce" => Some(Self::BounceOut),
78            "bounce-in-out" | "ease-in-out-bounce" => Some(Self::BounceInOut),
79            _ => None,
80        }
81    }
82
83    /// Evaluate the curve at normalized progress `t` in [0.0, 1.0].
84    #[inline]
85    pub fn eval(&self, t: f64) -> f64 {
86        let t = t.clamp(0.0, 1.0);
87        match self {
88            Self::Linear => t,
89            Self::QuadIn => t * t,
90            Self::QuadOut => t * (2.0 - t),
91            Self::QuadInOut => {
92                if t < 0.5 {
93                    2.0 * t * t
94                } else {
95                    -1.0 + (4.0 - 2.0 * t) * t
96                }
97            }
98            Self::CubicIn => t * t * t,
99            Self::CubicOut => {
100                let f = t - 1.0;
101                f * f * f + 1.0
102            }
103            Self::CubicInOut => {
104                if t < 0.5 {
105                    4.0 * t * t * t
106                } else {
107                    let f = 2.0 * t - 2.0;
108                    0.5 * f * f * f + 1.0
109                }
110            }
111            Self::QuartIn => t * t * t * t,
112            Self::QuartOut => {
113                let f = t - 1.0;
114                1.0 - f * f * f * f
115            }
116            Self::QuartInOut => {
117                if t < 0.5 {
118                    8.0 * t * t * t * t
119                } else {
120                    let f = t - 1.0;
121                    1.0 - 8.0 * f * f * f * f
122                }
123            }
124            Self::QuintIn => t * t * t * t * t,
125            Self::QuintOut => {
126                let f = t - 1.0;
127                f * f * f * f * f + 1.0
128            }
129            Self::QuintInOut => {
130                if t < 0.5 {
131                    16.0 * t * t * t * t * t
132                } else {
133                    let f = 2.0 * t - 2.0;
134                    0.5 * f * f * f * f * f + 1.0
135                }
136            }
137            Self::SineIn => 1.0 - (t * PI * 0.5).cos(),
138            Self::SineOut => (t * PI * 0.5).sin(),
139            Self::SineInOut => 0.5 * (1.0 - (PI * t).cos()),
140            Self::ExpoIn => {
141                if t == 0.0 {
142                    0.0
143                } else {
144                    (2.0f64).powf(10.0 * (t - 1.0))
145                }
146            }
147            Self::ExpoOut => {
148                if t == 1.0 {
149                    1.0
150                } else {
151                    1.0 - (2.0f64).powf(-10.0 * t)
152                }
153            }
154            Self::ExpoInOut => {
155                if t == 0.0 {
156                    0.0
157                } else if t == 1.0 {
158                    1.0
159                } else if t < 0.5 {
160                    0.5 * (2.0f64).powf(20.0 * t - 10.0)
161                } else {
162                    1.0 - 0.5 * (2.0f64).powf(-20.0 * t + 10.0)
163                }
164            }
165            Self::CircIn => 1.0 - (1.0 - t * t).sqrt(),
166            Self::CircOut => (1.0 - (t - 1.0).powi(2)).sqrt(),
167            Self::CircInOut => {
168                if t < 0.5 {
169                    0.5 * (1.0 - (1.0 - 4.0 * t * t).sqrt())
170                } else {
171                    0.5 * ((1.0 - (2.0 * t - 2.0).powi(2)).sqrt() + 1.0)
172                }
173            }
174            Self::ElasticIn => {
175                if t == 0.0 {
176                    0.0
177                } else if t == 1.0 {
178                    1.0
179                } else {
180                    -(2.0f64).powf(10.0 * (t - 1.0)) * ((t - 1.1) * 5.0 * PI).sin()
181                }
182            }
183            Self::ElasticOut => {
184                if t == 0.0 {
185                    0.0
186                } else if t == 1.0 {
187                    1.0
188                } else {
189                    (2.0f64).powf(-10.0 * t) * ((t - 0.1) * 5.0 * PI).sin() + 1.0
190                }
191            }
192            Self::ElasticInOut => {
193                if t == 0.0 {
194                    0.0
195                } else if t == 1.0 {
196                    1.0
197                } else if t < 0.5 {
198                    -0.5 * (2.0f64).powf(20.0 * t - 10.0) * ((2.0 * t - 1.1) * 5.0 * PI).sin()
199                } else {
200                    0.5 * (2.0f64).powf(-20.0 * t + 10.0) * ((2.0 * t - 1.1) * 5.0 * PI).sin() + 1.0
201                }
202            }
203            Self::BackIn => {
204                let s = 1.70158;
205                t * t * ((s + 1.0) * t - s)
206            }
207            Self::BackOut => {
208                let s = 1.70158;
209                let f = t - 1.0;
210                f * f * ((s + 1.0) * f + s) + 1.0
211            }
212            Self::BackInOut => {
213                let s = 1.70158 * 1.525;
214                if t < 0.5 {
215                    0.5 * (4.0 * t * t * ((s + 1.0) * 2.0 * t - s))
216                } else {
217                    let f = 2.0 * t - 2.0;
218                    0.5 * (f * f * ((s + 1.0) * f + s) + 2.0)
219                }
220            }
221            Self::BounceIn => 1.0 - Self::BounceOut.eval(1.0 - t),
222            Self::BounceOut => {
223                let n1 = 7.5625;
224                let d1 = 2.75;
225                if t < 1.0 / d1 {
226                    n1 * t * t
227                } else if t < 2.0 / d1 {
228                    let t = t - 1.5 / d1;
229                    n1 * t * t + 0.75
230                } else if t < 2.5 / d1 {
231                    let t = t - 2.25 / d1;
232                    n1 * t * t + 0.9375
233                } else {
234                    let t = t - 2.625 / d1;
235                    n1 * t * t + 0.984375
236                }
237            }
238            Self::BounceInOut => {
239                if t < 0.5 {
240                    0.5 * Self::BounceIn.eval(2.0 * t)
241                } else {
242                    0.5 * Self::BounceOut.eval(2.0 * t - 1.0) + 0.5
243                }
244            }
245        }
246    }
247}
248
249/// Parametric Cubic Bézier curve defined by control points `(x1, y1)` and `(x2, y2)`.
250#[derive(Debug, Clone, Copy, PartialEq)]
251pub struct CubicBezier {
252    pub x1: f64,
253    pub y1: f64,
254    pub x2: f64,
255    pub y2: f64,
256}
257
258impl CubicBezier {
259    /// Create a cubic Bézier easing curve.
260    pub const fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
261        Self { x1, y1, x2, y2 }
262    }
263
264    /// Standard CSS ease: cubic-bezier(0.25, 0.1, 0.25, 1.0)
265    pub const fn ease() -> Self {
266        Self::new(0.25, 0.1, 0.25, 1.0)
267    }
268
269    /// Standard CSS ease-in: cubic-bezier(0.42, 0.0, 1.0, 1.0)
270    pub const fn ease_in() -> Self {
271        Self::new(0.42, 0.0, 1.0, 1.0)
272    }
273
274    /// Standard CSS ease-out: cubic-bezier(0.0, 0.0, 0.58, 1.0)
275    pub const fn ease_out() -> Self {
276        Self::new(0.0, 0.0, 0.58, 1.0)
277    }
278
279    /// Standard CSS ease-in-out: cubic-bezier(0.42, 0.0, 0.58, 1.0)
280    pub const fn ease_in_out() -> Self {
281        Self::new(0.42, 0.0, 0.58, 1.0)
282    }
283
284    #[inline]
285    fn sample_curve_x(&self, t: f64) -> f64 {
286        // 3*(1-t)^2*t*x1 + 3*(1-t)*t^2*x2 + t^3
287        let c_x = 3.0 * self.x1;
288        let b_x = 3.0 * (self.x2 - self.x1) - c_x;
289        let a_x = 1.0 - c_x - b_x;
290        ((a_x * t + b_x) * t + c_x) * t
291    }
292
293    #[inline]
294    fn sample_curve_y(&self, t: f64) -> f64 {
295        let c_y = 3.0 * self.y1;
296        let b_y = 3.0 * (self.y2 - self.y1) - c_y;
297        let a_y = 1.0 - c_y - b_y;
298        ((a_y * t + b_y) * t + c_y) * t
299    }
300
301    #[inline]
302    fn sample_curve_derivative_x(&self, t: f64) -> f64 {
303        let c_x = 3.0 * self.x1;
304        let b_x = 3.0 * (self.x2 - self.x1) - c_x;
305        let a_x = 1.0 - c_x - b_x;
306        (3.0 * a_x * t + 2.0 * b_x) * t + c_x
307    }
308
309    /// Solve for parametric parameter `t` given progress `x` using Newton-Raphson.
310    pub fn solve_t(&self, x: f64) -> f64 {
311        let x = x.clamp(0.0, 1.0);
312        let mut t = x;
313        // Newton-Raphson iteration (max 8 steps for sub-microsecond zero-heap convergence)
314        for _ in 0..8 {
315            let x2 = self.sample_curve_x(t) - x;
316            if x2.abs() < 1e-7 {
317                return t;
318            }
319            let d2 = self.sample_curve_derivative_x(t);
320            if d2.abs() < 1e-7 {
321                break;
322            }
323            t -= x2 / d2;
324        }
325
326        // Fallback binary subdivision if Newton diverges
327        let mut t0 = 0.0;
328        let mut t1 = 1.0;
329        let mut t = x;
330        for _ in 0..12 {
331            let x2 = self.sample_curve_x(t);
332            if (x2 - x).abs() < 1e-7 {
333                return t;
334            }
335            if x > x2 {
336                t0 = t;
337            } else {
338                t1 = t;
339            }
340            t = (t1 + t0) * 0.5;
341        }
342        t
343    }
344
345    /// Evaluate the cubic Bézier curve at `x` in [0.0, 1.0].
346    #[inline]
347    pub fn eval(&self, x: f64) -> f64 {
348        if x <= 0.0 {
349            return 0.0;
350        }
351        if x >= 1.0 {
352            return 1.0;
353        }
354        let t = self.solve_t(x);
355        self.sample_curve_y(t)
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn linear_eval_endpoints() {
365        assert_eq!(EasingCurve::Linear.eval(0.0), 0.0);
366        assert_eq!(EasingCurve::Linear.eval(0.5), 0.5);
367        assert_eq!(EasingCurve::Linear.eval(1.0), 1.0);
368    }
369
370    #[test]
371    fn all_curves_stay_in_bounds_at_endpoints() {
372        let curves = [
373            EasingCurve::Linear,
374            EasingCurve::QuadIn,
375            EasingCurve::QuadOut,
376            EasingCurve::QuadInOut,
377            EasingCurve::CubicIn,
378            EasingCurve::CubicOut,
379            EasingCurve::CubicInOut,
380            EasingCurve::SineIn,
381            EasingCurve::SineOut,
382            EasingCurve::SineInOut,
383            EasingCurve::ExpoIn,
384            EasingCurve::ExpoOut,
385            EasingCurve::CircIn,
386            EasingCurve::CircOut,
387            EasingCurve::ElasticIn,
388            EasingCurve::ElasticOut,
389            EasingCurve::BackIn,
390            EasingCurve::BackOut,
391            EasingCurve::BounceIn,
392            EasingCurve::BounceOut,
393        ];
394        for c in &curves {
395            let v0 = c.eval(0.0);
396            let v1 = c.eval(1.0);
397            assert!(v0.abs() < 1e-6, "curve {c:?} at 0.0 was {v0}");
398            assert!((v1 - 1.0).abs() < 1e-6, "curve {c:?} at 1.0 was {v1}");
399        }
400    }
401
402    #[test]
403    fn cubic_bezier_ease_in_out() {
404        let bez = CubicBezier::ease_in_out();
405        assert_eq!(bez.eval(0.0), 0.0);
406        assert_eq!(bez.eval(1.0), 1.0);
407        let mid = bez.eval(0.5);
408        assert!((mid - 0.5).abs() < 1e-3);
409    }
410}