alpha2-eval 0.9.0

Pure alpha2 timeline evaluation.
Documentation
//! A repeating or continued curve spelled out as keyframes.

use super::{CurveError, part_keys, stepped};
use crate::{SampleContext, sample_scalar};
use alpha2_model::{Animated, Extrapolation, Interpolation, Keyframe, MAX_KEYFRAMES};
use alpha2_time::{MediaTime, TimeRange};

struct Spelled {
    keys: Vec<(i128, Interpolation, Option<f32>)>,
}

impl Spelled {
    fn push(&mut self, time: i128, interpolation: Interpolation) -> Result<(), CurveError> {
        self.write(time, interpolation, None)
    }

    fn write(
        &mut self,
        time: i128,
        interpolation: Interpolation,
        value: Option<f32>,
    ) -> Result<(), CurveError> {
        if self.keys.len() >= MAX_KEYFRAMES {
            return Err(CurveError::TooManyKeys);
        }
        self.keys.push((time, interpolation, value));
        Ok(())
    }

    fn forward(
        &mut self,
        keyframes: &[Keyframe<f32>],
        shift: i128,
        wraps: bool,
    ) -> Result<(), CurveError> {
        let count = keyframes.len();
        for (index, keyframe) in keyframes[..count - 1].iter().enumerate() {
            let time = i128::from(keyframe.time.ticks()) + shift;
            if !wraps || index + 2 < count {
                self.push(time, keyframe.interpolation.clone())?;
                continue;
            }
            let last = &keyframes[count - 1];
            let length = i128::from(last.time.ticks()) - i128::from(keyframe.time.ticks());
            if length == 1 {
                self.push(time, Interpolation::Hold)?;
                continue;
            }
            for part in part_keys(keyframe, last, keyframe.time.ticks(), last.time.ticks() - 1) {
                self.push(i128::from(part.time.ticks()) + shift, part.interpolation)?;
            }
            self.push(time + length - 1, Interpolation::Hold)?;
        }
        Ok(())
    }

    fn mirrored(&mut self, keyframes: &[Keyframe<f32>], base: i128) -> Result<(), CurveError> {
        let end = i128::from(keyframes[keyframes.len() - 1].time.ticks());
        for pair in keyframes.windows(2).rev() {
            let (left, right) = (&pair[0], &pair[1]);
            let time = base + end - i128::from(right.time.ticks());
            match left.interpolation {
                Interpolation::Hold => {
                    self.push(time, Interpolation::Hold)?;
                    if right.time.ticks() - left.time.ticks() > 1 {
                        self.push(time + 1, Interpolation::Hold)?;
                    }
                }
                Interpolation::Steps(steps) => {
                    self.push(time, Interpolation::Hold)?;
                    let risers = stepped(left, right, steps, left.time.ticks(), right.time.ticks());
                    let mut next = right.time.ticks();
                    for riser in risers.iter().rev() {
                        let shown = base + end - i128::from(next) + 1;
                        if shown < base + end - i128::from(left.time.ticks()) {
                            self.push(shown, Interpolation::Hold)?;
                        }
                        next = riser.time.ticks();
                    }
                }
                Interpolation::Points { ref points } => self.push(
                    time,
                    Interpolation::Points {
                        points: alpha2_model::easing_points_reversed(points),
                    },
                )?,
                Interpolation::Linear => self.push(time, Interpolation::Linear)?,
                Interpolation::CubicBezier(curve) => {
                    self.push(time, Interpolation::CubicBezier(curve.reversed()))?;
                }
                Interpolation::ValueBezier(curve) => {
                    self.push(time, Interpolation::ValueBezier(curve.reversed()))?;
                }
            }
        }
        Ok(())
    }

    fn pass(
        &mut self,
        keyframes: &[Keyframe<f32>],
        mode: Extrapolation,
        pass: i128,
        start: i128,
        period: i128,
    ) -> Result<(), CurveError> {
        if mode == Extrapolation::PingPong && pass.rem_euclid(2) == 1 {
            self.mirrored(keyframes, start + pass * period)
        } else {
            self.forward(keyframes, pass * period, mode == Extrapolation::Repeat)
        }
    }
}

