Skip to main content

ssruntime/eval/
playback_controller.rs

1use crate::eval::math::*;
2use alloc::vec::Vec;
3
4#[derive(Debug, PartialEq, Eq, Copy, Clone)]
5pub enum PlaybackStyle {
6    Normal = 0,
7    PingPong = 1,
8}
9
10#[derive(Debug, PartialEq, Eq, Copy, Clone)]
11pub enum PlaybackDirection {
12    Forward = 1,
13    Backward = -1,
14}
15
16/// Pure, deterministic mapping from "frames elapsed since playback started"
17/// (`diff`, with per-instance `speed` already applied) to the resolved
18/// playback frame within the inclusive `[start, end]` range, applying loop
19/// count and playback style / direction. Matches SpriteStudio 6 SDK's
20/// `SsAnimeDecoder::updateInstance` semantics, including the inclusive
21/// `inst_scale = (end - start) + 1` cycle length and the duplicated peak /
22/// trough frames at PingPong reversal boundaries.
23///
24/// Returns `(frame, finished)` where `finished` is `true` once the
25/// configured `loops` have completed. For `loops == -1` (infinite) and
26/// `loops == 0` (treated as infinite to match `PlaybackController::update`)
27/// `finished` is always `false`. `diff < 0` is clamped to `0`.
28///
29/// `loops > 0` defines total cycles. A "cycle" is `(end - start) + 1`
30/// frames for `Normal` and `2 * ((end - start) + 1)` frames for `PingPong`
31/// (one full there-and-back, with the turn-around frame appearing in both
32/// halves to match SS6).
33pub fn resolve_frame(diff: f32, start: i32, end: i32, loops: i32, style: PlaybackStyle, direction: PlaybackDirection) -> (f32, bool) {
34    let length = (end - start + 1) as f32;
35    if length <= 0.0 {
36        let f = match direction {
37            PlaybackDirection::Forward => start as f32,
38            PlaybackDirection::Backward => end as f32,
39        };
40        return (f, true);
41    }
42
43    let cycle_len = match style {
44        PlaybackStyle::Normal => length,
45        PlaybackStyle::PingPong => length * 2.0,
46    };
47
48    let total_len = if loops > 0 { Some((loops as f32) * cycle_len) } else { None };
49
50    let elapsed = diff.max(0.0);
51
52    let finished = match total_len {
53        Some(total) => elapsed >= total,
54        None => false,
55    };
56
57    if finished {
58        let final_frame = match (style, direction) {
59            (PlaybackStyle::Normal, PlaybackDirection::Forward) => end as f32,
60            (PlaybackStyle::Normal, PlaybackDirection::Backward) => start as f32,
61            (PlaybackStyle::PingPong, PlaybackDirection::Forward) => start as f32,
62            (PlaybackStyle::PingPong, PlaybackDirection::Backward) => end as f32,
63        };
64        return (final_frame, true);
65    }
66
67    let phase = elapsed - floorf(elapsed / cycle_len) * cycle_len;
68    let local_offset = match style {
69        PlaybackStyle::Normal => phase,
70        PlaybackStyle::PingPong => {
71            // Phase [0, length) is the forward half (start → end), and
72            // [length, 2*length) is the reverse half (end → start). The
73            // turn-around frame (end) appears at both `phase = length - 1`
74            // and `phase = length`, matching SS6's nowloop transition where
75            // reftime=length plays end again at the start of the reverse
76            // loop.
77            if phase < length { phase } else { cycle_len - 1.0 - phase }
78        }
79    };
80
81    let frame = match direction {
82        PlaybackDirection::Forward => start as f32 + local_offset,
83        PlaybackDirection::Backward => end as f32 - local_offset,
84    };
85
86    let frame = if frame < start as f32 { start as f32 } else { frame };
87
88    (frame, false)
89}
90
91/// The settings that describe how a host plays an animation rather than the
92/// animation itself, so they outlive a change of animation: the speed, the
93/// frame-rate override, the frame skip, and the direction and style. A track
94/// keeps one and hands it to every source laid on it.
95///
96/// The section and the loop count are not here: a section is frame numbers of
97/// one animation, and a loop count is restated with each animation.
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub(crate) struct PlaybackPolicy {
100    pub(crate) speed_scale: f32,
101    pub(crate) frame_rate_override: Option<i32>,
102    pub(crate) is_skip_frames: bool,
103    pub(crate) playback_direction: PlaybackDirection,
104    pub(crate) playback_style: PlaybackStyle,
105}
106
107impl PlaybackPolicy {
108    /// What a controller starts with before a host sets anything.
109    pub(crate) const DEFAULT: Self = Self { speed_scale: 1.0, frame_rate_override: None, is_skip_frames: true, playback_direction: PlaybackDirection::Forward, playback_style: PlaybackStyle::Normal };
110
111    /// Stores a speed the way [`PlaybackController::set_speed_scale`] does.
112    pub(crate) fn set_speed_scale(&mut self, speed_scale: f32) {
113        self.speed_scale = normalise_speed_scale(speed_scale);
114    }
115
116    /// Stores a rate the way [`PlaybackController::set_frame_rate`] does.
117    pub(crate) fn set_frame_rate(&mut self, frame_rate: i32) {
118        self.frame_rate_override = normalise_frame_rate(frame_rate);
119    }
120}
121
122/// A negative speed clamps to `0.0`, which stops the playhead.
123fn normalise_speed_scale(speed_scale: f32) -> f32 {
124    if speed_scale > 0.0 { speed_scale } else { 0.0 }
125}
126
127/// `0` or a negative rate is no override at all.
128fn normalise_frame_rate(frame_rate: i32) -> Option<i32> {
129    if frame_rate > 0 { Some(frame_rate) } else { None }
130}
131
132pub struct PlaybackController {
133    is_pausing: bool,
134    is_playing: bool,
135
136    anime_data_start_frame: i32,
137    anime_data_end_frame: i32,
138    anime_data_fps: i32,
139
140    start_frame: i32,
141    end_frame: i32,
142    /// The rate the host asked for, when it asked for one at all. Kept apart
143    /// from `anime_data_fps` so `setup` can re-read the clip's own rate without
144    /// having to guess whether the current value was a host's choice or just
145    /// what the previous clip happened to be authored at.
146    frame_rate_override: Option<i32>,
147    speed_scale: f32,
148    loops: i32,
149
150    update_interval: f32,
151    playback_style: PlaybackStyle,
152    playback_direction: PlaybackDirection,
153    is_skip_frames: bool,
154
155    playback_forward: i32,
156    current_frame: f32,
157    next_frame_time: f32,
158    remain_loops: i32,
159    end_frame_reached: bool,
160    just_looped: bool,
161
162    passed_frames: Vec<i32>,
163    needs_evaluation: bool,
164}
165
166impl PlaybackController {
167    pub fn get_frame_no(&self) -> f32 {
168        self.current_frame
169    }
170
171    /// `true` while the last frame of a cycle is being shown. With a finite
172    /// loop count this is raised once per cycle, not only on the last one, and
173    /// with an infinite loop count it is never raised.
174    ///
175    /// Internal playback state, absent from the C-API and the WASM bindings. A
176    /// `finished` notification reads [`is_finished`].
177    ///
178    /// [`is_finished`]: Self::is_finished
179    pub fn is_end_frame_reached(&self) -> bool {
180        self.end_frame_reached
181    }
182
183    /// `true` once the configured loops have completed, and sticky until the
184    /// next `play` / `setup`. Never becomes `true` under an infinite loop
185    /// count, nor after a bare `stop()` part-way through playback.
186    ///
187    /// `remain_loops` only reaches `0` on the branch that ends playback, so
188    /// this cannot be confused with `stop()` being called while the last frame
189    /// of a non-final cycle happens to be showing.
190    pub fn is_finished(&self) -> bool {
191        self.remain_loops == 0 && !self.is_playing
192    }
193
194    /// `true` for the single `update` that took the playhead back to the start
195    /// of its cycle. Cleared on entry to every `update`, so it must be polled
196    /// after each one or the pulse is lost. Never raised on the final cycle of
197    /// a finite loop count — that cycle finishes instead of looping.
198    pub fn just_looped(&self) -> bool {
199        self.just_looped
200    }
201
202    pub fn is_playing(&self) -> bool {
203        self.is_playing
204    }
205
206    pub fn is_pausing(&self) -> bool {
207        self.is_pausing
208    }
209
210    pub fn get_skip_frames(&self) -> bool {
211        self.is_skip_frames
212    }
213
214    pub fn is_playing_forward(&self) -> bool {
215        self.playback_forward == 1
216    }
217
218    pub fn get_playback_direction(&self) -> PlaybackDirection {
219        self.playback_direction
220    }
221
222    pub fn get_playback_style(&self) -> PlaybackStyle {
223        self.playback_style
224    }
225
226    pub fn get_loop_count(&self) -> i32 {
227        self.loops
228    }
229
230    pub fn get_remaining_loops(&self) -> i32 {
231        self.remain_loops
232    }
233
234    pub fn get_start_frame(&self) -> i32 {
235        self.start_frame
236    }
237
238    pub fn get_end_frame(&self) -> i32 {
239        self.end_frame
240    }
241
242    /// The bound animation's own range, which `set_animation_section` never
243    /// touches. `get_start_frame` / `get_end_frame` report the section, so a
244    /// caller that computes a section from them feeds its own last narrowing
245    /// back in.
246    pub fn get_anime_data_start_frame(&self) -> i32 {
247        self.anime_data_start_frame
248    }
249
250    pub fn get_anime_data_end_frame(&self) -> i32 {
251        self.anime_data_end_frame
252    }
253
254    pub fn get_frame_rate(&self) -> i32 {
255        self.effective_frame_rate()
256    }
257
258    /// The playback speed in effect, as a multiple of [`Self::get_frame_rate`].
259    ///
260    /// This is what [`Self::set_speed_scale`] *stored*, not what it was
261    /// handed: a negative rate clamps to `0.0` on the way in, so a host that
262    /// reads this back sees the stop it actually got.
263    pub fn get_speed_scale(&self) -> f32 {
264        self.speed_scale
265    }
266
267    pub fn get_passed_frames(&self) -> &[i32] {
268        &self.passed_frames
269    }
270}
271
272impl Default for PlaybackController {
273    fn default() -> Self {
274        Self::new()
275    }
276}
277
278impl PlaybackController {
279    pub fn new() -> Self {
280        Self {
281            is_pausing: false,
282            is_playing: false,
283
284            anime_data_start_frame: 0,
285            anime_data_end_frame: 0,
286            anime_data_fps: 0,
287
288            start_frame: 0,
289            end_frame: 0,
290            frame_rate_override: None,
291            speed_scale: 1.0,
292
293            update_interval: 0.0,
294            playback_style: PlaybackStyle::Normal,
295            playback_direction: PlaybackDirection::Forward,
296            is_skip_frames: true,
297
298            playback_forward: 1,
299            current_frame: 0.0,
300            next_frame_time: 0.0,
301            loops: -1,
302            remain_loops: -1,
303            end_frame_reached: false,
304            just_looped: false,
305
306            passed_frames: Vec::new(),
307            needs_evaluation: false,
308        }
309    }
310
311    pub fn reset_setup(&mut self) {
312        self.reset_state();
313
314        self.is_pausing = false;
315        self.is_playing = false;
316        self.anime_data_start_frame = 0;
317        self.anime_data_end_frame = 0;
318        self.anime_data_fps = 0;
319
320        self.start_frame = 0;
321        self.end_frame = 0;
322        self.frame_rate_override = None;
323        self.speed_scale = 1.0;
324        self.is_skip_frames = true;
325        self.playback_direction = PlaybackDirection::Forward;
326        self.playback_style = PlaybackStyle::Normal;
327        self.playback_forward = 1;
328
329        self.update_interval = 0.0;
330        self.passed_frames.clear();
331    }
332
333    fn reset_state(&mut self) {
334        self.next_frame_time = 0.0;
335        self.current_frame = 0.0;
336        self.end_frame_reached = false;
337        self.just_looped = false;
338        self.passed_frames.clear();
339        self.needs_evaluation = false;
340    }
341
342    /// Binds a new animation to this source.
343    ///
344    /// What resets and what survives is deliberate, and the line is **who sets
345    /// it**. A Player's state machine calls this on every transition, so
346    /// anything the transition itself specifies is reset — otherwise state N's
347    /// behaviour would depend on state N-1, and a `loops = 1` meant for an
348    /// attack would quietly follow the character into its walk. That covers the
349    /// section (frame indices mean nothing against a different clip) and the
350    /// loop count.
351    ///
352    /// The speed, the frame-rate override, the frame skip and the direction /
353    /// style survive, because a *different* system sets them: a slow-motion
354    /// effect, a haste buff, a "show every frame" capture mode. Resetting those
355    /// here would let an animation transition clobber a setting the state
356    /// machine never knew about. The Players' sub-frame flag is the same kind of
357    /// setting, on their side of the FFI.
358    ///
359    /// [`Self::reset_setup`] does reset them: it releases the slot for a
360    /// different owner, rather than handing the same one a new clip.
361    pub fn setup(&mut self, start_frame: i32, end_frame: i32, fps: i32) {
362        self.reset_state();
363
364        self.is_pausing = false;
365        self.is_playing = false;
366
367        self.anime_data_start_frame = start_frame;
368        self.anime_data_end_frame = end_frame;
369        self.anime_data_fps = fps;
370        self.start_frame = self.anime_data_start_frame;
371        self.end_frame = self.anime_data_end_frame;
372
373        self.current_frame = start_frame as f32;
374        // Resets `remain_loops` too: a stale count from a previous animation
375        // would otherwise raise `end_frame_reached` at the end of this one's
376        // first cycle.
377        self.set_loop_count(-1);
378
379        // The direction and style are the host's, like the speed and the frame
380        // skip: "play this backwards" describes the playback, not the clip that
381        // happens to be loaded. Only the *heading* is re-derived -- ping-pong
382        // may have flipped it mid-cycle, and a new animation starts on the
383        // outward leg of whatever direction is in force.
384        self.playback_forward = if self.playback_direction == PlaybackDirection::Forward { 1 } else { -1 };
385        // Carries the retained rate and any retained override onto the new
386        // animation; `anime_data_fps` alone would ignore the override.
387        self.recompute_update_interval();
388        self.passed_frames.clear();
389        self.needs_evaluation = false;
390    }
391
392    pub fn set_skip_frames(&mut self, skip: bool) {
393        self.is_skip_frames = skip;
394    }
395
396    /// Recomputes the per-frame interval from the effective frame rate and the
397    /// speed multiplier.
398    ///
399    /// A rate of zero — a speed of `0.0`, or no animation set up yet — leaves no
400    /// interval to advance by, and is stored as `0.0`: the sentinel `update`
401    /// already reads as "do not advance". Dividing by it instead would put an
402    /// infinity in the field and rely on the arithmetic to work out.
403    fn recompute_update_interval(&mut self) {
404        let rate = self.effective_frame_rate() as f32 * self.speed_scale;
405        self.update_interval = if rate > 0.0 { 1000.0 / rate } else { 0.0 };
406    }
407
408    /// Puts the host's playback policy on a controller that is about to be set
409    /// up, so neither a rebuilt slot nor a freshly laid source reads as a reset
410    /// of settings the host owns.
411    ///
412    /// Call it before `setup`, which derives the heading from the direction and
413    /// the frame interval from the rate; until then there is no animation to
414    /// advance.
415    pub(crate) fn adopt_policy(&mut self, policy: &PlaybackPolicy) {
416        self.speed_scale = policy.speed_scale;
417        self.frame_rate_override = policy.frame_rate_override;
418        self.is_skip_frames = policy.is_skip_frames;
419        self.playback_direction = policy.playback_direction;
420        self.playback_style = policy.playback_style;
421    }
422
423    /**
424     * Set the number of loops.
425     * n > 0: play n cycles, then stop
426     * -1: infinite loop
427     * 0: infinite loop (accepted as a synonym for -1)
428     *
429     * `0` and every negative value normalize to `-1` so that `update` and
430     * `resolve_frame` agree on the infinite sentinel.
431     */
432    pub fn set_loop_count(&mut self, loops: i32) {
433        self.loops = if loops > 0 { loops } else { -1 };
434        self.remain_loops = self.loops;
435    }
436
437    /// Overrides the rate the clip was authored at. `0` or any negative value
438    /// clears the override, handing playback back to the authored rate.
439    ///
440    /// This is an *absolute* rate — "this player runs at n fps" — where
441    /// [`Self::set_speed_scale`] is a multiple of whatever the clip was
442    /// authored at. Both are the host's, so both survive `setup`.
443    pub fn set_frame_rate(&mut self, frame_rate: i32) {
444        self.frame_rate_override = normalise_frame_rate(frame_rate);
445        self.recompute_update_interval();
446    }
447
448    /// The rate playback actually runs at: the host's override when it set one,
449    /// otherwise the rate the current clip was authored at.
450    fn effective_frame_rate(&self) -> i32 {
451        match self.frame_rate_override {
452            Some(fps) => fps,
453            None => self.anime_data_fps,
454        }
455    }
456
457    /**
458     * Set playback direction and playback style.
459     * Execute the function before calling play().
460     */
461    pub fn set_playback_direction(&mut self, direction: PlaybackDirection, style: PlaybackStyle) {
462        self.playback_direction = direction;
463        self.playback_style = style;
464
465        self.playback_forward = if self.playback_direction == PlaybackDirection::Forward { 1 } else { -1 };
466    }
467
468    /// Sets the playback speed as a multiple of the effective frame rate.
469    ///
470    /// `0.0` **stops the playhead** where it stands, rather than meaning "no
471    /// setting": time passes, `is_playing` stays true, and nothing advances.
472    /// That matches what a host means by a zero time scale, and what engine
473    /// animation players do with one.
474    ///
475    /// A negative rate is **not** reverse playback — direction is
476    /// [`Self::set_playback_direction`]'s business — and is clamped to a stop.
477    pub fn set_speed_scale(&mut self, speed_scale: f32) {
478        self.speed_scale = normalise_speed_scale(speed_scale);
479        self.recompute_update_interval();
480    }
481
482    /// Narrows playback to `[start_frame, end_frame]`, both ends included, so
483    /// a section whose ends are one frame plays that frame. An end outside the
484    /// animation's own range (`-1`, say) is the animation's edge on that side.
485    ///
486    /// Returns false, changing nothing, when both ends are in range and the end
487    /// is before the start: no section runs backwards.
488    pub fn set_animation_section(&mut self, start_frame: i32, end_frame: i32) -> bool {
489        let in_range = |frame: i32| frame >= self.anime_data_start_frame.max(0) && frame <= self.anime_data_end_frame;
490        if in_range(start_frame) && in_range(end_frame) && end_frame < start_frame {
491            return false;
492        }
493        self.start_frame = if in_range(start_frame) { start_frame } else { self.anime_data_start_frame };
494        self.end_frame = if in_range(end_frame) { end_frame } else { self.anime_data_end_frame };
495
496        self.current_frame = if self.playback_direction == PlaybackDirection::Forward { self.start_frame as f32 } else { self.end_frame as f32 };
497        self.needs_evaluation = true;
498        true
499    }
500
501    pub fn update(&mut self, delta: f32) -> f32 {
502        self.passed_frames.clear();
503        self.just_looped = false;
504
505        if self.needs_evaluation {
506            self.passed_frames.push(floorf(self.current_frame) as i32);
507            self.needs_evaluation = false;
508        }
509
510        let to_next_frame = self.is_playing && !self.is_pausing;
511        if to_next_frame && self.update_interval != 0.0 {
512            let s = if self.is_skip_frames {
513                // Timed Animation: Advance by the exact elapsed time (can skip frames)
514                (delta / self.update_interval) * self.playback_forward as f32
515            } else {
516                // Fixed Animation: Accumulate time and advance by exactly one frame at a time
517                self.next_frame_time += delta;
518                if self.next_frame_time >= self.update_interval {
519                    self.next_frame_time -= self.update_interval;
520                    self.playback_forward as f32
521                } else {
522                    0.0
523                }
524            };
525
526            if s != 0.0 {
527                self.end_frame_reached = false;
528
529                let playback_style = if self.start_frame == self.end_frame { PlaybackStyle::Normal } else { self.playback_style };
530
531                let next: f32 = self.current_frame + s;
532                let next_frame_no = floorf(next) as i32;
533                let mut next_frame_decimal = next - next_frame_no as f32;
534                let mut current_frame_no = floorf(self.current_frame) as i32;
535
536                let v = (next_frame_no - current_frame_no).abs();
537                for _ in 0..v {
538                    let mut frame_no = current_frame_no + self.playback_forward;
539
540                    let (start_limit, end_limit) = if self.playback_forward > 0 { (self.start_frame, self.end_frame) } else { (self.end_frame, self.start_frame) };
541
542                    if frame_no == end_limit && self.remain_loops != -1 {
543                        match &playback_style {
544                            PlaybackStyle::Normal => {
545                                self.end_frame_reached = true;
546                            }
547                            PlaybackStyle::PingPong => {
548                                let is_back_to_origin = match &self.playback_direction {
549                                    PlaybackDirection::Forward => self.playback_forward == -1,
550                                    PlaybackDirection::Backward => self.playback_forward == 1,
551                                };
552                                if is_back_to_origin {
553                                    self.end_frame_reached = true;
554                                }
555                            }
556                        }
557                    }
558
559                    let is_reached = if self.playback_forward > 0 { frame_no > end_limit } else { frame_no < end_limit };
560
561                    if is_reached {
562                        match &playback_style {
563                            PlaybackStyle::Normal => {
564                                if self.remain_loops == -1 {
565                                    // infinite loop
566                                    frame_no = start_limit;
567                                    self.just_looped = true;
568                                } else {
569                                    self.remain_loops -= 1;
570                                    if self.remain_loops == 0 {
571                                        self.is_playing = false;
572                                        self.end_frame_reached = true;
573                                        // Park on the end frame and stop. It is not pushed to
574                                        // `passed_frames`: reaching it is what let this branch be
575                                        // entered, so it was already reported -- either earlier in
576                                        // this same loop, or by the update that landed on it.
577                                        // Pushing again re-fires its events.
578                                        frame_no = end_limit;
579                                        current_frame_no = frame_no;
580                                        next_frame_decimal = 0.0;
581                                        break;
582                                    } else {
583                                        // continue to play the animation
584                                        frame_no = start_limit;
585                                        self.just_looped = true;
586                                    }
587                                }
588                            }
589                            PlaybackStyle::PingPong => {
590                                self.playback_forward *= -1;
591                                frame_no = current_frame_no + self.playback_forward;
592
593                                let is_back_to_origin = match &self.playback_direction {
594                                    PlaybackDirection::Forward => self.playback_forward == 1,
595                                    PlaybackDirection::Backward => self.playback_forward == -1,
596                                };
597                                if is_back_to_origin {
598                                    if self.remain_loops != -1 {
599                                        self.remain_loops -= 1;
600                                        if self.remain_loops == 0 {
601                                            self.is_playing = false;
602                                            self.end_frame_reached = true;
603                                            // Park on the turn-around frame and stop. Not pushed --
604                                            // the update that landed back on it already reported it
605                                            // (see the Normal arm above).
606                                            frame_no = if self.playback_direction == PlaybackDirection::Forward { self.start_frame } else { self.end_frame };
607                                            current_frame_no = frame_no;
608                                            next_frame_decimal = 0.0;
609                                            break;
610                                        } else {
611                                            self.just_looped = true;
612                                        }
613                                    } else {
614                                        // infinite loop
615                                        self.just_looped = true;
616                                    }
617                                } else {
618                                    next_frame_decimal = 1.0 - next_frame_decimal;
619                                    if next_frame_decimal >= 1.0 {
620                                        next_frame_decimal = 0.0;
621                                    }
622                                }
623                            }
624                        }
625                    }
626                    current_frame_no = frame_no;
627                    self.passed_frames.push(current_frame_no);
628                }
629                if self.is_playing {
630                    // A backward wrap keeps a decimal computed near frame 0, which
631                    // can round up to the next whole frame at this magnitude.
632                    let whole = current_frame_no as f32;
633                    self.current_frame = (whole + next_frame_decimal).min((whole + 1.0).next_down());
634                } else {
635                    self.current_frame = current_frame_no as f32;
636                }
637            }
638        }
639        self.current_frame
640    }
641}
642
643impl PlaybackController {
644    // playback control
645    pub fn play(&mut self) {
646        self.play_with_start_frame(-1.0)
647    }
648
649    pub fn play_with_start_frame(&mut self, frame_no: f32) {
650        self.is_playing = true;
651        self.is_pausing = false;
652
653        // Re-arm the loop counter and drop the terminal flags. Replaying a
654        // finished animation would otherwise inherit `remain_loops == 0`,
655        // which decrements straight to the infinite sentinel on the first
656        // wrap, and expose a stale `end_frame_reached` until the first
657        // advancing update.
658        self.remain_loops = self.loops;
659        self.end_frame_reached = false;
660        self.just_looped = false;
661
662        let mut current_frame = match &self.playback_direction {
663            PlaybackDirection::Forward => self.start_frame as f32,
664            PlaybackDirection::Backward => self.end_frame as f32,
665        };
666        if frame_no >= 0.0 {
667            current_frame = frame_no;
668        }
669        self.current_frame = current_frame;
670        self.needs_evaluation = true;
671    }
672
673    /// Holds playback where it stands. Idempotent: pausing an already-paused
674    /// animation leaves it paused. `is_playing` stays `true` — a pause is a
675    /// hold, not a stop — so a caller telling the two apart reads
676    /// [`Self::is_pausing`]. Use [`Self::resume`] to lift the hold; `play`
677    /// rewinds and is not a resume.
678    ///
679    /// Ignored when nothing is playing, so "stopped, and also paused" cannot
680    /// happen and `is_pausing` can be read on its own.
681    pub fn pause(&mut self) {
682        if !self.is_playing {
683            return;
684        }
685        self.is_pausing = true;
686    }
687
688    /// Lifts the hold set by [`Self::pause`], carrying on from the frame it
689    /// stopped at. Idempotent, and a no-op on an animation that was never
690    /// paused. Does not start a stopped animation — that is `play`'s job.
691    pub fn resume(&mut self) {
692        self.is_pausing = false;
693    }
694
695    /// Ends playback. The playhead stays where it stands — nothing rewinds —
696    /// so the host keeps drawing the frame it stopped on. Seek, or `play`,
697    /// to move it.
698    pub fn stop(&mut self) {
699        self.is_playing = false;
700        // A stopped animation is not a held one; the getter reads this alone.
701        self.is_pausing = false;
702    }
703
704    pub fn set_frame_no(&mut self, frame: f32) {
705        self.current_frame = self.clamp_to_section(frame);
706        self.needs_evaluation = true;
707    }
708
709    fn clamp_to_section(&self, frame: f32) -> f32 {
710        let low = self.start_frame as f32;
711        let high = self.end_frame as f32;
712        if frame < low {
713            low
714        } else if frame >= high + 1.0 {
715            high
716        } else {
717            frame
718        }
719    }
720
721    /// Sets `current_frame` to the position reached after `diff` frames have
722    /// elapsed since playback started, with the configured `start_frame` /
723    /// `end_frame` / `loops` / `playback_style` / `playback_direction`
724    /// applied. `diff` should already incorporate per-instance `speed`
725    /// (i.e. `diff = (parent_frame - event_frame) * speed`).
726    ///
727    /// Unlike `update(delta)` this is a deterministic, non-incremental
728    /// computation — the same `diff` always produces the same frame, which is
729    /// what allows parent-driven seek / reverse / frame-skip on Instance parts
730    /// to render correctly.
731    pub fn set_frame_relative(&mut self, diff: f32) {
732        let (frame, _finished) = resolve_frame(diff, self.start_frame, self.end_frame, self.loops, self.playback_style, self.playback_direction);
733        self.current_frame = frame;
734        self.needs_evaluation = true;
735    }
736
737    /**
738     * Set the current frame to the next frame.
739     * The function ignores direction and style.
740     */
741    pub fn next_frame(&mut self) {
742        let current_frame = floorf(self.current_frame) as i32;
743        if current_frame == self.end_frame {
744            return;
745        }
746        self.set_frame_no((current_frame + 1) as f32);
747    }
748
749    /**
750     * Set the current frame to the previous frame.
751     * The function ignores direction and style.
752     */
753    pub fn prev_frame(&mut self) {
754        let current_frame = floorf(self.current_frame) as i32;
755        if current_frame == self.start_frame {
756            return;
757        }
758        self.set_frame_no((current_frame - 1) as f32);
759    }
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    fn rf(diff: f32, start: i32, end: i32, loops: i32, style: PlaybackStyle, dir: PlaybackDirection) -> (f32, bool) {
767        resolve_frame(diff, start, end, loops, style, dir)
768    }
769
770    /// An end before the animation's own start is out of range, as one after its
771    /// end is, for an animation that does not start at frame 0.
772    #[test]
773    fn a_section_end_before_the_animation_start_is_the_animation_edge() {
774        let section = |start: i32, end: i32| {
775            let mut c = PlaybackController::new();
776            c.setup(20, 40, 60);
777            assert!(c.set_animation_section(start, end), "({start}, {end}) is not refused");
778            (c.get_start_frame(), c.get_end_frame(), c.get_frame_no())
779        };
780        assert_eq!(section(0, -1), (20, 40, 20.0));
781        assert_eq!(section(5, 25), (20, 25, 20.0));
782        assert_eq!(section(10, 30), (20, 30, 20.0));
783        assert_eq!(section(-1, 10), (20, 40, 20.0));
784        assert_eq!(section(21, 25), (21, 25, 21.0));
785
786        let mut c = PlaybackController::new();
787        c.setup(20, 40, 60);
788        assert!(!c.set_animation_section(30, 25), "both in range and backwards");
789
790        let mut c = PlaybackController::new();
791        c.setup(-10, 20, 60);
792        assert!(c.set_animation_section(-1, 5));
793        assert_eq!((c.get_start_frame(), c.get_end_frame()), (-10, 5), "a negative end stays the animation's edge");
794    }
795
796    /// A backward wrap keeps the decimal of a step that ended just under a whole
797    /// frame. Added to the section's last frame it must not round up past it.
798    #[test]
799    fn a_backward_wrap_stays_inside_the_section() {
800        let mut c = PlaybackController::new();
801        c.setup(0, 60, 30);
802        c.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::Normal);
803        c.set_speed_scale(0.5);
804        c.play();
805        for _ in 0..4 {
806            let frame = c.update(1000.0);
807            assert!((0.0..61.0).contains(&frame), "frame {frame} is outside [0, 61)");
808        }
809    }
810
811    #[test]
812    fn resolve_frame_normal_forward_finite() {
813        // start=0 end=10 inclusive → 11 frames per cycle (matches SS6 inst_scale)
814        let (start, end) = (0, 10);
815        let s = PlaybackStyle::Normal;
816        let d = PlaybackDirection::Forward;
817
818        assert_eq!(rf(-5.0, start, end, 1, s, d), (0.0, false));
819        assert_eq!(rf(0.0, start, end, 1, s, d), (0.0, false));
820        assert_eq!(rf(5.0, start, end, 1, s, d), (5.0, false));
821        assert_eq!(rf(10.0, start, end, 1, s, d), (10.0, false));
822        assert_eq!(rf(11.0, start, end, 1, s, d), (10.0, true));
823        assert_eq!(rf(50.0, start, end, 1, s, d), (10.0, true));
824
825        // 2 cycles = 22 frames
826        assert_eq!(rf(11.0, start, end, 2, s, d), (0.0, false));
827        assert_eq!(rf(15.0, start, end, 2, s, d), (4.0, false));
828        assert_eq!(rf(21.0, start, end, 2, s, d), (10.0, false));
829        assert_eq!(rf(22.0, start, end, 2, s, d), (10.0, true));
830        assert_eq!(rf(100.0, start, end, 2, s, d), (10.0, true));
831    }
832
833    #[test]
834    fn resolve_frame_normal_forward_infinite() {
835        let (start, end) = (0, 10);
836        let s = PlaybackStyle::Normal;
837        let d = PlaybackDirection::Forward;
838
839        assert_eq!(rf(0.0, start, end, -1, s, d), (0.0, false));
840        assert_eq!(rf(10.0, start, end, -1, s, d), (10.0, false));
841        assert_eq!(rf(11.0, start, end, -1, s, d), (0.0, false));
842        assert_eq!(rf(15.0, start, end, -1, s, d), (4.0, false));
843        assert_eq!(rf(22.0, start, end, -1, s, d), (0.0, false));
844        assert!(!rf(0.0, start, end, 0, s, d).1);
845        assert!(!rf(100.0, start, end, 0, s, d).1);
846    }
847
848    #[test]
849    fn resolve_frame_normal_backward() {
850        let (start, end) = (0, 10);
851        let s = PlaybackStyle::Normal;
852        let d = PlaybackDirection::Backward;
853
854        assert_eq!(rf(0.0, start, end, 1, s, d), (10.0, false));
855        assert_eq!(rf(3.0, start, end, 1, s, d), (7.0, false));
856        assert_eq!(rf(10.0, start, end, 1, s, d), (0.0, false));
857        assert_eq!(rf(11.0, start, end, 1, s, d), (0.0, true));
858        assert_eq!(rf(50.0, start, end, 1, s, d), (0.0, true));
859        // Infinite: cycle wraps; phase=15 → phase mod 11 = 4 → frame = end - 4 = 6.
860        assert_eq!(rf(15.0, start, end, -1, s, d), (6.0, false));
861    }
862
863    #[test]
864    fn resolve_frame_pingpong_forward() {
865        // start=0 end=10. cycle = 22 (forward 0..10 then reverse 10..0,
866        // peak 10 appears at phase 10 and phase 11 to match SS6).
867        let (start, end) = (0, 10);
868        let s = PlaybackStyle::PingPong;
869        let d = PlaybackDirection::Forward;
870
871        assert_eq!(rf(0.0, start, end, 1, s, d), (0.0, false));
872        assert_eq!(rf(5.0, start, end, 1, s, d), (5.0, false));
873        assert_eq!(rf(10.0, start, end, 1, s, d), (10.0, false));
874        assert_eq!(rf(11.0, start, end, 1, s, d), (10.0, false)); // peak duplicated
875        assert_eq!(rf(12.0, start, end, 1, s, d), (9.0, false));
876        assert_eq!(rf(21.0, start, end, 1, s, d), (0.0, false));
877        assert_eq!(rf(22.0, start, end, 1, s, d), (0.0, true));
878
879        // 2 cycles = 44
880        assert_eq!(rf(22.0, start, end, 2, s, d), (0.0, false));
881        assert_eq!(rf(33.0, start, end, 2, s, d), (10.0, false));
882        assert_eq!(rf(44.0, start, end, 2, s, d), (0.0, true));
883
884        // Infinite
885        assert_eq!(rf(22.0, start, end, -1, s, d), (0.0, false));
886        assert_eq!(rf(33.0, start, end, -1, s, d), (10.0, false));
887    }
888
889    #[test]
890    fn resolve_frame_pingpong_backward() {
891        let (start, end) = (0, 10);
892        let s = PlaybackStyle::PingPong;
893        let d = PlaybackDirection::Backward;
894
895        assert_eq!(rf(0.0, start, end, 1, s, d), (10.0, false));
896        assert_eq!(rf(5.0, start, end, 1, s, d), (5.0, false));
897        assert_eq!(rf(10.0, start, end, 1, s, d), (0.0, false));
898        assert_eq!(rf(11.0, start, end, 1, s, d), (0.0, false)); // trough duplicated
899        assert_eq!(rf(21.0, start, end, 1, s, d), (10.0, false));
900        assert_eq!(rf(22.0, start, end, 1, s, d), (10.0, true));
901    }
902
903    #[test]
904    fn resolve_frame_never_leaves_the_section_on_fractional_diffs() {
905        for &(start, end) in &[(0, 4), (5, 9), (5, 5)] {
906            for &style in &[PlaybackStyle::Normal, PlaybackStyle::PingPong] {
907                for &dir in &[PlaybackDirection::Forward, PlaybackDirection::Backward] {
908                    for i in 0..400 {
909                        let diff = i as f32 * 0.25;
910                        let (frame, _) = rf(diff, start, end, 3, style, dir);
911                        let reported = floorf(frame) as i32;
912                        assert!((start..=end).contains(&reported), "diff={diff} start={start} end={end} style={} dir={} resolved {frame} -> reports frame {reported}", style as i32, dir as i32);
913                    }
914                }
915            }
916        }
917    }
918
919    #[test]
920    fn resolve_frame_backward_holds_the_start_frame_through_its_slot() {
921        let (start, end) = (5, 9);
922        let s = PlaybackStyle::Normal;
923        let d = PlaybackDirection::Backward;
924
925        assert_eq!(rf(4.0, start, end, 3, s, d), (5.0, false));
926        assert_eq!(rf(4.5, start, end, 3, s, d), (5.0, false));
927        assert_eq!(rf(5.0, start, end, 3, s, d), (9.0, false));
928    }
929
930    #[test]
931    fn resolve_frame_pingpong_holds_the_trough_through_its_slot() {
932        let (start, end) = (5, 9);
933        let s = PlaybackStyle::PingPong;
934        let d = PlaybackDirection::Forward;
935
936        assert_eq!(rf(9.0, start, end, 3, s, d), (5.0, false));
937        assert_eq!(rf(9.5, start, end, 3, s, d), (5.0, false));
938        assert_eq!(rf(10.0, start, end, 3, s, d), (5.0, false));
939    }
940
941    #[test]
942    fn resolve_frame_zero_length_section_clamps() {
943        // end == start → single-frame section, length=1, valid.
944        let s = PlaybackStyle::Normal;
945        let d = PlaybackDirection::Forward;
946        assert_eq!(rf(0.0, 5, 5, 1, s, d), (5.0, false));
947        assert_eq!(rf(1.0, 5, 5, 1, s, d), (5.0, true));
948        assert_eq!(rf(100.0, 5, 5, -1, s, d), (5.0, false));
949    }
950
951    #[test]
952    fn set_frame_relative_applies_section_and_style() {
953        let mut t = PlaybackController::new();
954        t.setup(0, 100, 30);
955        // section [10, 20] inclusive → 11-frame cycle
956        t.set_animation_section(10, 20);
957        t.set_loop_count(-1);
958        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::Normal);
959
960        t.set_frame_relative(0.0);
961        assert_eq!(t.get_frame_no(), 10.0);
962        t.set_frame_relative(5.0);
963        assert_eq!(t.get_frame_no(), 15.0);
964        t.set_frame_relative(10.0);
965        assert_eq!(t.get_frame_no(), 20.0);
966        t.set_frame_relative(11.0);
967        assert_eq!(t.get_frame_no(), 10.0);
968        t.set_frame_relative(15.0);
969        assert_eq!(t.get_frame_no(), 14.0);
970    }
971
972    /// Drives `t` one frame at a time and records the loop / finish events a
973    /// Player would observe by polling after every `update`.
974    fn collect_events(t: &mut PlaybackController, steps: usize) -> Vec<(usize, &'static str)> {
975        let interval = 1000.0 / 30.0;
976        let mut events = Vec::new();
977        let mut was_finished = false;
978        for i in 0..steps {
979            t.update(interval);
980            if t.just_looped() {
981                events.push((i, "looped"));
982            }
983            if t.is_finished() && !was_finished {
984                events.push((i, "finished"));
985            }
986            was_finished = t.is_finished();
987        }
988        events
989    }
990
991    #[test]
992    fn set_loop_count_3_emits_looped_looped_finished() {
993        let mut t = PlaybackController::new();
994        t.setup(0, 4, 30);
995        t.set_loop_count(3);
996        t.set_skip_frames(false);
997        t.play();
998
999        let kinds: Vec<_> = collect_events(&mut t, 30).into_iter().map(|(_, k)| k).collect();
1000        assert_eq!(kinds, ["looped", "looped", "finished"]);
1001        assert_eq!(t.get_frame_no(), 4.0, "Should rest on the end frame");
1002        assert!(!t.is_playing());
1003    }
1004
1005    #[test]
1006    fn set_frame_no_keeps_sub_frame_progress_inside_the_last_frame() {
1007        let mut t = PlaybackController::new();
1008        t.setup(0, 10, 60);
1009
1010        t.set_frame_no(10.25);
1011        assert_eq!(t.get_frame_no(), 10.25, "frame 10 spans [10, 11); 10.25 is inside the section");
1012
1013        t.set_frame_no(11.0);
1014        assert_eq!(t.get_frame_no(), 10.0, "frame 11 is past the section");
1015
1016        t.set_frame_no(15.0);
1017        assert_eq!(t.get_frame_no(), 10.0);
1018
1019        t.set_frame_no(-1.0);
1020        assert_eq!(t.get_frame_no(), 0.0);
1021    }
1022
1023    #[test]
1024    fn writing_the_reported_frame_back_does_not_freeze_sub_frame_playback() {
1025        // The host loop Unity runs for an independent Instance child: advance the
1026        // controller, then hand the reported frame straight back through
1027        // `set_frame_no`. Clamping that write-back to `end_frame` truncates the
1028        // last frame's sub-frame progress every tick, so the head can never reach
1029        // the wrap and the child freezes on the section end.
1030        let mut t = PlaybackController::new();
1031        t.setup(0, 10, 60);
1032        t.set_loop_count(-1);
1033        t.play();
1034
1035        let quarter_frame = 1000.0 / 60.0 / 4.0;
1036        let mut looped = 0;
1037        for _ in 0..(11 * 4 * 2) {
1038            t.update(quarter_frame);
1039            let reported = t.get_frame_no();
1040            t.set_frame_no(reported);
1041            if t.just_looped() {
1042                looped += 1;
1043            }
1044        }
1045        assert_eq!(looped, 2, "infinite loop froze at frame {}", t.get_frame_no());
1046    }
1047
1048    #[test]
1049    fn infinite_loop_emits_looped_only_and_never_finishes() {
1050        let mut t = PlaybackController::new();
1051        t.setup(0, 4, 30);
1052        t.set_loop_count(-1);
1053        t.set_skip_frames(false);
1054        t.play();
1055
1056        // 30 steps over an inclusive 5-frame cycle wraps 6 times.
1057        let kinds: Vec<_> = collect_events(&mut t, 30).into_iter().map(|(_, k)| k).collect();
1058        assert_eq!(kinds, ["looped"; 6]);
1059        assert!(!t.is_finished());
1060        assert!(t.is_playing());
1061    }
1062
1063    #[test]
1064    fn set_loop_count_0_is_infinite() {
1065        let mut t = PlaybackController::new();
1066        t.setup(0, 4, 30);
1067        t.set_loop_count(0);
1068        assert_eq!(t.get_loop_count(), -1, "0 normalizes to the infinite sentinel");
1069        assert_eq!(t.get_remaining_loops(), -1);
1070        t.set_skip_frames(false);
1071        t.play();
1072
1073        let kinds: Vec<_> = collect_events(&mut t, 30).into_iter().map(|(_, k)| k).collect();
1074        assert_eq!(kinds, ["looped"; 6], "0 must behave exactly like -1");
1075        assert!(!t.is_end_frame_reached(), "Infinite loop must never raise end_frame_reached");
1076        assert!(!t.is_finished());
1077    }
1078
1079    #[test]
1080    fn is_finished_distinguishes_stop_from_completion() {
1081        // stop() part-way through must not read as finished...
1082        let mut t = PlaybackController::new();
1083        t.setup(0, 4, 30);
1084        t.set_loop_count(3);
1085        t.set_skip_frames(false);
1086        t.play();
1087        t.update(1000.0 / 30.0);
1088        t.stop();
1089        assert!(!t.is_playing());
1090        assert!(!t.is_finished(), "stop() mid-playback is not 'finished'");
1091
1092        // ...not even when the playhead is resting on the last frame of a
1093        // non-final cycle, where end_frame_reached is legitimately set.
1094        let mut t = PlaybackController::new();
1095        t.setup(0, 4, 30);
1096        t.set_loop_count(3);
1097        t.set_skip_frames(false);
1098        t.play();
1099        for _ in 0..4 {
1100            t.update(1000.0 / 30.0);
1101        }
1102        assert!(t.is_end_frame_reached(), "Should be showing the end frame of cycle 1");
1103        t.stop();
1104        assert!(!t.is_finished(), "end_frame_reached + stopped is not 'finished'");
1105    }
1106
1107    #[test]
1108    fn setup_rearms_loop_count_for_the_next_animation() {
1109        let mut t = PlaybackController::new();
1110        t.setup(0, 4, 30);
1111        t.set_loop_count(1);
1112        t.set_skip_frames(false);
1113        t.play();
1114        for _ in 0..6 {
1115            t.update(1000.0 / 30.0);
1116        }
1117        assert!(t.is_finished());
1118        assert_eq!(t.get_remaining_loops(), 0);
1119
1120        // A stale remain_loops == 0 would raise end_frame_reached at the end of
1121        // the next animation's first cycle even though it loops forever.
1122        t.setup(0, 4, 30);
1123        assert_eq!(t.get_loop_count(), -1);
1124        assert_eq!(t.get_remaining_loops(), -1, "remain_loops must not leak across setup()");
1125        t.set_skip_frames(false);
1126        t.play();
1127        let kinds: Vec<_> = collect_events(&mut t, 12).into_iter().map(|(_, k)| k).collect();
1128        assert_eq!(kinds, ["looped", "looped"]);
1129        assert!(!t.is_end_frame_reached());
1130    }
1131
1132    #[test]
1133    fn replaying_a_finished_animation_rearms_the_loop_count() {
1134        let mut t = PlaybackController::new();
1135        t.setup(0, 4, 30);
1136        t.set_loop_count(2);
1137        t.set_skip_frames(false);
1138        t.play();
1139        let kinds: Vec<_> = collect_events(&mut t, 30).into_iter().map(|(_, k)| k).collect();
1140        assert_eq!(kinds, ["looped", "finished"]);
1141
1142        // Without re-arming, remain_loops == 0 would decrement to the infinite
1143        // sentinel on the first wrap and the replay would never finish.
1144        t.play();
1145        assert!(!t.is_finished(), "play() must drop the stale terminal state");
1146        assert!(!t.is_end_frame_reached());
1147        let kinds: Vec<_> = collect_events(&mut t, 30).into_iter().map(|(_, k)| k).collect();
1148        assert_eq!(kinds, ["looped", "finished"], "Replay must honour the same loop count");
1149    }
1150
1151    /// Every frame `t` reports as passed, across `steps` updates.
1152    fn collect_passed(t: &mut PlaybackController, steps: usize) -> Vec<i32> {
1153        let interval = 1000.0 / 30.0;
1154        let mut all = Vec::new();
1155        for _ in 0..steps {
1156            t.update(interval);
1157            all.extend_from_slice(t.get_passed_frames());
1158        }
1159        all
1160    }
1161
1162    #[test]
1163    fn end_frame_is_reported_once_when_playback_stops() {
1164        // The update that stops playback parks on the end frame, which the
1165        // previous update already reported. Reporting it again re-fires any
1166        // user-data / signal / audio key authored on the last frame.
1167        let mut t = PlaybackController::new();
1168        t.setup(0, 4, 30);
1169        t.set_loop_count(1);
1170        t.set_skip_frames(false);
1171        t.play();
1172        assert_eq!(collect_passed(&mut t, 8), [0, 1, 2, 3, 4]);
1173    }
1174
1175    #[test]
1176    fn end_frame_is_reported_once_when_a_single_update_overruns_the_end() {
1177        // Frame-skipping with a delta big enough to walk the whole clip in one
1178        // update: the stop branch is then entered by the same inner loop that
1179        // just reported the end frame.
1180        let mut t = PlaybackController::new();
1181        t.setup(0, 4, 30);
1182        t.set_loop_count(1);
1183        t.set_skip_frames(true);
1184        t.play();
1185        t.update((1000.0 / 30.0) * 10.0);
1186        assert_eq!(t.get_passed_frames(), [0, 1, 2, 3, 4]);
1187        assert!(!t.is_playing());
1188    }
1189
1190    #[test]
1191    fn single_frame_clip_reports_its_only_frame_once() {
1192        let mut t = PlaybackController::new();
1193        t.setup(5, 5, 30);
1194        t.set_loop_count(1);
1195        t.set_skip_frames(false);
1196        t.play();
1197        assert_eq!(collect_passed(&mut t, 6), [5]);
1198    }
1199
1200    #[test]
1201    fn single_frame_pingpong_clip_stays_inside_the_section() {
1202        let mut t = PlaybackController::new();
1203        t.setup(5, 5, 30);
1204        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::PingPong);
1205        t.set_loop_count(3);
1206        t.set_skip_frames(false);
1207        t.play();
1208        assert_eq!(collect_passed(&mut t, 8), [5, 5, 5]);
1209    }
1210
1211    #[test]
1212    fn single_frame_pingpong_clip_stays_inside_the_section_when_backward() {
1213        let mut t = PlaybackController::new();
1214        t.setup(5, 5, 30);
1215        t.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::PingPong);
1216        t.set_loop_count(3);
1217        t.set_skip_frames(false);
1218        t.play();
1219        assert_eq!(collect_passed(&mut t, 8), [5, 5, 5]);
1220    }
1221
1222    #[test]
1223    fn narrowing_the_section_to_one_frame_reports_it() {
1224        let mut t = PlaybackController::new();
1225        t.setup(0, 9, 30);
1226        t.set_loop_count(1);
1227        t.set_skip_frames(false);
1228        t.play();
1229        collect_passed(&mut t, 1);
1230        t.set_animation_section(3, 3);
1231        assert_eq!(collect_passed(&mut t, 5), [3]);
1232    }
1233
1234    #[test]
1235    fn a_section_can_start_on_the_last_frame() {
1236        let mut t = PlaybackController::new();
1237        t.setup(0, 9, 30);
1238        t.set_animation_section(9, 9);
1239        assert_eq!((t.get_start_frame(), t.get_end_frame()), (9, 9));
1240        t.set_animation_section(9, -1);
1241        assert_eq!((t.get_start_frame(), t.get_end_frame()), (9, 9));
1242        t.set_loop_count(1);
1243        t.set_skip_frames(false);
1244        t.play();
1245        assert_eq!(collect_passed(&mut t, 5), [9]);
1246    }
1247
1248    #[test]
1249    fn a_section_ending_before_it_starts_is_refused() {
1250        let mut t = PlaybackController::new();
1251        t.setup(0, 9, 30);
1252        assert!(t.set_animation_section(2, 5));
1253        t.set_loop_count(1);
1254        t.set_skip_frames(false);
1255        t.play();
1256        collect_passed(&mut t, 2);
1257        let playhead = t.get_frame_no();
1258        assert!(!t.set_animation_section(5, 2));
1259        assert_eq!((t.get_start_frame(), t.get_end_frame()), (2, 5));
1260        assert_eq!(t.get_frame_no(), playhead);
1261        // An end out of range is the animation's edge, whatever its number.
1262        assert!(t.set_animation_section(5, -1));
1263        assert_eq!((t.get_start_frame(), t.get_end_frame()), (5, 9));
1264        assert!(t.set_animation_section(20, 3));
1265        assert_eq!((t.get_start_frame(), t.get_end_frame()), (0, 3));
1266    }
1267
1268    #[test]
1269    fn a_section_end_past_the_animation_is_its_last_frame() {
1270        let mut t = PlaybackController::new();
1271        t.setup(0, 9, 30);
1272        t.set_animation_section(10, 10);
1273        assert_eq!((t.get_start_frame(), t.get_end_frame()), (0, 9));
1274        t.set_animation_section(4, 10);
1275        assert_eq!((t.get_start_frame(), t.get_end_frame()), (4, 9));
1276    }
1277
1278    #[test]
1279    fn a_new_section_reports_its_own_start_frame() {
1280        let mut t = PlaybackController::new();
1281        t.setup(0, 9, 30);
1282        t.set_loop_count(1);
1283        t.set_skip_frames(false);
1284        t.play();
1285        collect_passed(&mut t, 1);
1286        t.set_animation_section(2, 5);
1287        assert_eq!(collect_passed(&mut t, 8), [2, 3, 4, 5]);
1288    }
1289
1290    #[test]
1291    fn seeking_outside_the_section_is_confined_to_it() {
1292        let mut t = PlaybackController::new();
1293        t.setup(0, 9, 30);
1294        t.set_animation_section(2, 5);
1295        t.set_loop_count(1);
1296        t.set_skip_frames(false);
1297        t.play();
1298
1299        t.set_frame_no(9.0);
1300        assert_eq!(t.get_frame_no(), 5.0);
1301        assert_eq!(collect_passed(&mut t, 3), [5]);
1302
1303        t.set_frame_no(-4.0);
1304        assert_eq!(t.get_frame_no(), 2.0);
1305    }
1306
1307    #[test]
1308    fn pingpong_reports_the_turnaround_frame_once_when_playback_stops() {
1309        let mut t = PlaybackController::new();
1310        t.setup(0, 3, 30);
1311        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::PingPong);
1312        t.set_loop_count(1);
1313        t.set_skip_frames(false);
1314        t.play();
1315        // Out 0..3, back 3..0. The trailing 0 -- where playback stops -- must be
1316        // reported once. (The peak is not doubled here: the duplicated
1317        // turn-around frame is a `resolve_frame` property, not an `update` one.)
1318        assert_eq!(collect_passed(&mut t, 10), [0, 1, 2, 3, 2, 1, 0]);
1319    }
1320
1321    #[test]
1322    fn looping_still_reports_every_frame_of_every_cycle() {
1323        let mut t = PlaybackController::new();
1324        t.setup(0, 2, 30);
1325        t.set_loop_count(2);
1326        t.set_skip_frames(false);
1327        t.play();
1328        assert_eq!(collect_passed(&mut t, 8), [0, 1, 2, 0, 1, 2]);
1329    }
1330
1331    #[test]
1332    fn test_normal_playback_no_loop() {
1333        let mut t = PlaybackController::new();
1334        t.setup(0, 10, 30);
1335        t.set_loop_count(1);
1336        t.set_skip_frames(false);
1337        t.play();
1338
1339        let interval = 1000.0 / 30.0;
1340
1341        // Frames 0 to 9
1342        for i in 1..=10 {
1343            let frame = t.update(interval);
1344            assert_eq!(frame, i as f32, "Failed at step {} (Forward)", i);
1345            assert!(t.is_playing());
1346        }
1347
1348        assert!(t.is_end_frame_reached(), "end_frame_reached should be true at frame 10");
1349
1350        // Next update should stop playback
1351        let frame = t.update(interval);
1352        assert_eq!(frame, 10.0, "Should remain at end frame when stopped");
1353        assert!(!t.is_playing(), "Should stop playing after 1 loop");
1354    }
1355
1356    #[test]
1357    fn test_normal_playback_loops() {
1358        let mut t = PlaybackController::new();
1359        t.setup(0, 10, 30);
1360        t.set_loop_count(2);
1361        t.set_skip_frames(false);
1362        t.play();
1363
1364        let interval = 1000.0 / 30.0;
1365
1366        // First loop: 0 -> 10
1367        for _ in 1..=10 {
1368            t.update(interval);
1369        }
1370        assert!(t.is_end_frame_reached(), "end_frame_reached should be true after first loop");
1371        assert_eq!(t.get_frame_no(), 10.0);
1372        assert_eq!(t.get_remaining_loops(), 2);
1373
1374        // Transition to second loop (shows frame 0)
1375        let frame = t.update(interval);
1376        assert_eq!(frame, 0.0, "Should jump back to start frame");
1377        assert_eq!(t.get_remaining_loops(), 1);
1378        assert!(!t.is_end_frame_reached(), "end_frame_reached should reset at start of new loop");
1379
1380        // Second loop: 0 -> 10
1381        for _ in 1..=10 {
1382            t.update(interval);
1383        }
1384        assert!(t.is_end_frame_reached());
1385
1386        // Final update stops
1387        t.update(interval);
1388        assert!(!t.is_playing(), "Should stop playing after 2 loops");
1389        assert_eq!(t.get_remaining_loops(), 0);
1390    }
1391
1392    #[test]
1393    fn test_pingpong_playback() {
1394        let mut t = PlaybackController::new();
1395        t.setup(0, 10, 30);
1396        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::PingPong);
1397        t.set_loop_count(1);
1398        t.set_skip_frames(false);
1399        t.play();
1400
1401        let interval = 1000.0 / 30.0;
1402
1403        // Forward: 0 -> 10
1404        for i in 1..=10 {
1405            let frame = t.update(interval);
1406            assert_eq!(frame, i as f32, "Forward failed at step {}", i);
1407        }
1408
1409        // At 10, it should NOT have reached end yet in PingPong (need to return to 0)
1410        assert!(!t.is_end_frame_reached(), "end_frame_reached should not be true at far end in PingPong");
1411
1412        // Backward: 10 -> 0
1413        for i in (0..=9).rev() {
1414            let frame = t.update(interval);
1415            assert_eq!(frame, i as f32, "Backward failed at step {}", i);
1416        }
1417
1418        assert!(t.is_end_frame_reached(), "end_frame_reached should be true after full PingPong cycle");
1419
1420        // Final update stops
1421        t.update(interval);
1422        assert!(!t.is_playing(), "Should stop playing after 1 PingPong loop");
1423    }
1424
1425    #[test]
1426    fn test_smooth_interpolation() {
1427        let mut t = PlaybackController::new();
1428        t.setup(0, 10, 30);
1429        t.set_skip_frames(true);
1430        t.play();
1431
1432        let delta = 1000.0 / 60.0; // Half a frame
1433
1434        let frame = t.update(delta);
1435        assert_eq!(floorf(frame), 0.0);
1436        let decimal = frame - floorf(frame);
1437        assert!(decimal > 0.4 && decimal < 0.6, "Expected around 0.5, got {}", decimal);
1438
1439        let frame = t.update(delta);
1440        assert_eq!(floorf(frame), 1.0);
1441        let decimal = frame - floorf(frame);
1442        assert!((0.0..0.1).contains(&decimal), "Expected around 0.0, got {}", decimal);
1443    }
1444
1445    #[test]
1446    fn test_infinite_loop() {
1447        let mut t = PlaybackController::new();
1448        t.setup(0, 10, 30);
1449        t.set_loop_count(-1);
1450        t.play();
1451
1452        let interval = 1000.0 / 30.0;
1453
1454        for _ in 0..100 {
1455            t.update(interval);
1456        }
1457
1458        assert!(t.is_playing(), "Infinite loop should never stop");
1459        assert_eq!(t.get_remaining_loops(), -1);
1460    }
1461
1462    #[test]
1463    fn test_fixed_animation_no_skip() {
1464        let mut t = PlaybackController::new();
1465        t.setup(0, 10, 30);
1466        t.set_skip_frames(false); // Fixed Animation mode
1467        t.play();
1468
1469        // 30 FPS, interval = 33.33ms
1470        // Supply a very large delta (e.g., 500ms = 15 frames worth of time)
1471        let delta = 500.0;
1472
1473        let frame = t.update(delta);
1474
1475        assert_eq!(frame, 1.0, "Fixed animation should only advance by 1 frame at a time");
1476
1477        // The remaining time (500 - 33.33) should be stored in next_frame_time.
1478        // Calling update with 0 delta should continue to advance frames until the buffer is empty.
1479        let frame = t.update(0.0);
1480        assert_eq!(frame, 2.0, "Should use buffered time to advance even with 0 delta");
1481    }
1482
1483    #[test]
1484    fn test_reverse_playback_no_loop() {
1485        let mut t = PlaybackController::new();
1486        t.setup(0, 10, 30);
1487        t.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::Normal);
1488        t.set_loop_count(1);
1489        t.set_skip_frames(false);
1490        t.play();
1491
1492        let interval = 1000.0 / 30.0;
1493
1494        // Starts at 10, goes down to 1
1495        for i in (0..=9).rev() {
1496            let frame = t.update(interval);
1497            assert_eq!(frame, i as f32, "Reverse failed at step {}", i);
1498        }
1499
1500        assert!(t.is_end_frame_reached(), "end_frame_reached should be true at frame 0 (start_frame for reverse)");
1501        t.update(interval);
1502        assert!(!t.is_playing(), "Should stop after 1 reverse loop");
1503    }
1504
1505    #[test]
1506    fn test_reverse_playback_loops() {
1507        let mut t = PlaybackController::new();
1508        t.setup(0, 10, 30);
1509        t.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::Normal);
1510        t.set_loop_count(2);
1511        t.set_skip_frames(false);
1512        t.play();
1513
1514        let interval = 1000.0 / 30.0;
1515
1516        // First loop: 10 -> 0
1517        for _ in 0..10 {
1518            t.update(interval);
1519        }
1520        assert!(t.is_end_frame_reached());
1521        assert_eq!(t.get_frame_no(), 0.0);
1522
1523        // Transition to second loop (jumps to 10)
1524        let frame = t.update(interval);
1525        assert_eq!(frame, 10.0);
1526        assert!(!t.is_end_frame_reached());
1527
1528        // Second loop: 10 -> 0
1529        for _ in 0..10 {
1530            t.update(interval);
1531        }
1532        assert!(t.is_end_frame_reached());
1533
1534        t.update(interval);
1535        assert!(!t.is_playing());
1536    }
1537
1538    #[test]
1539    fn test_reverse_pingpong_playback() {
1540        let mut t = PlaybackController::new();
1541        t.setup(0, 10, 30);
1542        t.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::PingPong);
1543        t.set_loop_count(1);
1544        t.set_skip_frames(false);
1545        t.play();
1546
1547        let interval = 1000.0 / 30.0;
1548
1549        // Backward first: 10 -> 0
1550        for i in (0..=9).rev() {
1551            let frame = t.update(interval);
1552            assert_eq!(frame, i as f32, "Initial backward failed at step {}", i);
1553        }
1554
1555        assert!(!t.is_end_frame_reached());
1556
1557        // Then Forward: 0 -> 10
1558        for i in 1..=10 {
1559            let frame = t.update(interval);
1560            assert_eq!(frame, i as f32, "Return forward failed at step {}", i);
1561        }
1562
1563        assert!(t.is_end_frame_reached());
1564        t.update(interval);
1565        assert!(!t.is_playing());
1566    }
1567
1568    #[test]
1569    fn test_skip_frames_multi_step() {
1570        let mut t = PlaybackController::new();
1571        t.setup(0, 10, 30);
1572        t.set_skip_frames(true);
1573        t.play();
1574
1575        // 30 FPS, interval = 33.33ms
1576        // Skip 2.5 frames at once (33.33 * 2.5 = 83.33ms)
1577        let delta = (1000.0 / 30.0) * 2.5;
1578
1579        let frame = t.update(delta);
1580        assert_eq!(floorf(frame), 2.0, "Should jump to frame 2");
1581        let decimal = frame - floorf(frame);
1582        assert!(decimal > 0.4 && decimal < 0.6, "Decimal should be around 0.5, got {}", decimal);
1583
1584        // Update another 1.0 frame
1585        let frame = t.update(1000.0 / 30.0);
1586        assert_eq!(floorf(frame), 3.0);
1587        let decimal = frame - floorf(frame);
1588        assert!(decimal > 0.4 && decimal < 0.6, "Decimal should stay around 0.5, got {}", decimal);
1589    }
1590
1591    #[test]
1592    fn test_skip_frames_loop_boundary() {
1593        let mut t = PlaybackController::new();
1594        t.setup(0, 10, 30);
1595        t.set_loop_count(2);
1596        t.set_skip_frames(true);
1597        t.play();
1598
1599        // Advance by 11.5 frames.
1600        // 0.0 -> 10.0 (end frame) -> 0.0 (start of next loop) -> 0.5 (decimal)
1601        let delta = (1000.0 / 30.0) * 11.5;
1602
1603        let frame = t.update(delta);
1604
1605        assert_eq!(floorf(frame), 0.0, "Should have looped back to start frame");
1606        let decimal = frame - floorf(frame);
1607        assert!(decimal > 0.4 && decimal < 0.6, "Should have 0.5 decimal after loop, got {}", decimal);
1608        assert_eq!(t.get_remaining_loops(), 1, "Should have 1 loop remaining");
1609    }
1610
1611    #[test]
1612    fn test_passed_frames_recording() {
1613        let mut t = PlaybackController::new();
1614        t.setup(0, 10, 30);
1615        t.set_skip_frames(true);
1616        t.play();
1617
1618        let interval = 1000.0 / 30.0;
1619
1620        // 1. Advance by 2.5 frames (0.0 -> 2.5)
1621        // Should pass frames 0, 1, and 2. (0 is the start frame, handled by needs_evaluation)
1622        t.update(interval * 2.5);
1623        assert_eq!(t.get_passed_frames(), &[0, 1, 2]);
1624
1625        // 2. Advance by another 1.0 frame (2.5 -> 3.5)
1626        // Should pass frame 3.
1627        t.update(interval);
1628        assert_eq!(t.get_passed_frames(), &[3]);
1629
1630        // 3. Large skip (3.5 -> 8.5)
1631        // Should pass 4, 5, 6, 7, 8.
1632        t.update(interval * 5.0);
1633        assert_eq!(t.get_passed_frames(), &[4, 5, 6, 7, 8]);
1634    }
1635
1636    #[test]
1637    fn test_passed_frames_looping() {
1638        let mut t = PlaybackController::new();
1639        t.setup(0, 5, 30); // 0 to 5
1640        t.set_loop_count(2);
1641        t.set_skip_frames(true);
1642        t.play();
1643
1644        let interval = 1000.0 / 30.0;
1645
1646        // Currently at 0.0. Skip to 2.5.
1647        // Should pass 0 (start), 1, 2
1648        t.update(interval * 2.5);
1649        assert_eq!(t.get_passed_frames(), &[0, 1, 2]);
1650
1651        // Skip across loop boundary: 2.5 -> 7.5
1652        // Frame sequence: 3, 4, 5 (hit end), 0 (loop), 1
1653        t.update(interval * 5.0);
1654        assert_eq!(t.get_passed_frames(), &[3, 4, 5, 0, 1]);
1655    }
1656
1657    #[test]
1658    fn test_passed_frames_start_frame() {
1659        let mut t = PlaybackController::new();
1660        t.setup(0, 10, 30);
1661        t.play();
1662
1663        let interval = 1000.0 / 30.0;
1664
1665        // Advance by 0.5 frames. We are still on frame 0, but since this is the very
1666        // first update after play(), frame 0 should be considered "passed/reached".
1667        t.update(interval * 0.5);
1668        assert_eq!(t.get_passed_frames(), &[0], "Start frame must be collected on first update");
1669
1670        // Advance by another 0.5 frames. We reach frame 1.
1671        t.update(interval * 0.5);
1672        assert_eq!(t.get_passed_frames(), &[1], "Should collect frame 1");
1673    }
1674
1675    #[test]
1676    fn test_skip_frames_pingpong_boundary() {
1677        let mut t = PlaybackController::new();
1678        t.setup(0, 10, 30);
1679        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::PingPong);
1680        t.set_skip_frames(true);
1681        t.play();
1682
1683        // Currently at 0.0.
1684        // Advance by 12.0 frames.
1685        // 0.0 -> 10.0 (hit end) -> (12.0 - 10.0 = 2.0 frames backwards) -> 8.0
1686        let delta = (1000.0 / 30.0) * 12.0;
1687
1688        let frame = t.update(delta);
1689        assert_eq!(floorf(frame), 8.0, "Should have bounced back to frame 8");
1690        let decimal = frame - floorf(frame);
1691        assert!((0.0..0.001).contains(&decimal), "Decimal should be exactly 0.0, got {}", decimal);
1692
1693        // Check passed_frames for pingpong boundary
1694        assert_eq!(t.get_passed_frames(), &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8]);
1695    }
1696
1697    #[test]
1698    fn test_passed_frames_high_speed() {
1699        let mut t = PlaybackController::new();
1700        t.setup(0, 20, 30);
1701        t.set_skip_frames(true);
1702        t.play();
1703
1704        let interval = 1000.0 / 30.0;
1705
1706        // Advance 15.5 frames at once (0.0 -> 15.5)
1707        t.update(interval * 15.5);
1708        let passed = t.get_passed_frames();
1709        // Expect 0 to 15
1710        let expected: Vec<i32> = (0..=15).collect();
1711        assert_eq!(passed, expected.as_slice());
1712    }
1713
1714    #[test]
1715    fn test_passed_frames_multiple_loops() {
1716        let mut t = PlaybackController::new();
1717        t.setup(0, 5, 30); // Total 6 frames (0,1,2,3,4,5)
1718        t.set_loop_count(-1); // Infinite
1719        t.set_skip_frames(true);
1720        t.play();
1721
1722        let interval = 1000.0 / 30.0;
1723
1724        // Current at 0.0. Advance 14.5 frames.
1725        // 0, 1, 2, 3, 4, 5 (end) -> 0, 1, 2, 3, 4, 5 (end) -> 0, 1, 2 (current 2.5)
1726        t.update(interval * 14.5);
1727        let passed = t.get_passed_frames();
1728        let expected = vec![0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2];
1729        assert_eq!(passed, expected.as_slice());
1730    }
1731
1732    #[test]
1733    fn test_passed_frames_backward_skip() {
1734        let mut t = PlaybackController::new();
1735        t.setup(0, 10, 30);
1736        t.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::Normal);
1737        t.set_skip_frames(true);
1738        t.play(); // Starts at 10.0
1739
1740        let interval = 1000.0 / 30.0;
1741
1742        // 10.0 -> 2.5 (Skip 7.5 frames backward)
1743        t.update(interval * 7.5);
1744        let passed = t.get_passed_frames();
1745        // Expected: 10 (start), 9, 8, 7, 6, 5, 4, 3, 2 (final floor(2.5))
1746        let expected = vec![10, 9, 8, 7, 6, 5, 4, 3, 2];
1747        assert_eq!(passed, expected.as_slice());
1748    }
1749
1750    #[test]
1751    fn test_passed_frames_pingpong_multi_skip() {
1752        let mut t = PlaybackController::new();
1753        t.setup(0, 5, 30);
1754        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::PingPong);
1755        t.set_skip_frames(true);
1756        t.play(); // Starts at 0.0
1757
1758        let interval = 1000.0 / 30.0;
1759
1760        // Advance 12.5 frames.
1761        // 0 -> 5 (Forward end) : 0,1,2,3,4,5
1762        // 5 -> 0 (Backward end) : 4,3,2,1,0
1763        // 0 -> 2.5 (Forward) : 1, 2
1764        t.update(interval * 12.5);
1765        let passed = t.get_passed_frames();
1766        let expected = vec![0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2];
1767        assert_eq!(passed, expected.as_slice());
1768    }
1769
1770    #[test]
1771    fn test_is_looped_flag_normal_infinite() {
1772        let mut t = PlaybackController::new();
1773        t.setup(0, 5, 30); // 0 to 5 (6 frames)
1774        t.set_loop_count(-1); // Infinite
1775        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::Normal);
1776        t.set_skip_frames(false);
1777        t.play();
1778
1779        let interval = 1000.0 / 30.0;
1780
1781        // 0..4
1782        for _ in 0..5 {
1783            t.update(interval);
1784            assert!(!t.just_looped(), "Should not be looped yet");
1785        }
1786
1787        // Frame 5 -> 0 (Loop)
1788        t.update(interval);
1789        assert!(t.just_looped(), "Should be looped at boundary");
1790        assert!(!t.is_end_frame_reached(), "Should not reach end frame in infinite loop");
1791
1792        // Next frame, flag should reset
1793        t.update(interval);
1794        assert!(!t.just_looped(), "just_looped should reset on next update");
1795    }
1796
1797    #[test]
1798    fn test_is_looped_flag_pingpong() {
1799        let mut t = PlaybackController::new();
1800        t.setup(0, 5, 30); // 0 to 5
1801        t.set_loop_count(2);
1802        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::PingPong);
1803        t.set_skip_frames(false);
1804        t.play();
1805
1806        let interval = 1000.0 / 30.0;
1807
1808        // Forward 0..4
1809        for _ in 0..5 {
1810            t.update(interval);
1811            assert!(!t.just_looped(), "Should not be looped during forward");
1812        }
1813
1814        // Frame 5 -> Start backward
1815        t.update(interval);
1816        // In ping-pong, hitting the far end doesn't count as a "loop" completion until we return to origin
1817        assert!(!t.just_looped(), "Should not loop at far end of pingpong");
1818
1819        // Backward 4..1
1820        for _ in 0..4 {
1821            t.update(interval);
1822            assert!(!t.just_looped(), "Should not be looped during backward");
1823        }
1824
1825        // Frame 0 -> 1 (Loop 1 complete)
1826        t.update(interval);
1827        assert!(t.just_looped(), "Should be looped when returning to origin in pingpong");
1828        assert!(!t.is_end_frame_reached());
1829
1830        // Forward 1..4 again
1831        for _ in 0..4 {
1832            t.update(interval);
1833            assert!(!t.just_looped());
1834        }
1835
1836        // Frame 5 -> Start backward again
1837        t.update(interval);
1838        assert!(!t.just_looped());
1839
1840        // Backward 4..1
1841        for _ in 0..4 {
1842            t.update(interval);
1843            assert!(!t.just_looped());
1844        }
1845
1846        // Frame 0 -> End
1847        t.update(interval);
1848        assert!(!t.just_looped(), "Should not loop on final end");
1849        assert!(t.is_end_frame_reached(), "Should reach end frame on last loop");
1850    }
1851
1852    // ---- pause / resume / stop contract ------------------------------------
1853    //
1854    // The four transport verbs are what every Player publishes, so their
1855    // semantics are pinned here rather than left to each Player to rediscover.
1856
1857    fn primed(loops: i32) -> PlaybackController {
1858        let mut t = PlaybackController::new();
1859        t.setup(0, 4, 30);
1860        t.set_loop_count(loops);
1861        t.set_skip_frames(false);
1862        t
1863    }
1864
1865    #[test]
1866    fn a_controller_that_never_played_is_neither_playing_nor_paused() {
1867        let t = PlaybackController::new();
1868        assert!(!t.is_playing());
1869        assert!(!t.is_pausing());
1870
1871        let t = primed(-1);
1872        assert!(!t.is_playing(), "setup() alone must not start playback");
1873        assert!(!t.is_pausing(), "setup() alone must not report a hold");
1874    }
1875
1876    #[test]
1877    fn update_does_not_advance_until_play_is_called() {
1878        // The guard that keeps a never-played controller still is `is_playing`
1879        // alone: the playhead must not move, and no frame must be reported as
1880        // passed, for a controller that was only set up.
1881        let mut t = primed(-1);
1882        assert!(!t.is_playing());
1883        assert!(!t.is_pausing());
1884
1885        for _ in 0..20 {
1886            t.update(1000.0 / 30.0);
1887            assert_eq!(t.get_frame_no(), 0.0, "setup() alone must not advance the playhead");
1888            assert!(!t.is_playing(), "update() must not start playback on its own");
1889            assert!(!t.just_looped());
1890            assert!(!t.is_finished());
1891        }
1892
1893        // ...and the same after a stop, which also leaves is_pausing false.
1894        t.play();
1895        t.update(1000.0 / 30.0);
1896        t.stop();
1897        let stopped_at = t.get_frame_no();
1898        assert!(!t.is_pausing());
1899        for _ in 0..20 {
1900            t.update(1000.0 / 30.0);
1901            assert_eq!(t.get_frame_no(), stopped_at, "a stopped controller must not advance");
1902        }
1903    }
1904
1905    #[test]
1906    fn pause_is_idempotent_and_never_resumes() {
1907        let mut t = primed(-1);
1908        t.play();
1909        t.update(1000.0 / 30.0);
1910        let held_at = t.get_frame_no();
1911
1912        t.pause();
1913        assert!(t.is_pausing());
1914        t.pause();
1915        assert!(t.is_pausing(), "a second pause() must not lift the hold");
1916
1917        // Held: time passes, the playhead does not.
1918        for _ in 0..4 {
1919            t.update(1000.0 / 30.0);
1920        }
1921        assert_eq!(t.get_frame_no(), held_at, "a paused animation must not advance");
1922        assert!(t.is_playing(), "a pause is a hold, not a stop");
1923    }
1924
1925    #[test]
1926    fn resume_is_idempotent_and_carries_on_in_place() {
1927        let mut t = primed(-1);
1928        t.play();
1929        t.update(1000.0 / 30.0);
1930        t.pause();
1931        let held_at = t.get_frame_no();
1932
1933        t.resume();
1934        assert!(!t.is_pausing());
1935        t.resume();
1936        assert!(!t.is_pausing(), "a second resume() must not re-pause");
1937        assert_eq!(t.get_frame_no(), held_at, "resume() must not move the playhead");
1938
1939        t.update(1000.0 / 30.0);
1940        assert!(t.get_frame_no() > held_at, "resume() must let the playhead advance again");
1941    }
1942
1943    #[test]
1944    fn resume_does_not_start_a_stopped_animation() {
1945        let mut t = primed(-1);
1946        t.play();
1947        t.update(1000.0 / 30.0);
1948        t.stop();
1949        assert!(!t.is_playing());
1950
1951        t.resume();
1952        assert!(!t.is_playing(), "resume() lifts a hold; starting is play()'s job");
1953    }
1954
1955    #[test]
1956    fn play_clears_a_hold_and_rewinds_to_the_section_start() {
1957        let mut t = primed(-1);
1958        t.play();
1959        for _ in 0..3 {
1960            t.update(1000.0 / 30.0);
1961        }
1962        t.pause();
1963        assert!(t.is_pausing());
1964        assert!(t.get_frame_no() > 0.0);
1965
1966        // play() is a head-out, not a resume: it drops the hold *and* rewinds.
1967        t.play();
1968        assert!(!t.is_pausing(), "play() must clear the hold");
1969        assert_eq!(t.get_frame_no(), 0.0, "play() must rewind to the section start");
1970    }
1971
1972    #[test]
1973    fn stop_clears_the_hold_and_holds_the_playhead() {
1974        let mut t = primed(-1);
1975        t.play();
1976        for _ in 0..3 {
1977            t.update(1000.0 / 30.0);
1978        }
1979        t.pause();
1980        let stopped_at = t.get_frame_no();
1981
1982        t.stop();
1983        assert!(!t.is_playing());
1984        assert!(!t.is_pausing(), "a stopped animation must not report itself held");
1985        assert_eq!(t.get_frame_no(), stopped_at, "stop() does not rewind");
1986    }
1987
1988    #[test]
1989    fn setup_clears_a_hold_left_by_the_previous_animation() {
1990        let mut t = primed(-1);
1991        t.play();
1992        t.update(1000.0 / 30.0);
1993        t.pause();
1994        assert!(t.is_pausing());
1995
1996        // Switching animations must not carry the hold across, or the next
1997        // play() would look like it did nothing.
1998        t.setup(0, 9, 30);
1999        assert!(!t.is_pausing());
2000        assert!(!t.is_playing());
2001    }
2002
2003    #[test]
2004    fn pausing_while_stopped_is_ignored() {
2005        // `is_pausing` implies `is_playing`: "stopped, and also paused" is not a
2006        // state this controller can be put into, so a host may read is_pausing
2007        // on its own without also testing is_playing.
2008        let mut t = primed(-1);
2009        t.pause();
2010        assert!(!t.is_pausing(), "pausing a never-played animation must do nothing");
2011
2012        t.play();
2013        t.update(1000.0 / 30.0);
2014        t.stop();
2015        t.pause();
2016        assert!(!t.is_pausing(), "pausing a stopped animation must do nothing");
2017        assert!(!t.is_playing());
2018
2019        // The hold is still available the moment something is actually playing.
2020        t.play();
2021        t.pause();
2022        assert!(t.is_pausing());
2023        assert!(t.is_playing());
2024    }
2025
2026    // ---- what survives setup ----------------------------------------------
2027
2028    #[test]
2029    fn setup_keeps_the_speed_and_frame_skip_the_host_chose() {
2030        // The settings a *different* system owns — a slow-motion effect, a
2031        // "show every frame" capture mode, a rewind mode — must not be clobbered
2032        // by an animation transition. What the transition itself specifies does
2033        // reset, so transitions stay independent of the one before them.
2034        let mut t = PlaybackController::new();
2035        t.setup(0, 4, 30);
2036
2037        t.set_speed_scale(2.0);
2038        t.set_skip_frames(false);
2039        t.set_loop_count(3);
2040        t.set_animation_section(1, 3);
2041        t.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::PingPong);
2042
2043        // A different clip, at a different frame rate.
2044        t.setup(0, 9, 60);
2045
2046        assert_eq!(t.speed_scale, 2.0, "speed is the host's, not the clip's");
2047        assert!(!t.get_skip_frames(), "frame skip is the host's, not the clip's");
2048
2049        assert!(t.playback_direction == PlaybackDirection::Backward, "direction is the host's, not the clip's");
2050        assert!(t.playback_style == PlaybackStyle::PingPong, "style is the host's, not the clip's");
2051        assert_eq!(t.playback_forward, -1, "and the heading is re-derived from it");
2052
2053        assert_eq!(t.get_loop_count(), -1, "loop count is per-transition");
2054        assert_eq!((t.start_frame, t.end_frame), (0, 9), "the section is the new clip's own range");
2055    }
2056
2057    #[test]
2058    fn setup_restarts_a_ping_pong_on_the_outward_leg() {
2059        // The direction survives, but the *heading* does not: a ping-pong that
2060        // was on its way back when the animation changed would otherwise start
2061        // the new one walking the wrong way out of the gate.
2062        let mut t = PlaybackController::new();
2063        t.setup(0, 9, 30);
2064        t.set_playback_direction(PlaybackDirection::Forward, PlaybackStyle::PingPong);
2065        t.playback_forward = -1; // mid-cycle: the return leg
2066
2067        t.setup(0, 9, 30);
2068
2069        assert!(t.playback_style == PlaybackStyle::PingPong, "the mode is kept");
2070        assert_eq!(t.playback_forward, 1, "but the new animation starts outbound");
2071    }
2072
2073    #[test]
2074    fn releasing_a_slot_resets_the_direction() {
2075        // reset_setup hands the slot to a different owner, so unlike setup it
2076        // must not leak the previous one's direction.
2077        let mut t = PlaybackController::new();
2078        t.setup(0, 4, 30);
2079        t.set_playback_direction(PlaybackDirection::Backward, PlaybackStyle::PingPong);
2080        t.reset_setup();
2081        assert!(t.playback_direction == PlaybackDirection::Forward);
2082        assert!(t.playback_style == PlaybackStyle::Normal);
2083        assert_eq!(t.playback_forward, 1);
2084    }
2085
2086    #[test]
2087    fn a_retained_speed_applies_to_the_new_animations_frame_rate() {
2088        // Observable rather than field-level: the retained rate has to be folded
2089        // into `update_interval` against the *new* clip's fps, not the old one's.
2090        // The clip is long enough that one second cannot wrap the loop and hide
2091        // the result behind a modulo.
2092        let mut t = PlaybackController::new();
2093        t.setup(0, 1000, 30);
2094        t.set_skip_frames(true);
2095        t.set_speed_scale(2.0);
2096
2097        t.setup(0, 1000, 60); // same host, new clip at 60fps
2098        t.play();
2099        t.update(1000.0); // one second
2100
2101        // 60fps x2 = 120 frames in a second; losing the speed, or folding it into
2102        // the old clip's 30fps, gives 60.
2103        assert!((t.get_frame_no() - 120.0).abs() < 1.0, "expected ~120 frames, got {}", t.get_frame_no());
2104    }
2105
2106    #[test]
2107    fn the_speed_reads_back_as_it_was_stored() {
2108        // The getter exists so a host does not have to keep its own copy of the
2109        // rate — the copy is what drifts. What it returns is the value that was
2110        // *stored*, so a clamped negative reads back as the stop it became
2111        // rather than as the reverse playback it was mistaken for.
2112        let mut t = PlaybackController::new();
2113        t.setup(0, 4, 30);
2114        assert_eq!(t.get_speed_scale(), 1.0, "the default is 1x");
2115
2116        t.set_speed_scale(2.5);
2117        assert_eq!(t.get_speed_scale(), 2.5);
2118
2119        t.set_speed_scale(0.0);
2120        assert_eq!(t.get_speed_scale(), 0.0, "zero is a setting, not 'unset'");
2121
2122        t.set_speed_scale(-1.0);
2123        assert_eq!(t.get_speed_scale(), 0.0, "a negative rate clamps to a stop, and reads back as one");
2124    }
2125
2126    #[test]
2127    fn releasing_a_slot_does_reset_the_speed() {
2128        // reset_setup hands the slot to a different owner, so unlike setup it
2129        // must not leak the previous one's settings.
2130        let mut t = PlaybackController::new();
2131        t.setup(0, 4, 30);
2132        t.set_speed_scale(2.0);
2133        t.reset_setup();
2134        assert_eq!(t.speed_scale, 1.0);
2135    }
2136
2137    #[test]
2138    fn an_fps_override_survives_setup_and_the_authored_rate_does_not() {
2139        // `set_frame_rate` is the host saying "this player runs at n fps", so it
2140        // outlives a transition the way the speed multiplier does. The clip's own
2141        // rate is data and is re-read every time.
2142        let mut t = PlaybackController::new();
2143        t.setup(0, 1000, 30);
2144        assert_eq!(t.get_frame_rate(), 30, "no override yet: the clip's own rate");
2145
2146        t.set_frame_rate(60);
2147        assert_eq!(t.get_frame_rate(), 60);
2148
2149        t.setup(0, 1000, 24); // a different clip, authored at 24
2150        assert_eq!(t.get_frame_rate(), 60, "the host's rate outlives the transition");
2151
2152        // ...and clearing it hands playback back to the *new* clip's rate, not
2153        // the one that was current when the override was set.
2154        t.set_frame_rate(0);
2155        assert_eq!(t.get_frame_rate(), 24);
2156    }
2157
2158    #[test]
2159    fn setup_folds_the_override_into_the_update_interval() {
2160        // `setup` computes the interval from the effective rate, as every other
2161        // writer does.
2162        let mut t = PlaybackController::new();
2163        t.setup(0, 1000, 30);
2164        t.set_skip_frames(true);
2165        t.set_frame_rate(60);
2166
2167        t.setup(0, 1000, 24); // authored 24, override 60
2168        t.play();
2169        t.update(1000.0);
2170
2171        assert!((t.get_frame_no() - 60.0).abs() < 1.0, "expected ~60 frames (the override), got {} (24 would mean setup ignored it)", t.get_frame_no());
2172    }
2173
2174    #[test]
2175    fn the_override_and_the_speed_multiply() {
2176        // They compose: 60fps at x0.5 is 30 frames a second, whatever the clip
2177        // was authored at.
2178        let mut t = PlaybackController::new();
2179        t.setup(0, 1000, 24);
2180        t.set_skip_frames(true);
2181        t.set_frame_rate(60);
2182        t.set_speed_scale(0.5);
2183        t.play();
2184        t.update(1000.0);
2185
2186        assert!((t.get_frame_no() - 30.0).abs() < 1.0, "expected ~30 frames, got {}", t.get_frame_no());
2187    }
2188
2189    #[test]
2190    fn releasing_a_slot_clears_the_override_too() {
2191        let mut t = PlaybackController::new();
2192        t.setup(0, 4, 30);
2193        t.set_frame_rate(60);
2194        t.reset_setup();
2195        t.setup(0, 4, 30);
2196        assert_eq!(t.get_frame_rate(), 30, "a recycled slot must not inherit the previous owner's rate");
2197    }
2198
2199    #[test]
2200    fn a_zero_speed_freezes_the_playhead() {
2201        let mut t = PlaybackController::new();
2202        t.setup(0, 1000, 30);
2203        t.set_skip_frames(true);
2204        t.play();
2205        t.update(1000.0 / 30.0);
2206        let held_at = t.get_frame_no();
2207        assert!(held_at > 0.0, "sanity: it was advancing before the speed changed");
2208
2209        t.set_speed_scale(0.0);
2210        for _ in 0..10 {
2211            t.update(1000.0);
2212        }
2213        assert_eq!(t.get_frame_no(), held_at, "a zero speed must not advance the playhead");
2214        assert!(t.is_playing(), "frozen is not stopped");
2215        assert!(!t.is_pausing(), "nor is it the pause flag");
2216
2217        // ...and it is not a one-way door.
2218        t.set_speed_scale(1.0);
2219        t.update(1000.0 / 30.0);
2220        assert!(t.get_frame_no() > held_at, "restoring a positive speed resumes advancing");
2221    }
2222
2223    #[test]
2224    fn a_zero_speed_freezes_fixed_stepping_too() {
2225        // The other advance path: with frame skip off, `update` accumulates time
2226        // against the interval instead of dividing by it.
2227        let mut t = PlaybackController::new();
2228        t.setup(0, 1000, 30);
2229        t.set_skip_frames(false);
2230        t.set_speed_scale(0.0);
2231        t.play();
2232        let held_at = t.get_frame_no();
2233        for _ in 0..10 {
2234            t.update(1000.0);
2235        }
2236        assert_eq!(t.get_frame_no(), held_at);
2237    }
2238
2239    #[test]
2240    fn a_negative_speed_stops_rather_than_running_forward() {
2241        // Reverse is `set_playback_direction`'s job. Clamping to a stop makes an
2242        // unsupported request visible; normalizing to 1.0 hid it behind
2243        // full-speed forward playback.
2244        let mut t = PlaybackController::new();
2245        t.setup(0, 1000, 30);
2246        t.set_skip_frames(true);
2247        t.set_speed_scale(-1.0);
2248        t.play();
2249        let held_at = t.get_frame_no();
2250        t.update(1000.0);
2251        assert_eq!(t.get_frame_no(), held_at);
2252    }
2253}