Skip to main content

clairlune_render/
clock.rs

1//! Which moment of the character's life a frame shows.
2//!
3//! - `Clock::Live`: the seeded state machine plays freely (PLAN.md section 4.4);
4//!   live mode never repeats exactly. Particles sit on the cell grid: stills,
5//!   thumbnails and the CPU fallback.
6//! - `Clock::Smooth`: the same, with particles at sub-cell pixel positions,
7//!   so a higher frame rate moves them smoothly instead of a cell at a time:
8//!   live playback on a GPU (PLAN.md section 4.4).
9//! - `Clock::Loop(loop_ms)`: a seamless loop for GIF export. The character follows
10//!   the activity's `gif.loop_script`, its first looping state repeated to fill
11//!   the loop, then time-scaled so the script ends exactly at `loop_ms`; pacing
12//!   is snapped to a period that divides the loop. Frame `t = loop_ms` equals
13//!   frame `t = 0`.
14
15use clairlune_scene::activity::Activity;
16use clairlune_scene::anim::DEFAULT_ONE_SHOT_MS;
17use clairlune_scene::{CharacterTrack, Motion};
18use clairlune_sprites::Character;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum Clock {
22    Live,
23    Smooth,
24    Loop(u64),
25}
26
27/// One state of the loop script, placed on the loop's timeline.
28#[derive(Clone, Debug, PartialEq, Eq)]
29struct Segment {
30    state: String,
31    start: u64,
32    len: u64,
33    /// The state's own animation length (one cycle), in animation time.
34    cycle: u64,
35}
36
37/// The character's timeline for one seamless loop.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct LoopScript {
40    loop_ms: u64,
41    segments: Vec<Segment>,
42}
43
44impl LoopScript {
45    pub fn new(activity: &Activity, character: &dyn Character, loop_ms: u64) -> Self {
46        let script: Vec<String> = activity
47            .gif
48            .as_ref()
49            .map(|g| g.loop_script.clone())
50            .filter(|s| !s.is_empty())
51            .unwrap_or_else(|| vec![activity.animation.start.clone()]);
52        let cycle = |s: &str| {
53            character
54                .animation(&activity.id, s)
55                .map(|a| a.duration_ms())
56                .unwrap_or(DEFAULT_ONE_SHOT_MS)
57                .max(1)
58        };
59        let looping = |s: &str| activity.animation.states.get(s).is_some_and(|d| d.looping);
60
61        // Repeat the first looping state's cycle while it still fits in the loop.
62        let base: u64 = script.iter().map(|s| cycle(s)).sum();
63        let rep = script.iter().position(|s| looping(s)).unwrap_or(0);
64        let rep_cycle = cycle(&script[rep]);
65        let mut extra = 0;
66        while base + (extra + 1) * rep_cycle <= loop_ms {
67            extra += 1;
68        }
69        let mut natural: Vec<(String, u64)> = Vec::new();
70        for (i, s) in script.iter().enumerate() {
71            let n = if i == rep { 1 + extra } else { 1 };
72            for _ in 0..n {
73                natural.push((s.clone(), cycle(s)));
74            }
75        }
76
77        // Time-scale onto [0, loop_ms) with integer boundaries.
78        let total: u64 = natural.iter().map(|(_, c)| c).sum::<u64>().max(1);
79        let mut segments = Vec::with_capacity(natural.len());
80        let mut cum = 0u64;
81        for (state, c) in natural {
82            let start = cum * loop_ms / total;
83            cum += c;
84            let end = cum * loop_ms / total;
85            if end > start {
86                segments.push(Segment {
87                    state,
88                    start,
89                    len: end - start,
90                    cycle: c,
91                });
92            }
93        }
94        Self { loop_ms, segments }
95    }
96
97    /// State and elapsed animation time at `t` (wraps every `loop_ms`).
98    pub fn at(&self, t_ms: u64) -> (&str, u64) {
99        let t = t_ms % self.loop_ms.max(1);
100        let seg = self
101            .segments
102            .iter()
103            .rev()
104            .find(|s| s.start <= t)
105            .unwrap_or(&self.segments[0]);
106        let elapsed = (t - seg.start) * seg.cycle / seg.len.max(1);
107        (&seg.state, elapsed.min(seg.cycle - 1))
108    }
109}
110
111/// The character track with pacing snapped to a period that divides the loop.
112pub fn loop_track(track: CharacterTrack, loop_ms: u64) -> CharacterTrack {
113    match track.motion {
114        Motion::Pace {
115            x_min,
116            x_max,
117            period_ms,
118        } => {
119            // Whole round trips per loop, nearest to the natural speed, dividing the loop.
120            let target = (loop_ms as f64 / period_ms.max(1) as f64).round().max(1.0) as u64;
121            let n = (1..=loop_ms)
122                .filter(|n| loop_ms.is_multiple_of(*n))
123                .min_by_key(|n| n.abs_diff(target))
124                .unwrap_or(1);
125            CharacterTrack {
126                motion: Motion::Pace {
127                    x_min,
128                    x_max,
129                    period_ms: loop_ms / n,
130                },
131                ..track
132            }
133        }
134        Motion::Fly {
135            x_min,
136            x_max,
137            period_ms,
138            lift,
139            bob,
140            bob_ms,
141        } => {
142            let Motion::Pace { period_ms, .. } = loop_track(
143                CharacterTrack {
144                    motion: Motion::Pace {
145                        x_min,
146                        x_max,
147                        period_ms,
148                    },
149                    ..track
150                },
151                loop_ms,
152            )
153            .motion
154            else {
155                unreachable!("pacing stays pacing")
156            };
157            // The bob too: whole periods per loop.
158            let n = (loop_ms / bob_ms.max(1)).max(1);
159            let bob_ms = (1..=n)
160                .rev()
161                .find(|k| loop_ms.is_multiple_of(*k))
162                .map_or(loop_ms, |k| loop_ms / k);
163            CharacterTrack {
164                motion: Motion::Fly {
165                    x_min,
166                    x_max,
167                    period_ms,
168                    lift,
169                    bob,
170                    bob_ms,
171                },
172                ..track
173            }
174        }
175        Motion::Stationary { .. } => track,
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use clairlune_scene::activity::builtin_catalog;
183    use clairlune_sprites::builtin_character;
184
185    #[test]
186    fn script_fills_the_loop_and_wraps() {
187        for a in &builtin_catalog().activities {
188            for loop_ms in [6000, 12000] {
189                let s = LoopScript::new(a, builtin_character(), loop_ms);
190                assert_eq!(s.segments.first().unwrap().start, 0, "{}", a.id);
191                let last = s.segments.last().unwrap();
192                assert_eq!(last.start + last.len, loop_ms, "{}", a.id);
193                assert_eq!(s.at(0), s.at(loop_ms));
194                // Starts on the first frame of the script's first state.
195                assert_eq!(s.at(0).1, 0);
196            }
197        }
198    }
199
200    #[test]
201    fn pacing_divides_the_loop() {
202        let track = CharacterTrack {
203            y: 0,
204            scale: 1,
205            face_left: false,
206            motion: Motion::Pace {
207                x_min: 0,
208                x_max: 100,
209                period_ms: 4700,
210            },
211        };
212        let t = loop_track(track, 6000);
213        let Motion::Pace { period_ms, .. } = t.motion else {
214            panic!()
215        };
216        assert!(6000u64.is_multiple_of(period_ms));
217        assert_eq!(t.at(0), t.at(6000));
218    }
219
220    #[test]
221    fn flying_divides_the_loop() {
222        let track = CharacterTrack {
223            y: 500,
224            scale: 2,
225            face_left: false,
226            motion: Motion::Fly {
227                x_min: 0,
228                x_max: 900,
229                period_ms: 13_300,
230                lift: 200,
231                bob: 6,
232                bob_ms: 3000,
233            },
234        };
235        for loop_ms in [6000, 12000] {
236            let t = loop_track(track, loop_ms);
237            assert_eq!(t.at(0), t.at(loop_ms));
238            assert_eq!(t.at(1234), t.at(1234 + loop_ms));
239        }
240    }
241}