/// Spells out as keyframes what the value's `before` and `after` show over `range`, and sets
/// each side the range reaches to `hold`: copies of the keyframes for every pass of a repeating
/// mode that meets the range, and one keyframe at the range's edge for `linear`.
///
/// Every keyframe written holds the value the evaluator gives at its tick (the last keyframe of
/// a side left as it is keeps its own, which a wrap there does not show). Between them the
/// curve is the same, with two exceptions that stay within rounding: the last segment of a
/// `repeat` pass, which ends one tick early and holds across the wrap, and a mirrored
/// `ping_pong` pass, whose curves are written reversed. A value that is not keyed is left
/// alone.
///
/// The result shows the old curve inside `range` only. Past the range a spelled side holds,
/// and a repeating side the range does not reach repeats all the keyframes there now are.
///
/// # Errors
///
/// [`CurveError::TooManyKeys`] when the result would hold more than [`MAX_KEYFRAMES`]
/// keyframes; the value is then left as it was.
pub fn materialize(animation: &mut Animated<f32>, range: TimeRange) -> Result<(), CurveError> {
    let live = animation.clone();
    let Animated::Keyframes {
        keyframes,
        before,
        after,
    } = animation
    else {
        return Ok(());
    };
    let [first, .., last] = keyframes.as_slice() else {
        return Ok(());
    };
    let (start, end) = (
        i128::from(first.time.ticks()),
        i128::from(last.time.ticks()),
    );
    let period = end - start;
    let (from, to) = (
        i128::from(range.start().ticks()),
        i128::from(range.end().ticks()) - 1,
    );
    if to < from {
        return Ok(());
    }
    let wraps = matches!(after, Extrapolation::Repeat | Extrapolation::RepeatOffset);
    let reaches_before = from < start && *before != Extrapolation::Hold;
    let reaches_after = *after != Extrapolation::Hold && (to > end || (to == end && wraps));
    let pass_of = |tick: i128| (tick - start).div_euclid(period);
    let count = keyframes.len();
    let mut spelled = Spelled { keys: Vec::new() };

    if reaches_before {
        if *before == Extrapolation::Linear {
            spelled.push(from, Interpolation::Linear)?;
        } else {
            for pass in pass_of(from)..0 {
                spelled.pass(keyframes, *before, pass, start, period)?;
            }
        }
    }
    if reaches_after && *after != Extrapolation::Linear {
        spelled.pass(keyframes, *after, 0, start, period)?;
        for pass in 1..=pass_of(to) {
            spelled.pass(keyframes, *after, pass, start, period)?;
        }
        if *after != Extrapolation::Repeat {
            spelled.push(start + (pass_of(to) + 1) * period, Interpolation::Linear)?;
        }
    } else {
        for keyframe in &keyframes[..count - 1] {
            spelled.push(
                i128::from(keyframe.time.ticks()),
                keyframe.interpolation.clone(),
            )?;
        }
        if reaches_after {
            spelled.push(end, Interpolation::Linear)?;
            spelled.push(to + 1, Interpolation::Linear)?;
        } else {
            spelled.write(end, last.interpolation.clone(), Some(last.value))?;
        }
    }

    let written = spelled
        .keys
        .into_iter()
        .filter_map(|(time, interpolation, value)| {
            let time = MediaTime(i64::try_from(time).ok()?);
            Some(Keyframe {
                time,
                value: value.unwrap_or_else(|| sample_scalar(&live, time, &SampleContext::NONE)),
                interpolation,
            })
        })
        .collect();
    *keyframes = written;
    if reaches_before {
        *before = Extrapolation::Hold;
    }
    if reaches_after {
        *after = Extrapolation::Hold;
    }
    Ok(())
}