alpha2-eval 0.10.0

Pure alpha2 timeline evaluation.
Documentation
//! Handles computed from keyframes or from another tool's numbers.

use super::{WideKey, as_value_curve, narrow, span};
use alpha2_model::{Animated, Interpolation, ValueBezier};
use alpha2_time::MediaTime;

/// How [`auto_tangents`] chooses the slope at a keyframe.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AutoTangent {
    /// The slope from the previous keyframe to the next (Catmull-Rom).
    Smooth,
    /// The steepest slope that keeps the curve inside the range of each pair of neighbouring
    /// keyframes (Steffen's monotone interpolation).
    Monotone,
    /// No slope: the curve stops at the keyframe.
    Flat,
    /// The slope of each side's own chord, so both sides are straight.
    Linear,
}

/// Writes value-curve handles at the chosen keyframes (every keyframe when `keys` is `None`)
/// from their neighbours. Each segment beside a chosen keyframe becomes an unweighted value
/// curve (a cubic Hermite curve) that keeps the slope at its other end; held segments are left
/// alone. A keyframe beside a held segment or at an end takes the slope of its one moving side.
pub fn auto_tangents(animation: &mut Animated<f32>, mode: AutoTangent, keys: Option<&[MediaTime]>) {
    let Animated::Keyframes { keyframes, .. } = animation else {
        return;
    };
    tangents_of(keyframes, mode, keys);
}

fn slope_through(left: f64, right: f64, left_length: f64, right_length: f64) -> f64 {
    let through = (left * right_length + right * left_length) / (left_length + right_length);
    let sign = |slope: f64| {
        if slope > 0.0 {
            1.0
        } else if slope < 0.0 {
            -1.0
        } else {
            0.0
        }
    };
    (sign(left) + sign(right)) * left.abs().min(right.abs()).min(through.abs() / 2.0)
}

pub(crate) fn tangents_of<K: WideKey>(
    keyframes: &mut [K],
    mode: AutoTangent,
    keys: Option<&[MediaTime]>,
) {
    let count = keyframes.len();
    let moving = |keyframes: &[K], segment: usize| {
        !matches!(keyframes[segment].interpolation(), Interpolation::Hold)
    };
    let chord = |keyframes: &[K], segment: usize| {
        (keyframes[segment + 1].value() - keyframes[segment].value())
            / span(keyframes[segment].time(), keyframes[segment + 1].time())
    };
    let slopes: Vec<Option<[f64; 2]>> = (0..count)
        .map(|index| {
            if keys.is_some_and(|keys| !keys.contains(&keyframes[index].time())) {
                return None;
            }
            let before = (index > 0 && moving(keyframes, index - 1)).then(|| index - 1);
            let after = (index + 1 < count && moving(keyframes, index)).then_some(index);
            let slope = match (mode, before, after) {
                (AutoTangent::Flat, _, _) => 0.0,
                (AutoTangent::Linear, before, after) => {
                    return Some([
                        before.map_or(0.0, |segment| chord(keyframes, segment)),
                        after.map_or(0.0, |segment| chord(keyframes, segment)),
                    ]);
                }
                (_, Some(before), None) => chord(keyframes, before),
                (_, None, Some(after)) => chord(keyframes, after),
                (_, None, None) => 0.0,
                (AutoTangent::Smooth, Some(_), Some(_)) => {
                    (keyframes[index + 1].value() - keyframes[index - 1].value())
                        / span(keyframes[index - 1].time(), keyframes[index + 1].time())
                }
                (AutoTangent::Monotone, Some(before), Some(after)) => slope_through(
                    chord(keyframes, before),
                    chord(keyframes, after),
                    span(keyframes[before].time(), keyframes[index].time()),
                    span(keyframes[index].time(), keyframes[index + 1].time()),
                ),
            };
            Some([slope, slope])
        })
        .collect();
    for segment in 0..count.saturating_sub(1) {
        let (leave, arrive) = (slopes[segment], slopes[segment + 1]);
        if leave.is_none() && arrive.is_none() {
            continue;
        }
        let (from, to) = (keyframes[segment].value(), keyframes[segment + 1].value());
        let Some(curve) = as_value_curve(keyframes[segment].interpolation(), from, to) else {
            continue;
        };
        let length = span(keyframes[segment].time(), keyframes[segment + 1].time());
        let leave = leave.map_or_else(
            || curve.end_slope_between(from, to, false),
            |[_, slope]| slope * length,
        );
        let arrive = arrive.map_or_else(
            || curve.end_slope_between(from, to, true),
            |[slope, _]| slope * length,
        );
        keyframes[segment].set_interpolation(Interpolation::ValueBezier(ValueBezier::unweighted(
            narrow(leave / 3.0),
            narrow(0.0 - arrive / 3.0),
        )));
    }
}

/// The value curve of a segment `seconds` long whose ends have these `(speed, influence)`
/// pairs, as After Effects shows them: speed in value per second, influence in percent of the
/// segment's length.
///
/// The formula is the one the After Effects scripting community documents
/// (`x = influence / 100`, handle value `speed * x * seconds`); it is not checked against the
/// application here.
#[must_use]
pub fn from_speed_influence(seconds: f64, leave: (f64, f64), arrive: (f64, f64)) -> ValueBezier {
    let (first, last) = (leave.1 / 100.0, arrive.1 / 100.0);
    ValueBezier::weighted(
        narrow(first),
        narrow(leave.0 * first * seconds),
        narrow(1.0 - last),
        narrow(0.0 - arrive.0 * last * seconds),
    )
}

/// The Hermite value curve of a segment `seconds` long that leaves at slope `leave` and
/// arrives at slope `arrive`, both in value per second (glTF cubic spline tangents, unweighted
/// tangents of Unity, Unreal and Maya).
#[must_use]
pub fn from_slopes(seconds: f64, leave: f64, arrive: f64) -> ValueBezier {
    ValueBezier::unweighted(
        narrow(leave * seconds / 3.0),
        narrow(0.0 - arrive * seconds / 3.0),
    )
}

/// The value curve whose four control points are given in (time, value), as Blender and Maya
/// store weighted handles. Handles that reach past the other key give time coordinates outside
/// what the engine takes; pass the result through [`contain`].
#[must_use]
pub fn from_handle_points(
    start: (f64, f64),
    leave: (f64, f64),
    arrive: (f64, f64),
    end: (f64, f64),
) -> ValueBezier {
    let length = end.0 - start.0;
    ValueBezier::weighted(
        narrow((leave.0 - start.0) / length),
        narrow(leave.1 - start.1),
        narrow((arrive.0 - start.0) / length),
        narrow(arrive.1 - end.1),
    )
}

/// `curve` with each handle whose time coordinate lies outside `0..=1` shortened along its own
/// direction until it lies on that edge: time and value are scaled alike, and a handle that
/// points backwards in time collapses onto its keyframe. The result never runs backwards.
#[must_use]
pub fn contain(curve: ValueBezier) -> ValueBezier {
    let Some((x1, x2)) = curve.weights() else {
        return curve;
    };
    let (x1, x2) = (f64::from(x1), f64::from(x2));
    let first = if x1 > 1.0 {
        1.0 / x1
    } else if x1 < 0.0 {
        0.0
    } else {
        1.0
    };
    let back = 1.0 - x2;
    let last = if back > 1.0 {
        1.0 / back
    } else if back < 0.0 {
        0.0
    } else {
        1.0
    };
    ValueBezier::weighted(
        narrow(x1 * first),
        narrow(f64::from(curve.leave) * first),
        narrow(1.0 - back * last),
        narrow(f64::from(curve.arrive) * last),
    )
}