alpha2-eval 0.9.0

Pure alpha2 timeline evaluation.
Documentation
//! A `path` position written as position keyframes.

use super::{
    Cubic, CurveError, materialize, narrow, part_keys, segment_value, span, stepped, timing_curve,
};
use crate::animation::{motion_segments, screen_aspect};
use alpha2_geometry::kurbo::{PathSeg, Vec2 as Vector};
use alpha2_geometry::spatial::{along_path, cut_along, segment_fractions};
use alpha2_model::{
    Animated, AnimatedPoint, EasingPoint, Extrapolation, Interpolation, Keyframe, MAX_KEYFRAMES,
    MotionPath, PointKeyframe, Vec2,
};
use alpha2_time::{MediaTime, TimeRange};
use std::collections::BTreeMap;

struct Geometry {
    segments: Vec<PathSeg>,
    closed: bool,
    fractions: Vec<f64>,
    aspect: f64,
}

impl Geometry {
    fn point(&self, distance: f64) -> Vec2 {
        self.model(
            along_path(&self.segments, self.closed, distance)
                .0
                .to_vec2(),
        )
    }

    fn model(&self, vector: Vector) -> Vec2 {
        Vec2::new(narrow(vector.x / self.aspect), narrow(vector.y))
    }

    fn thresholds(&self, low: f64, high: f64) -> Result<Vec<f64>, CurveError> {
        let mut thresholds = Vec::new();
        if self.closed {
            let Some((_, starts)) = self.fractions.split_last() else {
                return Ok(thresholds);
            };
            #[expect(
                clippy::cast_possible_truncation,
                reason = "a turn count of a finite value"
            )]
            let turns = (low.floor() as i64)..=(high.ceil() as i64);
            let count = u64::try_from(turns.end().saturating_sub(*turns.start())).unwrap_or(0);
            if count.saturating_mul(starts.len() as u64) > MAX_KEYFRAMES as u64 {
                return Err(CurveError::TooManyKeys);
            }
            for turn in turns {
                #[expect(clippy::cast_precision_loss, reason = "a turn count")]
                let turn = turn as f64;
                thresholds.extend(starts.iter().map(|start| turn + start));
            }
        } else {
            thresholds.extend(&self.fractions);
        }
        thresholds.retain(|threshold| *threshold > low && *threshold < high);
        Ok(thresholds)
    }

    fn on_path(&self, from: f64, to: f64) -> (f64, f64) {
        if self.closed {
            let turn = f64::midpoint(from, to).floor();
            (from - turn, to - turn)
        } else {
            (from.clamp(0.0, 1.0), to.clamp(0.0, 1.0))
        }
    }

    fn handles_between(&self, from: f64, to: f64) -> (Vec2, Vec2) {
        let (from, to) = self.on_path(from, to);
        let middle = f64::midpoint(from, to);
        let Some(index) = self
            .fractions
            .windows(2)
            .position(|ends| ends[1] > ends[0] && middle <= ends[1])
        else {
            return (Vec2::default(), Vec2::default());
        };
        let PathSeg::Cubic(cubic) = self.segments[index] else {
            return (Vec2::default(), Vec2::default());
        };
        if cubic.p1 == cubic.p0 && cubic.p2 == cubic.p3 {
            return (Vec2::default(), Vec2::default());
        }
        let (start, end) = (self.fractions[index], self.fractions[index + 1]);
        let local = |fraction: f64| ((fraction - start) / (end - start)).clamp(0.0, 1.0);
        let (low, high) = (local(from.min(to)), local(from.max(to)));
        let rest = cut_along(
            cubic.p0,
            cubic.p1 - cubic.p0,
            cubic.p2 - cubic.p3,
            cubic.p3,
            low,
        );
        let (leave, arrive) = if high < 1.0 {
            let part = cut_along(
                rest.point,
                rest.cut_out,
                rest.to_in,
                cubic.p3,
                (high - low) / (1.0 - low),
            );
            (part.from_out, part.cut_in)
        } else {
            (rest.cut_out, rest.to_in)
        };
        let (leave, arrive) = (self.model(leave), self.model(arrive));
        if from <= to {
            (leave, arrive)
        } else {
            (arrive, leave)
        }
    }
}

