animato-timeline 0.2.0

Timeline, sequence, and stagger composition for the Animato animation library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Timeline composition primitives.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use animato_core::{Playable, Update};
use animato_tween::Loop;
use core::fmt;

/// Positioning rule for a timeline entry.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum At<'a> {
    /// Start at an explicit absolute time in seconds.
    Absolute(f32),
    /// Start at timeline time `0.0`.
    Start,
    /// Start when the current last entry ends.
    End,
    /// Start at the same time as an existing labeled entry.
    Label(&'a str),
    /// Start relative to the current timeline end.
    Offset(f32),
}

/// Current playback state of a [`Timeline`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TimelineState {
    /// Ready but not advancing.
    Idle,
    /// Actively advancing.
    Playing,
    /// Paused mid-playback.
    Paused,
    /// Finished all finite playback.
    Completed,
}

struct TimelineEntry {
    label: String,
    animation: Box<dyn Playable + Send>,
    start_at: f32,
    duration: f32,
    completed: bool,
}

impl fmt::Debug for TimelineEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TimelineEntry")
            .field("label", &self.label)
            .field("start_at", &self.start_at)
            .field("duration", &self.duration)
            .field("completed", &self.completed)
            .finish()
    }
}

impl TimelineEntry {
    fn end_at(&self) -> f32 {
        self.start_at + self.duration
    }
}

/// Composes multiple animations on one shared clock.
///
/// Entries are stored by label, absolute start time, and cached duration.
/// Normal one-shot playback advances children incrementally. Seeking and
/// timeline-level loops resynchronize children through [`Playable::seek_to`].
pub struct Timeline {
    entries: Vec<TimelineEntry>,
    elapsed: f32,
    state: TimelineState,
    /// Timeline-level looping behavior.
    pub looping: Loop,
}

impl fmt::Debug for Timeline {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Timeline")
            .field("entries", &self.entries)
            .field("elapsed", &self.elapsed)
            .field("state", &self.state)
            .field("looping", &self.looping)
            .finish()
    }
}

impl Default for Timeline {
    fn default() -> Self {
        Self::new()
    }
}

