alpha2-eval 0.9.0

Pure alpha2 timeline evaluation.
Documentation
//! Keyframes rewritten so that each holds a value inside a range, for a property whose range is
//! applied after its curve.

use super::{Cubic, coordinate, part_keys, segment_value, span};
use alpha2_model::{Domain, Interpolation, Keyframe};
use alpha2_time::MediaTime;

#[derive(Copy, Clone, Eq, PartialEq)]
enum Side {
    Below,
    Inside,
    Above,
}

struct Segment<'a> {
    left: &'a Keyframe<f32>,
    right: &'a Keyframe<f32>,
}

impl Segment<'_> {
    fn value(&self, tick: i64) -> f32 {
        segment_value(self.left, self.right, tick)
    }

    fn turns(&self) -> Vec<i64> {
        let (start, end) = (self.left.time.ticks(), self.right.time.ticks());
        let length = span(self.left.time, self.right.time);
        let corners = match &self.left.interpolation {
            Interpolation::Points { points } => points.as_slice(),
            _ => &[],
        };
        let mut ticks: Vec<i64> = Cubic::of(self.left, self.right)
            .into_iter()
            .flat_map(|cubic| {
                cubic
                    .turns()
                    .map(|u| coordinate(self.left.time) + cubic.progress_at(u) * length)
                    .collect::<Vec<_>>()
            })
            .chain(
                corners
                    .iter()
                    .map(|point| coordinate(self.left.time) + f64::from(point.x) * length),
            )
            .map(|time| {
                #[expect(clippy::cast_possible_truncation, reason = "a time inside the segment")]
                let tick = time.floor() as i64;
                tick.clamp(start, end)
            })
            .collect();
        ticks.push(end);
        ticks.sort_unstable();
        ticks.dedup();
        ticks
    }

    fn stretches(&self, from: i64, to: i64, domain: Domain, out: &mut Vec<(i64, Side)>) {
        let first = |passed: &dyn Fn(f32) -> bool| {
            let (mut low, mut high) = (from, to + 1);
            while low < high {
                let middle = low + (high - low) / 2;
                if passed(self.value(middle)) {
                    high = middle;
                } else {
                    low = middle + 1;
                }
            }
            low
        };
        let rising = self.value(from) <= self.value(to);
        let (enters, leaves, before, after) = if rising {
            (
                first(&|value| value >= domain.min),
                first(&|value| value > domain.max),
                Side::Below,
                Side::Above,
            )
        } else {
            (
                first(&|value| value <= domain.max),
                first(&|value| value < domain.min),
                Side::Above,
                Side::Below,
            )
        };
        for (start, side) in [(from, before), (enters, Side::Inside), (leaves, after)] {
            let end = match side {
                Side::Inside => leaves,
                _ if side == before => enters,
                _ => to + 1,
            };
            if start < end && out.last().is_none_or(|(_, last)| *last != side) {
                out.push((start, side));
            }
        }
    }
}

pub(crate) fn keys_within(keys: &[Keyframe<f32>], domain: Domain) -> Vec<Keyframe<f32>> {
    let inside = |value: f32| value >= domain.min && value <= domain.max;
    let key = |tick: i64, value: f32, interpolation: Interpolation| Keyframe {
        time: MediaTime(tick),
        value: domain.clamp(value),
        interpolation,
    };
    let mut out = Vec::with_capacity(keys.len());
    for (index, left) in keys.iter().enumerate() {
        let Some(right) = keys.get(index + 1) else {
            out.push(key(
                left.time.ticks(),
                left.value,
                left.interpolation.clone(),
            ));
            break;
        };
        if matches!(left.interpolation, Interpolation::Hold)
            || (inside(left.value) && inside(right.value))
        {
            out.push(key(
                left.time.ticks(),
                left.value,
                left.interpolation.clone(),
            ));
            continue;
        }
        let segment = Segment { left, right };
        let (start, end) = (left.time.ticks(), right.time.ticks());
        let mut stretches = Vec::new();
        let mut from = start;
        for turn in segment.turns() {
            if from <= turn {
                segment.stretches(from, turn, domain, &mut stretches);
                from = turn + 1;
            }
        }
        for (position, (first, side)) in stretches.iter().enumerate() {
            let last = stretches
                .get(position + 1)
                .map_or(end, |(next, _)| next - 1);
            if *first == end {
                continue;
            }
            if *side != Side::Inside || *first == last {
                out.push(key(*first, segment.value(*first), Interpolation::Hold));
                continue;
            }
            out.extend(
                part_keys(left, right, *first, last)
                    .into_iter()
                    .map(|part| key(part.time.ticks(), part.value, part.interpolation)),
            );
            if last != end {
                out.push(key(last, segment.value(last), Interpolation::Hold));
            }
        }
    }
    out
}