fn steps_as_holds(keyframes: &[Keyframe<f32>]) -> Result<Vec<Keyframe<f32>>, CurveError> {
    let mut held = Vec::with_capacity(keyframes.len());
    for pair in keyframes.windows(2) {
        let (left, right) = (&pair[0], &pair[1]);
        match left.interpolation {
            Interpolation::Steps(steps) => held.extend(stepped(
                left,
                right,
                steps,
                left.time.ticks(),
                right.time.ticks(),
            )),
            _ => held.push(left.clone()),
        }
        if held.len() >= MAX_KEYFRAMES {
            return Err(CurveError::TooManyKeys);
        }
    }
    held.extend(keyframes.last().cloned());
    Ok(held)
}

#[expect(clippy::cast_possible_truncation, reason = "a tick inside the segment")]
fn tick_at(left: &Keyframe<f32>, right: &Keyframe<f32>, progress: f64) -> Option<MediaTime> {
    let tick = (super::coordinate(left.time) + progress * span(left.time, right.time)).round();
    let tick = tick as i64;
    (tick > left.time.ticks() && tick < right.time.ticks()).then_some(MediaTime(tick))
}

fn turns(left: &Keyframe<f32>, right: &Keyframe<f32>) -> Vec<MediaTime> {
    if let Some(cubic) = Cubic::of(left, right) {
        return cubic
            .turns()
            .filter_map(|u| tick_at(left, right, cubic.progress_at(u)))
            .collect();
    }
    let Interpolation::Points { points } = &left.interpolation else {
        return Vec::new();
    };
    let corners: Vec<EasingPoint> = std::iter::once(EasingPoint { x: 0.0, y: 0.0 })
        .chain(points.iter().copied())
        .chain(std::iter::once(EasingPoint { x: 1.0, y: 1.0 }))
        .collect();
    corners
        .windows(3)
        .filter(|corner| {
            let before = f64::from(corner[1].y) - f64::from(corner[0].y);
            let after = f64::from(corner[2].y) - f64::from(corner[1].y);
            before * after < 0.0
        })
        .filter_map(|corner| tick_at(left, right, f64::from(corner[1].x)))
        .collect()
}

fn crossings(
    left: &Keyframe<f32>,
    right: &Keyframe<f32>,
    geometry: &Geometry,
) -> Result<Vec<(MediaTime, f64)>, CurveError> {
    if matches!(left.interpolation, Interpolation::Hold) {
        return Ok(Vec::new());
    }
    let (from, to) = (f64::from(left.value), f64::from(right.value));
    let rising = from < to;
    let (start, end) = (left.time.ticks(), right.time.ticks());
    Ok(geometry
        .thresholds(from.min(to), from.max(to))?
        .into_iter()
        .filter_map(|threshold| {
            let past = |tick: i64| {
                let value = f64::from(segment_value(left, right, tick));
                if rising {
                    value >= threshold
                } else {
                    value <= threshold
                }
            };
            let (mut before, mut after) = (start, end);
            while after - before > 1 {
                let middle = before + (after - before) / 2;
                if past(middle) {
                    after = middle;
                } else {
                    before = middle;
                }
            }
            (after < end).then_some((MediaTime(after), threshold))
        })
        .collect())
}

fn split_where(
    keyframes: &[Keyframe<f32>],
    mut at: impl FnMut(&Keyframe<f32>, &Keyframe<f32>) -> Result<Vec<MediaTime>, CurveError>,
) -> Result<Vec<Keyframe<f32>>, CurveError> {
    let mut split = Vec::with_capacity(keyframes.len());
    for pair in keyframes.windows(2) {
        let (left, right) = (&pair[0], &pair[1]);
        let mut cuts: Vec<i64> = at(left, right)?.iter().map(|time| time.ticks()).collect();
        cuts.sort_unstable();
        cuts.dedup();
        let mut from = left.time.ticks();
        for to in cuts.into_iter().chain([right.time.ticks()]) {
            split.extend(part_keys(left, right, from, to));
            from = to;
        }
        if split.len() >= MAX_KEYFRAMES {
            return Err(CurveError::TooManyKeys);
        }
    }
    split.extend(keyframes.last().cloned());
    Ok(split)
}

