Skip to main content

sui_animation/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::{fmt, sync::Arc};
4
5use sui_core::{Color, ColorSpace, Point, Rect, Size, Transform, Vector};
6pub use sui_core::{MotionPolicy, MotionPreference};
7
8pub const ANIMATION_DOCUMENT_VERSION: u32 = 2;
9/// The oldest document version this build still reads. Version 2 added
10/// timeline markers.
11pub const MIN_ANIMATION_DOCUMENT_VERSION: u32 = 1;
12
13pub trait Interpolate: Sized {
14    fn interpolate(from: Self, to: Self, t: f32) -> Self;
15
16    /// Like [`Interpolate::interpolate`], but lets `t` leave `0..=1` so a
17    /// spring can overshoot its target. Values that cannot extend past their
18    /// endpoints, such as colors, clamp instead.
19    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
20        Self::interpolate(from, to, t)
21    }
22}
23
24impl Interpolate for f32 {
25    fn interpolate(from: Self, to: Self, t: f32) -> Self {
26        Self::extrapolate(from, to, t.clamp(0.0, 1.0))
27    }
28
29    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
30        // Endpoint-exact: `from + (to - from) * 1.0` accumulates float error
31        // and lands one bit away from `to`, so settled animations would never
32        // exactly reach their target value.
33        if t == 0.0 {
34            return from;
35        }
36        if t == 1.0 {
37            return to;
38        }
39        from + ((to - from) * t)
40    }
41}
42
43impl Interpolate for Point {
44    fn interpolate(from: Self, to: Self, t: f32) -> Self {
45        Self::extrapolate(from, to, t.clamp(0.0, 1.0))
46    }
47
48    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
49        Point::new(
50            f32::extrapolate(from.x, to.x, t),
51            f32::extrapolate(from.y, to.y, t),
52        )
53    }
54}
55
56impl Interpolate for Vector {
57    fn interpolate(from: Self, to: Self, t: f32) -> Self {
58        Self::extrapolate(from, to, t.clamp(0.0, 1.0))
59    }
60
61    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
62        Vector::new(
63            f32::extrapolate(from.x, to.x, t),
64            f32::extrapolate(from.y, to.y, t),
65        )
66    }
67}
68
69impl Interpolate for Size {
70    fn interpolate(from: Self, to: Self, t: f32) -> Self {
71        Self::extrapolate(from, to, t.clamp(0.0, 1.0))
72    }
73
74    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
75        Size::new(
76            f32::extrapolate(from.width, to.width, t).max(0.0),
77            f32::extrapolate(from.height, to.height, t).max(0.0),
78        )
79    }
80}
81
82impl Interpolate for Rect {
83    fn interpolate(from: Self, to: Self, t: f32) -> Self {
84        Self::extrapolate(from, to, t.clamp(0.0, 1.0))
85    }
86
87    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
88        Rect::from_origin_size(
89            Point::extrapolate(from.origin, to.origin, t),
90            Size::extrapolate(from.size, to.size, t),
91        )
92    }
93}
94
95/// Blends the translation, rotation, scale, and shear of two transforms
96/// separately, the way CSS interpolates matrices. Blending the raw matrix
97/// entries would shrink a rotating shape halfway through its turn. Rotation
98/// takes the shorter way around. Degenerate transforms (zero scale) cannot be
99/// decomposed and fall back to blending the matrix entries.
100impl Interpolate for Transform {
101    fn interpolate(from: Self, to: Self, t: f32) -> Self {
102        Self::extrapolate(from, to, t.clamp(0.0, 1.0))
103    }
104
105    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
106        if t == 0.0 || from == to {
107            return from;
108        }
109        if t == 1.0 {
110            return to;
111        }
112        match (DecomposedTransform::new(from), DecomposedTransform::new(to)) {
113            (Some(start), Some(end)) => start.extrapolate(end, t).compose(),
114            _ => Transform::new(
115                f32::extrapolate(from.xx, to.xx, t),
116                f32::extrapolate(from.yx, to.yx, t),
117                f32::extrapolate(from.xy, to.xy, t),
118                f32::extrapolate(from.yy, to.yy, t),
119                f32::extrapolate(from.dx, to.dx, t),
120                f32::extrapolate(from.dy, to.dy, t),
121            ),
122        }
123    }
124}
125
126/// An affine transform split as `translate * rotate * [[scale_x, shear],
127/// [0, scale_y]]`. A mirrored transform has a negative `scale_y`.
128#[derive(Debug, Clone, Copy, PartialEq)]
129struct DecomposedTransform {
130    translation: Vector,
131    rotation: f32,
132    scale_x: f32,
133    scale_y: f32,
134    shear: f32,
135}
136
137impl DecomposedTransform {
138    fn new(transform: Transform) -> Option<Self> {
139        let scale_x = transform.xx.hypot(transform.yx);
140        if !scale_x.is_finite() || scale_x <= f32::EPSILON {
141            return None;
142        }
143        let rotation = transform.yx.atan2(transform.xx);
144        let (sin, cos) = rotation.sin_cos();
145        Some(Self {
146            translation: Vector::new(transform.dx, transform.dy),
147            rotation,
148            scale_x,
149            scale_y: (cos * transform.yy) - (sin * transform.xy),
150            shear: (cos * transform.xy) + (sin * transform.yy),
151        })
152    }
153
154    fn extrapolate(self, to: Self, t: f32) -> Self {
155        let turn = (to.rotation - self.rotation + std::f32::consts::PI)
156            .rem_euclid(std::f32::consts::TAU)
157            - std::f32::consts::PI;
158        Self {
159            translation: Vector::extrapolate(self.translation, to.translation, t),
160            rotation: self.rotation + turn * t,
161            scale_x: f32::extrapolate(self.scale_x, to.scale_x, t),
162            scale_y: f32::extrapolate(self.scale_y, to.scale_y, t),
163            shear: f32::extrapolate(self.shear, to.shear, t),
164        }
165    }
166
167    fn compose(self) -> Transform {
168        let (sin, cos) = self.rotation.sin_cos();
169        Transform::new(
170            cos * self.scale_x,
171            sin * self.scale_x,
172            (cos * self.shear) - (sin * self.scale_y),
173            (sin * self.shear) + (cos * self.scale_y),
174            self.translation.x,
175            self.translation.y,
176        )
177    }
178}
179
180/// Colors blend in premultiplied OKLab (see [`Color::mix_oklab`]): mixes are
181/// perceptually even, and fades from a transparent color keep their hue
182/// instead of passing through a dark fringe.
183impl Interpolate for Color {
184    fn interpolate(from: Self, to: Self, t: f32) -> Self {
185        from.mix_oklab(to, t)
186    }
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Default)]
190pub enum Easing {
191    #[default]
192    Linear,
193    EaseIn,
194    EaseOut,
195    EaseInOut,
196    CubicBezier {
197        x1: f32,
198        y1: f32,
199        x2: f32,
200        y2: f32,
201    },
202}
203
204impl Easing {
205    pub fn sample(self, t: f32) -> f32 {
206        let t = t.clamp(0.0, 1.0);
207        match self {
208            Self::Linear => t,
209            Self::EaseIn => t * t,
210            Self::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
211            Self::EaseInOut => {
212                if t < 0.5 {
213                    2.0 * t * t
214                } else {
215                    1.0 - ((-2.0 * t + 2.0).powi(2) * 0.5)
216                }
217            }
218            Self::CubicBezier { x1, y1, x2, y2 } => sample_cubic_bezier(x1, y1, x2, y2, t),
219        }
220    }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq)]
224pub struct Transition<T> {
225    pub start: T,
226    pub end: T,
227    pub start_time: f64,
228    pub duration: f64,
229    pub easing: Easing,
230}
231
232impl<T> Transition<T>
233where
234    T: Copy + Interpolate,
235{
236    pub fn new(start: T, end: T, start_time: f64, duration: f64, easing: Easing) -> Self {
237        Self {
238            start,
239            end,
240            start_time,
241            duration: duration.max(0.0),
242            easing,
243        }
244    }
245
246    pub fn progress(&self, time: f64) -> f32 {
247        if self.duration <= f64::EPSILON {
248            return 1.0;
249        }
250        let elapsed = time - self.start_time;
251        // Snap to completion with a hair of tolerance: durations often
252        // originate as f32 theme tokens, so a fixed-step advance can land
253        // float dust short of `duration` and would otherwise sample at
254        // t = 1 - ε, leaving settled states one bit away from their target.
255        if elapsed >= self.duration * (1.0 - 1e-6) {
256            return 1.0;
257        }
258        (elapsed / self.duration).clamp(0.0, 1.0) as f32
259    }
260
261    pub fn sample(&self, time: f64) -> T {
262        T::interpolate(
263            self.start,
264            self.end,
265            self.easing.sample(self.progress(time)),
266        )
267    }
268
269    pub fn is_complete(&self, time: f64) -> bool {
270        self.progress(time) >= 1.0
271    }
272}
273
274/// A spring described the way designers tune one: how long it takes to
275/// settle, and how much it bounces.
276///
277/// `duration` is the period of the undamped spring in seconds, which is
278/// close to how long the motion reads as taking. `bounce` runs from `-1` to
279/// `1`: `0` settles as fast as possible without overshooting, positive values
280/// overshoot and oscillate, and negative values approach more gently.
281#[derive(Debug, Clone, Copy, PartialEq)]
282pub struct SpringSpec {
283    pub duration: f32,
284    pub bounce: f32,
285}
286
287impl SpringSpec {
288    /// Settles without overshoot.
289    pub const SMOOTH: Self = Self::new(0.35, 0.0);
290    /// Quick, with a hint of overshoot.
291    pub const SNAPPY: Self = Self::new(0.3, 0.15);
292    /// Visibly overshoots and settles back.
293    pub const BOUNCY: Self = Self::new(0.45, 0.4);
294
295    /// How far from rest, as a share of the distance travelled, a spring
296    /// counts as settled.
297    pub const REST_THRESHOLD: f64 = 1.0e-3;
298
299    pub const fn new(duration: f32, bounce: f32) -> Self {
300        Self { duration, bounce }
301    }
302
303    /// The spec matching a unit-mass spring with this `stiffness` and
304    /// `damping`.
305    pub fn from_physics(stiffness: f32, damping: f32) -> Self {
306        let stiffness = stiffness.max(f32::EPSILON);
307        let ratio = damping.max(0.0) / (2.0 * stiffness.sqrt());
308        let bounce = if ratio <= 1.0 {
309            1.0 - ratio
310        } else {
311            1.0 / ratio - 1.0
312        };
313        Self::new(std::f32::consts::TAU / stiffness.sqrt(), bounce)
314    }
315
316    fn resolved_duration(self) -> f64 {
317        f64::from(self.duration).max(1.0e-3)
318    }
319
320    /// Bounce is kept short of `1`, which would oscillate forever.
321    fn resolved_bounce(self) -> f64 {
322        f64::from(self.bounce).clamp(-0.95, 0.95)
323    }
324
325    /// Stiffness of the equivalent unit-mass spring.
326    pub fn stiffness(self) -> f32 {
327        self.physics().0 as f32
328    }
329
330    /// Damping of the equivalent unit-mass spring.
331    pub fn damping(self) -> f32 {
332        self.physics().1 as f32
333    }
334
335    /// The damping ratio: below 1 oscillates, 1 is critically damped.
336    pub fn damping_ratio(self) -> f32 {
337        self.resolved_damping_ratio() as f32
338    }
339
340    fn resolved_damping_ratio(self) -> f64 {
341        let bounce = self.resolved_bounce();
342        if bounce >= 0.0 {
343            1.0 - bounce
344        } else {
345            1.0 / (1.0 + bounce)
346        }
347    }
348
349    fn physics(self) -> (f64, f64) {
350        let angular = std::f64::consts::TAU / self.resolved_duration();
351        let stiffness = angular * angular;
352        let damping = 2.0 * self.resolved_damping_ratio() * angular;
353        (stiffness, damping)
354    }
355
356    /// Progress from 0 to 1 after `elapsed` seconds of a spring released
357    /// from rest. Bouncy springs overshoot past 1 before settling.
358    pub fn progress(self, elapsed: f64) -> f32 {
359        if elapsed <= 0.0 {
360            return 0.0;
361        }
362        if elapsed >= self.settling_duration() {
363            return 1.0;
364        }
365        let (stiffness, damping) = self.physics();
366        let (displacement, _) = spring_state(stiffness, damping, 1.0, 0.0, elapsed);
367        (1.0 - displacement) as f32
368    }
369
370    /// Seconds until a spring released from rest stays within
371    /// [`SpringSpec::REST_THRESHOLD`] of its target.
372    pub fn settling_duration(self) -> f64 {
373        let (stiffness, damping) = self.physics();
374        let ratio = self.resolved_damping_ratio();
375        let angular = stiffness.sqrt();
376        if ratio < 1.0 - 1.0e-4 {
377            // The oscillation stays inside an exponential envelope, whose
378            // amplitude for a release from rest is 1 / sqrt(1 - ratio^2).
379            let amplitude = 1.0 / (1.0 - ratio * ratio).sqrt();
380            return (amplitude / Self::REST_THRESHOLD).ln() / (ratio * angular);
381        }
382        // Critically damped and overdamped springs released from rest approach
383        // the target without crossing it, so the first time within the
384        // threshold is final.
385        let within =
386            |t: f64| spring_state(stiffness, damping, 1.0, 0.0, t).0 <= Self::REST_THRESHOLD;
387        let mut high = 1.0 / angular;
388        while !within(high) && high < 600.0 {
389            high *= 2.0;
390        }
391        let mut low = 0.0;
392        for _ in 0..40 {
393            let middle = (low + high) * 0.5;
394            if within(middle) {
395                high = middle;
396            } else {
397                low = middle;
398            }
399        }
400        high
401    }
402}
403
404impl Default for SpringSpec {
405    fn default() -> Self {
406        Self::SMOOTH
407    }
408}
409
410/// Displacement and velocity of a unit-mass damped spring `elapsed` seconds
411/// after it started at `displacement` with `velocity`. This is the exact
412/// solution, so it is stable and gives the same motion at any frame rate.
413fn spring_state(
414    stiffness: f64,
415    damping: f64,
416    displacement: f64,
417    velocity: f64,
418    elapsed: f64,
419) -> (f64, f64) {
420    let t = elapsed.max(0.0);
421    if stiffness <= f64::EPSILON {
422        // No spring: damping alone slows the initial velocity.
423        if damping <= f64::EPSILON {
424            return (displacement + velocity * t, velocity);
425        }
426        let decay = (-damping * t).exp();
427        return (
428            displacement + velocity * (1.0 - decay) / damping,
429            velocity * decay,
430        );
431    }
432
433    let angular = stiffness.sqrt();
434    let ratio = damping / (2.0 * angular);
435    if (ratio - 1.0).abs() <= 1.0e-4 {
436        // Critically damped.
437        let slope = velocity + angular * displacement;
438        let decay = (-angular * t).exp();
439        (
440            decay * (displacement + slope * t),
441            decay * (velocity - angular * slope * t),
442        )
443    } else if ratio < 1.0 {
444        // Underdamped: a decaying oscillation.
445        let damped = angular * (1.0 - ratio * ratio).sqrt();
446        let decay_rate = ratio * angular;
447        let sine_weight = (velocity + decay_rate * displacement) / damped;
448        let decay = (-decay_rate * t).exp();
449        let (sin, cos) = (damped * t).sin_cos();
450        let position = decay * (displacement * cos + sine_weight * sin);
451        let slope = decay
452            * ((sine_weight * damped - decay_rate * displacement) * cos
453                - (displacement * damped + decay_rate * sine_weight) * sin);
454        (position, slope)
455    } else {
456        // Overdamped: two decaying exponentials.
457        let root = (ratio * ratio - 1.0).sqrt();
458        let fast = -angular * (ratio + root);
459        let slow = -angular * (ratio - root);
460        let fast_weight = (velocity - slow * displacement) / (fast - slow);
461        let slow_weight = displacement - fast_weight;
462        let (fast_decay, slow_decay) = ((fast * t).exp(), (slow * t).exp());
463        (
464            fast_weight * fast_decay + slow_weight * slow_decay,
465            fast * fast_weight * fast_decay + slow * slow_weight * slow_decay,
466        )
467    }
468}
469
470/// A spring that follows a moving target, stepped by elapsed time. Use it for
471/// physics-driven motion, such as a dragged handle that springs home carrying
472/// the velocity of the fling; for transitions between states prefer
473/// [`MotionValue`] with an [`AnimationSpec::Spring`].
474#[derive(Debug, Clone, Copy, PartialEq)]
475pub struct SpringF32 {
476    pub value: f32,
477    pub velocity: f32,
478    pub stiffness: f32,
479    pub damping: f32,
480}
481
482impl SpringF32 {
483    /// Distance from the target below which [`SpringF32::is_settled`] reports
484    /// the spring at rest; the speed limit is ten times this per second.
485    pub const REST_EPSILON: f32 = 1.0e-3;
486
487    pub fn new(value: f32) -> Self {
488        Self {
489            value,
490            velocity: 0.0,
491            stiffness: 180.0,
492            damping: 24.0,
493        }
494    }
495
496    /// A spring at rest at `value` with the stiffness and damping of `spec`.
497    pub fn from_spec(value: f32, spec: SpringSpec) -> Self {
498        Self::new(value).with_spec(spec)
499    }
500
501    pub fn with_config(mut self, stiffness: f32, damping: f32) -> Self {
502        self.stiffness = stiffness.max(0.0);
503        self.damping = damping.max(0.0);
504        self
505    }
506
507    pub fn with_spec(self, spec: SpringSpec) -> Self {
508        self.with_config(spec.stiffness(), spec.damping())
509    }
510
511    pub fn with_velocity(mut self, velocity: f32) -> Self {
512        self.velocity = velocity;
513        self
514    }
515
516    /// Advance the spring by `delta` seconds toward `target` and return the
517    /// new value. The step is exact, so large or uneven deltas neither
518    /// destabilize the spring nor change its path.
519    pub fn step(&mut self, target: f32, delta: f64) -> f32 {
520        let dt = delta.max(0.0);
521        if dt <= f64::EPSILON {
522            return self.value;
523        }
524
525        let (displacement, velocity) = spring_state(
526            f64::from(self.stiffness),
527            f64::from(self.damping),
528            f64::from(self.value - target),
529            f64::from(self.velocity),
530            dt,
531        );
532        self.value = target + displacement as f32;
533        self.velocity = velocity as f32;
534        self.value
535    }
536
537    /// Whether the spring rests at `target`.
538    pub fn is_settled(&self, target: f32) -> bool {
539        (self.value - target).abs() <= Self::REST_EPSILON
540            && self.velocity.abs() <= Self::REST_EPSILON * 10.0
541    }
542
543    /// Snap to `target` once the spring has settled there. Returns whether it
544    /// is at rest.
545    pub fn settle(&mut self, target: f32) -> bool {
546        if self.is_settled(target) {
547            self.value = target;
548            self.velocity = 0.0;
549            return true;
550        }
551        false
552    }
553}
554
555#[derive(Debug, Clone, Copy, PartialEq)]
556pub struct Blink {
557    pub period: f64,
558    pub duty_cycle: f32,
559    pub phase: f64,
560}
561
562impl Blink {
563    pub fn new(period: f64) -> Self {
564        Self {
565            period: period.max(f64::EPSILON),
566            duty_cycle: 0.5,
567            phase: 0.0,
568        }
569    }
570
571    pub fn with_duty_cycle(mut self, duty_cycle: f32) -> Self {
572        self.duty_cycle = duty_cycle.clamp(0.0, 1.0);
573        self
574    }
575
576    pub fn with_phase(mut self, phase: f64) -> Self {
577        self.phase = phase;
578        self
579    }
580
581    pub fn is_on(&self, time: f64) -> bool {
582        let cycle = ((time + self.phase).rem_euclid(self.period)) / self.period;
583        cycle < self.duty_cycle as f64
584    }
585}
586
587#[derive(Debug, Clone, Copy, PartialEq)]
588pub struct Pulse {
589    pub period: f64,
590    pub min: f32,
591    pub max: f32,
592    pub phase: f64,
593    pub easing: Easing,
594}
595
596impl Pulse {
597    pub fn new(period: f64, min: f32, max: f32) -> Self {
598        Self {
599            period: period.max(f64::EPSILON),
600            min,
601            max,
602            phase: 0.0,
603            easing: Easing::EaseInOut,
604        }
605    }
606
607    pub fn with_phase(mut self, phase: f64) -> Self {
608        self.phase = phase;
609        self
610    }
611
612    pub fn with_easing(mut self, easing: Easing) -> Self {
613        self.easing = easing;
614        self
615    }
616
617    pub fn sample(&self, time: f64) -> f32 {
618        let cycle = ((time + self.phase).rem_euclid(self.period)) / self.period;
619        let triangle = if cycle <= 0.5 {
620            (cycle * 2.0) as f32
621        } else {
622            ((1.0 - cycle) * 2.0) as f32
623        };
624        f32::interpolate(self.min, self.max, self.easing.sample(triangle))
625    }
626}
627
628/// How a value travels to a new target: a timed curve or a spring.
629#[derive(Debug, Clone, Copy, PartialEq)]
630pub enum AnimationSpec {
631    /// Follow `easing` for `duration` seconds.
632    Tween { duration: f64, easing: Easing },
633    /// Move like a spring released from rest; see [`SpringSpec`].
634    Spring(SpringSpec),
635}
636
637impl AnimationSpec {
638    /// Jump straight to the target.
639    pub const INSTANT: Self = Self::tween(0.0, Easing::Linear);
640
641    pub const fn tween(duration: f64, easing: Easing) -> Self {
642        Self::Tween { duration, easing }
643    }
644
645    pub const fn spring(spec: SpringSpec) -> Self {
646        Self::Spring(spec)
647    }
648
649    /// Seconds until the value arrives: the tween's duration, or how long the
650    /// spring takes to settle.
651    pub fn duration(self) -> f64 {
652        match self {
653            Self::Tween { duration, .. } => duration.max(0.0),
654            Self::Spring(spring) => spring.settling_duration(),
655        }
656    }
657
658    /// Whether the animation finishes immediately.
659    pub fn is_instant(self) -> bool {
660        match self {
661            Self::Tween { duration, .. } => duration <= f64::EPSILON,
662            Self::Spring(_) => false,
663        }
664    }
665
666    /// Progress toward the target after `elapsed` seconds: 0 at the start and
667    /// exactly 1 once complete. Springs may overshoot past 1 on the way.
668    pub fn progress(self, elapsed: f64) -> f32 {
669        match self {
670            Self::Tween { duration, easing } => {
671                if self.is_complete(elapsed) {
672                    return 1.0;
673                }
674                easing.sample((elapsed / duration).clamp(0.0, 1.0) as f32)
675            }
676            Self::Spring(spring) => spring.progress(elapsed),
677        }
678    }
679
680    pub fn is_complete(self, elapsed: f64) -> bool {
681        match self {
682            // Snap to completion with a hair of tolerance: durations often
683            // originate as f32 theme tokens, so a fixed-step advance can land
684            // float dust short of `duration`.
685            Self::Tween { duration, .. } => {
686                elapsed >= 0.0 && (duration <= f64::EPSILON || elapsed >= duration * (1.0 - 1e-6))
687            }
688            Self::Spring(spring) => elapsed >= spring.settling_duration(),
689        }
690    }
691
692    /// The same motion played at `time_scale` speed: `0.5` takes twice as long.
693    pub fn time_scaled(self, time_scale: f32) -> Self {
694        let time_scale = MotionPolicy::FULL.with_time_scale(time_scale).time_scale();
695        match self {
696            Self::Tween { duration, easing } => Self::Tween {
697                duration: duration / f64::from(time_scale),
698                easing,
699            },
700            Self::Spring(spring) => Self::Spring(SpringSpec {
701                duration: spring.duration / time_scale,
702                ..spring
703            }),
704        }
705    }
706
707    /// The motion to play under `policy`: instant when motion is off,
708    /// stretched by the policy's time scale otherwise.
709    pub fn with_policy(self, policy: MotionPolicy) -> Self {
710        if policy.allows_motion() {
711            self.time_scaled(policy.time_scale())
712        } else {
713            Self::INSTANT
714        }
715    }
716
717    /// Like [`AnimationSpec::with_policy`], for motion that moves content:
718    /// instant unless the policy allows movement.
719    pub fn with_movement_policy(self, policy: MotionPolicy) -> Self {
720        if policy.allows_movement() {
721            self.with_policy(policy)
722        } else {
723            Self::INSTANT
724        }
725    }
726}
727
728impl From<SpringSpec> for AnimationSpec {
729    fn from(spring: SpringSpec) -> Self {
730        Self::Spring(spring)
731    }
732}
733
734/// How many overlapping retargets a [`MotionValue`] blends before folding the
735/// oldest into its starting point.
736const MOTION_SEGMENTS: usize = 4;
737
738#[derive(Debug, Clone, Copy, PartialEq)]
739struct MotionSegment<T> {
740    target: T,
741    start_time: f64,
742    spec: AnimationSpec,
743}
744
745impl<T> MotionSegment<T> {
746    fn progress(&self, time: f64) -> f32 {
747        self.spec.progress(time - self.start_time)
748    }
749
750    fn is_complete(&self, time: f64) -> bool {
751        self.spec.is_complete(time - self.start_time)
752    }
753}
754
755/// A value that animates toward its latest target on an absolute clock.
756///
757/// Retargeting mid-flight keeps the motion's momentum: the new animation
758/// blends from the still-running previous one instead of restarting from a
759/// standstill, so a hover that ends halfway through its fade-in turns around
760/// smoothly rather than stopping dead.
761#[derive(Debug, Clone, Copy, PartialEq)]
762pub struct MotionValue<T> {
763    base: T,
764    segments: [Option<MotionSegment<T>>; MOTION_SEGMENTS],
765}
766
767impl<T: Copy> MotionValue<T> {
768    pub const fn new(value: T) -> Self {
769        Self {
770            base: value,
771            segments: [None; MOTION_SEGMENTS],
772        }
773    }
774
775    /// The value this motion is heading to.
776    pub fn target(&self) -> T {
777        self.segments
778            .iter()
779            .rev()
780            .flatten()
781            .next()
782            .map_or(self.base, |segment| segment.target)
783    }
784
785    pub fn is_animating(&self) -> bool {
786        self.segments[0].is_some()
787    }
788
789    /// Stop animating and rest at `value`.
790    pub fn jump_to(&mut self, value: T) {
791        self.base = value;
792        self.segments = [None; MOTION_SEGMENTS];
793    }
794
795    fn segment_count(&self) -> usize {
796        self.segments.iter().flatten().count()
797    }
798}
799
800impl<T> MotionValue<T>
801where
802    T: Interpolate + Copy + PartialEq,
803{
804    /// The value at `time`.
805    pub fn value(&self, time: f64) -> T {
806        self.segments
807            .iter()
808            .flatten()
809            .fold(self.base, |value, segment| {
810                T::extrapolate(value, segment.target, segment.progress(time))
811            })
812    }
813
814    /// Start animating from the value at `time` toward `target`. Returns
815    /// whether the value is animating afterwards.
816    pub fn animate_to(&mut self, target: T, time: f64, spec: AnimationSpec) -> bool {
817        self.animate_to_after(target, time, 0.0, spec)
818    }
819
820    /// Like [`MotionValue::animate_to`], starting `delay` seconds after
821    /// `time`. Until then the value keeps doing what it was doing.
822    pub fn animate_to_after(
823        &mut self,
824        target: T,
825        time: f64,
826        delay: f64,
827        spec: AnimationSpec,
828    ) -> bool {
829        self.advance(time);
830        if target == self.target() {
831            return self.is_animating();
832        }
833        let delay = if delay.is_finite() {
834            delay.max(0.0)
835        } else {
836            0.0
837        };
838        if spec.is_instant() && delay <= 0.0 {
839            self.jump_to(target);
840            return false;
841        }
842
843        if self.segment_count() == MOTION_SEGMENTS {
844            // Fold the oldest animation into the starting point where it
845            // stands now. The value stays continuous; only that animation's
846            // remaining drift is dropped.
847            if let Some(oldest) = self.segments[0] {
848                self.base = T::extrapolate(self.base, oldest.target, oldest.progress(time));
849            }
850            self.segments.rotate_left(1);
851            self.segments[MOTION_SEGMENTS - 1] = None;
852        }
853        let slot = self.segment_count();
854        self.segments[slot] = Some(MotionSegment {
855            target,
856            start_time: time + delay,
857            spec,
858        });
859        true
860    }
861
862    /// When the running animations will all have finished, or `None` at rest.
863    pub fn end_time(&self) -> Option<f64> {
864        self.segments
865            .iter()
866            .flatten()
867            .map(|segment| segment.start_time + segment.spec.duration())
868            .reduce(f64::max)
869    }
870
871    /// Whether an animation is still running at `time`, without dropping
872    /// finished ones.
873    pub fn is_animating_at(&self, time: f64) -> bool {
874        self.segments
875            .iter()
876            .flatten()
877            .any(|segment| !segment.is_complete(time))
878    }
879
880    /// Drop animations that have finished by `time`. Returns whether the
881    /// value is still animating.
882    pub fn advance(&mut self, time: f64) -> bool {
883        // A finished animation pins the value to its target, so it and every
884        // animation it was blending from can be dropped.
885        let finished = self
886            .segments
887            .iter()
888            .rposition(|segment| segment.is_some_and(|segment| segment.is_complete(time)));
889        if let Some(index) = finished {
890            if let Some(segment) = self.segments[index] {
891                self.base = segment.target;
892            }
893            self.segments.rotate_left(index + 1);
894            for slot in &mut self.segments[MOTION_SEGMENTS - index - 1..] {
895                *slot = None;
896            }
897        }
898        self.is_animating()
899    }
900}
901
902/// Where a [`Stagger`] starts: the item that animates first.
903#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
904pub enum StaggerOrigin {
905    #[default]
906    First,
907    Last,
908    /// The middle item first, spreading out to both ends.
909    Center,
910    /// The item at this index first, spreading out from it.
911    Index(usize),
912}
913
914/// Delays that start a group of animations one after another, such as list
915/// items cascading in.
916///
917/// `delay(index, count)` gives each item's delay: `interval` seconds per step
918/// away from the origin, shrunk if needed so the last item starts within
919/// `max_delay`.
920#[derive(Debug, Clone, Copy, PartialEq)]
921pub struct Stagger {
922    pub interval: f64,
923    pub origin: StaggerOrigin,
924    pub max_delay: Option<f64>,
925}
926
927impl Stagger {
928    /// Items start at the same time.
929    pub const NONE: Self = Self::new(0.0);
930
931    pub const fn new(interval: f64) -> Self {
932        Self {
933            interval,
934            origin: StaggerOrigin::First,
935            max_delay: None,
936        }
937    }
938
939    pub const fn from(mut self, origin: StaggerOrigin) -> Self {
940        self.origin = origin;
941        self
942    }
943
944    /// Start the last item no later than `max_delay` seconds, however many
945    /// items there are.
946    pub const fn max_delay(mut self, max_delay: f64) -> Self {
947        self.max_delay = Some(max_delay);
948        self
949    }
950
951    fn steps(self, index: usize, count: usize) -> f64 {
952        let index = index as f64;
953        let last = count.saturating_sub(1) as f64;
954        match self.origin {
955            StaggerOrigin::First => index,
956            StaggerOrigin::Last => last - index,
957            StaggerOrigin::Center => (index - last * 0.5).abs(),
958            StaggerOrigin::Index(origin) => (index - origin as f64).abs(),
959        }
960    }
961
962    /// The delay in seconds for item `index` of `count`.
963    pub fn delay(self, index: usize, count: usize) -> f64 {
964        let interval = if self.interval.is_finite() {
965            self.interval.max(0.0)
966        } else {
967            0.0
968        };
969        if interval <= 0.0 || count == 0 {
970            return 0.0;
971        }
972        let steps = self.steps(index.min(count - 1), count).max(0.0);
973        let last = (count - 1) as f64;
974        let widest = match self.origin {
975            StaggerOrigin::First | StaggerOrigin::Last => last,
976            StaggerOrigin::Center => last * 0.5,
977            StaggerOrigin::Index(origin) => (origin as f64).max(last - origin as f64),
978        };
979        let interval = match self.max_delay {
980            Some(max_delay) if widest * interval > max_delay.max(0.0) && widest > 0.0 => {
981                max_delay.max(0.0) / widest
982            }
983            _ => interval,
984        };
985        steps * interval
986    }
987}
988
989impl Default for Stagger {
990    fn default() -> Self {
991        Self::NONE
992    }
993}
994
995/// A value animated by elapsed time: call [`AnimatedValue::tick`] with each
996/// frame's delta. Retargeting keeps momentum like [`MotionValue`].
997#[derive(Debug, Clone, Copy, PartialEq)]
998pub struct AnimatedValue<T> {
999    motion: MotionValue<T>,
1000    current: T,
1001    clock: f64,
1002    spec: AnimationSpec,
1003}
1004
1005impl<T> AnimatedValue<T>
1006where
1007    T: Interpolate + Copy + PartialEq,
1008{
1009    pub fn new(initial: T) -> Self {
1010        Self {
1011            motion: MotionValue::new(initial),
1012            current: initial,
1013            clock: 0.0,
1014            spec: AnimationSpec::tween(0.2, Easing::EaseInOut),
1015        }
1016    }
1017
1018    pub fn with_duration(mut self, seconds: f32) -> Self {
1019        self.set_duration(seconds);
1020        self
1021    }
1022
1023    pub fn with_easing(mut self, easing: Easing) -> Self {
1024        self.set_easing(easing);
1025        self
1026    }
1027
1028    pub fn with_spec(mut self, spec: AnimationSpec) -> Self {
1029        self.spec = spec;
1030        self
1031    }
1032
1033    /// Use a tween of `seconds` for later targets, keeping the easing.
1034    pub fn set_duration(&mut self, seconds: f32) {
1035        let easing = match self.spec {
1036            AnimationSpec::Tween { easing, .. } => easing,
1037            AnimationSpec::Spring(_) => Easing::EaseInOut,
1038        };
1039        self.spec = AnimationSpec::tween(f64::from(seconds.max(0.0)), easing);
1040    }
1041
1042    /// Use a tween with `easing` for later targets, keeping the duration.
1043    pub fn set_easing(&mut self, easing: Easing) {
1044        self.spec = AnimationSpec::tween(self.spec.duration(), easing);
1045    }
1046
1047    pub fn set_spec(&mut self, spec: AnimationSpec) {
1048        self.spec = spec;
1049    }
1050
1051    pub fn spec(&self) -> AnimationSpec {
1052        self.spec
1053    }
1054
1055    pub fn set_target(&mut self, target: T) {
1056        self.set_target_after(target, 0.0);
1057    }
1058
1059    /// Like [`AnimatedValue::set_target`], starting `delay` seconds of ticks
1060    /// from now.
1061    pub fn set_target_after(&mut self, target: T, delay: f64) {
1062        self.motion
1063            .animate_to_after(target, self.clock, delay, self.spec);
1064        self.current = self.motion.value(self.clock);
1065    }
1066
1067    pub fn jump_to(&mut self, value: T) {
1068        self.motion.jump_to(value);
1069        self.current = value;
1070    }
1071
1072    /// Advance by `delta_seconds`. Returns whether the value is still
1073    /// animating.
1074    pub fn tick(&mut self, delta_seconds: f32) -> bool {
1075        if !self.motion.is_animating() {
1076            return false;
1077        }
1078        self.clock += f64::from(delta_seconds.max(0.0));
1079        let animating = self.motion.advance(self.clock);
1080        self.current = self.motion.value(self.clock);
1081        animating
1082    }
1083
1084    pub fn value(&self) -> T {
1085        self.current
1086    }
1087
1088    pub fn target(&self) -> T {
1089        self.motion.target()
1090    }
1091
1092    pub fn is_animating(&self) -> bool {
1093        self.motion.is_animating()
1094    }
1095}
1096
1097#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1098pub struct AnimationTargetId(String);
1099
1100impl AnimationTargetId {
1101    pub fn new(id: impl Into<String>) -> Self {
1102        Self(id.into())
1103    }
1104
1105    pub fn as_str(&self) -> &str {
1106        &self.0
1107    }
1108}
1109
1110impl fmt::Display for AnimationTargetId {
1111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1112        f.write_str(self.as_str())
1113    }
1114}
1115
1116impl From<&str> for AnimationTargetId {
1117    fn from(value: &str) -> Self {
1118        Self::new(value)
1119    }
1120}
1121
1122impl From<String> for AnimationTargetId {
1123    fn from(value: String) -> Self {
1124        Self::new(value)
1125    }
1126}
1127
1128#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1129pub struct AnimationPropertyPath(String);
1130
1131impl AnimationPropertyPath {
1132    pub fn new(path: impl Into<String>) -> Self {
1133        Self(path.into())
1134    }
1135
1136    pub fn as_str(&self) -> &str {
1137        &self.0
1138    }
1139}
1140
1141impl fmt::Display for AnimationPropertyPath {
1142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143        f.write_str(self.as_str())
1144    }
1145}
1146
1147impl From<&str> for AnimationPropertyPath {
1148    fn from(value: &str) -> Self {
1149        Self::new(value)
1150    }
1151}
1152
1153impl From<String> for AnimationPropertyPath {
1154    fn from(value: String) -> Self {
1155        Self::new(value)
1156    }
1157}
1158
1159#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1160pub enum AnimationProperty {
1161    LayerOpacity,
1162    LayerTranslation,
1163    FillColor,
1164    Bounds,
1165    Custom(AnimationPropertyPath),
1166}
1167
1168impl AnimationProperty {
1169    pub fn path(&self) -> &str {
1170        match self {
1171            Self::LayerOpacity => "layer.opacity",
1172            Self::LayerTranslation => "layer.translation",
1173            Self::FillColor => "fill.color",
1174            Self::Bounds => "bounds",
1175            Self::Custom(path) => path.as_str(),
1176        }
1177    }
1178}
1179
1180#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1181pub struct AnimationBinding {
1182    pub target: AnimationTargetId,
1183    pub property: AnimationProperty,
1184}
1185
1186impl AnimationBinding {
1187    pub fn new(target: impl Into<AnimationTargetId>, property: AnimationProperty) -> Self {
1188        Self {
1189            target: target.into(),
1190            property,
1191        }
1192    }
1193}
1194
1195#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1196pub enum AnimationValueKind {
1197    Scalar,
1198    Point,
1199    Vector,
1200    Size,
1201    Rect,
1202    Color,
1203    Transform,
1204}
1205
1206#[derive(Debug, Clone, Copy, PartialEq)]
1207pub enum AnimationValue {
1208    Scalar(f32),
1209    Point(Point),
1210    Vector(Vector),
1211    Size(Size),
1212    Rect(Rect),
1213    Color(Color),
1214    Transform(Transform),
1215}
1216
1217impl AnimationValue {
1218    pub fn kind(self) -> AnimationValueKind {
1219        match self {
1220            Self::Scalar(_) => AnimationValueKind::Scalar,
1221            Self::Point(_) => AnimationValueKind::Point,
1222            Self::Vector(_) => AnimationValueKind::Vector,
1223            Self::Size(_) => AnimationValueKind::Size,
1224            Self::Rect(_) => AnimationValueKind::Rect,
1225            Self::Color(_) => AnimationValueKind::Color,
1226            Self::Transform(_) => AnimationValueKind::Transform,
1227        }
1228    }
1229
1230    pub fn as_scalar(self) -> Option<f32> {
1231        match self {
1232            Self::Scalar(value) => Some(value),
1233            _ => None,
1234        }
1235    }
1236
1237    pub fn as_vector(self) -> Option<Vector> {
1238        match self {
1239            Self::Vector(value) => Some(value),
1240            _ => None,
1241        }
1242    }
1243
1244    pub fn as_color(self) -> Option<Color> {
1245        match self {
1246            Self::Color(value) => Some(value),
1247            _ => None,
1248        }
1249    }
1250}
1251
1252impl Interpolate for AnimationValue {
1253    fn interpolate(from: Self, to: Self, t: f32) -> Self {
1254        Self::extrapolate(from, to, t.clamp(0.0, 1.0))
1255    }
1256
1257    fn extrapolate(from: Self, to: Self, t: f32) -> Self {
1258        match (from, to) {
1259            (Self::Scalar(from), Self::Scalar(to)) => Self::Scalar(f32::extrapolate(from, to, t)),
1260            (Self::Point(from), Self::Point(to)) => Self::Point(Point::extrapolate(from, to, t)),
1261            (Self::Vector(from), Self::Vector(to)) => {
1262                Self::Vector(Vector::extrapolate(from, to, t))
1263            }
1264            (Self::Size(from), Self::Size(to)) => Self::Size(Size::extrapolate(from, to, t)),
1265            (Self::Rect(from), Self::Rect(to)) => Self::Rect(Rect::extrapolate(from, to, t)),
1266            (Self::Color(from), Self::Color(to)) => Self::Color(Color::extrapolate(from, to, t)),
1267            (Self::Transform(from), Self::Transform(to)) => {
1268                Self::Transform(Transform::extrapolate(from, to, t))
1269            }
1270            (from, to) => {
1271                if t >= 1.0 {
1272                    to
1273                } else {
1274                    from
1275                }
1276            }
1277        }
1278    }
1279}
1280
1281impl From<f32> for AnimationValue {
1282    fn from(value: f32) -> Self {
1283        Self::Scalar(value)
1284    }
1285}
1286
1287impl From<Point> for AnimationValue {
1288    fn from(value: Point) -> Self {
1289        Self::Point(value)
1290    }
1291}
1292
1293impl From<Vector> for AnimationValue {
1294    fn from(value: Vector) -> Self {
1295        Self::Vector(value)
1296    }
1297}
1298
1299impl From<Size> for AnimationValue {
1300    fn from(value: Size) -> Self {
1301        Self::Size(value)
1302    }
1303}
1304
1305impl From<Rect> for AnimationValue {
1306    fn from(value: Rect) -> Self {
1307        Self::Rect(value)
1308    }
1309}
1310
1311impl From<Color> for AnimationValue {
1312    fn from(value: Color) -> Self {
1313        Self::Color(value)
1314    }
1315}
1316
1317impl From<Transform> for AnimationValue {
1318    fn from(value: Transform) -> Self {
1319        Self::Transform(value)
1320    }
1321}
1322
1323#[derive(Debug, Clone, Copy, PartialEq)]
1324pub struct Keyframe<T> {
1325    pub time: f64,
1326    pub value: T,
1327    pub easing: Easing,
1328}
1329
1330impl<T> Keyframe<T> {
1331    pub fn new(time: f64, value: T) -> Self {
1332        Self {
1333            time: time.max(0.0),
1334            value,
1335            easing: Easing::Linear,
1336        }
1337    }
1338
1339    pub fn with_easing(mut self, easing: Easing) -> Self {
1340        self.easing = easing;
1341        self
1342    }
1343}
1344
1345#[derive(Debug, Clone, PartialEq)]
1346pub struct Track<T = AnimationValue> {
1347    pub binding: AnimationBinding,
1348    pub keyframes: Vec<Keyframe<T>>,
1349    pub enabled: bool,
1350}
1351
1352impl<T> Track<T> {
1353    pub fn new(binding: AnimationBinding) -> Self {
1354        Self {
1355            binding,
1356            keyframes: Vec::new(),
1357            enabled: true,
1358        }
1359    }
1360
1361    pub fn with_keyframes(mut self, keyframes: impl IntoIterator<Item = Keyframe<T>>) -> Self {
1362        self.keyframes.extend(keyframes);
1363        self
1364    }
1365
1366    pub fn push_keyframe(&mut self, keyframe: Keyframe<T>) {
1367        self.keyframes.push(keyframe);
1368    }
1369
1370    pub fn with_enabled(mut self, enabled: bool) -> Self {
1371        self.enabled = enabled;
1372        self
1373    }
1374}
1375
1376impl<T> Track<T>
1377where
1378    T: Copy + Interpolate,
1379{
1380    pub fn sample(&self, time: f64) -> Option<T> {
1381        if !self.enabled || self.keyframes.is_empty() {
1382            return None;
1383        }
1384
1385        let mut first = &self.keyframes[0];
1386        let mut last = &self.keyframes[0];
1387        let mut previous = None;
1388        let mut next = None;
1389
1390        for keyframe in &self.keyframes {
1391            if keyframe.time < first.time {
1392                first = keyframe;
1393            }
1394            if keyframe.time > last.time {
1395                last = keyframe;
1396            }
1397            if keyframe.time <= time
1398                && previous
1399                    .map(|candidate: &Keyframe<T>| keyframe.time >= candidate.time)
1400                    .unwrap_or(true)
1401            {
1402                previous = Some(keyframe);
1403            }
1404            if keyframe.time >= time
1405                && next
1406                    .map(|candidate: &Keyframe<T>| keyframe.time <= candidate.time)
1407                    .unwrap_or(true)
1408            {
1409                next = Some(keyframe);
1410            }
1411        }
1412
1413        let Some(previous) = previous else {
1414            return Some(first.value);
1415        };
1416        let Some(next) = next else {
1417            return Some(last.value);
1418        };
1419        if (next.time - previous.time).abs() <= f64::EPSILON {
1420            return Some(next.value);
1421        }
1422
1423        let progress = ((time - previous.time) / (next.time - previous.time)).clamp(0.0, 1.0);
1424        Some(T::interpolate(
1425            previous.value,
1426            next.value,
1427            previous.easing.sample(progress as f32),
1428        ))
1429    }
1430}
1431
1432fn sample_sorted_keyframes<T>(keyframes: &[Keyframe<T>], time: f64) -> Option<T>
1433where
1434    T: Copy + Interpolate,
1435{
1436    let first = keyframes.first()?;
1437    let last = keyframes.last()?;
1438    if time <= first.time {
1439        return Some(first.value);
1440    }
1441    if time >= last.time {
1442        return Some(last.value);
1443    }
1444
1445    let next_index = keyframes.partition_point(|keyframe| keyframe.time < time);
1446    let previous_index = next_index.saturating_sub(1);
1447    let previous = &keyframes[previous_index];
1448    let next = &keyframes[next_index];
1449    if (next.time - previous.time).abs() <= f64::EPSILON {
1450        return Some(next.value);
1451    }
1452
1453    let progress = ((time - previous.time) / (next.time - previous.time)).clamp(0.0, 1.0);
1454    Some(T::interpolate(
1455        previous.value,
1456        next.value,
1457        previous.easing.sample(progress as f32),
1458    ))
1459}
1460
1461#[derive(Debug, Clone, PartialEq)]
1462pub struct Clip<T = AnimationValue> {
1463    pub id: String,
1464    pub start_time: f64,
1465    pub duration: f64,
1466    pub tracks: Vec<Track<T>>,
1467    pub enabled: bool,
1468}
1469
1470impl<T> Clip<T> {
1471    pub fn new(id: impl Into<String>, start_time: f64, duration: f64) -> Self {
1472        Self {
1473            id: id.into(),
1474            start_time: start_time.max(0.0),
1475            duration: duration.max(0.0),
1476            tracks: Vec::new(),
1477            enabled: true,
1478        }
1479    }
1480
1481    pub fn with_track(mut self, track: Track<T>) -> Self {
1482        self.tracks.push(track);
1483        self
1484    }
1485
1486    pub fn push_track(&mut self, track: Track<T>) {
1487        self.tracks.push(track);
1488    }
1489
1490    pub fn end_time(&self) -> f64 {
1491        self.start_time + self.duration
1492    }
1493
1494    pub fn contains_time(&self, time: f64) -> bool {
1495        self.enabled && time >= self.start_time && time <= self.end_time()
1496    }
1497}
1498
1499impl<T> Clip<T>
1500where
1501    T: Copy + Interpolate,
1502{
1503    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
1504        let mut buffer = SampleBuffer::new();
1505        self.sample_into(time, &mut buffer);
1506        buffer.into_samples()
1507    }
1508
1509    pub fn sample_into<'a>(
1510        &self,
1511        time: f64,
1512        samples: &'a mut SampleBuffer<T>,
1513    ) -> SampleBatch<'a, T> {
1514        samples.clear();
1515        self.append_samples(time, samples.samples_mut());
1516        samples.batch()
1517    }
1518
1519    fn append_samples(&self, time: f64, samples: &mut Vec<SampledAnimationValue<T>>) {
1520        if !self.contains_time(time) {
1521            return;
1522        }
1523
1524        let local_time = time - self.start_time;
1525        for track in &self.tracks {
1526            if let Some(value) = track.sample(local_time) {
1527                samples.push(SampledAnimationValue {
1528                    clip_id: self.id.clone(),
1529                    binding: track.binding.clone(),
1530                    time,
1531                    value,
1532                });
1533            }
1534        }
1535    }
1536}
1537
1538/// A named point in time on a timeline. Players report the markers the
1539/// playhead passes, so an app can start the next step of a sequence or play a
1540/// sound in time with the animation.
1541#[derive(Debug, Clone, PartialEq)]
1542pub struct TimelineMarker {
1543    pub name: String,
1544    pub time: f64,
1545}
1546
1547impl TimelineMarker {
1548    pub fn new(name: impl Into<String>, time: f64) -> Self {
1549        Self {
1550            name: name.into(),
1551            time,
1552        }
1553    }
1554}
1555
1556#[derive(Debug, Clone, PartialEq)]
1557pub struct Timeline<T = AnimationValue> {
1558    pub duration: f64,
1559    pub clips: Vec<Clip<T>>,
1560    pub markers: Vec<TimelineMarker>,
1561}
1562
1563impl<T> Timeline<T> {
1564    pub fn new(duration: f64) -> Self {
1565        Self {
1566            duration: duration.max(0.0),
1567            clips: Vec::new(),
1568            markers: Vec::new(),
1569        }
1570    }
1571
1572    pub fn with_clip(mut self, clip: Clip<T>) -> Self {
1573        self.clips.push(clip);
1574        self
1575    }
1576
1577    pub fn push_clip(&mut self, clip: Clip<T>) {
1578        self.clips.push(clip);
1579    }
1580
1581    pub fn with_marker(mut self, name: impl Into<String>, time: f64) -> Self {
1582        self.push_marker(TimelineMarker::new(name, time));
1583        self
1584    }
1585
1586    pub fn push_marker(&mut self, marker: TimelineMarker) {
1587        self.markers.push(marker);
1588    }
1589}
1590
1591impl<T> Default for Timeline<T> {
1592    fn default() -> Self {
1593        Self::new(0.0)
1594    }
1595}
1596
1597impl<T> Timeline<T>
1598where
1599    T: Copy + Interpolate,
1600{
1601    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
1602        let mut buffer = SampleBuffer::new();
1603        self.sample_into(time, &mut buffer);
1604        buffer.into_samples()
1605    }
1606
1607    pub fn sample_into<'a>(
1608        &self,
1609        time: f64,
1610        samples: &'a mut SampleBuffer<T>,
1611    ) -> SampleBatch<'a, T> {
1612        let clamped_time = time.clamp(0.0, self.duration.max(0.0));
1613        samples.clear();
1614        let samples_vec = samples.samples_mut();
1615        for clip in &self.clips {
1616            clip.append_samples(clamped_time, samples_vec);
1617        }
1618        samples.batch()
1619    }
1620}
1621
1622impl<T> Timeline<T>
1623where
1624    T: Clone,
1625{
1626    pub fn compile(&self) -> CompiledTimeline<T> {
1627        CompiledTimeline::from_timeline(self)
1628    }
1629
1630    pub fn compile_shared(&self) -> SharedCompiledTimeline<T> {
1631        self.compile().into_shared()
1632    }
1633}
1634
1635#[derive(Debug, Clone, PartialEq)]
1636pub struct CompiledTimeline<T = AnimationValue> {
1637    duration: f64,
1638    clips: Vec<CompiledClip<T>>,
1639    markers: Vec<TimelineMarker>,
1640    sample_capacity: usize,
1641}
1642
1643pub type SharedCompiledTimeline<T = AnimationValue> = Arc<CompiledTimeline<T>>;
1644
1645impl<T> CompiledTimeline<T>
1646where
1647    T: Clone,
1648{
1649    pub fn from_timeline(timeline: &Timeline<T>) -> Self {
1650        let clips = timeline
1651            .clips
1652            .iter()
1653            .filter(|clip| clip.enabled)
1654            .filter_map(CompiledClip::from_clip)
1655            .collect::<Vec<_>>();
1656        let sample_capacity = clips.iter().map(|clip| clip.tracks.len()).sum();
1657        let duration = timeline.duration.max(0.0);
1658        let mut markers = timeline
1659            .markers
1660            .iter()
1661            .filter(|marker| marker.time.is_finite())
1662            .map(|marker| {
1663                TimelineMarker::new(marker.name.clone(), marker.time.clamp(0.0, duration))
1664            })
1665            .collect::<Vec<_>>();
1666        markers.sort_by(|left, right| left.time.total_cmp(&right.time));
1667        Self {
1668            duration,
1669            clips,
1670            markers,
1671            sample_capacity,
1672        }
1673    }
1674}
1675
1676impl<T> CompiledTimeline<T> {
1677    pub fn into_shared(self) -> SharedCompiledTimeline<T> {
1678        Arc::new(self)
1679    }
1680
1681    pub fn duration(&self) -> f64 {
1682        self.duration
1683    }
1684
1685    pub fn clips(&self) -> &[CompiledClip<T>] {
1686        &self.clips
1687    }
1688
1689    /// The timeline's markers, in time order.
1690    pub fn markers(&self) -> &[TimelineMarker] {
1691        &self.markers
1692    }
1693
1694    /// Append the markers the playhead passed over `span` to `hits`, in the
1695    /// order it met them.
1696    pub fn markers_in(&self, span: PlaybackSpan, hits: &mut Vec<TimelineMarker>) {
1697        let start = hits.len();
1698        hits.extend(
1699            self.markers
1700                .iter()
1701                .filter(|marker| span.contains(marker.time))
1702                .cloned(),
1703        );
1704        if span.to < span.from {
1705            hits[start..].reverse();
1706        }
1707    }
1708
1709    pub fn sample_capacity(&self) -> usize {
1710        self.sample_capacity
1711    }
1712}
1713
1714impl<T> CompiledTimeline<T>
1715where
1716    T: Clone,
1717{
1718    pub fn to_shared(&self) -> SharedCompiledTimeline<T> {
1719        Arc::new(self.clone())
1720    }
1721
1722    pub fn player(&self) -> AnimationPlayer<T> {
1723        AnimationPlayer::new(self.to_shared())
1724    }
1725}
1726
1727impl<T> CompiledTimeline<T>
1728where
1729    T: Copy + Interpolate,
1730{
1731    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
1732        let mut buffer = SampleBuffer::with_capacity(self.sample_capacity);
1733        self.sample_into(time, &mut buffer);
1734        buffer.into_samples()
1735    }
1736
1737    pub fn sample_into<'a>(
1738        &self,
1739        time: f64,
1740        samples: &'a mut SampleBuffer<T>,
1741    ) -> SampleBatch<'a, T> {
1742        let clamped_time = time.clamp(0.0, self.duration);
1743        samples.clear();
1744        samples.reserve_capacity(self.sample_capacity);
1745        let samples_vec = samples.samples_mut();
1746        for clip in &self.clips {
1747            clip.append_samples(clamped_time, samples_vec);
1748        }
1749        samples.batch()
1750    }
1751}
1752
1753impl<T> From<&Timeline<T>> for CompiledTimeline<T>
1754where
1755    T: Clone,
1756{
1757    fn from(timeline: &Timeline<T>) -> Self {
1758        Self::from_timeline(timeline)
1759    }
1760}
1761
1762#[derive(Debug, Clone, PartialEq)]
1763pub struct CompiledClip<T = AnimationValue> {
1764    id: String,
1765    start_time: f64,
1766    duration: f64,
1767    tracks: Vec<CompiledTrack<T>>,
1768}
1769
1770impl<T> CompiledClip<T>
1771where
1772    T: Clone,
1773{
1774    fn from_clip(clip: &Clip<T>) -> Option<Self> {
1775        let tracks = clip
1776            .tracks
1777            .iter()
1778            .filter(|track| track.enabled && !track.keyframes.is_empty())
1779            .map(CompiledTrack::from_track)
1780            .collect::<Vec<_>>();
1781        if tracks.is_empty() {
1782            return None;
1783        }
1784
1785        Some(Self {
1786            id: clip.id.clone(),
1787            start_time: clip.start_time,
1788            duration: clip.duration,
1789            tracks,
1790        })
1791    }
1792}
1793
1794impl<T> CompiledClip<T> {
1795    pub fn id(&self) -> &str {
1796        &self.id
1797    }
1798
1799    pub fn start_time(&self) -> f64 {
1800        self.start_time
1801    }
1802
1803    pub fn duration(&self) -> f64 {
1804        self.duration
1805    }
1806
1807    pub fn end_time(&self) -> f64 {
1808        self.start_time + self.duration
1809    }
1810
1811    pub fn tracks(&self) -> &[CompiledTrack<T>] {
1812        &self.tracks
1813    }
1814
1815    pub fn contains_time(&self, time: f64) -> bool {
1816        time >= self.start_time && time <= self.end_time()
1817    }
1818}
1819
1820impl<T> CompiledClip<T>
1821where
1822    T: Copy + Interpolate,
1823{
1824    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
1825        let mut buffer = SampleBuffer::new();
1826        self.sample_into(time, &mut buffer);
1827        buffer.into_samples()
1828    }
1829
1830    pub fn sample_into<'a>(
1831        &self,
1832        time: f64,
1833        samples: &'a mut SampleBuffer<T>,
1834    ) -> SampleBatch<'a, T> {
1835        samples.clear();
1836        self.append_samples(time, samples.samples_mut());
1837        samples.batch()
1838    }
1839
1840    fn append_samples(&self, time: f64, samples: &mut Vec<SampledAnimationValue<T>>) {
1841        if !self.contains_time(time) {
1842            return;
1843        }
1844
1845        let local_time = time - self.start_time;
1846        for track in &self.tracks {
1847            if let Some(value) = track.sample(local_time) {
1848                samples.push(SampledAnimationValue {
1849                    clip_id: self.id.clone(),
1850                    binding: track.binding.clone(),
1851                    time,
1852                    value,
1853                });
1854            }
1855        }
1856    }
1857}
1858
1859#[derive(Debug, Clone, PartialEq)]
1860pub struct CompiledTrack<T = AnimationValue> {
1861    binding: AnimationBinding,
1862    keyframes: Vec<Keyframe<T>>,
1863}
1864
1865impl<T> CompiledTrack<T>
1866where
1867    T: Clone,
1868{
1869    fn from_track(track: &Track<T>) -> Self {
1870        let mut keyframes = track.keyframes.clone();
1871        keyframes.sort_by(|left, right| left.time.total_cmp(&right.time));
1872        Self {
1873            binding: track.binding.clone(),
1874            keyframes,
1875        }
1876    }
1877}
1878
1879impl<T> CompiledTrack<T> {
1880    pub fn binding(&self) -> &AnimationBinding {
1881        &self.binding
1882    }
1883
1884    pub fn keyframes(&self) -> &[Keyframe<T>] {
1885        &self.keyframes
1886    }
1887}
1888
1889impl<T> CompiledTrack<T>
1890where
1891    T: Copy + Interpolate,
1892{
1893    pub fn sample(&self, time: f64) -> Option<T> {
1894        sample_sorted_keyframes(&self.keyframes, time)
1895    }
1896}
1897
1898#[derive(Debug, Clone, PartialEq)]
1899pub struct SampledAnimationValue<T = AnimationValue> {
1900    pub clip_id: String,
1901    pub binding: AnimationBinding,
1902    pub time: f64,
1903    pub value: T,
1904}
1905
1906#[derive(Debug, Clone, PartialEq, Default)]
1907pub struct SampleBuffer<T = AnimationValue> {
1908    samples: Vec<SampledAnimationValue<T>>,
1909}
1910
1911impl<T> SampleBuffer<T> {
1912    pub fn new() -> Self {
1913        Self {
1914            samples: Vec::new(),
1915        }
1916    }
1917
1918    pub fn with_capacity(capacity: usize) -> Self {
1919        Self {
1920            samples: Vec::with_capacity(capacity),
1921        }
1922    }
1923
1924    pub fn len(&self) -> usize {
1925        self.samples.len()
1926    }
1927
1928    pub fn is_empty(&self) -> bool {
1929        self.samples.is_empty()
1930    }
1931
1932    pub fn capacity(&self) -> usize {
1933        self.samples.capacity()
1934    }
1935
1936    pub fn clear(&mut self) {
1937        self.samples.clear();
1938    }
1939
1940    pub fn reserve_capacity(&mut self, target_capacity: usize) {
1941        self.samples
1942            .reserve(target_capacity.saturating_sub(self.samples.capacity()));
1943    }
1944
1945    pub fn samples(&self) -> &[SampledAnimationValue<T>] {
1946        &self.samples
1947    }
1948
1949    pub fn batch(&self) -> SampleBatch<'_, T> {
1950        SampleBatch {
1951            samples: &self.samples,
1952        }
1953    }
1954
1955    pub fn into_samples(self) -> Vec<SampledAnimationValue<T>> {
1956        self.samples
1957    }
1958
1959    fn samples_mut(&mut self) -> &mut Vec<SampledAnimationValue<T>> {
1960        &mut self.samples
1961    }
1962}
1963
1964impl<T> AsRef<[SampledAnimationValue<T>]> for SampleBuffer<T> {
1965    fn as_ref(&self) -> &[SampledAnimationValue<T>] {
1966        self.samples()
1967    }
1968}
1969
1970#[derive(Debug, Clone, Copy, PartialEq)]
1971pub struct SampleBatch<'a, T = AnimationValue> {
1972    samples: &'a [SampledAnimationValue<T>],
1973}
1974
1975impl<'a, T> SampleBatch<'a, T> {
1976    pub fn samples(self) -> &'a [SampledAnimationValue<T>] {
1977        self.samples
1978    }
1979
1980    pub fn iter(self) -> std::slice::Iter<'a, SampledAnimationValue<T>> {
1981        self.samples.iter()
1982    }
1983
1984    pub fn len(self) -> usize {
1985        self.samples.len()
1986    }
1987
1988    pub fn is_empty(self) -> bool {
1989        self.samples.is_empty()
1990    }
1991}
1992
1993impl<'a, T> IntoIterator for SampleBatch<'a, T> {
1994    type Item = &'a SampledAnimationValue<T>;
1995    type IntoIter = std::slice::Iter<'a, SampledAnimationValue<T>>;
1996
1997    fn into_iter(self) -> Self::IntoIter {
1998        self.iter()
1999    }
2000}
2001
2002#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2003pub enum LoopMode {
2004    #[default]
2005    Once,
2006    /// Start over from the beginning at the end.
2007    Repeat,
2008    /// Play forward, then backward, and so on: the playback rate reverses at
2009    /// each end.
2010    PingPong,
2011}
2012
2013/// A stretch of timeline the playhead moved over in one tick.
2014///
2015/// `from` is where the playhead started and `to` where it stopped, so `to <
2016/// from` when playing backward. A span covers the times it moved onto, `to`
2017/// included, and its start only when `includes_start` is set: when playback
2018/// began there or wrapped around to it.
2019#[derive(Debug, Clone, Copy, PartialEq)]
2020pub struct PlaybackSpan {
2021    pub from: f64,
2022    pub to: f64,
2023    pub includes_start: bool,
2024}
2025
2026impl PlaybackSpan {
2027    /// Whether the playhead passed `time` over this span.
2028    pub fn contains(self, time: f64) -> bool {
2029        if time == self.from {
2030            return self.includes_start;
2031        }
2032        if self.to >= self.from {
2033            self.from < time && time <= self.to
2034        } else {
2035            self.to <= time && time < self.from
2036        }
2037    }
2038}
2039
2040/// Upper bound on the loops one tick plays through, so a huge delta with a
2041/// tiny timeline cannot stall a frame.
2042const MAX_LOOPS_PER_TICK: usize = 64;
2043
2044#[derive(Debug, Clone, Copy, PartialEq)]
2045pub struct PlaybackState {
2046    pub playhead: f64,
2047    pub playback_rate: f64,
2048    pub playing: bool,
2049    pub loop_mode: LoopMode,
2050    /// Seconds to wait before the playhead moves when playback starts from
2051    /// the beginning or a seek. Resuming after a pause does not wait.
2052    pub start_delay: f64,
2053    /// Seconds to hold at each end before looping.
2054    pub loop_delay: f64,
2055    wait: f64,
2056    fresh: bool,
2057}
2058
2059impl Default for PlaybackState {
2060    fn default() -> Self {
2061        Self {
2062            playhead: 0.0,
2063            playback_rate: 1.0,
2064            playing: false,
2065            loop_mode: LoopMode::Once,
2066            start_delay: 0.0,
2067            loop_delay: 0.0,
2068            wait: 0.0,
2069            fresh: true,
2070        }
2071    }
2072}
2073
2074impl PlaybackState {
2075    pub fn play(&mut self) {
2076        if !self.playing && self.fresh {
2077            self.wait = sanitize_delay(self.start_delay);
2078        }
2079        self.playing = true;
2080    }
2081
2082    pub fn pause(&mut self) {
2083        self.playing = false;
2084    }
2085
2086    pub fn stop(&mut self) {
2087        self.playing = false;
2088        self.playhead = 0.0;
2089        self.playback_rate = self.playback_rate.abs();
2090        self.wait = 0.0;
2091        self.fresh = true;
2092    }
2093
2094    pub fn seek(&mut self, time: f64, duration: f64) {
2095        self.playhead = time.clamp(0.0, duration.max(0.0));
2096        self.wait = 0.0;
2097        self.fresh = true;
2098    }
2099
2100    /// Seconds left before the playhead moves again: the start delay or a
2101    /// hold between loops.
2102    pub fn waiting(&self) -> f64 {
2103        self.wait
2104    }
2105
2106    pub fn tick(&mut self, delta_seconds: f64, duration: f64) -> bool {
2107        self.tick_spans(delta_seconds, duration, |_| {})
2108    }
2109
2110    /// Advance like [`PlaybackState::tick`], reporting each stretch of
2111    /// timeline the playhead moves over; a tick that loops reports several.
2112    pub fn tick_spans(
2113        &mut self,
2114        delta_seconds: f64,
2115        duration: f64,
2116        mut visit: impl FnMut(PlaybackSpan),
2117    ) -> bool {
2118        if !self.playing {
2119            return false;
2120        }
2121
2122        let previous_time = self.playhead;
2123        let duration = duration.max(0.0);
2124        if duration <= f64::EPSILON {
2125            self.playhead = 0.0;
2126            self.playing = false;
2127            return previous_time != self.playhead;
2128        }
2129
2130        let mut remaining = sanitize_delay(delta_seconds);
2131        let mut loops = 0;
2132        while remaining > 0.0 && self.playing {
2133            if self.wait > 0.0 {
2134                let waited = self.wait.min(remaining);
2135                self.wait -= waited;
2136                remaining -= waited;
2137                continue;
2138            }
2139            let rate = self.playback_rate;
2140            if rate == 0.0 || !rate.is_finite() {
2141                break;
2142            }
2143            let from = self.playhead.clamp(0.0, duration);
2144            let edge = if rate > 0.0 { duration } else { 0.0 };
2145            let time_to_edge = ((edge - from) / rate).max(0.0);
2146            let includes_start = std::mem::take(&mut self.fresh);
2147            if remaining < time_to_edge {
2148                self.playhead = (from + remaining * rate).clamp(0.0, duration);
2149                visit(PlaybackSpan {
2150                    from,
2151                    to: self.playhead,
2152                    includes_start,
2153                });
2154                break;
2155            }
2156
2157            self.playhead = edge;
2158            visit(PlaybackSpan {
2159                from,
2160                to: edge,
2161                includes_start,
2162            });
2163            remaining -= time_to_edge;
2164            loops += 1;
2165            match self.loop_mode {
2166                LoopMode::Once => self.playing = false,
2167                LoopMode::Repeat => {
2168                    self.playhead = duration - edge;
2169                    self.fresh = true;
2170                    self.wait = sanitize_delay(self.loop_delay);
2171                }
2172                LoopMode::PingPong => {
2173                    self.playback_rate = -rate;
2174                    self.wait = sanitize_delay(self.loop_delay);
2175                }
2176            }
2177            if loops >= MAX_LOOPS_PER_TICK {
2178                break;
2179            }
2180        }
2181
2182        previous_time != self.playhead
2183    }
2184}
2185
2186fn sanitize_delay(delay: f64) -> f64 {
2187    if delay.is_finite() {
2188        delay.max(0.0)
2189    } else {
2190        0.0
2191    }
2192}
2193
2194#[derive(Debug, Clone, PartialEq)]
2195pub struct AnimationPlayer<T = AnimationValue> {
2196    timeline: SharedCompiledTimeline<T>,
2197    playback: PlaybackState,
2198    passed_markers: Vec<TimelineMarker>,
2199}
2200
2201impl<T> AnimationPlayer<T> {
2202    pub fn new(timeline: SharedCompiledTimeline<T>) -> Self {
2203        Self {
2204            timeline,
2205            playback: PlaybackState::default(),
2206            passed_markers: Vec::new(),
2207        }
2208    }
2209
2210    pub fn from_compiled(timeline: CompiledTimeline<T>) -> Self {
2211        Self::new(timeline.into_shared())
2212    }
2213
2214    pub fn timeline(&self) -> &CompiledTimeline<T> {
2215        self.timeline.as_ref()
2216    }
2217
2218    pub fn shared_timeline(&self) -> SharedCompiledTimeline<T> {
2219        Arc::clone(&self.timeline)
2220    }
2221
2222    pub fn playback(&self) -> PlaybackState {
2223        self.playback
2224    }
2225
2226    pub fn playback_mut(&mut self) -> &mut PlaybackState {
2227        &mut self.playback
2228    }
2229
2230    pub fn with_loop_mode(mut self, loop_mode: LoopMode) -> Self {
2231        self.playback.loop_mode = loop_mode;
2232        self
2233    }
2234
2235    pub fn repeat(self) -> Self {
2236        self.with_loop_mode(LoopMode::Repeat)
2237    }
2238
2239    pub fn ping_pong(self) -> Self {
2240        self.with_loop_mode(LoopMode::PingPong)
2241    }
2242
2243    pub fn once(self) -> Self {
2244        self.with_loop_mode(LoopMode::Once)
2245    }
2246
2247    pub fn with_playback_rate(mut self, playback_rate: f64) -> Self {
2248        self.playback.playback_rate = playback_rate;
2249        self
2250    }
2251
2252    /// Wait `delay` seconds before playing from the start.
2253    pub fn with_start_delay(mut self, delay: f64) -> Self {
2254        self.playback.start_delay = delay;
2255        self
2256    }
2257
2258    /// Hold `delay` seconds at each end before looping.
2259    pub fn with_loop_delay(mut self, delay: f64) -> Self {
2260        self.playback.loop_delay = delay;
2261        self
2262    }
2263
2264    /// The markers the playhead passed in the last tick, in order.
2265    pub fn passed_markers(&self) -> &[TimelineMarker] {
2266        &self.passed_markers
2267    }
2268
2269    pub fn play(&mut self) {
2270        self.playback.play();
2271    }
2272
2273    pub fn pause(&mut self) {
2274        self.playback.pause();
2275    }
2276
2277    pub fn stop(&mut self) {
2278        self.playback.stop();
2279    }
2280
2281    pub fn seek(&mut self, time: f64) {
2282        self.playback.seek(time, self.timeline.duration());
2283    }
2284}
2285
2286impl<T> AnimationPlayer<T>
2287where
2288    T: Copy + Interpolate,
2289{
2290    pub fn sample(&self) -> Vec<SampledAnimationValue<T>> {
2291        self.timeline.sample(self.playback.playhead)
2292    }
2293
2294    pub fn sample_into<'a>(&self, samples: &'a mut SampleBuffer<T>) -> SampleBatch<'a, T> {
2295        self.timeline.sample_into(self.playback.playhead, samples)
2296    }
2297
2298    pub fn tick_into<'a>(
2299        &mut self,
2300        delta_seconds: f64,
2301        samples: &'a mut SampleBuffer<T>,
2302    ) -> AnimationTick<'a, T> {
2303        let timeline = &self.timeline;
2304        let passed_markers = &mut self.passed_markers;
2305        passed_markers.clear();
2306        let advanced = self
2307            .playback
2308            .tick_spans(delta_seconds, timeline.duration(), |span| {
2309                timeline.markers_in(span, passed_markers);
2310            });
2311        let samples = self.timeline.sample_into(self.playback.playhead, samples);
2312        AnimationTick {
2313            samples,
2314            playback: self.playback,
2315            advanced,
2316            should_continue: self.playback.playing,
2317        }
2318    }
2319}
2320
2321#[derive(Debug, Clone, Copy, PartialEq)]
2322pub struct AnimationTick<'a, T = AnimationValue> {
2323    pub samples: SampleBatch<'a, T>,
2324    pub playback: PlaybackState,
2325    pub advanced: bool,
2326    pub should_continue: bool,
2327}
2328
2329impl<'a, T> AnimationTick<'a, T> {
2330    pub fn samples(self) -> SampleBatch<'a, T> {
2331        self.samples
2332    }
2333
2334    pub fn sample_values(self) -> &'a [SampledAnimationValue<T>] {
2335        self.samples.samples()
2336    }
2337}
2338
2339#[derive(Debug, Clone, PartialEq)]
2340pub struct AnimationDocument {
2341    pub version: u32,
2342    pub name: String,
2343    pub timeline: Timeline,
2344}
2345
2346impl AnimationDocument {
2347    pub fn new(name: impl Into<String>, timeline: Timeline) -> Self {
2348        Self {
2349            version: ANIMATION_DOCUMENT_VERSION,
2350            name: name.into(),
2351            timeline,
2352        }
2353    }
2354
2355    pub fn to_document_format(&self) -> String {
2356        let mut output = String::new();
2357        output.push_str("sui-animation-document\t");
2358        output.push_str(&self.version.to_string());
2359        output.push('\n');
2360        output.push_str("name\t");
2361        output.push_str(&escape_document_field(&self.name));
2362        output.push('\n');
2363        output.push_str("duration\t");
2364        output.push_str(&format_f64(self.timeline.duration));
2365        output.push('\n');
2366
2367        for marker in &self.timeline.markers {
2368            output.push_str("marker\t");
2369            output.push_str(&escape_document_field(&marker.name));
2370            output.push('\t');
2371            output.push_str(&format_f64(marker.time));
2372            output.push('\n');
2373        }
2374
2375        for clip in &self.timeline.clips {
2376            output.push_str("clip\t");
2377            output.push_str(&escape_document_field(&clip.id));
2378            output.push('\t');
2379            output.push_str(&format_f64(clip.start_time));
2380            output.push('\t');
2381            output.push_str(&format_f64(clip.duration));
2382            output.push('\t');
2383            output.push_str(format_bool(clip.enabled));
2384            output.push('\n');
2385
2386            for track in &clip.tracks {
2387                output.push_str("track\t");
2388                output.push_str(&escape_document_field(track.binding.target.as_str()));
2389                output.push('\t');
2390                output.push_str(&escape_document_field(track.binding.property.path()));
2391                output.push('\t');
2392                output.push_str(format_bool(track.enabled));
2393                output.push('\n');
2394
2395                for keyframe in &track.keyframes {
2396                    output.push_str("key\t");
2397                    output.push_str(&format_f64(keyframe.time));
2398                    output.push('\t');
2399                    output.push_str(&format_easing(keyframe.easing));
2400                    output.push('\t');
2401                    output.push_str(&format_animation_value(keyframe.value));
2402                    output.push('\n');
2403                }
2404
2405                output.push_str("endtrack\n");
2406            }
2407
2408            output.push_str("endclip\n");
2409        }
2410
2411        output
2412    }
2413
2414    pub fn from_document_format(input: &str) -> Result<Self, AnimationDocumentFormatError> {
2415        AnimationDocumentFormatParser::new(input).parse()
2416    }
2417}
2418
2419impl Default for AnimationDocument {
2420    fn default() -> Self {
2421        Self::new("Untitled animation", Timeline::default())
2422    }
2423}
2424
2425#[derive(Debug, Clone, PartialEq, Eq)]
2426pub struct AnimationDocumentFormatError {
2427    pub line: Option<usize>,
2428    pub message: String,
2429}
2430
2431impl AnimationDocumentFormatError {
2432    fn new(line: Option<usize>, message: impl Into<String>) -> Self {
2433        Self {
2434            line,
2435            message: message.into(),
2436        }
2437    }
2438}
2439
2440impl fmt::Display for AnimationDocumentFormatError {
2441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2442        match self.line {
2443            Some(line) => write!(
2444                f,
2445                "animation document format error on line {line}: {}",
2446                self.message
2447            ),
2448            None => write!(f, "animation document format error: {}", self.message),
2449        }
2450    }
2451}
2452
2453impl std::error::Error for AnimationDocumentFormatError {}
2454
2455#[derive(Debug, Clone, Copy, PartialEq)]
2456pub struct TimelineSnap {
2457    pub enabled: bool,
2458    pub interval: f64,
2459}
2460
2461impl TimelineSnap {
2462    pub fn new(interval: f64) -> Self {
2463        Self {
2464            enabled: true,
2465            interval: interval.max(f64::EPSILON),
2466        }
2467    }
2468
2469    pub fn disabled() -> Self {
2470        Self {
2471            enabled: false,
2472            interval: 1.0 / 60.0,
2473        }
2474    }
2475
2476    pub fn snap_time(self, time: f64) -> f64 {
2477        if !self.enabled {
2478            return time.max(0.0);
2479        }
2480        ((time.max(0.0) / self.interval).round() * self.interval).max(0.0)
2481    }
2482}
2483
2484impl Default for TimelineSnap {
2485    fn default() -> Self {
2486        Self::new(1.0 / 24.0)
2487    }
2488}
2489
2490#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2491pub struct KeyframeSelection {
2492    pub clip_index: usize,
2493    pub track_index: usize,
2494    pub keyframe_index: usize,
2495}
2496
2497#[derive(Debug, Clone, PartialEq, Eq, Default)]
2498pub struct AnimationSelection {
2499    pub clip_index: Option<usize>,
2500    pub track_index: Option<usize>,
2501    pub keyframes: Vec<KeyframeSelection>,
2502}
2503
2504#[derive(Debug, Clone, PartialEq)]
2505pub enum AnimationEditorCommand {
2506    SetPlayhead(f64),
2507    SetZoom(f32),
2508    SetScroll(f32),
2509    SetSnapping(TimelineSnap),
2510    ClearSelection,
2511    SelectClip(usize),
2512    SelectTrack {
2513        clip_index: usize,
2514        track_index: usize,
2515    },
2516    SelectKeyframe(KeyframeSelection),
2517    AddKeyframe {
2518        clip_index: usize,
2519        track_index: usize,
2520        keyframe: Keyframe<AnimationValue>,
2521    },
2522    UpdateKeyframeEasing {
2523        selection: KeyframeSelection,
2524        easing: Easing,
2525    },
2526    /// Move a keyframe to `time`, snapped and kept inside the timeline.
2527    MoveKeyframe {
2528        selection: KeyframeSelection,
2529        time: f64,
2530    },
2531    RemoveKeyframe(KeyframeSelection),
2532    /// Add a marker at `time`, snapped and kept inside the timeline.
2533    AddMarker {
2534        name: String,
2535        time: f64,
2536    },
2537    /// Move the marker at `index` to `time`, snapped and kept inside the
2538    /// timeline.
2539    MoveMarker {
2540        index: usize,
2541        time: f64,
2542    },
2543    RenameMarker {
2544        index: usize,
2545        name: String,
2546    },
2547    RemoveMarker(usize),
2548}
2549
2550#[derive(Debug, Clone, PartialEq)]
2551pub struct AnimationEditorState {
2552    pub document: AnimationDocument,
2553    pub playback: PlaybackState,
2554    pub selection: AnimationSelection,
2555    pub zoom: f32,
2556    pub scroll: f32,
2557    pub snap: TimelineSnap,
2558    undo_stack: Vec<AnimationDocument>,
2559    redo_stack: Vec<AnimationDocument>,
2560}
2561
2562impl AnimationEditorState {
2563    pub fn new(document: AnimationDocument) -> Self {
2564        Self {
2565            document,
2566            playback: PlaybackState::default(),
2567            selection: AnimationSelection::default(),
2568            zoom: 1.0,
2569            scroll: 0.0,
2570            snap: TimelineSnap::default(),
2571            undo_stack: Vec::new(),
2572            redo_stack: Vec::new(),
2573        }
2574    }
2575
2576    pub fn undo_len(&self) -> usize {
2577        self.undo_stack.len()
2578    }
2579
2580    pub fn redo_len(&self) -> usize {
2581        self.redo_stack.len()
2582    }
2583
2584    pub fn can_undo(&self) -> bool {
2585        !self.undo_stack.is_empty()
2586    }
2587
2588    pub fn can_redo(&self) -> bool {
2589        !self.redo_stack.is_empty()
2590    }
2591
2592    pub fn apply_command(&mut self, command: AnimationEditorCommand) -> bool {
2593        match command {
2594            AnimationEditorCommand::SetPlayhead(time) => {
2595                self.playback.seek(time, self.document.timeline.duration);
2596                true
2597            }
2598            AnimationEditorCommand::SetZoom(zoom) => {
2599                self.zoom = zoom.max(0.05);
2600                true
2601            }
2602            AnimationEditorCommand::SetScroll(scroll) => {
2603                self.scroll = scroll.max(0.0);
2604                true
2605            }
2606            AnimationEditorCommand::SetSnapping(snap) => {
2607                self.snap = snap;
2608                true
2609            }
2610            AnimationEditorCommand::ClearSelection => {
2611                self.selection = AnimationSelection::default();
2612                true
2613            }
2614            AnimationEditorCommand::SelectClip(clip_index) => {
2615                self.selection.clip_index = Some(clip_index);
2616                self.selection.track_index = None;
2617                self.selection.keyframes.clear();
2618                true
2619            }
2620            AnimationEditorCommand::SelectTrack {
2621                clip_index,
2622                track_index,
2623            } => {
2624                self.selection.clip_index = Some(clip_index);
2625                self.selection.track_index = Some(track_index);
2626                self.selection.keyframes.clear();
2627                true
2628            }
2629            AnimationEditorCommand::SelectKeyframe(selection) => {
2630                self.selection.clip_index = Some(selection.clip_index);
2631                self.selection.track_index = Some(selection.track_index);
2632                if !self.selection.keyframes.contains(&selection) {
2633                    self.selection.keyframes.push(selection);
2634                }
2635                true
2636            }
2637            AnimationEditorCommand::AddKeyframe {
2638                clip_index,
2639                track_index,
2640                mut keyframe,
2641            } => {
2642                let Some(track) = self
2643                    .document
2644                    .timeline
2645                    .clips
2646                    .get(clip_index)
2647                    .and_then(|clip| clip.tracks.get(track_index))
2648                else {
2649                    return false;
2650                };
2651                let mut updated_track = track.clone();
2652                keyframe.time = self.snap.snap_time(keyframe.time);
2653                updated_track.push_keyframe(keyframe);
2654
2655                self.push_undo_snapshot();
2656                self.document.timeline.clips[clip_index].tracks[track_index] = updated_track;
2657                self.redo_stack.clear();
2658                true
2659            }
2660            AnimationEditorCommand::UpdateKeyframeEasing { selection, easing } => {
2661                let Some(track) = self
2662                    .document
2663                    .timeline
2664                    .clips
2665                    .get(selection.clip_index)
2666                    .and_then(|clip| clip.tracks.get(selection.track_index))
2667                else {
2668                    return false;
2669                };
2670                let Some(keyframe) = track.keyframes.get(selection.keyframe_index) else {
2671                    return false;
2672                };
2673
2674                let mut updated_track = track.clone();
2675                let mut updated_keyframe = *keyframe;
2676                updated_keyframe.easing = easing;
2677                updated_track.keyframes[selection.keyframe_index] = updated_keyframe;
2678
2679                self.push_undo_snapshot();
2680                self.document.timeline.clips[selection.clip_index].tracks[selection.track_index] =
2681                    updated_track;
2682                self.redo_stack.clear();
2683                true
2684            }
2685            AnimationEditorCommand::MoveKeyframe { selection, time } => {
2686                let duration = self.document.timeline.duration.max(0.0);
2687                let time = self.snap.snap_time(time).clamp(0.0, duration);
2688                let Some(keyframe) = self
2689                    .document
2690                    .timeline
2691                    .clips
2692                    .get(selection.clip_index)
2693                    .and_then(|clip| clip.tracks.get(selection.track_index))
2694                    .and_then(|track| track.keyframes.get(selection.keyframe_index))
2695                else {
2696                    return false;
2697                };
2698                if keyframe.time == time {
2699                    return false;
2700                }
2701
2702                self.push_undo_snapshot();
2703                self.document.timeline.clips[selection.clip_index].tracks[selection.track_index]
2704                    .keyframes[selection.keyframe_index]
2705                    .time = time;
2706                self.redo_stack.clear();
2707                true
2708            }
2709            AnimationEditorCommand::RemoveKeyframe(selection) => {
2710                let Some(track) = self
2711                    .document
2712                    .timeline
2713                    .clips
2714                    .get(selection.clip_index)
2715                    .and_then(|clip| clip.tracks.get(selection.track_index))
2716                else {
2717                    return false;
2718                };
2719                if selection.keyframe_index >= track.keyframes.len() {
2720                    return false;
2721                }
2722
2723                let mut updated_track = track.clone();
2724                updated_track.keyframes.remove(selection.keyframe_index);
2725
2726                self.push_undo_snapshot();
2727                self.document.timeline.clips[selection.clip_index].tracks[selection.track_index] =
2728                    updated_track;
2729                self.selection
2730                    .keyframes
2731                    .retain(|selected| *selected != selection);
2732                self.redo_stack.clear();
2733                true
2734            }
2735            AnimationEditorCommand::AddMarker { name, time } => {
2736                let time = self.marker_time(time);
2737                self.push_undo_snapshot();
2738                self.document
2739                    .timeline
2740                    .push_marker(TimelineMarker::new(name, time));
2741                self.redo_stack.clear();
2742                true
2743            }
2744            AnimationEditorCommand::MoveMarker { index, time } => {
2745                let time = self.marker_time(time);
2746                let Some(marker) = self.document.timeline.markers.get(index) else {
2747                    return false;
2748                };
2749                if marker.time == time {
2750                    return false;
2751                }
2752                self.push_undo_snapshot();
2753                self.document.timeline.markers[index].time = time;
2754                self.redo_stack.clear();
2755                true
2756            }
2757            AnimationEditorCommand::RenameMarker { index, name } => {
2758                let Some(marker) = self.document.timeline.markers.get(index) else {
2759                    return false;
2760                };
2761                if marker.name == name {
2762                    return false;
2763                }
2764                self.push_undo_snapshot();
2765                self.document.timeline.markers[index].name = name;
2766                self.redo_stack.clear();
2767                true
2768            }
2769            AnimationEditorCommand::RemoveMarker(index) => {
2770                if index >= self.document.timeline.markers.len() {
2771                    return false;
2772                }
2773                self.push_undo_snapshot();
2774                self.document.timeline.markers.remove(index);
2775                self.redo_stack.clear();
2776                true
2777            }
2778        }
2779    }
2780
2781    fn marker_time(&self, time: f64) -> f64 {
2782        let duration = self.document.timeline.duration.max(0.0);
2783        self.snap.snap_time(time).clamp(0.0, duration)
2784    }
2785
2786    pub fn undo(&mut self) -> bool {
2787        let Some(previous) = self.undo_stack.pop() else {
2788            return false;
2789        };
2790        self.redo_stack.push(self.document.clone());
2791        self.document = previous;
2792        true
2793    }
2794
2795    pub fn redo(&mut self) -> bool {
2796        let Some(next) = self.redo_stack.pop() else {
2797            return false;
2798        };
2799        self.undo_stack.push(self.document.clone());
2800        self.document = next;
2801        true
2802    }
2803
2804    fn push_undo_snapshot(&mut self) {
2805        self.undo_stack.push(self.document.clone());
2806    }
2807}
2808
2809impl Default for AnimationEditorState {
2810    fn default() -> Self {
2811        Self::new(AnimationDocument::default())
2812    }
2813}
2814
2815struct AnimationDocumentFormatParser<'a> {
2816    input: &'a str,
2817}
2818
2819impl<'a> AnimationDocumentFormatParser<'a> {
2820    fn new(input: &'a str) -> Self {
2821        Self { input }
2822    }
2823
2824    fn parse(self) -> Result<AnimationDocument, AnimationDocumentFormatError> {
2825        let mut version = None;
2826        let mut name = None;
2827        let mut duration = None;
2828        let mut clips = Vec::new();
2829        let mut markers = Vec::new();
2830        let mut current_clip: Option<Clip> = None;
2831        let mut current_track: Option<Track> = None;
2832
2833        for (line_index, raw_line) in self.input.lines().enumerate() {
2834            let line_no = line_index + 1;
2835            let line = raw_line.trim_end_matches('\r');
2836            if line.is_empty() {
2837                continue;
2838            }
2839
2840            let fields = line.split('\t').collect::<Vec<_>>();
2841            match fields.first().copied().unwrap_or_default() {
2842                "sui-animation-document" => {
2843                    expect_field_count(line_no, &fields, 2)?;
2844                    if version.is_some() {
2845                        return Err(AnimationDocumentFormatError::new(
2846                            Some(line_no),
2847                            "duplicate document header",
2848                        ));
2849                    }
2850                    let parsed_version = parse_u32_field(line_no, fields[1], "version")?;
2851                    if !(MIN_ANIMATION_DOCUMENT_VERSION..=ANIMATION_DOCUMENT_VERSION)
2852                        .contains(&parsed_version)
2853                    {
2854                        return Err(AnimationDocumentFormatError::new(
2855                            Some(line_no),
2856                            format!(
2857                                "unsupported document version {parsed_version}; expected {MIN_ANIMATION_DOCUMENT_VERSION} to {ANIMATION_DOCUMENT_VERSION}"
2858                            ),
2859                        ));
2860                    }
2861                    version = Some(parsed_version);
2862                }
2863                "name" => {
2864                    ensure_document_header(line_no, version)?;
2865                    expect_field_count(line_no, &fields, 2)?;
2866                    ensure_no_open_track_or_clip(line_no, &current_track, &current_clip)?;
2867                    name = Some(unescape_document_field(fields[1], line_no)?);
2868                }
2869                "duration" => {
2870                    ensure_document_header(line_no, version)?;
2871                    expect_field_count(line_no, &fields, 2)?;
2872                    ensure_no_open_track_or_clip(line_no, &current_track, &current_clip)?;
2873                    duration = Some(parse_f64_field(line_no, fields[1], "duration")?);
2874                }
2875                "marker" => {
2876                    ensure_document_header(line_no, version)?;
2877                    expect_field_count(line_no, &fields, 3)?;
2878                    ensure_no_open_track_or_clip(line_no, &current_track, &current_clip)?;
2879                    let name = unescape_document_field(fields[1], line_no)?;
2880                    let time = parse_f64_field(line_no, fields[2], "marker time")?;
2881                    markers.push(TimelineMarker::new(name, time));
2882                }
2883                "clip" => {
2884                    ensure_document_header(line_no, version)?;
2885                    expect_field_count(line_no, &fields, 5)?;
2886                    if current_clip.is_some() {
2887                        return Err(AnimationDocumentFormatError::new(
2888                            Some(line_no),
2889                            "nested clips are not allowed",
2890                        ));
2891                    }
2892                    let id = unescape_document_field(fields[1], line_no)?;
2893                    let start_time = parse_f64_field(line_no, fields[2], "clip start time")?;
2894                    let clip_duration = parse_f64_field(line_no, fields[3], "clip duration")?;
2895                    let enabled = parse_bool_field(line_no, fields[4], "clip enabled")?;
2896                    let mut clip = Clip::new(id, start_time, clip_duration);
2897                    clip.enabled = enabled;
2898                    current_clip = Some(clip);
2899                }
2900                "track" => {
2901                    ensure_document_header(line_no, version)?;
2902                    expect_field_count(line_no, &fields, 4)?;
2903                    if current_clip.is_none() {
2904                        return Err(AnimationDocumentFormatError::new(
2905                            Some(line_no),
2906                            "track must appear inside a clip",
2907                        ));
2908                    }
2909                    if current_track.is_some() {
2910                        return Err(AnimationDocumentFormatError::new(
2911                            Some(line_no),
2912                            "nested tracks are not allowed",
2913                        ));
2914                    }
2915                    let target =
2916                        AnimationTargetId::new(unescape_document_field(fields[1], line_no)?);
2917                    let property_path = unescape_document_field(fields[2], line_no)?;
2918                    let enabled = parse_bool_field(line_no, fields[3], "track enabled")?;
2919                    let mut track = Track::new(AnimationBinding::new(
2920                        target,
2921                        animation_property_from_path(property_path),
2922                    ));
2923                    track.enabled = enabled;
2924                    current_track = Some(track);
2925                }
2926                "key" => {
2927                    ensure_document_header(line_no, version)?;
2928                    expect_field_count(line_no, &fields, 4)?;
2929                    let Some(track) = &mut current_track else {
2930                        return Err(AnimationDocumentFormatError::new(
2931                            Some(line_no),
2932                            "keyframe must appear inside a track",
2933                        ));
2934                    };
2935                    let time = parse_f64_field(line_no, fields[1], "keyframe time")?;
2936                    let easing = parse_easing(line_no, fields[2])?;
2937                    let value = parse_animation_value(line_no, fields[3])?;
2938                    track.push_keyframe(Keyframe::new(time, value).with_easing(easing));
2939                }
2940                "endtrack" => {
2941                    ensure_document_header(line_no, version)?;
2942                    expect_field_count(line_no, &fields, 1)?;
2943                    let Some(track) = current_track.take() else {
2944                        return Err(AnimationDocumentFormatError::new(
2945                            Some(line_no),
2946                            "endtrack without an open track",
2947                        ));
2948                    };
2949                    let Some(clip) = &mut current_clip else {
2950                        return Err(AnimationDocumentFormatError::new(
2951                            Some(line_no),
2952                            "endtrack without an open clip",
2953                        ));
2954                    };
2955                    clip.push_track(track);
2956                }
2957                "endclip" => {
2958                    ensure_document_header(line_no, version)?;
2959                    expect_field_count(line_no, &fields, 1)?;
2960                    if current_track.is_some() {
2961                        return Err(AnimationDocumentFormatError::new(
2962                            Some(line_no),
2963                            "endclip reached before endtrack",
2964                        ));
2965                    }
2966                    let Some(clip) = current_clip.take() else {
2967                        return Err(AnimationDocumentFormatError::new(
2968                            Some(line_no),
2969                            "endclip without an open clip",
2970                        ));
2971                    };
2972                    clips.push(clip);
2973                }
2974                other => {
2975                    return Err(AnimationDocumentFormatError::new(
2976                        Some(line_no),
2977                        format!("unknown directive {other:?}"),
2978                    ));
2979                }
2980            }
2981        }
2982
2983        if version.is_none() {
2984            return Err(AnimationDocumentFormatError::new(
2985                None,
2986                "missing document header",
2987            ));
2988        }
2989        if current_track.is_some() {
2990            return Err(AnimationDocumentFormatError::new(None, "unclosed track"));
2991        }
2992        if current_clip.is_some() {
2993            return Err(AnimationDocumentFormatError::new(None, "unclosed clip"));
2994        }
2995
2996        Ok(AnimationDocument {
2997            version: ANIMATION_DOCUMENT_VERSION,
2998            name: name
2999                .ok_or_else(|| AnimationDocumentFormatError::new(None, "missing document name"))?,
3000            timeline: Timeline {
3001                duration: duration.ok_or_else(|| {
3002                    AnimationDocumentFormatError::new(None, "missing timeline duration")
3003                })?,
3004                clips,
3005                markers,
3006            },
3007        })
3008    }
3009}
3010
3011fn format_bool(value: bool) -> &'static str {
3012    if value { "true" } else { "false" }
3013}
3014
3015fn format_f64(value: f64) -> String {
3016    value.to_string()
3017}
3018
3019fn format_f32(value: f32) -> String {
3020    value.to_string()
3021}
3022
3023fn escape_document_field(value: &str) -> String {
3024    let mut escaped = String::new();
3025    for ch in value.chars() {
3026        match ch {
3027            '\\' => escaped.push_str("\\\\"),
3028            '\n' => escaped.push_str("\\n"),
3029            '\r' => escaped.push_str("\\r"),
3030            '\t' => escaped.push_str("\\t"),
3031            _ => escaped.push(ch),
3032        }
3033    }
3034    escaped
3035}
3036
3037fn unescape_document_field(
3038    value: &str,
3039    line_no: usize,
3040) -> Result<String, AnimationDocumentFormatError> {
3041    let mut unescaped = String::new();
3042    let mut chars = value.chars();
3043    while let Some(ch) = chars.next() {
3044        if ch != '\\' {
3045            unescaped.push(ch);
3046            continue;
3047        }
3048
3049        match chars.next() {
3050            Some('\\') => unescaped.push('\\'),
3051            Some('n') => unescaped.push('\n'),
3052            Some('r') => unescaped.push('\r'),
3053            Some('t') => unescaped.push('\t'),
3054            Some(other) => {
3055                return Err(AnimationDocumentFormatError::new(
3056                    Some(line_no),
3057                    format!("unsupported escape sequence \\{other}"),
3058                ));
3059            }
3060            None => {
3061                return Err(AnimationDocumentFormatError::new(
3062                    Some(line_no),
3063                    "unterminated escape sequence",
3064                ));
3065            }
3066        }
3067    }
3068    Ok(unescaped)
3069}
3070
3071fn expect_field_count(
3072    line_no: usize,
3073    fields: &[&str],
3074    expected: usize,
3075) -> Result<(), AnimationDocumentFormatError> {
3076    if fields.len() == expected {
3077        return Ok(());
3078    }
3079
3080    Err(AnimationDocumentFormatError::new(
3081        Some(line_no),
3082        format!("expected {expected} fields, found {}", fields.len()),
3083    ))
3084}
3085
3086fn ensure_document_header(
3087    line_no: usize,
3088    version: Option<u32>,
3089) -> Result<(), AnimationDocumentFormatError> {
3090    if version.is_some() {
3091        return Ok(());
3092    }
3093
3094    Err(AnimationDocumentFormatError::new(
3095        Some(line_no),
3096        "document header must be the first directive",
3097    ))
3098}
3099
3100fn ensure_no_open_track_or_clip(
3101    line_no: usize,
3102    track: &Option<Track>,
3103    clip: &Option<Clip>,
3104) -> Result<(), AnimationDocumentFormatError> {
3105    if track.is_none() && clip.is_none() {
3106        return Ok(());
3107    }
3108
3109    Err(AnimationDocumentFormatError::new(
3110        Some(line_no),
3111        "document metadata must appear before clips",
3112    ))
3113}
3114
3115fn parse_u32_field(
3116    line_no: usize,
3117    value: &str,
3118    label: &str,
3119) -> Result<u32, AnimationDocumentFormatError> {
3120    value.parse::<u32>().map_err(|_| {
3121        AnimationDocumentFormatError::new(Some(line_no), format!("invalid {label}: {value:?}"))
3122    })
3123}
3124
3125fn parse_f64_field(
3126    line_no: usize,
3127    value: &str,
3128    label: &str,
3129) -> Result<f64, AnimationDocumentFormatError> {
3130    let parsed = value.parse::<f64>().map_err(|_| {
3131        AnimationDocumentFormatError::new(Some(line_no), format!("invalid {label}: {value:?}"))
3132    })?;
3133    if parsed.is_finite() {
3134        Ok(parsed)
3135    } else {
3136        Err(AnimationDocumentFormatError::new(
3137            Some(line_no),
3138            format!("{label} must be finite"),
3139        ))
3140    }
3141}
3142
3143fn parse_f32_field(
3144    line_no: usize,
3145    value: &str,
3146    label: &str,
3147) -> Result<f32, AnimationDocumentFormatError> {
3148    let parsed = value.parse::<f32>().map_err(|_| {
3149        AnimationDocumentFormatError::new(Some(line_no), format!("invalid {label}: {value:?}"))
3150    })?;
3151    if parsed.is_finite() {
3152        Ok(parsed)
3153    } else {
3154        Err(AnimationDocumentFormatError::new(
3155            Some(line_no),
3156            format!("{label} must be finite"),
3157        ))
3158    }
3159}
3160
3161fn parse_bool_field(
3162    line_no: usize,
3163    value: &str,
3164    label: &str,
3165) -> Result<bool, AnimationDocumentFormatError> {
3166    match value {
3167        "true" => Ok(true),
3168        "false" => Ok(false),
3169        _ => Err(AnimationDocumentFormatError::new(
3170            Some(line_no),
3171            format!("{label} must be true or false"),
3172        )),
3173    }
3174}
3175
3176fn format_easing(easing: Easing) -> String {
3177    match easing {
3178        Easing::Linear => "linear".to_string(),
3179        Easing::EaseIn => "ease-in".to_string(),
3180        Easing::EaseOut => "ease-out".to_string(),
3181        Easing::EaseInOut => "ease-in-out".to_string(),
3182        Easing::CubicBezier { x1, y1, x2, y2 } => format!(
3183            "cubic-bezier:{},{},{},{}",
3184            format_f32(x1),
3185            format_f32(y1),
3186            format_f32(x2),
3187            format_f32(y2)
3188        ),
3189    }
3190}
3191
3192fn parse_easing(line_no: usize, value: &str) -> Result<Easing, AnimationDocumentFormatError> {
3193    match value {
3194        "linear" => Ok(Easing::Linear),
3195        "ease-in" => Ok(Easing::EaseIn),
3196        "ease-out" => Ok(Easing::EaseOut),
3197        "ease-in-out" => Ok(Easing::EaseInOut),
3198        _ => {
3199            let Some(params) = value.strip_prefix("cubic-bezier:") else {
3200                return Err(AnimationDocumentFormatError::new(
3201                    Some(line_no),
3202                    format!("unknown easing {value:?}"),
3203                ));
3204            };
3205            let values = parse_f32_list(line_no, params, "cubic-bezier")?;
3206            if values.len() != 4 {
3207                return Err(AnimationDocumentFormatError::new(
3208                    Some(line_no),
3209                    "cubic-bezier easing requires four values",
3210                ));
3211            }
3212            Ok(Easing::CubicBezier {
3213                x1: values[0],
3214                y1: values[1],
3215                x2: values[2],
3216                y2: values[3],
3217            })
3218        }
3219    }
3220}
3221
3222fn format_animation_value(value: AnimationValue) -> String {
3223    match value {
3224        AnimationValue::Scalar(value) => format!("scalar:{}", format_f32(value)),
3225        AnimationValue::Point(value) => {
3226            format!("point:{},{}", format_f32(value.x), format_f32(value.y))
3227        }
3228        AnimationValue::Vector(value) => {
3229            format!("vector:{},{}", format_f32(value.x), format_f32(value.y))
3230        }
3231        AnimationValue::Size(value) => {
3232            format!(
3233                "size:{},{}",
3234                format_f32(value.width),
3235                format_f32(value.height)
3236            )
3237        }
3238        AnimationValue::Rect(value) => {
3239            format!(
3240                "rect:{},{},{},{}",
3241                format_f32(value.x()),
3242                format_f32(value.y()),
3243                format_f32(value.width()),
3244                format_f32(value.height())
3245            )
3246        }
3247        AnimationValue::Color(value) => {
3248            format!(
3249                "color:{},{},{},{},{}",
3250                format_color_space(value.space),
3251                format_f32(value.red),
3252                format_f32(value.green),
3253                format_f32(value.blue),
3254                format_f32(value.alpha)
3255            )
3256        }
3257        AnimationValue::Transform(value) => {
3258            format!(
3259                "transform:{},{},{},{},{},{}",
3260                format_f32(value.xx),
3261                format_f32(value.yx),
3262                format_f32(value.xy),
3263                format_f32(value.yy),
3264                format_f32(value.dx),
3265                format_f32(value.dy)
3266            )
3267        }
3268    }
3269}
3270
3271fn parse_animation_value(
3272    line_no: usize,
3273    value: &str,
3274) -> Result<AnimationValue, AnimationDocumentFormatError> {
3275    let Some((kind, payload)) = value.split_once(':') else {
3276        return Err(AnimationDocumentFormatError::new(
3277            Some(line_no),
3278            "animation value must include a kind prefix",
3279        ));
3280    };
3281
3282    match kind {
3283        "scalar" => Ok(AnimationValue::Scalar(parse_f32_field(
3284            line_no,
3285            payload,
3286            "scalar value",
3287        )?)),
3288        "point" => {
3289            let values = parse_fixed_f32_list(line_no, payload, "point", 2)?;
3290            Ok(AnimationValue::Point(Point::new(values[0], values[1])))
3291        }
3292        "vector" => {
3293            let values = parse_fixed_f32_list(line_no, payload, "vector", 2)?;
3294            Ok(AnimationValue::Vector(Vector::new(values[0], values[1])))
3295        }
3296        "size" => {
3297            let values = parse_fixed_f32_list(line_no, payload, "size", 2)?;
3298            Ok(AnimationValue::Size(Size::new(values[0], values[1])))
3299        }
3300        "rect" => {
3301            let values = parse_fixed_f32_list(line_no, payload, "rect", 4)?;
3302            Ok(AnimationValue::Rect(Rect::new(
3303                values[0], values[1], values[2], values[3],
3304            )))
3305        }
3306        "color" => {
3307            let parts = payload.split(',').collect::<Vec<_>>();
3308            if parts.len() != 5 {
3309                return Err(AnimationDocumentFormatError::new(
3310                    Some(line_no),
3311                    "color value requires color space plus four channels",
3312                ));
3313            }
3314            Ok(AnimationValue::Color(Color::new(
3315                parse_color_space(line_no, parts[0])?,
3316                parse_f32_field(line_no, parts[1], "red channel")?,
3317                parse_f32_field(line_no, parts[2], "green channel")?,
3318                parse_f32_field(line_no, parts[3], "blue channel")?,
3319                parse_f32_field(line_no, parts[4], "alpha channel")?,
3320            )))
3321        }
3322        "transform" => {
3323            let values = parse_fixed_f32_list(line_no, payload, "transform", 6)?;
3324            Ok(AnimationValue::Transform(Transform::new(
3325                values[0], values[1], values[2], values[3], values[4], values[5],
3326            )))
3327        }
3328        _ => Err(AnimationDocumentFormatError::new(
3329            Some(line_no),
3330            format!("unknown animation value kind {kind:?}"),
3331        )),
3332    }
3333}
3334
3335fn parse_f32_list(
3336    line_no: usize,
3337    value: &str,
3338    label: &str,
3339) -> Result<Vec<f32>, AnimationDocumentFormatError> {
3340    value
3341        .split(',')
3342        .map(|field| parse_f32_field(line_no, field, label))
3343        .collect()
3344}
3345
3346fn parse_fixed_f32_list(
3347    line_no: usize,
3348    value: &str,
3349    label: &str,
3350    expected: usize,
3351) -> Result<Vec<f32>, AnimationDocumentFormatError> {
3352    let values = parse_f32_list(line_no, value, label)?;
3353    if values.len() == expected {
3354        return Ok(values);
3355    }
3356
3357    Err(AnimationDocumentFormatError::new(
3358        Some(line_no),
3359        format!("{label} value requires {expected} numbers"),
3360    ))
3361}
3362
3363fn format_color_space(color_space: ColorSpace) -> &'static str {
3364    match color_space {
3365        ColorSpace::Srgb => "srgb",
3366        ColorSpace::LinearSrgb => "linear-srgb",
3367        ColorSpace::DisplayP3 => "display-p3",
3368        ColorSpace::LinearDisplayP3 => "linear-display-p3",
3369    }
3370}
3371
3372fn parse_color_space(
3373    line_no: usize,
3374    value: &str,
3375) -> Result<ColorSpace, AnimationDocumentFormatError> {
3376    match value {
3377        "srgb" => Ok(ColorSpace::Srgb),
3378        "linear-srgb" => Ok(ColorSpace::LinearSrgb),
3379        "display-p3" => Ok(ColorSpace::DisplayP3),
3380        "linear-display-p3" => Ok(ColorSpace::LinearDisplayP3),
3381        _ => Err(AnimationDocumentFormatError::new(
3382            Some(line_no),
3383            format!("unknown color space {value:?}"),
3384        )),
3385    }
3386}
3387
3388fn animation_property_from_path(path: String) -> AnimationProperty {
3389    match path.as_str() {
3390        "layer.opacity" => AnimationProperty::LayerOpacity,
3391        "layer.translation" => AnimationProperty::LayerTranslation,
3392        "fill.color" => AnimationProperty::FillColor,
3393        "bounds" => AnimationProperty::Bounds,
3394        _ => AnimationProperty::Custom(AnimationPropertyPath::new(path)),
3395    }
3396}
3397
3398/// The CSS `cubic-bezier()` timing function: solve the curve's x for `t`,
3399/// then return its y. Newton's method converges in a few steps on typical
3400/// curves; bisection takes over where the slope is too flat for it.
3401fn sample_cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 {
3402    if t <= 0.0 {
3403        return 0.0;
3404    }
3405    if t >= 1.0 {
3406        return 1.0;
3407    }
3408
3409    // Polynomial coefficients of each coordinate, in f64 for accuracy.
3410    let coefficients = |p1: f32, p2: f32| {
3411        let c = 3.0 * f64::from(p1);
3412        let b = 3.0 * (f64::from(p2) - f64::from(p1)) - c;
3413        let a = 1.0 - c - b;
3414        (a, b, c)
3415    };
3416    let (ax, bx, cx) = coefficients(x1, x2);
3417    let (ay, by, cy) = coefficients(y1, y2);
3418    let curve_x = |u: f64| ((ax * u + bx) * u + cx) * u;
3419    let slope_x = |u: f64| (3.0 * ax * u + 2.0 * bx) * u + cx;
3420    let target = f64::from(t);
3421    const EPSILON: f64 = 1e-7;
3422
3423    let mut u = target;
3424    let mut solved = false;
3425    for _ in 0..8 {
3426        let error = curve_x(u) - target;
3427        if error.abs() < EPSILON {
3428            solved = true;
3429            break;
3430        }
3431        let slope = slope_x(u);
3432        if slope.abs() < 1e-6 {
3433            break;
3434        }
3435        u -= error / slope;
3436    }
3437    if !solved {
3438        let (mut low, mut high) = (0.0, 1.0);
3439        u = target;
3440        for _ in 0..64 {
3441            let x = curve_x(u);
3442            if (x - target).abs() < EPSILON {
3443                break;
3444            }
3445            if x < target {
3446                low = u;
3447            } else {
3448                high = u;
3449            }
3450            u = (low + high) * 0.5;
3451        }
3452    }
3453
3454    (((ay * u + by) * u + cy) * u) as f32
3455}
3456
3457#[cfg(test)]
3458mod tests {
3459    use super::{
3460        AnimatedValue, AnimationBinding, AnimationDocument, AnimationEditorCommand,
3461        AnimationEditorState, AnimationPlayer, AnimationProperty, AnimationPropertyPath,
3462        AnimationSpec, AnimationTargetId, AnimationValue, Blink, Clip, Easing, Interpolate,
3463        Keyframe, KeyframeSelection, LoopMode, MotionPolicy, MotionPreference, MotionValue,
3464        PlaybackSpan, PlaybackState, Pulse, SampleBuffer, SpringF32, SpringSpec, Stagger,
3465        StaggerOrigin, Timeline, TimelineMarker, Track, Transition,
3466    };
3467    use sui_core::{Color, ColorSpace, Rect, Transform, Vector};
3468
3469    fn opacity_binding() -> AnimationBinding {
3470        AnimationBinding::new(
3471            AnimationTargetId::new("hero-card"),
3472            AnimationProperty::LayerOpacity,
3473        )
3474    }
3475
3476    #[test]
3477    fn interpolate_supports_common_sui_values() {
3478        assert!((f32::interpolate(2.0, 6.0, 0.25) - 3.0).abs() < 1e-6);
3479        assert_eq!(
3480            Vector::interpolate(Vector::new(0.0, 4.0), Vector::new(8.0, 12.0), 0.5),
3481            Vector::new(4.0, 8.0)
3482        );
3483        assert_eq!(
3484            Rect::interpolate(
3485                Rect::new(0.0, 2.0, 10.0, 20.0),
3486                Rect::new(10.0, 12.0, 30.0, 40.0),
3487                0.5
3488            ),
3489            Rect::new(5.0, 7.0, 20.0, 30.0)
3490        );
3491        let interpolated = Color::interpolate(
3492            Color::rgba(0.2, 0.4, 0.6, 1.0),
3493            Color::rgba(0.6, 0.8, 1.0, 0.0),
3494            0.5,
3495        );
3496        // Premultiplied blending: fading toward a transparent color keeps
3497        // the visible color and only lowers its opacity.
3498        let expected = Color::rgba(0.2, 0.4, 0.6, 0.5);
3499        assert_eq!(interpolated.space, expected.space);
3500        assert!((interpolated.red - expected.red).abs() < 1e-4);
3501        assert!((interpolated.green - expected.green).abs() < 1e-4);
3502        assert!((interpolated.blue - expected.blue).abs() < 1e-4);
3503        assert!((interpolated.alpha - expected.alpha).abs() < 1e-6);
3504    }
3505
3506    #[test]
3507    fn transform_interpolation_rotates_without_shrinking() {
3508        let quarter_turn = Transform::rotation(std::f32::consts::FRAC_PI_2);
3509
3510        let halfway = Transform::interpolate(Transform::IDENTITY, quarter_turn, 0.5);
3511
3512        let eighth = Transform::rotation(std::f32::consts::FRAC_PI_4);
3513        for (actual, expected) in [
3514            (halfway.xx, eighth.xx),
3515            (halfway.yx, eighth.yx),
3516            (halfway.xy, eighth.xy),
3517            (halfway.yy, eighth.yy),
3518        ] {
3519            assert!((actual - expected).abs() < 1e-5, "{actual} vs {expected}");
3520        }
3521        // Blending the matrix entries would give a scale of about 0.707.
3522        assert!((halfway.xx.hypot(halfway.yx) - 1.0).abs() < 1e-5);
3523    }
3524
3525    #[test]
3526    fn transform_interpolation_blends_scale_translation_and_short_rotation() {
3527        let from = Transform::scale(1.0, 2.0).then(Transform::translation(10.0, 0.0));
3528        let to = Transform::scale(3.0, 4.0).then(Transform::translation(30.0, 20.0));
3529
3530        let halfway = Transform::interpolate(from, to, 0.5);
3531
3532        assert!((halfway.xx - 2.0).abs() < 1e-5);
3533        assert!((halfway.yy - 3.0).abs() < 1e-5);
3534        assert!((halfway.dx - 20.0).abs() < 1e-5);
3535        assert!((halfway.dy - 10.0).abs() < 1e-5);
3536        assert_eq!(Transform::interpolate(from, to, 0.0), from);
3537        assert_eq!(Transform::interpolate(from, to, 1.0), to);
3538
3539        // From 170 degrees to -170 degrees turns 20 degrees through 180.
3540        let near_half = Transform::rotation(170_f32.to_radians());
3541        let past_half = Transform::rotation((-170_f32).to_radians());
3542        let middle = Transform::interpolate(near_half, past_half, 0.5);
3543        assert!((middle.xx + 1.0).abs() < 1e-5, "{middle:?}");
3544    }
3545
3546    #[test]
3547    fn extrapolation_lets_scalars_overshoot_but_clamps_colors() {
3548        assert_eq!(f32::extrapolate(0.0, 10.0, 1.2), 12.0);
3549        assert_eq!(f32::interpolate(0.0, 10.0, 1.2), 10.0);
3550        assert_eq!(
3551            Color::extrapolate(Color::BLACK, Color::WHITE, 1.5),
3552            Color::WHITE
3553        );
3554    }
3555
3556    #[test]
3557    fn transition_samples_ease_in_out_curve() {
3558        let transition = Transition::new(0.0_f32, 1.0, 10.0, 2.0, Easing::EaseInOut);
3559
3560        assert_eq!(transition.sample(10.0), 0.0);
3561        assert!(transition.sample(11.0) > 0.45 && transition.sample(11.0) < 0.55);
3562        assert_eq!(transition.sample(12.0), 1.0);
3563        assert!(transition.is_complete(12.0));
3564    }
3565
3566    #[test]
3567    fn cubic_bezier_easing_has_stable_endpoints() {
3568        let easing = Easing::CubicBezier {
3569            x1: 0.4,
3570            y1: 0.0,
3571            x2: 0.2,
3572            y2: 1.0,
3573        };
3574
3575        assert_eq!(easing.sample(0.0), 0.0);
3576        assert_eq!(easing.sample(1.0), 1.0);
3577        let midpoint = easing.sample(0.5);
3578        assert!(midpoint > 0.0 && midpoint < 1.0);
3579    }
3580
3581    #[test]
3582    fn track_samples_keyframes_without_requiring_sorted_input() {
3583        let track = Track::new(opacity_binding()).with_keyframes([
3584            Keyframe::new(1.0, 1.0_f32),
3585            Keyframe::new(0.0, 0.0_f32).with_easing(Easing::Linear),
3586        ]);
3587
3588        assert_eq!(track.sample(-1.0), Some(0.0));
3589        assert_eq!(track.sample(0.5), Some(0.5));
3590        assert_eq!(track.sample(2.0), Some(1.0));
3591    }
3592
3593    #[test]
3594    fn timeline_samples_clip_tracks_in_global_time() {
3595        let opacity_track = Track::new(opacity_binding()).with_keyframes([
3596            Keyframe::new(0.0, AnimationValue::Scalar(0.25)),
3597            Keyframe::new(2.0, AnimationValue::Scalar(1.0)),
3598        ]);
3599        let timeline =
3600            Timeline::new(4.0).with_clip(Clip::new("intro", 1.0, 2.0).with_track(opacity_track));
3601
3602        assert!(timeline.sample(0.5).is_empty());
3603        let samples = timeline.sample(2.0);
3604        assert_eq!(samples.len(), 1);
3605        assert_eq!(samples[0].clip_id, "intro");
3606        let opacity = samples[0]
3607            .value
3608            .as_scalar()
3609            .expect("opacity sample should be scalar");
3610        assert!((opacity - 0.625).abs() < 1e-6);
3611    }
3612
3613    #[test]
3614    fn timeline_sample_into_reuses_output_storage() {
3615        let opacity_track = Track::new(opacity_binding()).with_keyframes([
3616            Keyframe::new(0.0, AnimationValue::Scalar(0.25)),
3617            Keyframe::new(1.0, AnimationValue::Scalar(0.75)),
3618        ]);
3619        let timeline =
3620            Timeline::new(1.0).with_clip(Clip::new("intro", 0.0, 1.0).with_track(opacity_track));
3621        let mut samples = SampleBuffer::with_capacity(8);
3622        let initial_capacity = samples.capacity();
3623
3624        {
3625            let batch = timeline.sample_into(0.5, &mut samples);
3626            assert_eq!(batch.len(), 1);
3627            assert_eq!(batch.samples()[0].clip_id, "intro");
3628            assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.5));
3629        }
3630        assert_eq!(samples.capacity(), initial_capacity);
3631
3632        {
3633            let batch = timeline.sample_into(2.0, &mut samples);
3634            assert_eq!(batch.len(), 1);
3635            assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.75));
3636        }
3637        assert_eq!(samples.capacity(), initial_capacity);
3638    }
3639
3640    #[test]
3641    fn compiled_timeline_sorts_tracks_and_omits_disabled_data() {
3642        let opacity_track = Track::new(opacity_binding()).with_keyframes([
3643            Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
3644            Keyframe::new(0.0, AnimationValue::Scalar(0.0)).with_easing(Easing::Linear),
3645        ]);
3646        let disabled_track = Track::new(AnimationBinding::new(
3647            AnimationTargetId::new("hero-card"),
3648            AnimationProperty::FillColor,
3649        ))
3650        .with_enabled(false)
3651        .with_keyframes([
3652            Keyframe::new(0.0, AnimationValue::Color(Color::rgba(1.0, 0.0, 0.0, 1.0))),
3653            Keyframe::new(1.0, AnimationValue::Color(Color::rgba(0.0, 0.0, 1.0, 1.0))),
3654        ]);
3655        let disabled_clip = Clip::new("disabled", 0.0, 1.0).with_track(
3656            Track::new(opacity_binding()).with_keyframes([
3657                Keyframe::new(0.0, AnimationValue::Scalar(0.0)),
3658                Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
3659            ]),
3660        );
3661        let mut disabled_clip = disabled_clip;
3662        disabled_clip.enabled = false;
3663        let timeline = Timeline::new(1.0)
3664            .with_clip(
3665                Clip::new("intro", 0.0, 1.0)
3666                    .with_track(opacity_track)
3667                    .with_track(disabled_track),
3668            )
3669            .with_clip(disabled_clip);
3670
3671        let compiled = timeline.compile();
3672        let mut samples = SampleBuffer::new();
3673        let batch = compiled.sample_into(0.5, &mut samples);
3674
3675        assert_eq!(compiled.clips().len(), 1);
3676        assert_eq!(compiled.sample_capacity(), 1);
3677        assert_eq!(batch.len(), 1);
3678        assert_eq!(batch.samples()[0].clip_id, "intro");
3679        assert_eq!(
3680            batch.samples()[0].binding.property,
3681            AnimationProperty::LayerOpacity
3682        );
3683        assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.5));
3684    }
3685
3686    #[test]
3687    fn animation_player_ticks_shared_compiled_timeline_into_sample_buffer() {
3688        let timeline = Timeline::new(1.0).with_clip(Clip::new("intro", 0.0, 1.0).with_track(
3689            Track::new(opacity_binding()).with_keyframes([
3690                Keyframe::new(0.0, AnimationValue::Scalar(0.0)).with_easing(Easing::Linear),
3691                Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
3692            ]),
3693        ));
3694        let compiled = timeline.compile_shared();
3695        let mut player = AnimationPlayer::new(compiled.clone()).repeat();
3696        let mut sibling = AnimationPlayer::new(compiled);
3697        let mut samples = SampleBuffer::with_capacity(1);
3698        player.play();
3699
3700        let tick = player.tick_into(0.5, &mut samples);
3701
3702        assert!(tick.advanced);
3703        assert!(tick.should_continue);
3704        assert_eq!(tick.playback.playhead, 0.5);
3705        assert_eq!(tick.sample_values()[0].value.as_scalar(), Some(0.5));
3706
3707        sibling.seek(0.25);
3708        let batch = sibling.sample_into(&mut samples);
3709        assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.25));
3710    }
3711
3712    #[test]
3713    fn playback_state_advances_and_repeats() {
3714        let mut playback = PlaybackState {
3715            loop_mode: LoopMode::Repeat,
3716            ..PlaybackState::default()
3717        };
3718        playback.play();
3719
3720        assert!(playback.tick(1.25, 1.0));
3721        assert!((playback.playhead - 0.25).abs() < 1e-6);
3722        assert!(playback.playing);
3723    }
3724
3725    #[test]
3726    fn blink_is_deterministic_for_same_time_inputs() {
3727        let blink = Blink::new(0.8).with_duty_cycle(0.25).with_phase(0.1);
3728
3729        assert_eq!(blink.is_on(1.25), blink.is_on(1.25));
3730        assert!(blink.is_on(0.0));
3731        assert!(!blink.is_on(0.35));
3732    }
3733
3734    #[test]
3735    fn pulse_samples_repeatable_range() {
3736        let pulse = Pulse::new(1.0, 0.2, 1.0);
3737        let a = pulse.sample(0.25);
3738        let b = pulse.sample(0.25);
3739        assert_eq!(a, b);
3740        assert!((0.2..=1.0).contains(&a));
3741    }
3742
3743    #[test]
3744    fn spring_steps_are_exact_at_any_frame_rate() {
3745        let spec = SpringSpec::BOUNCY;
3746        let mut fine = SpringF32::from_spec(0.0, spec);
3747        let mut coarse = SpringF32::from_spec(0.0, spec);
3748        for _ in 0..240 {
3749            fine.step(1.0, 1.0 / 240.0);
3750        }
3751        for _ in 0..10 {
3752            coarse.step(1.0, 0.1);
3753        }
3754
3755        assert!((fine.value - coarse.value).abs() < 1e-4);
3756        assert!((fine.velocity - coarse.velocity).abs() < 1e-3);
3757    }
3758
3759    #[test]
3760    fn stiff_springs_stay_stable_across_long_frames() {
3761        let mut spring = SpringF32::new(0.0).with_config(4000.0, 20.0);
3762
3763        // Explicit integration would blow up at this step size.
3764        for _ in 0..20 {
3765            spring.step(1.0, 0.25);
3766        }
3767
3768        assert!(spring.value.is_finite());
3769        assert!(spring.settle(1.0));
3770        assert_eq!(spring.value, 1.0);
3771        assert_eq!(spring.velocity, 0.0);
3772    }
3773
3774    #[test]
3775    fn spring_carries_fling_velocity() {
3776        let mut flung = SpringF32::from_spec(0.0, SpringSpec::SMOOTH).with_velocity(20.0);
3777
3778        flung.step(0.0, 0.05);
3779
3780        assert!(flung.value > 0.3, "a fling travels before springing back");
3781        assert!(!flung.is_settled(0.0));
3782    }
3783
3784    #[test]
3785    fn spring_spec_maps_bounce_to_damping() {
3786        assert!((SpringSpec::SMOOTH.damping_ratio() - 1.0).abs() < 1e-6);
3787        assert!((SpringSpec::new(0.3, 0.25).damping_ratio() - 0.75).abs() < 1e-6);
3788        assert!(SpringSpec::new(0.3, -0.5).damping_ratio() > 1.0);
3789
3790        let round_trip =
3791            SpringSpec::from_physics(SpringSpec::BOUNCY.stiffness(), SpringSpec::BOUNCY.damping());
3792        assert!((round_trip.duration - SpringSpec::BOUNCY.duration).abs() < 1e-4);
3793        assert!((round_trip.bounce - SpringSpec::BOUNCY.bounce).abs() < 1e-4);
3794    }
3795
3796    #[test]
3797    fn spring_progress_overshoots_only_when_bouncy_and_settles_exactly() {
3798        let peak = |spec: SpringSpec| {
3799            (0..400)
3800                .map(|step| spec.progress(f64::from(step) / 200.0))
3801                .fold(0.0_f32, f32::max)
3802        };
3803
3804        assert!(peak(SpringSpec::BOUNCY) > 1.05);
3805        assert!(peak(SpringSpec::SMOOTH) <= 1.0);
3806        assert!(peak(SpringSpec::new(0.3, -0.4)) <= 1.0);
3807        for spec in [SpringSpec::SMOOTH, SpringSpec::SNAPPY, SpringSpec::BOUNCY] {
3808            let settle = spec.settling_duration();
3809            assert!(settle > f64::from(spec.duration) * 0.5 && settle < 3.0);
3810            assert_eq!(spec.progress(settle), 1.0);
3811            assert!((spec.progress(settle * 0.999) - 1.0).abs() < 2e-3);
3812            assert_eq!(spec.progress(0.0), 0.0);
3813        }
3814    }
3815
3816    #[test]
3817    fn animation_spec_follows_the_motion_policy() {
3818        let spec = AnimationSpec::tween(0.2, Easing::EaseOut);
3819        let slow = MotionPolicy::FULL.with_time_scale(0.5);
3820
3821        assert_eq!(spec.with_policy(slow).duration(), 0.4);
3822        assert!(
3823            spec.with_policy(MotionPolicy::new(MotionPreference::Off))
3824                .is_instant()
3825        );
3826        let reduced = MotionPolicy::new(MotionPreference::Reduced);
3827        assert_eq!(spec.with_policy(reduced), spec);
3828        assert!(spec.with_movement_policy(reduced).is_instant());
3829        let spring = AnimationSpec::spring(SpringSpec::SMOOTH).with_policy(slow);
3830        let nominal = AnimationSpec::spring(SpringSpec::SMOOTH).duration();
3831        assert!((spring.duration() - nominal * 2.0).abs() < 1e-3);
3832    }
3833
3834    fn velocity(motion: &MotionValue<f32>, time: f64) -> f32 {
3835        let step = 1.0e-4;
3836        (motion.value(time + step) - motion.value(time - step)) / (2.0 * step) as f32
3837    }
3838
3839    #[test]
3840    fn motion_value_reaches_its_target_exactly() {
3841        let mut motion = MotionValue::new(0.0_f32);
3842
3843        assert!(motion.animate_to(1.0, 10.0, AnimationSpec::tween(0.2, Easing::Linear)));
3844        assert!((motion.value(10.1) - 0.5).abs() < 1e-5);
3845        assert!(motion.advance(10.1));
3846        assert!(!motion.advance(10.2));
3847        assert_eq!(motion.value(10.2), 1.0);
3848        assert!(!motion.animate_to(1.0, 10.3, AnimationSpec::tween(0.2, Easing::Linear)));
3849    }
3850
3851    #[test]
3852    fn retargeting_keeps_velocity_instead_of_restarting_from_rest() {
3853        let spec = AnimationSpec::tween(0.3, Easing::EaseInOut);
3854        let mut motion = MotionValue::new(0.0_f32);
3855        motion.animate_to(1.0, 0.0, spec);
3856        let before = velocity(&motion, 0.15);
3857        assert!(before > 1.0);
3858
3859        motion.animate_to(0.0, 0.15, spec);
3860
3861        // The value keeps moving the way it was going and turns around
3862        // smoothly, rather than stopping dead at the retarget.
3863        assert!((velocity(&motion, 0.15) - before).abs() < 0.05 * before);
3864        assert!(motion.value(0.2) > motion.value(0.15));
3865        assert!(!motion.advance(0.45));
3866        assert_eq!(motion.value(0.45), 0.0);
3867    }
3868
3869    #[test]
3870    fn spring_retargets_keep_momentum_too() {
3871        let spec = AnimationSpec::spring(SpringSpec::SNAPPY);
3872        let mut motion = MotionValue::new(0.0_f32);
3873        motion.animate_to(100.0, 0.0, spec);
3874        let before = velocity(&motion, 0.08);
3875
3876        motion.animate_to(-100.0, 0.08, spec);
3877
3878        assert!((velocity(&motion, 0.08) - before).abs() < 0.05 * before.abs());
3879        assert!(motion.animate_to(-100.0, 0.1, spec));
3880        let settled = 0.08 + spec.duration() + 0.01;
3881        assert!(!motion.advance(settled));
3882        assert_eq!(motion.value(settled), -100.0);
3883    }
3884
3885    #[test]
3886    fn rapid_retargets_fold_old_motion_without_jumping() {
3887        let spec = AnimationSpec::tween(1.0, Easing::EaseInOut);
3888        let mut motion = MotionValue::new(0.0_f32);
3889        let mut time = 0.0;
3890        for step in 0..12 {
3891            let before = motion.value(time);
3892            motion.animate_to(if step % 2 == 0 { 1.0 } else { 0.0 }, time, spec);
3893            assert!((motion.value(time) - before).abs() < 1e-5);
3894            time += 0.05;
3895        }
3896
3897        assert_eq!(motion.target(), 0.0);
3898        assert!(!motion.advance(time + 1.0));
3899        assert_eq!(motion.value(time + 1.0), 0.0);
3900    }
3901
3902    #[test]
3903    fn animated_value_supports_springs() {
3904        let mut value = AnimatedValue::new(0.0_f32).with_spec(SpringSpec::BOUNCY.into());
3905        value.set_target(1.0);
3906
3907        let mut peak = 0.0_f32;
3908        while value.tick(1.0 / 60.0) {
3909            peak = peak.max(value.value());
3910        }
3911
3912        assert!(peak > 1.05);
3913        assert_eq!(value.value(), 1.0);
3914    }
3915
3916    #[test]
3917    fn spring_helpers_converge_toward_target_values() {
3918        let mut spring = SpringF32::new(0.0).with_config(140.0, 22.0);
3919        let mut value = 0.0;
3920        for _ in 0..120 {
3921            value = spring.step(1.0, 1.0 / 120.0);
3922        }
3923
3924        assert!(value > 0.95);
3925        assert!((value - 1.0).abs() < 0.05);
3926    }
3927
3928    #[test]
3929    fn animated_value_reaches_target_and_reports_completion() {
3930        let mut animated = AnimatedValue::new(0.0_f32)
3931            .with_duration(0.2)
3932            .with_easing(Easing::Linear);
3933        animated.set_target(1.0);
3934        assert!(animated.is_animating());
3935
3936        assert!(animated.tick(0.1));
3937        assert!((animated.value() - 0.5).abs() < 1e-4);
3938
3939        assert!(!animated.tick(0.1));
3940        assert_eq!(animated.value(), 1.0);
3941        assert!(!animated.is_animating());
3942        assert!(!animated.tick(0.1));
3943    }
3944
3945    #[test]
3946    fn animated_value_with_zero_duration_snaps_immediately() {
3947        let mut animated = AnimatedValue::new(2.0_f32).with_duration(0.0);
3948        animated.set_target(9.0);
3949
3950        assert!(!animated.is_animating());
3951        assert_eq!(animated.value(), 9.0);
3952        assert!(!animated.tick(1.0));
3953    }
3954
3955    #[test]
3956    fn editor_state_adds_keyframes_and_undoes_document_changes() {
3957        let track = Track::new(opacity_binding());
3958        let document = AnimationDocument::new(
3959            "Editor test",
3960            Timeline::new(2.0).with_clip(Clip::new("intro", 0.0, 2.0).with_track(track)),
3961        );
3962        let mut editor = AnimationEditorState::new(document);
3963
3964        assert!(editor.apply_command(AnimationEditorCommand::AddKeyframe {
3965            clip_index: 0,
3966            track_index: 0,
3967            keyframe: Keyframe::new(0.51, AnimationValue::Scalar(0.8)),
3968        }));
3969        assert_eq!(editor.undo_len(), 1);
3970        assert_eq!(
3971            editor.document.timeline.clips[0].tracks[0].keyframes[0].time,
3972            0.5
3973        );
3974
3975        assert!(editor.undo());
3976        assert!(
3977            editor.document.timeline.clips[0].tracks[0]
3978                .keyframes
3979                .is_empty()
3980        );
3981        assert!(editor.redo());
3982        assert_eq!(
3983            editor.document.timeline.clips[0].tracks[0].keyframes.len(),
3984            1
3985        );
3986    }
3987
3988    #[test]
3989    fn editor_moves_keyframes_with_snapping_and_undo() {
3990        let mut editor = AnimationEditorState::new(AnimationDocument::new(
3991            "move",
3992            Timeline::new(1.0).with_clip(Clip::new("intro", 0.0, 1.0).with_track(
3993                Track::new(opacity_binding()).with_keyframes([
3994                    Keyframe::new(0.0, AnimationValue::Scalar(0.0)),
3995                    Keyframe::new(0.5, AnimationValue::Scalar(1.0)),
3996                ]),
3997            )),
3998        ));
3999        let selection = KeyframeSelection {
4000            clip_index: 0,
4001            track_index: 0,
4002            keyframe_index: 1,
4003        };
4004        let keyframe_time = |editor: &AnimationEditorState| {
4005            editor.document.timeline.clips[0].tracks[0].keyframes[1].time
4006        };
4007
4008        assert!(editor.apply_command(AnimationEditorCommand::MoveKeyframe {
4009            selection,
4010            time: 0.74,
4011        }));
4012        assert!((keyframe_time(&editor) - 0.75).abs() < 1e-9);
4013        assert!(editor.apply_command(AnimationEditorCommand::MoveKeyframe {
4014            selection,
4015            time: 4.0,
4016        }));
4017        assert_eq!(keyframe_time(&editor), 1.0);
4018        assert!(!editor.apply_command(AnimationEditorCommand::MoveKeyframe {
4019            selection,
4020            time: 1.0,
4021        }));
4022        assert_eq!(editor.undo_len(), 2);
4023        assert!(editor.undo());
4024        assert!((keyframe_time(&editor) - 0.75).abs() < 1e-9);
4025    }
4026
4027    #[test]
4028    fn editor_selection_tracks_keyframes_without_mutating_document() {
4029        let mut editor = AnimationEditorState::default();
4030        let selection = KeyframeSelection {
4031            clip_index: 2,
4032            track_index: 1,
4033            keyframe_index: 3,
4034        };
4035
4036        assert!(editor.apply_command(AnimationEditorCommand::SelectKeyframe(selection)));
4037        assert_eq!(editor.selection.keyframes, vec![selection]);
4038        assert_eq!(editor.undo_len(), 0);
4039    }
4040
4041    #[test]
4042    fn editor_updates_keyframe_easing_with_undo() {
4043        let track = Track::new(opacity_binding()).with_keyframes([
4044            Keyframe::new(0.0, AnimationValue::Scalar(0.0)),
4045            Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
4046        ]);
4047        let document = AnimationDocument::new(
4048            "Easing test",
4049            Timeline::new(1.0).with_clip(Clip::new("intro", 0.0, 1.0).with_track(track)),
4050        );
4051        let mut editor = AnimationEditorState::new(document);
4052        let selection = KeyframeSelection {
4053            clip_index: 0,
4054            track_index: 0,
4055            keyframe_index: 0,
4056        };
4057
4058        assert!(
4059            editor.apply_command(AnimationEditorCommand::UpdateKeyframeEasing {
4060                selection,
4061                easing: Easing::EaseInOut,
4062            })
4063        );
4064        assert_eq!(
4065            editor.document.timeline.clips[0].tracks[0].keyframes[0].easing,
4066            Easing::EaseInOut
4067        );
4068        assert!(editor.undo());
4069        assert_eq!(
4070            editor.document.timeline.clips[0].tracks[0].keyframes[0].easing,
4071            Easing::Linear
4072        );
4073    }
4074
4075    #[test]
4076    fn animation_document_format_round_trips_timeline_data() {
4077        let target = AnimationTargetId::new("preview card\tmain");
4078        let binding = |property| AnimationBinding::new(target.clone(), property);
4079        let mut fill_track = Track::new(binding(AnimationProperty::FillColor)).with_keyframes([
4080            Keyframe::new(
4081                0.0,
4082                AnimationValue::Color(Color::new(ColorSpace::DisplayP3, 0.1, 0.2, 0.3, 0.4)),
4083            )
4084            .with_easing(Easing::CubicBezier {
4085                x1: 0.4,
4086                y1: 0.0,
4087                x2: 0.2,
4088                y2: 1.0,
4089            }),
4090            Keyframe::new(
4091                1.0,
4092                AnimationValue::Color(Color::new(ColorSpace::LinearDisplayP3, 0.7, 0.6, 0.5, 1.0)),
4093            ),
4094        ]);
4095        fill_track.enabled = false;
4096        let mut clip = Clip::new("intro\nclip", 0.25, 2.0)
4097            .with_track(
4098                Track::new(binding(AnimationProperty::LayerTranslation)).with_keyframes([
4099                    Keyframe::new(0.0, AnimationValue::Vector(Vector::new(-12.0, 4.5)))
4100                        .with_easing(Easing::EaseInOut),
4101                    Keyframe::new(1.0, AnimationValue::Vector(Vector::new(22.0, -8.0))),
4102                ]),
4103            )
4104            .with_track(fill_track)
4105            .with_track(
4106                Track::new(binding(AnimationProperty::Custom(
4107                    AnimationPropertyPath::new("paint.radius"),
4108                )))
4109                .with_keyframes([
4110                    Keyframe::new(0.0, AnimationValue::Scalar(6.0)).with_easing(Easing::EaseOut),
4111                    Keyframe::new(1.0, AnimationValue::Scalar(18.0)),
4112                ]),
4113            )
4114            .with_track(
4115                Track::new(binding(AnimationProperty::Custom(
4116                    AnimationPropertyPath::new("local.transform"),
4117                )))
4118                .with_keyframes([Keyframe::new(
4119                    0.5,
4120                    AnimationValue::Transform(Transform::translation(8.0, 9.0)),
4121                )]),
4122            );
4123        clip.enabled = true;
4124        let document = AnimationDocument::new(
4125            "Demo\tAnimation\nDocument",
4126            Timeline::new(3.5).with_clip(clip),
4127        );
4128
4129        let serialized = document.to_document_format();
4130        assert!(serialized.starts_with("sui-animation-document\t2\n"));
4131        assert!(serialized.contains("paint.radius"));
4132
4133        let parsed = AnimationDocument::from_document_format(&serialized)
4134            .expect("serialized document should parse");
4135        assert_eq!(parsed, document);
4136        assert_eq!(parsed.to_document_format(), serialized);
4137    }
4138
4139    #[test]
4140    fn animation_document_format_rejects_unsupported_versions() {
4141        let err = AnimationDocument::from_document_format(
4142            "sui-animation-document\t99\nname\tBad\nduration\t1\n",
4143        )
4144        .expect_err("unsupported version should fail");
4145
4146        assert_eq!(err.line, Some(1));
4147        assert!(err.message.contains("unsupported document version"));
4148    }
4149
4150    #[test]
4151    fn animation_document_format_rejects_unclosed_tracks() {
4152        let err = AnimationDocument::from_document_format(
4153            "sui-animation-document\t1\nname\tBad\nduration\t1\nclip\tintro\t0\t1\ttrue\ntrack\ttarget\tlayer.opacity\ttrue\n",
4154        )
4155        .expect_err("unclosed track should fail");
4156
4157        assert!(err.message.contains("unclosed track"));
4158    }
4159
4160    #[test]
4161    fn delayed_motion_holds_its_course_until_it_starts() {
4162        let mut value = MotionValue::new(0.0_f32);
4163        let spec = AnimationSpec::tween(1.0, Easing::Linear);
4164        assert!(value.animate_to_after(1.0, 0.0, 0.5, spec));
4165
4166        assert_eq!(value.value(0.25), 0.0);
4167        assert!(value.is_animating_at(0.25));
4168        assert!((value.value(1.0) - 0.5).abs() < 1e-5);
4169        assert_eq!(value.end_time(), Some(1.5));
4170        assert_eq!(value.value(1.5), 1.0);
4171
4172        // Retargeting before a delayed start keeps the running motion going
4173        // until the new one begins.
4174        let mut value = MotionValue::new(0.0_f32);
4175        value.animate_to(1.0, 0.0, spec);
4176        value.animate_to_after(0.0, 0.5, 0.25, spec);
4177        assert!((value.value(0.6) - 0.6).abs() < 1e-5);
4178    }
4179
4180    #[test]
4181    fn a_delayed_jump_waits_for_its_delay() {
4182        let mut value = MotionValue::new(0.0_f32);
4183        assert!(value.animate_to_after(1.0, 0.0, 0.2, AnimationSpec::INSTANT));
4184        assert_eq!(value.value(0.1), 0.0);
4185        assert_eq!(value.value(0.2), 1.0);
4186        assert!(!value.advance(0.3));
4187    }
4188
4189    #[test]
4190    fn stagger_spreads_delays_from_its_origin() {
4191        let stagger = Stagger::new(0.05);
4192        let delays = (0..4)
4193            .map(|index| stagger.delay(index, 4))
4194            .collect::<Vec<_>>();
4195        assert_eq!(delays, vec![0.0, 0.05, 0.1, 0.15000000000000002]);
4196
4197        let last = stagger.from(StaggerOrigin::Last);
4198        assert_eq!(last.delay(3, 4), 0.0);
4199        assert!((last.delay(0, 4) - 0.15).abs() < 1e-9);
4200
4201        let center = stagger.from(StaggerOrigin::Center);
4202        assert!((center.delay(0, 5) - 0.1).abs() < 1e-9);
4203        assert_eq!(center.delay(2, 5), 0.0);
4204
4205        let from_item = stagger.from(StaggerOrigin::Index(1));
4206        assert!((from_item.delay(4, 5) - 0.15).abs() < 1e-9);
4207
4208        // A long list fits its cascade inside the cap.
4209        let capped = Stagger::new(0.05).max_delay(0.2);
4210        assert!((capped.delay(99, 100) - 0.2).abs() < 1e-9);
4211        assert!((capped.delay(50, 100) - 50.0 * 0.2 / 99.0).abs() < 1e-9);
4212
4213        assert_eq!(Stagger::NONE.delay(3, 4), 0.0);
4214        assert_eq!(stagger.delay(0, 0), 0.0);
4215    }
4216
4217    #[test]
4218    fn ping_pong_playback_reverses_at_each_end() {
4219        let mut playback = PlaybackState {
4220            loop_mode: LoopMode::PingPong,
4221            ..PlaybackState::default()
4222        };
4223        playback.play();
4224        playback.tick(1.25, 1.0);
4225        assert!((playback.playhead - 0.75).abs() < 1e-9);
4226        assert!(playback.playback_rate < 0.0);
4227
4228        playback.tick(1.0, 1.0);
4229        assert!((playback.playhead - 0.25).abs() < 1e-9);
4230        assert!(playback.playback_rate > 0.0);
4231        assert!(playback.playing);
4232
4233        playback.stop();
4234        assert_eq!(playback.playback_rate, 1.0);
4235    }
4236
4237    #[test]
4238    fn playback_waits_before_starting_and_between_loops() {
4239        let mut playback = PlaybackState {
4240            loop_mode: LoopMode::Repeat,
4241            start_delay: 0.5,
4242            loop_delay: 0.25,
4243            ..PlaybackState::default()
4244        };
4245        playback.play();
4246        assert!(!playback.tick(0.4, 1.0));
4247        assert_eq!(playback.playhead, 0.0);
4248        playback.tick(0.2, 1.0);
4249        assert!((playback.playhead - 0.1).abs() < 1e-9);
4250
4251        // Reach the end, hold there, then start over.
4252        playback.tick(0.9, 1.0);
4253        assert_eq!(playback.playhead, 0.0);
4254        assert!((playback.waiting() - 0.25).abs() < 1e-9);
4255        playback.tick(0.35, 1.0);
4256        assert!((playback.playhead - 0.1).abs() < 1e-9);
4257
4258        // Resuming after a pause does not wait again.
4259        playback.pause();
4260        playback.play();
4261        playback.tick(0.1, 1.0);
4262        assert!((playback.playhead - 0.2).abs() < 1e-9);
4263    }
4264
4265    #[test]
4266    fn once_playback_still_stops_at_either_end() {
4267        let mut playback = PlaybackState::default();
4268        playback.play();
4269        playback.tick(2.0, 1.0);
4270        assert_eq!(playback.playhead, 1.0);
4271        assert!(!playback.playing);
4272
4273        let mut backward = PlaybackState {
4274            playhead: 0.5,
4275            playback_rate: -1.0,
4276            ..PlaybackState::default()
4277        };
4278        backward.play();
4279        backward.tick(1.0, 1.0);
4280        assert_eq!(backward.playhead, 0.0);
4281        assert!(!backward.playing);
4282    }
4283
4284    #[test]
4285    fn playback_spans_cover_what_the_playhead_passed() {
4286        let span = PlaybackSpan {
4287            from: 0.2,
4288            to: 0.6,
4289            includes_start: false,
4290        };
4291        assert!(!span.contains(0.2));
4292        assert!(span.contains(0.4));
4293        assert!(span.contains(0.6));
4294        assert!(!span.contains(0.7));
4295
4296        let backward = PlaybackSpan {
4297            from: 0.6,
4298            to: 0.2,
4299            includes_start: true,
4300        };
4301        assert!(backward.contains(0.6));
4302        assert!(backward.contains(0.2));
4303        assert!(!backward.contains(0.1));
4304    }
4305
4306    fn marker_names(player: &AnimationPlayer) -> Vec<&str> {
4307        player
4308            .passed_markers()
4309            .iter()
4310            .map(|marker| marker.name.as_str())
4311            .collect()
4312    }
4313
4314    #[test]
4315    fn players_report_each_marker_once_per_pass() {
4316        let timeline = Timeline::<AnimationValue>::new(1.0)
4317            .with_marker("start", 0.0)
4318            .with_marker("middle", 0.5)
4319            .with_marker("end", 1.0);
4320        let mut player = timeline.compile().player().repeat();
4321        let mut samples = SampleBuffer::new();
4322        player.play();
4323
4324        player.tick_into(0.25, &mut samples);
4325        assert_eq!(marker_names(&player), ["start"]);
4326        player.tick_into(0.25, &mut samples);
4327        assert_eq!(marker_names(&player), ["middle"]);
4328        player.tick_into(0.25, &mut samples);
4329        assert!(player.passed_markers().is_empty());
4330        // Wrapping passes the end and then the start again.
4331        player.tick_into(0.5, &mut samples);
4332        assert_eq!(marker_names(&player), ["end", "start"]);
4333
4334        let mut ping_pong = timeline.compile().player().ping_pong();
4335        ping_pong.play();
4336        ping_pong.tick_into(1.75, &mut samples);
4337        assert_eq!(
4338            marker_names(&ping_pong),
4339            ["start", "middle", "end", "middle"]
4340        );
4341        ping_pong.tick_into(0.25, &mut samples);
4342        assert_eq!(marker_names(&ping_pong), ["start"]);
4343        ping_pong.tick_into(0.25, &mut samples);
4344        assert!(ping_pong.passed_markers().is_empty());
4345    }
4346
4347    #[test]
4348    fn animation_documents_keep_markers_and_read_version_one() {
4349        let document =
4350            AnimationDocument::new("Markers", Timeline::new(2.0).with_marker("cue\tone", 0.5));
4351        let serialized = document.to_document_format();
4352        assert!(serialized.starts_with("sui-animation-document\t2\n"));
4353        let parsed = AnimationDocument::from_document_format(&serialized).expect("markers parse");
4354        assert_eq!(
4355            parsed.timeline.markers,
4356            vec![TimelineMarker::new("cue\tone", 0.5)]
4357        );
4358
4359        let version_one = AnimationDocument::from_document_format(
4360            "sui-animation-document\t1\nname\tOld\nduration\t1\n",
4361        )
4362        .expect("version 1 documents still parse");
4363        assert!(version_one.timeline.markers.is_empty());
4364    }
4365
4366    #[test]
4367    fn editor_commands_add_move_rename_and_remove_markers_with_undo() {
4368        let mut editor =
4369            AnimationEditorState::new(AnimationDocument::new("Markers", Timeline::new(1.0)));
4370        assert!(editor.apply_command(AnimationEditorCommand::AddMarker {
4371            name: "cue".to_string(),
4372            time: 0.49,
4373        }));
4374        let snapped = editor.document.timeline.markers[0].time;
4375        assert!(
4376            (snapped - 0.5).abs() < 1e-9,
4377            "snapped to the grid: {snapped}"
4378        );
4379
4380        assert!(editor.apply_command(AnimationEditorCommand::MoveMarker {
4381            index: 0,
4382            time: 4.0,
4383        }));
4384        assert_eq!(editor.document.timeline.markers[0].time, 1.0);
4385        assert!(editor.apply_command(AnimationEditorCommand::RenameMarker {
4386            index: 0,
4387            name: "done".to_string(),
4388        }));
4389        assert!(!editor.apply_command(AnimationEditorCommand::RemoveMarker(3)));
4390        assert!(editor.apply_command(AnimationEditorCommand::RemoveMarker(0)));
4391        assert!(editor.document.timeline.markers.is_empty());
4392
4393        assert!(editor.undo());
4394        assert_eq!(editor.document.timeline.markers[0].name, "done");
4395    }
4396}