impl Timeline {
    /// Create an empty timeline.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            elapsed: 0.0,
            state: TimelineState::Idle,
            looping: Loop::Once,
        }
    }

    /// Add an animation at the requested position.
    ///
    /// Missing [`At::Label`] references fall back to [`At::End`] behavior.
    pub fn add<A>(mut self, label: impl Into<String>, animation: A, at: At<'_>) -> Self
    where
        A: Playable + Send + 'static,
    {
        let start_at = self.resolve_start(at);
        let duration = animation.duration().max(0.0);
        self.entries.push(TimelineEntry {
            label: label.into(),
            animation: Box::new(animation),
            start_at,
            duration,
            completed: false,
        });
        self
    }

    pub(crate) fn add_boxed_with_duration(
        mut self,
        label: impl Into<String>,
        animation: Box<dyn Playable + Send>,
        at: At<'_>,
        duration: f32,
    ) -> Self {
        let start_at = self.resolve_start(at);
        self.entries.push(TimelineEntry {
            label: label.into(),
            animation,
            start_at,
            duration: duration.max(0.0),
            completed: false,
        });
        self
    }

    /// Set timeline-level looping behavior.
    pub fn looping(mut self, mode: Loop) -> Self {
        self.looping = mode;
        self
    }

    /// Begin playback.
    pub fn play(&mut self) {
        if self.state == TimelineState::Completed {
            self.reset();
        }
        if self.duration() == 0.0 {
            self.state = TimelineState::Completed;
        } else {
            self.state = TimelineState::Playing;
            self.sync_to_elapsed();
        }
    }

    /// Pause playback.
    pub fn pause(&mut self) {
        if self.state == TimelineState::Playing {
            self.state = TimelineState::Paused;
        }
    }

    /// Resume playback after a pause.
    pub fn resume(&mut self) {
        if self.state == TimelineState::Paused {
            self.state = TimelineState::Playing;
        }
    }

    /// Reset the timeline and all children to the beginning.
    pub fn reset(&mut self) {
        self.elapsed = 0.0;
        self.state = TimelineState::Idle;
        for entry in self.entries.iter_mut() {
            entry.animation.reset();
            entry.completed = false;
        }
    }

    /// Seek by normalized progress through the timeline.
    pub fn seek(&mut self, progress: f32) {
        let total = self.playback_duration();
        let seek_duration = if total.is_finite() {
            total
        } else {
            self.duration()
        };
        self.seek_abs(seek_duration * progress.clamp(0.0, 1.0));
    }

    /// Seek to an absolute time in seconds.
    pub fn seek_abs(&mut self, secs: f32) {
        let total = self.playback_duration();
        let secs = secs.max(0.0);
        self.elapsed = if total.is_finite() {
            secs.min(total)
        } else {
            secs
        };
        self.sync_to_elapsed();
        if total.is_finite() && self.elapsed >= total {
            self.state = TimelineState::Completed;
        } else if self.state == TimelineState::Completed {
            self.state = TimelineState::Playing;
        }
    }

    /// Base duration in seconds, equal to the last finishing entry.
    pub fn duration(&self) -> f32 {
        self.entries
            .iter()
            .map(TimelineEntry::end_at)
            .fold(0.0, f32::max)
    }

    /// Current normalized progress through finite playback.
    pub fn progress(&self) -> f32 {
        let total = self.playback_duration();
        if total == 0.0 {
            return 1.0;
        }
        if total.is_finite() {
            (self.elapsed / total).clamp(0.0, 1.0)
        } else {
            let base = self.duration();
            if base == 0.0 {
                1.0
            } else {
                (self.local_time_for_elapsed(self.elapsed) / base).clamp(0.0, 1.0)
            }
        }
    }

    /// `true` when the timeline has finished all finite playback.
    pub fn is_complete(&self) -> bool {
        self.state == TimelineState::Completed
    }

    /// Current timeline state.
    pub fn state(&self) -> TimelineState {
        self.state
    }

    /// Current total elapsed timeline time in seconds.
    pub fn elapsed(&self) -> f32 {
        self.elapsed
    }

    /// Number of entries in the timeline.
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Find a child animation by label and concrete type.
    pub fn get<T>(&self, label: &str) -> Option<&T>
    where
        T: Playable + 'static,
    {
        self.entries
            .iter()
            .find(|entry| entry.label == label)
            .and_then(|entry| entry.animation.as_any().downcast_ref::<T>())
    }

    /// Find a mutable child animation by label and concrete type.
    pub fn get_mut<T>(&mut self, label: &str) -> Option<&mut T>
    where
        T: Playable + 'static,
    {
        self.entries
            .iter_mut()
            .find(|entry| entry.label == label)
            .and_then(|entry| entry.animation.as_any_mut().downcast_mut::<T>())
    }

    fn resolve_start(&self, at: At<'_>) -> f32 {
        match at {
            At::Absolute(secs) => secs.max(0.0),
            At::Start => 0.0,
            At::End => self.duration(),
            At::Label(label) => self
                .entries
                .iter()
                .find(|entry| entry.label == label)
                .map_or_else(|| self.duration(), |entry| entry.start_at),
            At::Offset(offset) => (self.duration() + offset).max(0.0),
        }
    }

    fn playback_duration(&self) -> f32 {
        let base = self.duration();
        if base == 0.0 {
            return 0.0;
        }
        match self.looping {
            Loop::Once => base,
            Loop::Times(n) => base * n.max(1) as f32,
            Loop::Forever | Loop::PingPong => f32::INFINITY,
        }
    }

    fn local_time_for_elapsed(&self, elapsed: f32) -> f32 {
        let base = self.duration();
        if base == 0.0 {
            return 0.0;
        }

        match self.looping {
            Loop::Once => elapsed.min(base),
            Loop::Times(n) => {
                let total = base * n.max(1) as f32;
                if elapsed >= total {
                    base
                } else {
                    elapsed % base
                }
            }
            Loop::Forever => elapsed % base,
            Loop::PingPong => {
                let cycle = elapsed % (base * 2.0);
                if cycle <= base {
                    cycle
                } else {
                    base * 2.0 - cycle
                }
            }
        }
    }

    fn tick_forward(&mut self, prev: f32, next: f32) {
        for entry in self.entries.iter_mut() {
            let start = entry.start_at;
            let end = entry.end_at();

            if next < start {
                entry.animation.reset();
                entry.completed = false;
                continue;
            }

            if prev <= start && next >= start {
                entry.animation.reset();
                entry.completed = false;
            }

            if entry.duration == 0.0 {
                if next >= start {
                    entry.animation.seek_to(1.0);
                    entry.completed = true;
                }
                continue;
            }

            let overlap_start = prev.max(start);
            let overlap_end = next.min(end);
            if overlap_end > overlap_start {
                let still_running = entry.animation.update(overlap_end - overlap_start);
                if !still_running {
                    entry.completed = true;
                }
            }

            if next >= end {
                entry.animation.seek_to(1.0);
                entry.completed = true;
            }
        }
    }

    fn sync_to_elapsed(&mut self) {
        let local_time = self.local_time_for_elapsed(self.elapsed);
        for entry in self.entries.iter_mut() {
            let start = entry.start_at;
            let end = entry.end_at();

            if local_time <= start {
                entry.animation.reset();
                entry.completed = false;
            } else if local_time >= end || entry.duration == 0.0 {
                entry.animation.seek_to(1.0);
                entry.completed = true;
            } else {
                let progress = (local_time - start) / entry.duration;
                entry.animation.seek_to(progress);
                entry.completed = false;
            }
        }
    }
}

