Skip to main content

alpha2_eval/curves/
tangents.rs

1//! Handles computed from keyframes or from another tool's numbers.
2
3use super::{WideKey, as_value_curve, narrow, span};
4use alpha2_model::{Animated, Interpolation, ValueBezier};
5use alpha2_time::MediaTime;
6
7/// How [`auto_tangents`] chooses the slope at a keyframe.
8#[derive(Copy, Clone, Debug, Eq, PartialEq)]
9pub enum AutoTangent {
10    /// The slope from the previous keyframe to the next (Catmull-Rom).
11    Smooth,
12    /// The steepest slope that keeps the curve inside the range of each pair of neighbouring
13    /// keyframes (Steffen's monotone interpolation).
14    Monotone,
15    /// No slope: the curve stops at the keyframe.
16    Flat,
17    /// The slope of each side's own chord, so both sides are straight.
18    Linear,
19}
20
21/// Writes value-curve handles at the chosen keyframes (every keyframe when `keys` is `None`)
22/// from their neighbours. Each segment beside a chosen keyframe becomes an unweighted value
23/// curve (a cubic Hermite curve) that keeps the slope at its other end; held segments are left
24/// alone. A keyframe beside a held segment or at an end takes the slope of its one moving side.
25pub fn auto_tangents(animation: &mut Animated<f32>, mode: AutoTangent, keys: Option<&[MediaTime]>) {
26    let Animated::Keyframes { keyframes, .. } = animation else {
27        return;
28    };
29    tangents_of(keyframes, mode, keys);
30}
31
32fn slope_through(left: f64, right: f64, left_length: f64, right_length: f64) -> f64 {
33    let through = (left * right_length + right * left_length) / (left_length + right_length);
34    let sign = |slope: f64| {
35        if slope > 0.0 {
36            1.0
37        } else if slope < 0.0 {
38            -1.0
39        } else {
40            0.0
41        }
42    };
43    (sign(left) + sign(right)) * left.abs().min(right.abs()).min(through.abs() / 2.0)
44}
45
46pub(crate) fn tangents_of<K: WideKey>(
47    keyframes: &mut [K],
48    mode: AutoTangent,
49    keys: Option<&[MediaTime]>,
50) {
51    let count = keyframes.len();
52    let moving = |keyframes: &[K], segment: usize| {
53        !matches!(keyframes[segment].interpolation(), Interpolation::Hold)
54    };
55    let chord = |keyframes: &[K], segment: usize| {
56        (keyframes[segment + 1].value() - keyframes[segment].value())
57            / span(keyframes[segment].time(), keyframes[segment + 1].time())
58    };
59    let slopes: Vec<Option<[f64; 2]>> = (0..count)
60        .map(|index| {
61            if keys.is_some_and(|keys| !keys.contains(&keyframes[index].time())) {
62                return None;
63            }
64            let before = (index > 0 && moving(keyframes, index - 1)).then(|| index - 1);
65            let after = (index + 1 < count && moving(keyframes, index)).then_some(index);
66            let slope = match (mode, before, after) {
67                (AutoTangent::Flat, _, _) => 0.0,
68                (AutoTangent::Linear, before, after) => {
69                    return Some([
70                        before.map_or(0.0, |segment| chord(keyframes, segment)),
71                        after.map_or(0.0, |segment| chord(keyframes, segment)),
72                    ]);
73                }
74                (_, Some(before), None) => chord(keyframes, before),
75                (_, None, Some(after)) => chord(keyframes, after),
76                (_, None, None) => 0.0,
77                (AutoTangent::Smooth, Some(_), Some(_)) => {
78                    (keyframes[index + 1].value() - keyframes[index - 1].value())
79                        / span(keyframes[index - 1].time(), keyframes[index + 1].time())
80                }
81                (AutoTangent::Monotone, Some(before), Some(after)) => slope_through(
82                    chord(keyframes, before),
83                    chord(keyframes, after),
84                    span(keyframes[before].time(), keyframes[index].time()),
85                    span(keyframes[index].time(), keyframes[index + 1].time()),
86                ),
87            };
88            Some([slope, slope])
89        })
90        .collect();
91    for segment in 0..count.saturating_sub(1) {
92        let (leave, arrive) = (slopes[segment], slopes[segment + 1]);
93        if leave.is_none() && arrive.is_none() {
94            continue;
95        }
96        let (from, to) = (keyframes[segment].value(), keyframes[segment + 1].value());
97        let Some(curve) = as_value_curve(keyframes[segment].interpolation(), from, to) else {
98            continue;
99        };
100        let length = span(keyframes[segment].time(), keyframes[segment + 1].time());
101        let leave = leave.map_or_else(
102            || curve.end_slope_between(from, to, false),
103            |[_, slope]| slope * length,
104        );
105        let arrive = arrive.map_or_else(
106            || curve.end_slope_between(from, to, true),
107            |[slope, _]| slope * length,
108        );
109        keyframes[segment].set_interpolation(Interpolation::ValueBezier(ValueBezier::unweighted(
110            narrow(leave / 3.0),
111            narrow(0.0 - arrive / 3.0),
112        )));
113    }
114}
115
116/// The value curve of a segment `seconds` long whose ends have these `(speed, influence)`
117/// pairs, as After Effects shows them: speed in value per second, influence in percent of the
118/// segment's length.
119///
120/// The formula is the one the After Effects scripting community documents
121/// (`x = influence / 100`, handle value `speed * x * seconds`); it is not checked against the
122/// application here.
123#[must_use]
124pub fn from_speed_influence(seconds: f64, leave: (f64, f64), arrive: (f64, f64)) -> ValueBezier {
125    let (first, last) = (leave.1 / 100.0, arrive.1 / 100.0);
126    ValueBezier::weighted(
127        narrow(first),
128        narrow(leave.0 * first * seconds),
129        narrow(1.0 - last),
130        narrow(0.0 - arrive.0 * last * seconds),
131    )
132}
133
134/// The Hermite value curve of a segment `seconds` long that leaves at slope `leave` and
135/// arrives at slope `arrive`, both in value per second (glTF cubic spline tangents, unweighted
136/// tangents of Unity, Unreal and Maya).
137#[must_use]
138pub fn from_slopes(seconds: f64, leave: f64, arrive: f64) -> ValueBezier {
139    ValueBezier::unweighted(
140        narrow(leave * seconds / 3.0),
141        narrow(0.0 - arrive * seconds / 3.0),
142    )
143}
144
145/// The value curve whose four control points are given in (time, value), as Blender and Maya
146/// store weighted handles. Handles that reach past the other key give time coordinates outside
147/// what the engine takes; pass the result through [`contain`].
148#[must_use]
149pub fn from_handle_points(
150    start: (f64, f64),
151    leave: (f64, f64),
152    arrive: (f64, f64),
153    end: (f64, f64),
154) -> ValueBezier {
155    let length = end.0 - start.0;
156    ValueBezier::weighted(
157        narrow((leave.0 - start.0) / length),
158        narrow(leave.1 - start.1),
159        narrow((arrive.0 - start.0) / length),
160        narrow(arrive.1 - end.1),
161    )
162}
163
164/// `curve` with each handle whose time coordinate lies outside `0..=1` shortened along its own
165/// direction until it lies on that edge: time and value are scaled alike, and a handle that
166/// points backwards in time collapses onto its keyframe. The result never runs backwards.
167#[must_use]
168pub fn contain(curve: ValueBezier) -> ValueBezier {
169    let Some((x1, x2)) = curve.weights() else {
170        return curve;
171    };
172    let (x1, x2) = (f64::from(x1), f64::from(x2));
173    let first = if x1 > 1.0 {
174        1.0 / x1
175    } else if x1 < 0.0 {
176        0.0
177    } else {
178        1.0
179    };
180    let back = 1.0 - x2;
181    let last = if back > 1.0 {
182        1.0 / back
183    } else if back < 0.0 {
184        0.0
185    } else {
186        1.0
187    };
188    ValueBezier::weighted(
189        narrow(x1 * first),
190        narrow(f64::from(curve.leave) * first),
191        narrow(1.0 - back * last),
192        narrow(f64::from(curve.arrive) * last),
193    )
194}