arc-motion 0.1.0

Physics-first animation & motion engine for GPUI: analytical ODE springs, cubic bezier, FLIP shared layout, presence, drag/rubber-band, inertia, and SVG path morphing.
Documentation
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Cubic-bezier easing solver (Newton-Raphson + bisection fallback) matching CSS / Motion to < 0.001.

use arc_tokens::CubicBezierSpec;
use gpui_kit::base::Easing;

const NEWTON_ITERATIONS: usize = 8;
const NEWTON_MIN_SLOPE: f64 = 1e-5;
const SUBDIVISION_PRECISION: f64 = 1e-7;
const SUBDIVISION_MAX_ITERATIONS: usize = 24;

/// High-precision CSS `cubic-bezier(x1, y1, x2, y2)` curve evaluator.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CubicBezier {
    pub x1: f64,
    pub y1: f64,
    pub x2: f64,
    pub y2: f64,
}

impl CubicBezier {
    pub const fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
        Self { x1, y1, x2, y2 }
    }

    pub const fn from_spec(spec: CubicBezierSpec) -> Self {
        Self {
            x1: spec.x1 as f64,
            y1: spec.y1 as f64,
            x2: spec.x2 as f64,
            y2: spec.y2 as f64,
        }
    }

    pub fn to_base_easing(self) -> Easing {
        Easing::cubic_bezier(
            self.x1 as f32,
            self.y1 as f32,
            self.x2 as f32,
            self.y2 as f32,
        )
        .expect("CubicBezier x control points must be within 0..=1")
    }

    /// Evaluates `y` for normalized time `x` in `0.0..=1.0`.
    pub fn sample(self, x: f32) -> f32 {
        self.sample_f64(f64::from(x)) as f32
    }

    pub fn sample_f64(self, x: f64) -> f64 {
        let x = x.clamp(0.0, 1.0);
        if x == 0.0 || x == 1.0 {
            return x;
        }
        if (self.x1 - self.y1).abs() < f64::EPSILON && (self.x2 - self.y2).abs() < f64::EPSILON {
            return x;
        }
        let t = self.solve_t_for_x(x);
        calc_bezier(t, self.y1, self.y2)
    }

    fn solve_t_for_x(self, target_x: f64) -> f64 {
        // Newton-Raphson first
        let mut guess_t = target_x;
        for _ in 0..NEWTON_ITERATIONS {
            let current_x = calc_bezier(guess_t, self.x1, self.x2) - target_x;
            if current_x.abs() < SUBDIVISION_PRECISION {
                return guess_t;
            }
            let slope = calc_slope(guess_t, self.x1, self.x2);
            if slope.abs() < NEWTON_MIN_SLOPE {
                break;
            }
            guess_t = (guess_t - current_x / slope).clamp(0.0, 1.0);
        }

        // Bisection fallback guarantees convergence for every valid CSS bezier
        let mut low = 0.0;
        let mut high = 1.0;
        let mut t = target_x;
        for _ in 0..SUBDIVISION_MAX_ITERATIONS {
            t = 0.5 * (low + high);
            let current_x = calc_bezier(t, self.x1, self.x2) - target_x;
            if current_x.abs() < SUBDIVISION_PRECISION {
                break;
            }
            if current_x > 0.0 {
                high = t;
            } else {
                low = t;
            }
        }
        t
    }
}

impl From<CubicBezierSpec> for CubicBezier {
    fn from(spec: CubicBezierSpec) -> Self {
        Self::from_spec(spec)
    }
}

#[inline]
fn calc_bezier(t: f64, a1: f64, a2: f64) -> f64 {
    (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) * t
}

#[inline]
fn calc_slope(t: f64, a1: f64, a2: f64) -> f64 {
    3.0 * (1.0 - 3.0 * a2 + 3.0 * a1) * t * t + 2.0 * (3.0 * a2 - 6.0 * a1) * t + 3.0 * a1
}

#[cfg(test)]
mod tests {
    use arc_tokens::ArcMotionTokens;

    use super::*;

    /// Exact port of Motion's `motion-utils/dist/es/easing/cubic-bezier.mjs` binary subdivision
    /// for cross-checking our Newton + bisection solver.
    fn motion_reference_bezier(x1: f64, y1: f64, x2: f64, y2: f64, x: f64) -> f64 {
        if x == 0.0 || x == 1.0 {
            return x;
        }
        let mut low = 0.0;
        let mut high = 1.0;
        let mut t = 0.0;
        for _ in 0..12 {
            t = low + (high - low) / 2.0;
            let current_x = calc_bezier(t, x1, x2) - x;
            if current_x > 0.0 {
                high = t;
            } else {
                low = t;
            }
            if current_x.abs() <= 1e-7 {
                break;
            }
        }
        calc_bezier(t, y1, y2)
    }

    #[test]
    fn all_four_arc_curves_match_motion_within_0_001() {
        let ease = ArcMotionTokens::DEFAULT.ease;
        let curves = [
            ("enter", ease.enter),
            ("exit", ease.exit),
            ("standard", ease.standard),
            ("in_out", ease.in_out),
        ];
        for (name, spec) in curves {
            let bezier = CubicBezier::from_spec(spec);
            assert_eq!(bezier.sample(0.0), 0.0);
            assert_eq!(bezier.sample(1.0), 1.0);

            for step in 1..100 {
                let x = f64::from(step) / 100.0;
                let ours = bezier.sample_f64(x);
                let reference = motion_reference_bezier(
                    f64::from(spec.x1),
                    f64::from(spec.y1),
                    f64::from(spec.x2),
                    f64::from(spec.y2),
                    x,
                );
                let diff = (ours - reference).abs();
                assert!(
                    diff < 0.001,
                    "curve '{name}' at x={x}: ours={ours}, ref={reference}, diff={diff}"
                );
            }
        }
    }

    #[test]
    fn matches_gpui_base_easing_and_preserves_overshoot() {
        let enter = CubicBezier::from_spec(ArcMotionTokens::DEFAULT.ease.enter);
        let base = enter.to_base_easing();
        for step in 0..=20 {
            let x = step as f32 / 20.0;
            assert!((enter.sample(x) - base.sample(x)).abs() < 1e-4);
        }

        // Overshoot curve (y2 > 1.0)
        let overshoot = CubicBezier::new(0.34, 1.56, 0.64, 1.0);
        assert!(overshoot.sample(0.5) > 1.0);
    }
}