Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_tick/
lib.rs

1//! Fixed-timestep game clock shared by every PSoXide game.
2//!
3//! Game logic runs in fixed ticks of a whole number of VBlanks; rendering runs
4//! as often as the frame cost allows and shows the latest tick (optionally
5//! interpolated with [`FixedClock::phase_q12`]). Logic speed then never
6//! depends on how long a frame takes to draw.
7//!
8//! Each game picks its own [`TickConfig`] (tick rate and catch-up policy);
9//! the functions are the same everywhere, so behaviour and the
10//! [`TickStats`] consistency counters mean the same thing in every game.
11//!
12//! The clock never reads hardware. Callers pass the current VBlank count
13//! (`psx_rt::interrupts::vblank_count()` on the console), which keeps every
14//! rule host-testable.
15//!
16//! ```
17//! use psx_tick::{FixedClock, TickConfig, TickRate};
18//! let now = 100;
19//! let mut clock = FixedClock::new(TickConfig::new(TickRate::HZ60), now);
20//! // A frame that took three VBlanks owes three ticks.
21//! let mut ran = 0;
22//! while clock.due(now + 2) {
23//!     ran += 1; // simulate one tick
24//! }
25//! clock.end_frame();
26//! assert_eq!(ran, 3);
27//! ```
28#![no_std]
29
30/// Tick length in VBlanks: 1 is 60 Hz on NTSC, 2 is 30 Hz, 3 is 20 Hz.
31#[derive(Copy, Clone, Debug, PartialEq, Eq)]
32pub struct TickRate(u16);
33
34impl TickRate {
35    /// One tick per VBlank (60 Hz NTSC, 50 Hz PAL).
36    pub const HZ60: TickRate = TickRate(1);
37    /// One tick every second VBlank.
38    pub const HZ30: TickRate = TickRate(2);
39    /// One tick every third VBlank.
40    pub const HZ20: TickRate = TickRate(3);
41
42    /// One tick every `vblanks` VBlanks (0 is treated as 1).
43    #[must_use]
44    pub const fn every_vblanks(vblanks: u16) -> TickRate {
45        TickRate(if vblanks == 0 { 1 } else { vblanks })
46    }
47
48    /// Tick length in VBlanks.
49    pub const fn vblanks(self) -> u16 {
50        self.0
51    }
52}
53
54/// What to do when a frame falls further behind than the game allows.
55#[derive(Copy, Clone, Debug, PartialEq, Eq)]
56pub enum CatchUp {
57    /// Run every owed tick before the next render. Logic time never drops.
58    Unbounded,
59    /// Run at most this many ticks per frame, render, and carry the rest of
60    /// the debt into the next frames. Logic time never drops; a long stall is
61    /// caught up over several rendered frames instead of one frozen burst.
62    Interleave(u16),
63    /// Run at most this many ticks per frame and drop the rest of the debt
64    /// (counted in [`TickStats::dropped`]). Game time then falls behind real
65    /// time, so use it only where a burst would be worse than a slowdown.
66    Cap(u16),
67}
68
69/// A game's clock settings.
70#[derive(Copy, Clone, Debug, PartialEq, Eq)]
71pub struct TickConfig {
72    /// Tick length.
73    pub rate: TickRate,
74    /// Catch-up policy.
75    pub catch_up: CatchUp,
76}
77
78impl TickConfig {
79    /// `rate` with unbounded catch-up.
80    pub const fn new(rate: TickRate) -> TickConfig {
81        TickConfig {
82            rate,
83            catch_up: CatchUp::Unbounded,
84        }
85    }
86
87    /// At most `max_ticks` ticks per frame, the rest carried forward.
88    pub const fn with_interleave(self, max_ticks: u16) -> TickConfig {
89        TickConfig {
90            rate: self.rate,
91            catch_up: CatchUp::Interleave(if max_ticks == 0 { 1 } else { max_ticks }),
92        }
93    }
94
95    /// At most `max_ticks` ticks per frame, the rest dropped.
96    pub const fn with_cap(self, max_ticks: u16) -> TickConfig {
97        TickConfig {
98            rate: self.rate,
99            catch_up: CatchUp::Cap(if max_ticks == 0 { 1 } else { max_ticks }),
100        }
101    }
102}
103
104/// The fastest a game may change the picture: the fewest VBlanks between two
105/// display flips.
106///
107/// Every PSoXide game is capped at [`PresentCap::HZ30`] (a flip at most every
108/// second VBlank, 30 fps NTSC and 25 fps PAL) unless it opts out by name with
109/// [`PresentCap::UNCAPPED`]. A frame built inside one VBlank interval then waits
110/// for the next flip slot instead of flipping at 60 for a moment and falling back,
111/// which reads as a stutter. Frames slower than the cap are untouched: the cap
112/// bounds the rate from above and never speeds anything up.
113///
114/// `psx-rt` enforces it where the flip happens (see
115/// `psx_rt::interrupts::set_present_cap`); [`FlipGate`] is the same rule as pure
116/// logic, so it is host-testable and a tool can check a recorded run against it.
117#[derive(Copy, Clone, Debug, PartialEq, Eq)]
118pub struct PresentCap(u8);
119
120impl PresentCap {
121    /// At most one flip every second VBlank (30 fps NTSC, 25 PAL): the default.
122    pub const HZ30: PresentCap = PresentCap(2);
123    /// A flip on every VBlank (60 fps NTSC, 50 PAL). The explicit opt-out, for a
124    /// game that deliberately targets the full display rate.
125    pub const UNCAPPED: PresentCap = PresentCap(1);
126
127    /// At most one flip every `vblanks` VBlanks (0 is treated as 1).
128    pub const fn every_vblanks(vblanks: u8) -> PresentCap {
129        PresentCap(if vblanks == 0 { 1 } else { vblanks })
130    }
131
132    /// The fewest VBlanks between two flips.
133    #[must_use]
134    pub const fn min_vblanks(self) -> u8 {
135        self.0
136    }
137}
138
139impl Default for PresentCap {
140    /// [`PresentCap::HZ30`].
141    fn default() -> PresentCap {
142        PresentCap::HZ30
143    }
144}
145
146/// Buckets in [`FlipHistogram`]: flips 0 to 6 VBlanks after the previous one,
147/// and the last bucket for 7 or more.
148pub const FLIP_HISTOGRAM_BUCKETS: usize = 8;
149
150/// How many flips came `k` VBlanks after the one before.
151///
152/// `psx-rt` keeps one in RAM (`psx_rt::interrupts::flip_histogram`, read with
153/// [`from_buckets`](Self::from_buckets)), so a run's
154/// flip pacing can be read off a frame dump or a RAM watch and checked with
155/// [`below`](Self::below).
156#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
157pub struct FlipHistogram {
158    buckets: [u32; FLIP_HISTOGRAM_BUCKETS],
159}
160
161impl FlipHistogram {
162    /// `buckets()[k]`: flips `k` VBlanks after the previous one (the last bucket
163    /// is "that many or more"). The first flip after a reset has no previous one
164    /// and is counted in the last bucket.
165    #[must_use]
166    pub const fn buckets(&self) -> &[u32; FLIP_HISTOGRAM_BUCKETS] {
167        &self.buckets
168    }
169
170    /// The histogram of `buckets` as `psx_rt::interrupts::flip_histogram` returns it.
171    #[must_use]
172    pub const fn from_buckets(buckets: [u32; FLIP_HISTOGRAM_BUCKETS]) -> FlipHistogram {
173        FlipHistogram { buckets }
174    }
175
176    /// Flips that came sooner than `min_vblanks` after the one before: zero for
177    /// a game that honours its cap.
178    #[must_use]
179    pub fn below(&self, min_vblanks: u8) -> u32 {
180        let end = usize::from(min_vblanks).min(FLIP_HISTOGRAM_BUCKETS);
181        self.buckets[..end].iter().sum()
182    }
183
184    /// All flips counted.
185    #[must_use]
186    pub fn total(&self) -> u32 {
187        self.buckets.iter().sum()
188    }
189
190    fn record(&mut self, interval: u32) {
191        let k = (interval as usize).min(FLIP_HISTOGRAM_BUCKETS - 1);
192        self.buckets[k] = self.buckets[k].saturating_add(1);
193    }
194}
195
196/// The presentation cap as a state machine, one call per VBlank edge: the
197/// reference for what `psx-rt`'s VBlank handler does with a queued flip.
198///
199/// ```
200/// use psx_tick::{FlipGate, PresentCap};
201/// let mut gate = FlipGate::new(PresentCap::HZ30);
202/// // A flip wanted on every edge is granted on every second one.
203/// let granted: Vec<bool> = (0..6).map(|_| gate.edge(true)).collect();
204/// assert_eq!(granted, [true, false, true, false, true, false]);
205/// assert_eq!(gate.histogram().below(2), 0);
206/// ```
207#[derive(Copy, Clone, Debug, PartialEq, Eq)]
208pub struct FlipGate {
209    min: u32,
210    hold: u32,
211    age: u32,
212    histogram: FlipHistogram,
213}
214
215impl FlipGate {
216    /// A gate with `cap`, free to flip at the first edge.
217    #[must_use]
218    pub const fn new(cap: PresentCap) -> FlipGate {
219        FlipGate {
220            min: cap.min_vblanks() as u32,
221            hold: 0,
222            age: FLIP_HISTOGRAM_BUCKETS as u32 - 1,
223            histogram: FlipHistogram {
224                buckets: [0; FLIP_HISTOGRAM_BUCKETS],
225            },
226        }
227    }
228
229    /// One VBlank edge. `flip_wanted` is whether a finished frame is waiting to
230    /// be shown. Returns whether the flip was applied: it is held back while
231    /// fewer than the cap's VBlanks have passed since the last one.
232    pub fn edge(&mut self, flip_wanted: bool) -> bool {
233        let flipped = flip_wanted && self.hold == 0;
234        if flipped {
235            self.histogram.record(self.age);
236            self.age = 0;
237            self.hold = self.min;
238        }
239        self.hold = self.hold.saturating_sub(1);
240        self.age = self.age.saturating_add(1);
241        flipped
242    }
243
244    /// The flip intervals so far.
245    #[must_use]
246    pub const fn histogram(&self) -> FlipHistogram {
247        self.histogram
248    }
249}
250
251/// Buckets in [`TickStats::ticks_per_frame`]; the last one collects
252/// every frame with that many ticks or more.
253pub const TICK_HISTOGRAM_BUCKETS: usize = 9;
254
255/// Frame-consistency counters since construction or [`FixedClock::reset_stats`].
256#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
257pub struct TickStats {
258    /// Frames closed with [`FixedClock::end_frame`].
259    pub frames: u32,
260    /// Ticks run.
261    pub ticks: u32,
262    /// Ticks the catch-up cap dropped (only [`CatchUp::Cap`] drops any).
263    pub dropped: u32,
264    /// Most ticks any single frame ran.
265    pub max_frame_ticks: u16,
266    /// `ticks_per_frame[k]`: frames that ran `k` ticks (the last bucket is
267    /// "that many or more"). A steady game sits in one or two buckets.
268    pub ticks_per_frame: [u32; TICK_HISTOGRAM_BUCKETS],
269}
270
271/// Fixed-timestep clock. See the crate docs.
272#[derive(Copy, Clone, Debug, PartialEq, Eq)]
273pub struct FixedClock {
274    rate: u16,
275    cap: u16,
276    drop_excess: bool,
277    next_due: u32,
278    tick: u32,
279    frame_ticks: u16,
280    stats: TickStats,
281}
282
283#[inline(always)]
284fn reached(now: u32, target: u32) -> bool {
285    now.wrapping_sub(target) < 0x8000_0000
286}
287
288impl FixedClock {
289    /// A clock whose first tick is due at VBlank `first_due`.
290    pub const fn new(config: TickConfig, first_due: u32) -> FixedClock {
291        FixedClock {
292            rate: config.rate.vblanks(),
293            cap: match config.catch_up {
294                CatchUp::Unbounded => 0,
295                CatchUp::Interleave(n) | CatchUp::Cap(n) => n,
296            },
297            drop_excess: matches!(config.catch_up, CatchUp::Cap(_)),
298            next_due: first_due,
299            tick: 0,
300            frame_ticks: 0,
301            stats: TickStats {
302                frames: 0,
303                ticks: 0,
304                dropped: 0,
305                max_frame_ticks: 0,
306                ticks_per_frame: [0; TICK_HISTOGRAM_BUCKETS],
307            },
308        }
309    }
310
311    /// Forget any owed time and make the next tick due at `first_due`.
312    /// Call after a load, a pause menu or anything else that should not be
313    /// caught up. Not counted as dropped ticks.
314    pub fn realign(&mut self, first_due: u32) {
315        self.next_due = first_due;
316    }
317
318    /// `true` when a tick is due at VBlank `now`: run one tick, then ask
319    /// again. The tick is counted as run when this returns `true`.
320    ///
321    /// Reading `now` fresh each time lets a frame keep catching up while its
322    /// own ticks take time, exactly as a `while vblank >= next` loop does.
323    pub fn due(&mut self, now: u32) -> bool {
324        if !reached(now, self.next_due) {
325            return false;
326        }
327        if self.cap != 0 && self.frame_ticks >= self.cap {
328            if !self.drop_excess {
329                return false;
330            }
331            let behind = now.wrapping_sub(self.next_due) / u32::from(self.rate) + 1;
332            self.stats.dropped = self.stats.dropped.saturating_add(behind);
333            self.next_due = self
334                .next_due
335                .wrapping_add(behind.wrapping_mul(u32::from(self.rate)));
336            return false;
337        }
338        self.consume();
339        true
340    }
341
342    /// `true` when a tick is due at VBlank `now`, without running it and
343    /// ignoring the catch-up policy. For schedulers that decide first and
344    /// commit later with [`consume`](Self::consume); game loops use
345    /// [`due`](Self::due).
346    pub fn is_due(&self, now: u32) -> bool {
347        reached(now, self.next_due)
348    }
349
350    /// Record one tick as run: advance the deadline and the counters. The
351    /// caller has already decided it was due (see [`is_due`](Self::is_due)).
352    pub fn consume(&mut self) {
353        self.next_due = self.next_due.wrapping_add(u32::from(self.rate));
354        self.tick = self.tick.wrapping_add(1);
355        self.frame_ticks = self.frame_ticks.saturating_add(1);
356        self.stats.ticks = self.stats.ticks.saturating_add(1);
357    }
358
359    /// Close the current frame: record how many ticks it ran and start
360    /// counting the next frame's.
361    pub fn end_frame(&mut self) {
362        let k = usize::from(self.frame_ticks).min(TICK_HISTOGRAM_BUCKETS - 1);
363        self.stats.ticks_per_frame[k] = self.stats.ticks_per_frame[k].saturating_add(1);
364        self.stats.frames = self.stats.frames.saturating_add(1);
365        self.stats.max_frame_ticks = self.stats.max_frame_ticks.max(self.frame_ticks);
366        self.frame_ticks = 0;
367    }
368
369    /// Ticks run since construction.
370    pub const fn tick(&self) -> u32 {
371        self.tick
372    }
373
374    /// Ticks run so far in the current frame.
375    pub const fn frame_ticks(&self) -> u16 {
376        self.frame_ticks
377    }
378
379    /// Tick length in VBlanks.
380    pub const fn rate(&self) -> TickRate {
381        TickRate(self.rate)
382    }
383
384    /// VBlank at which the next tick is due.
385    pub const fn next_due(&self) -> u32 {
386        self.next_due
387    }
388
389    /// How far VBlank `now` is from the last tick toward the next one, in
390    /// Q12 (0 = the last tick has just been reached, 4096 = the next one is
391    /// due). Renderers draw `lerp(previous, latest, phase)`: one tick of
392    /// latency in exchange for motion that moves on every rendered frame at
393    /// any tick rate. A game ticking every VBlank can simply draw the latest
394    /// state instead.
395    pub fn phase_q12(&self, now: u32) -> u16 {
396        let ahead = self.next_due.wrapping_sub(now) as i32;
397        let rate = i32::from(self.rate);
398        if ahead <= 0 {
399            4096
400        } else {
401            (((rate - ahead.min(rate)) << 12) / rate) as u16
402        }
403    }
404
405    /// Consistency counters.
406    pub const fn stats(&self) -> TickStats {
407        self.stats
408    }
409
410    /// Zero the consistency counters (for example at the start of a level).
411    pub fn reset_stats(&mut self) {
412        self.stats = TickStats::default();
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    fn run(clock: &mut FixedClock, now: u32) -> u32 {
421        let mut n = 0;
422        while clock.due(now) {
423            n += 1;
424        }
425        clock.end_frame();
426        n
427    }
428
429    #[test]
430    fn sixty_hz_runs_one_tick_per_vblank_and_catches_up_a_slow_frame() {
431        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), 10);
432        assert_eq!(run(&mut c, 9), 0);
433        assert_eq!(run(&mut c, 10), 1);
434        assert_eq!(run(&mut c, 11), 1);
435        assert_eq!(run(&mut c, 15), 4);
436        assert_eq!(c.tick(), 6);
437        assert_eq!(c.stats().ticks_per_frame[..5], [1, 2, 0, 0, 1]);
438        assert_eq!(c.stats().max_frame_ticks, 4);
439        assert_eq!(c.stats().dropped, 0);
440    }
441
442    #[test]
443    fn twenty_hz_ticks_every_third_vblank() {
444        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ20), 3);
445        let ticks: u32 = (0..=30).map(|now| run(&mut c, now)).sum();
446        assert_eq!(ticks, 10); // due at 3, 6, ..., 30
447        assert_eq!(c.next_due(), 33);
448    }
449
450    #[test]
451    fn logic_time_matches_real_time_whatever_the_frame_lengths() {
452        // Frames of 1..7 VBlanks in a fixed pattern: every tick owed by
453        // VBlank 1000 has run, the same count a 60 fps game would have run.
454        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ30), 0);
455        let mut now = 0u32;
456        let mut k = 0u32;
457        while now < 1000 {
458            run(&mut c, now);
459            now += 1 + (k % 7);
460            k += 1;
461        }
462        run(&mut c, 1000);
463        assert_eq!(c.tick(), 501); // ticks at 0, 2, ..., 1000
464        assert_eq!(c.stats().dropped, 0);
465    }
466
467    #[test]
468    fn cap_drops_the_excess_and_counts_it() {
469        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60).with_cap(4), 0);
470        assert_eq!(run(&mut c, 0), 1);
471        // 10 ticks owed (1..=10), 4 allowed.
472        assert_eq!(run(&mut c, 10), 4);
473        assert_eq!(c.stats().dropped, 6);
474        assert_eq!(c.next_due(), 11);
475        assert_eq!(run(&mut c, 11), 1);
476    }
477
478    #[test]
479    fn interleave_renders_between_bursts_and_loses_no_time() {
480        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60).with_interleave(4), 0);
481        assert_eq!(run(&mut c, 0), 1);
482        assert_eq!(run(&mut c, 10), 4); // ticks 1..=4
483        assert_eq!(run(&mut c, 10), 4); // 5..=8
484        assert_eq!(run(&mut c, 11), 3); // 9..=11: caught up
485        assert_eq!(c.tick(), 12);
486        assert_eq!(c.stats().dropped, 0);
487    }
488
489    #[test]
490    fn is_due_and_consume_split_the_decision_from_the_commit() {
491        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), 5);
492        assert!(!c.is_due(4));
493        assert!(c.is_due(5));
494        assert!(c.is_due(5)); // a query does not run the tick
495        c.consume();
496        assert!(!c.is_due(5));
497        assert_eq!((c.tick(), c.frame_ticks(), c.next_due()), (1, 1, 6));
498    }
499
500    #[test]
501    fn realign_forgets_debt_without_counting_it_dropped() {
502        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), 0);
503        run(&mut c, 0);
504        c.realign(501); // a 500-VBlank load
505        assert_eq!(run(&mut c, 501), 1);
506        assert_eq!(c.stats().dropped, 0);
507    }
508
509    #[test]
510    fn phase_sweeps_from_last_tick_to_next() {
511        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ20), 0);
512        run(&mut c, 0); // next due at 3
513        assert_eq!(c.phase_q12(0), 0);
514        assert_eq!(c.phase_q12(1), 1365);
515        assert_eq!(c.phase_q12(2), 2730);
516        assert_eq!(c.phase_q12(3), 4096);
517        let mut s = FixedClock::new(TickConfig::new(TickRate::HZ60), 0);
518        run(&mut s, 0);
519        assert_eq!(s.phase_q12(0), 0);
520        assert_eq!(s.phase_q12(1), 4096);
521    }
522
523    #[test]
524    fn the_default_cap_never_flips_twice_in_two_vblanks_whatever_is_asked() {
525        let mut gate = FlipGate::new(PresentCap::default());
526        let mut last = None;
527        for edge in 0..1000u32 {
528            // An irregular request pattern, heavy on back-to-back wants.
529            let wanted = edge % 5 != 3;
530            if gate.edge(wanted) {
531                if let Some(prev) = last {
532                    assert!(edge - prev >= 2, "flips at {prev} and {edge}");
533                }
534                last = Some(edge);
535            }
536        }
537        assert_eq!(gate.histogram().below(2), 0);
538        assert!(gate.histogram().total() > 400);
539    }
540
541    #[test]
542    fn a_slower_game_is_not_delayed_and_uncapped_flips_every_edge() {
543        // A flip wanted every third edge is granted at once.
544        let mut gate = FlipGate::new(PresentCap::HZ30);
545        let granted: u32 = (0..30).map(|e| u32::from(gate.edge(e % 3 == 0))).sum();
546        assert_eq!(granted, 10);
547        assert_eq!(gate.histogram().buckets()[3], 9);
548        let mut free = FlipGate::new(PresentCap::UNCAPPED);
549        assert!((0..10).all(|_| free.edge(true)));
550        assert_eq!(free.histogram().buckets()[1], 9);
551        assert_eq!(free.histogram().below(2), 9);
552    }
553
554    #[test]
555    fn caps_below_one_vblank_are_one_and_slower_caps_hold_longer() {
556        assert_eq!(PresentCap::every_vblanks(0), PresentCap::UNCAPPED);
557        let mut gate = FlipGate::new(PresentCap::every_vblanks(3));
558        let mut granted = [false; 7];
559        for slot in &mut granted {
560            *slot = gate.edge(true);
561        }
562        assert_eq!(granted, [true, false, false, true, false, false, true]);
563    }
564
565    #[test]
566    fn survives_vblank_counter_wraparound() {
567        let start = u32::MAX - 2;
568        let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), start);
569        assert_eq!(run(&mut c, start.wrapping_add(5)), 6);
570        assert_eq!(c.next_due(), start.wrapping_add(6));
571    }
572}