namespace Titano.Core.Motion;
///
/// Cubic Bézier timing curve from (0, 0) to (1, 1) with control points (X1, Y1) and (X2, Y2), as in CSS
/// cubic-bezier(). X1 and X2 must lie in [0, 1] so time is monotonic; Y values may overshoot.
///
public readonly record struct BezierEasing
{
public BezierEasing(double x1, double y1, double x2, double y2)
{
if (!(x1 is >= 0 and <= 1) || !(x2 is >= 0 and <= 1)) throw new ArgumentOutOfRangeException(nameof(x1), "Control-point x must be within [0, 1].");
if (!double.IsFinite(y1) || !double.IsFinite(y2)) throw new ArgumentOutOfRangeException(nameof(y1));
(X1, Y1, X2, Y2) = (x1, y1, x2, y2);
}
public double X1 { get; }
public double Y1 { get; }
public double X2 { get; }
public double Y2 { get; }
public static BezierEasing Linear { get; } = new(0, 0, 1, 1);
/// Starts at rest, arrives at speed.
public static BezierEasing EaseIn { get; } = new(0.42, 0, 1, 1);
/// Starts at speed, arrives at rest.
public static BezierEasing EaseOut { get; } = new(0, 0, 0.58, 1);
/// At rest at both ends: chains of these segments are C1-continuous.
public static BezierEasing EaseInOut { get; } = new(0.42, 0, 0.58, 1);
/// Eased progress y for time fraction t ∈ [0, 1] (exactly 0 and 1 at the ends).
public double Evaluate(double t)
{
if (t <= 0) return 0;
if (t >= 1) return 1;
return Polynomial(Y1, Y2, Parameter(t));
}
/// Curve parameter s with x(s) = t: Newton's method from s = t, bisection when it stalls.
private double Parameter(double t)
{
var s = t;
for (var i = 0; i < 8; i++)
{
var error = Polynomial(X1, X2, s) - t;
if (double.Abs(error) < 1e-12) return s;
var slope = Derivative(X1, X2, s);
if (double.Abs(slope) < 1e-9) break;
var next = s - error / slope;
if (next is < 0 or > 1) break;
s = next;
}
double lo = 0, hi = 1;
s = t;
for (var i = 0; i < 60 && hi - lo > 1e-14; i++)
{
if (Polynomial(X1, X2, s) < t) lo = s;
else hi = s;
s = 0.5 * (lo + hi);
}
return s;
}
/// B(s) = 3(1−s)²s·p1 + 3(1−s)s²·p2 + s³ in Horner form.
private static double Polynomial(double p1, double p2, double s)
{
var c = 3 * p1;
var b = 3 * (p2 - p1) - c;
var a = 1 - c - b;
return ((a * s + b) * s + c) * s;
}
private static double Derivative(double p1, double p2, double s)
{
var c = 3 * p1;
var b = 3 * (p2 - p1) - c;
var a = 1 - c - b;
return (3 * a * s + 2 * b) * s + c;
}
}