fn timing(left: &Keyframe<f32>, right: &Keyframe<f32>) -> Interpolation {
    let change = f64::from(right.value) - f64::from(left.value);
    if change == 0.0 {
        return Interpolation::Hold;
    }
    match &left.interpolation {
        Interpolation::ValueBezier(curve) => {
            timing_curve(*curve, change).map_or(Interpolation::Hold, Interpolation::CubicBezier)
        }
        Interpolation::Steps(_) => Interpolation::Hold,
        other => other.clone(),
    }
}

/// The position keyframes that show what the `path` position `motion` shows over `range`, with
/// lengths measured in a space `aspect` wide per unit high: the same path at the same speed.
///
/// Next to a cut, where the distance turns back or passes a vertex between two ticks, the result
/// is off by at most the travel of one tick. Both sides of the result hold. A keyed position
/// points the way it travels, so where the distance backs up, `orient: "path"` turns half a turn
/// from what the path position shows. A constant `distance` gives a constant position.
///
/// # Errors
///
/// [`CurveError::NotKeyed`] for a `distance` bound to data, [`CurveError::Empty`] for one without
/// keyframes, and [`CurveError::TooManyKeys`] when the result would hold more than
/// [`alpha2_model::MAX_KEYFRAMES`] keyframes.
pub fn path_to_keys(
    motion: &MotionPath,
    range: TimeRange,
    aspect: f64,
) -> Result<AnimatedPoint, CurveError> {
    let aspect = screen_aspect(aspect);
    let (segments, closed) = motion_segments(motion, aspect);
    let geometry = Geometry {
        fractions: segment_fractions(&segments),
        segments,
        closed,
        aspect,
    };
    let mut distance = motion.distance.clone();
    match &mut distance {
        Animated::Constant { value } => {
            return Ok(AnimatedPoint::Constant {
                value: geometry.point(f64::from(*value)),
            });
        }
        Animated::Keyframes { keyframes, .. } if keyframes.is_empty() => {
            return Err(CurveError::Empty);
        }
        Animated::Keyframes { keyframes, .. } if keyframes.len() == 1 => {
            return Ok(AnimatedPoint::Constant {
                value: geometry.point(f64::from(keyframes[0].value)),
            });
        }
        Animated::Keyframes { .. } => {}
        Animated::Split { .. } | Animated::Data(_) => return Err(CurveError::NotKeyed),
    }
    materialize(&mut distance, range)?;
    let Animated::Keyframes { keyframes, .. } = distance else {
        return Err(CurveError::NotKeyed);
    };
    let keyframes = steps_as_holds(&keyframes)?;
    let keyframes = split_where(&keyframes, |left, right| Ok(turns(left, right)))?;
    let mut vertices = BTreeMap::new();
    let keyframes = split_where(&keyframes, |left, right| {
        let found = crossings(left, right, &geometry)?;
        for &(time, threshold) in &found {
            vertices.entry(time).or_insert(threshold);
        }
        Ok(found.into_iter().map(|(time, _)| time).collect())
    })?;
    let along: Vec<f64> = keyframes
        .iter()
        .map(|key| {
            vertices
                .get(&key.time)
                .copied()
                .unwrap_or_else(|| f64::from(key.value))
        })
        .collect();

    let mut keys: Vec<PointKeyframe> = keyframes
        .iter()
        .zip(&along)
        .map(|(key, &along)| PointKeyframe {
            time: key.time,
            value: geometry.point(along),
            interpolation: Interpolation::Hold,
            out_tangent: Vec2::default(),
            in_tangent: Vec2::default(),
        })
        .collect();
    for (index, pair) in keyframes.windows(2).enumerate() {
        let interpolation = timing(&pair[0], &pair[1]);
        if keys[index].value == keys[index + 1].value
            || matches!(interpolation, Interpolation::Hold)
        {
            continue;
        }
        let (leave, arrive) = geometry.handles_between(along[index], along[index + 1]);
        keys[index].interpolation = interpolation;
        keys[index].out_tangent = leave;
        keys[index + 1].in_tangent = arrive;
    }
    Ok(AnimatedPoint::Keyframes {
        keyframes: keys,
        before: Extrapolation::Hold,
        after: Extrapolation::Hold,
    })
}