impl Update for Timeline {
    fn update(&mut self, dt: f32) -> bool {
        match self.state {
            TimelineState::Completed => return false,
            TimelineState::Paused | TimelineState::Idle => return true,
            TimelineState::Playing => {}
        }

        let base = self.duration();
        if base == 0.0 {
            self.state = TimelineState::Completed;
            return false;
        }

        let dt = dt.max(0.0);
        let previous_elapsed = self.elapsed;
        let next_elapsed = previous_elapsed + dt;

        match self.looping {
            Loop::Once => {
                let prev_local = previous_elapsed.min(base);
                let next_local = next_elapsed.min(base);
                self.tick_forward(prev_local, next_local);
                self.elapsed = next_elapsed.min(base);
                if next_elapsed >= base {
                    self.state = TimelineState::Completed;
                    return false;
                }
            }
            Loop::Times(n) => {
                let total = base * n.max(1) as f32;
                self.elapsed = next_elapsed.min(total);
                self.sync_to_elapsed();
                if next_elapsed >= total {
                    self.state = TimelineState::Completed;
                    return false;
                }
            }
            Loop::Forever | Loop::PingPong => {
                self.elapsed = next_elapsed;
                self.sync_to_elapsed();
            }
        }

        true
    }
}

impl Playable for Timeline {
    fn duration(&self) -> f32 {
        self.playback_duration()
    }

    fn reset(&mut self) {
        Timeline::reset(self);
    }

    fn seek_to(&mut self, progress: f32) {
        Timeline::seek(self, progress);
    }

    fn is_complete(&self) -> bool {
        Timeline::is_complete(self)
    }

    fn as_any(&self) -> &dyn core::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use animato_core::Easing;
    use animato_tween::Tween;

    fn tween(end: f32, duration: f32) -> Tween<f32> {
        Tween::new(0.0_f32, end)
            .duration(duration)
            .easing(Easing::Linear)
            .build()
    }

    #[test]
    fn concurrent_entries_advance_together() {
        let mut timeline = Timeline::new().add("a", tween(1.0, 1.0), At::Start).add(
            "b",
            tween(100.0, 1.0),
            At::Label("a"),
        );

        timeline.play();
        timeline.update(0.5);

        assert_eq!(timeline.get::<Tween<f32>>("a").unwrap().value(), 0.5);
        assert_eq!(timeline.get::<Tween<f32>>("b").unwrap().value(), 50.0);
    }

    #[test]
    fn end_and_offset_position_entries() {
        let timeline = Timeline::new()
            .add("first", tween(1.0, 1.0), At::Start)
            .add("second", tween(1.0, 0.5), At::End)
            .add("third", tween(1.0, 0.25), At::Offset(0.25));

        assert_eq!(timeline.duration(), 2.0);
    }

    #[test]
    fn seek_abs_synchronizes_children() {
        let mut timeline = Timeline::new().add("a", tween(100.0, 2.0), At::Start);

        timeline.seek_abs(0.5);

        assert_eq!(timeline.get::<Tween<f32>>("a").unwrap().value(), 25.0);
    }

    #[test]
    fn pause_stops_timeline_progress() {
        let mut timeline = Timeline::new().add("a", tween(100.0, 1.0), At::Start);
        timeline.play();
        timeline.update(0.25);
        timeline.pause();
        timeline.update(0.5);

        assert_eq!(timeline.elapsed(), 0.25);
        assert_eq!(timeline.get::<Tween<f32>>("a").unwrap().value(), 25.0);
    }

    #[test]
    fn resume_continues_after_pause() {
        let mut timeline = Timeline::new().add("a", tween(100.0, 1.0), At::Start);
        timeline.play();
        timeline.update(0.25);
        timeline.pause();
        timeline.resume();
        timeline.update(0.25);

        assert_eq!(timeline.get::<Tween<f32>>("a").unwrap().value(), 50.0);
    }

    #[test]
    fn once_timeline_completes() {
        let mut timeline = Timeline::new().add("a", tween(1.0, 1.0), At::Start);
        timeline.play();

        assert!(!timeline.update(1.0));
        assert!(timeline.is_complete());
    }

    #[test]
    fn times_loop_repeats_then_completes() {
        let mut timeline = Timeline::new()
            .add("a", tween(100.0, 1.0), At::Start)
            .looping(Loop::Times(2));
        timeline.play();

        timeline.update(1.25);
        assert_eq!(timeline.get::<Tween<f32>>("a").unwrap().value(), 25.0);

        assert!(!timeline.update(1.0));
        assert!(timeline.is_complete());
        assert_eq!(timeline.get::<Tween<f32>>("a").unwrap().value(), 100.0);
    }

    #[test]
    fn ping_pong_reflects_timeline_time() {
        let mut timeline = Timeline::new()
            .add("a", tween(100.0, 1.0), At::Start)
            .looping(Loop::PingPong);
        timeline.play();
        timeline.update(1.25);

        assert_eq!(timeline.get::<Tween<f32>>("a").unwrap().value(), 75.0);
        assert!(!timeline.is_complete());
    }
}