Skip to main content

rusting_core/
time.rs

1use std::time::Duration;
2use std::{error::Error, fmt};
3
4use bevy_ecs::prelude::Resource;
5
6/// Frame and simulation timing visible to systems.
7#[derive(Resource, Clone, Copy, Debug)]
8pub struct FrameTime {
9    /// Number of successful application updates since the app started.
10    pub frame: u64,
11    /// Real time since the previous frame, even while paused.
12    pub real_delta: Duration,
13    /// Game time since the previous frame after pause and time scale.
14    pub delta: Duration,
15    /// Total game time, without time spent paused.
16    pub elapsed: Duration,
17    /// Time simulated by one fixed-schedule execution.
18    pub fixed_delta: Duration,
19    /// Number of completed fixed-schedule executions.
20    pub fixed_tick: u64,
21}
22
23impl Default for FrameTime {
24    fn default() -> Self {
25        Self {
26            frame: 0,
27            real_delta: Duration::ZERO,
28            delta: Duration::ZERO,
29            elapsed: Duration::ZERO,
30            fixed_delta: Duration::from_secs_f64(1.0 / 60.0),
31            fixed_tick: 0,
32        }
33    }
34}
35
36impl FrameTime {
37    /// Returns the current game-frame time as an easy-to-use `f32` value.
38    #[must_use]
39    pub fn delta_seconds(&self) -> f32 {
40        self.delta.as_secs_f32()
41    }
42
43    /// Returns total running game time as an easy-to-use `f32` value.
44    #[must_use]
45    pub fn elapsed_seconds(&self) -> f32 {
46        self.elapsed.as_secs_f32()
47    }
48}
49
50/// Pause, stepping, scale, and fixed-schedule catch-up controls.
51#[derive(Resource, Clone, Debug)]
52pub struct TimeControl {
53    /// Whether variable time and ordinary fixed-schedule executions are paused.
54    pub paused: bool,
55    /// Multiplier applied to real time while the simulation is running.
56    pub time_scale: f64,
57    /// Time simulated by one fixed-schedule execution.
58    pub fixed_delta: Duration,
59    /// Maximum number of accumulated fixed-schedule executions run per application update.
60    pub max_fixed_steps: u32,
61    accumulator: Duration,
62    pending_steps: u32,
63}
64
65impl Default for TimeControl {
66    fn default() -> Self {
67        Self {
68            paused: false,
69            time_scale: 1.0,
70            fixed_delta: Duration::from_secs_f64(1.0 / 60.0),
71            max_fixed_steps: 8,
72            accumulator: Duration::ZERO,
73            pending_steps: 0,
74        }
75    }
76}
77
78impl TimeControl {
79    /// Pauses variable time and ordinary fixed-schedule executions.
80    pub fn pause(&mut self) {
81        self.paused = true;
82    }
83
84    /// Resumes variable time and ordinary fixed-schedule executions.
85    pub fn resume(&mut self) {
86        self.paused = false;
87    }
88
89    /// Queues one fixed-schedule execution to be consumed while paused.
90    pub fn step(&mut self) {
91        self.pending_steps = self.pending_steps.saturating_add(1);
92    }
93}
94
95/// Errors produced while advancing simulation time.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum TimeAdvanceError {
98    /// The configured fixed timestep is zero.
99    InvalidFixedDelta,
100}
101
102impl fmt::Display for TimeAdvanceError {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            Self::InvalidFixedDelta => {
106                formatter.write_str("fixed delta must be greater than zero")
107            }
108        }
109    }
110}
111
112impl Error for TimeAdvanceError {}
113
114/// Advances frame and fixed-schedule bookkeeping by one application update.
115///
116/// Catch-up work is capped by [`TimeControl::max_fixed_steps`]. Remaining
117/// accumulated time is retained for later updates, up to one more capped
118/// update's worth; older backlog is dropped. A queued step is
119/// consumed only while paused and advances elapsed time by exactly one fixed
120/// timestep without consuming the accumulator.
121///
122/// # Errors
123///
124/// Returns [`TimeAdvanceError::InvalidFixedDelta`] when `control.fixed_delta`
125/// is zero, before mutating either the supplied [`TimeControl`] or
126/// [`FrameTime`].
127///
128/// # Panics
129///
130/// After fixed-delta validation, when the simulation is not paused, this may
131/// panic if `control.time_scale` is positive and non-finite, or if scaling
132/// `real_delta` by the non-negative time scale cannot be represented by
133/// [`Duration::mul_f64`]. Negative and `NaN` time scales are clamped to zero
134/// and do not panic.
135pub fn advance(
136    control: &mut TimeControl,
137    time: &mut FrameTime,
138    real_delta: Duration,
139) -> Result<u32, TimeAdvanceError> {
140    if control.fixed_delta.is_zero() {
141        return Err(TimeAdvanceError::InvalidFixedDelta);
142    }
143
144    let scaled_delta = if control.paused {
145        Duration::ZERO
146    } else {
147        real_delta.mul_f64(control.time_scale.max(0.0))
148    };
149    control.accumulator = control.accumulator.saturating_add(scaled_delta);
150
151    let mut fixed_steps = 0;
152    let fixed_delta = control.fixed_delta;
153    while control.accumulator >= fixed_delta
154        && fixed_steps < control.max_fixed_steps
155        && !control.paused
156    {
157        control.accumulator -= fixed_delta;
158        fixed_steps += 1;
159    }
160    if !control.paused && control.max_fixed_steps > 0 {
161        // Keep at most one more capped update of backlog, so one long stall
162        // does not make many later frames run the maximum number of steps.
163        control.accumulator = control
164            .accumulator
165            .min(fixed_delta.saturating_mul(control.max_fixed_steps));
166    }
167    let stepped_while_paused = control.paused && control.pending_steps > 0;
168    if stepped_while_paused {
169        control.pending_steps -= 1;
170        fixed_steps = 1;
171    }
172    let elapsed_delta = if stepped_while_paused {
173        fixed_delta
174    } else {
175        scaled_delta
176    };
177
178    time.frame = time.frame.saturating_add(1);
179    time.real_delta = real_delta;
180    time.delta = scaled_delta;
181    time.elapsed = time.elapsed.saturating_add(elapsed_delta);
182    time.fixed_delta = fixed_delta;
183    time.fixed_tick = time.fixed_tick.saturating_add(u64::from(fixed_steps));
184    Ok(fixed_steps)
185}
186
187/// Seed for gameplay randomness. Draw values with [`RandomSeed::value`],
188/// indexed by the fixed tick and a stream from [`RandomSeed::stream`], so a
189/// run repeats exactly for the same seed. Scenario tests set the seed they
190/// record. Simulation code takes all its randomness from here, never from a
191/// global or thread-local generator.
192#[derive(Resource, Clone, Copy, Debug, Default, PartialEq, Eq)]
193pub struct RandomSeed(pub u64);
194
195impl RandomSeed {
196    /// Uniform 64-bit value for `stream` at fixed `tick`. The same seed,
197    /// tick and stream always give the same value.
198    #[must_use]
199    pub fn value(self, tick: u64, stream: u64) -> u64 {
200        splitmix64(self.0 ^ splitmix64(tick ^ splitmix64(stream)))
201    }
202
203    /// Stream `key` of the subsystem called `subsystem`, such as
204    /// `"bursts"`. The name is hashed in, so two subsystems that pick the
205    /// same keys still draw independent values.
206    #[must_use]
207    pub fn stream(subsystem: &str, key: u64) -> u64 {
208        // FNV-1a over the name.
209        let name =
210            subsystem
211                .bytes()
212                .fold(0xCBF2_9CE4_8422_2325_u64, |hash, byte| {
213                    (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01B3)
214                });
215        splitmix64(name ^ splitmix64(key))
216    }
217
218    /// Uniform value in `[0, 1)` for `stream` at fixed `tick`.
219    #[must_use]
220    pub fn unit(self, tick: u64, stream: u64) -> f32 {
221        (self.value(tick, stream) >> 40) as f32 / (1_u64 << 24) as f32
222    }
223}
224
225fn splitmix64(mut value: u64) -> u64 {
226    value = value.wrapping_add(0x9E37_79B9_7F4A_7C15);
227    value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
228    value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
229    value ^ (value >> 31)
230}
231
232#[cfg(test)]
233mod tests {
234    use std::time::Duration;
235
236    use bevy_ecs::prelude::Resource;
237
238    use super::{
239        advance, FrameTime, RandomSeed, TimeAdvanceError, TimeControl,
240    };
241
242    #[test]
243    fn default_starts_at_frame_zero_with_sixty_hz_fixed_delta() {
244        let time = FrameTime::default();
245
246        assert_eq!(time.frame, 0);
247        assert_eq!(time.real_delta, Duration::ZERO);
248        assert_eq!(time.delta, Duration::ZERO);
249        assert_eq!(time.elapsed, Duration::ZERO);
250        assert_eq!(time.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
251        assert_eq!(time.fixed_tick, 0);
252    }
253
254    #[test]
255    fn duration_accessors_return_seconds() {
256        let time = FrameTime {
257            delta: Duration::from_millis(125),
258            elapsed: Duration::from_millis(2_500),
259            ..FrameTime::default()
260        };
261
262        assert_eq!(time.delta_seconds(), 0.125);
263        assert_eq!(time.elapsed_seconds(), 2.5);
264    }
265
266    #[test]
267    fn frame_time_is_an_ecs_resource() {
268        fn assert_resource<T: Resource>() {}
269
270        assert_resource::<FrameTime>();
271    }
272
273    #[test]
274    fn frame_time_is_clone_and_copy() {
275        fn assert_clone_copy<T: Clone + Copy>() {}
276
277        assert_clone_copy::<FrameTime>();
278    }
279
280    #[test]
281    fn time_control_defaults_and_public_traits_are_stable() {
282        fn assert_resource_clone_debug<
283            T: Resource + Clone + std::fmt::Debug,
284        >() {
285        }
286        fn assert_error_traits<T: std::error::Error + Clone + Copy + Eq>() {}
287
288        assert_resource_clone_debug::<TimeControl>();
289        assert_error_traits::<TimeAdvanceError>();
290
291        let control = TimeControl::default();
292        assert!(!control.paused);
293        assert_eq!(control.time_scale, 1.0);
294        assert_eq!(control.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
295        assert_eq!(control.max_fixed_steps, 8);
296        assert_eq!(control.accumulator, Duration::ZERO);
297        assert_eq!(control.pending_steps, 0);
298        assert_eq!(
299            TimeAdvanceError::InvalidFixedDelta.to_string(),
300            "fixed delta must be greater than zero"
301        );
302    }
303
304    #[test]
305    fn normal_scaled_advance_updates_all_bookkeeping() {
306        let mut control = TimeControl {
307            time_scale: 0.5,
308            fixed_delta: Duration::from_millis(10),
309            ..TimeControl::default()
310        };
311        let mut time = FrameTime::default();
312
313        assert_eq!(
314            advance(&mut control, &mut time, Duration::from_millis(25)),
315            Ok(1)
316        );
317        assert_eq!(control.accumulator, Duration::from_micros(2_500));
318        assert_eq!(time.frame, 1);
319        assert_eq!(time.real_delta, Duration::from_millis(25));
320        assert_eq!(time.delta, Duration::from_micros(12_500));
321        assert_eq!(time.elapsed, Duration::from_micros(12_500));
322        assert_eq!(time.fixed_delta, Duration::from_millis(10));
323        assert_eq!(time.fixed_tick, 1);
324    }
325
326    #[test]
327    fn catch_up_cap_retains_backlog_for_later_frames() {
328        let mut control = TimeControl {
329            fixed_delta: Duration::from_millis(10),
330            max_fixed_steps: 2,
331            ..TimeControl::default()
332        };
333        let mut time = FrameTime::default();
334
335        assert_eq!(
336            advance(&mut control, &mut time, Duration::from_millis(35)),
337            Ok(2)
338        );
339        assert_eq!(control.accumulator, Duration::from_millis(15));
340        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
341        assert_eq!(control.accumulator, Duration::from_millis(5));
342        assert_eq!(time.fixed_tick, 3);
343        assert_eq!(time.elapsed, Duration::from_millis(35));
344    }
345
346    #[test]
347    fn pause_drains_one_queued_step_per_update_and_resume_restores_time() {
348        let mut control = TimeControl {
349            fixed_delta: Duration::from_millis(10),
350            ..TimeControl::default()
351        };
352        let mut time = FrameTime::default();
353        control.pause();
354        control.step();
355        control.step();
356
357        assert_eq!(
358            advance(&mut control, &mut time, Duration::from_secs(1)),
359            Ok(1)
360        );
361        assert_eq!(time.delta, Duration::ZERO);
362        assert_eq!(time.elapsed, Duration::from_millis(10));
363        assert_eq!(control.pending_steps, 1);
364        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
365        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(0));
366
367        control.resume();
368        assert_eq!(
369            advance(&mut control, &mut time, Duration::from_millis(10)),
370            Ok(1)
371        );
372        assert_eq!(time.elapsed, Duration::from_millis(30));
373        assert_eq!(time.fixed_tick, 3);
374    }
375
376    #[test]
377    fn steps_queued_while_running_persist_until_paused() {
378        let mut control = TimeControl {
379            fixed_delta: Duration::from_millis(10),
380            ..TimeControl::default()
381        };
382        let mut time = FrameTime::default();
383        control.step();
384
385        assert_eq!(
386            advance(&mut control, &mut time, Duration::from_millis(10)),
387            Ok(1)
388        );
389        assert_eq!(control.pending_steps, 1);
390        control.pause();
391        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
392        assert_eq!(control.pending_steps, 0);
393    }
394
395    #[test]
396    fn negative_and_nan_time_scales_clamp_to_zero() {
397        for scale in [-1.0, f64::NAN] {
398            let mut control = TimeControl {
399                time_scale: scale,
400                fixed_delta: Duration::from_millis(10),
401                ..TimeControl::default()
402            };
403            let mut time = FrameTime::default();
404
405            assert_eq!(
406                advance(&mut control, &mut time, Duration::from_secs(1)),
407                Ok(0)
408            );
409            assert_eq!(control.accumulator, Duration::ZERO);
410            assert_eq!(time.delta, Duration::ZERO);
411            assert_eq!(time.elapsed, Duration::ZERO);
412        }
413    }
414
415    #[test]
416    #[should_panic]
417    fn positive_infinite_time_scale_panics_while_running() {
418        let mut control = TimeControl {
419            time_scale: f64::INFINITY,
420            ..TimeControl::default()
421        };
422        let mut time = FrameTime::default();
423
424        let _ = advance(&mut control, &mut time, Duration::from_secs(1));
425    }
426
427    #[test]
428    fn long_stall_backlog_is_bounded_to_one_capped_update() {
429        let mut control = TimeControl {
430            fixed_delta: Duration::from_millis(10),
431            max_fixed_steps: 2,
432            ..TimeControl::default()
433        };
434        let mut time = FrameTime::default();
435
436        assert_eq!(
437            advance(&mut control, &mut time, Duration::from_secs(5)),
438            Ok(2)
439        );
440        assert_eq!(control.accumulator, Duration::from_millis(20));
441        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(2));
442        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(0));
443    }
444
445    #[test]
446    fn zero_max_fixed_steps_retains_the_entire_backlog() {
447        let mut control = TimeControl {
448            fixed_delta: Duration::from_millis(10),
449            max_fixed_steps: 0,
450            ..TimeControl::default()
451        };
452        let mut time = FrameTime::default();
453
454        assert_eq!(
455            advance(&mut control, &mut time, Duration::from_millis(25)),
456            Ok(0)
457        );
458        assert_eq!(control.accumulator, Duration::from_millis(25));
459        assert_eq!(time.elapsed, Duration::from_millis(25));
460        assert_eq!(time.fixed_tick, 0);
461    }
462
463    #[test]
464    fn zero_fixed_delta_errors_before_mutating_either_resource() {
465        let mut control = TimeControl {
466            paused: true,
467            time_scale: 2.0,
468            fixed_delta: Duration::ZERO,
469            max_fixed_steps: 3,
470            accumulator: Duration::from_millis(7),
471            pending_steps: 2,
472        };
473        let mut time = FrameTime {
474            frame: 4,
475            real_delta: Duration::from_millis(1),
476            delta: Duration::from_millis(2),
477            elapsed: Duration::from_millis(3),
478            fixed_delta: Duration::from_millis(4),
479            fixed_tick: 5,
480        };
481
482        assert_eq!(
483            advance(&mut control, &mut time, Duration::from_secs(1)),
484            Err(TimeAdvanceError::InvalidFixedDelta)
485        );
486        assert!(control.paused);
487        assert_eq!(control.time_scale, 2.0);
488        assert_eq!(control.fixed_delta, Duration::ZERO);
489        assert_eq!(control.max_fixed_steps, 3);
490        assert_eq!(control.accumulator, Duration::from_millis(7));
491        assert_eq!(control.pending_steps, 2);
492        assert_eq!(time.frame, 4);
493        assert_eq!(time.real_delta, Duration::from_millis(1));
494        assert_eq!(time.delta, Duration::from_millis(2));
495        assert_eq!(time.elapsed, Duration::from_millis(3));
496        assert_eq!(time.fixed_delta, Duration::from_millis(4));
497        assert_eq!(time.fixed_tick, 5);
498    }
499
500    #[test]
501    fn paused_updates_and_steps_preserve_accumulated_partial_time() {
502        let mut control = TimeControl {
503            fixed_delta: Duration::from_millis(10),
504            ..TimeControl::default()
505        };
506        let mut time = FrameTime::default();
507        advance(&mut control, &mut time, Duration::from_millis(6)).unwrap();
508        control.pause();
509        advance(&mut control, &mut time, Duration::from_secs(1)).unwrap();
510        control.step();
511        advance(&mut control, &mut time, Duration::ZERO).unwrap();
512        assert_eq!(control.accumulator, Duration::from_millis(6));
513
514        control.resume();
515        assert_eq!(
516            advance(&mut control, &mut time, Duration::from_millis(4)),
517            Ok(1)
518        );
519        assert_eq!(control.accumulator, Duration::ZERO);
520    }
521
522    #[test]
523    fn counters_durations_and_step_queue_saturate() {
524        let mut control = TimeControl {
525            paused: true,
526            fixed_delta: Duration::from_nanos(1),
527            accumulator: Duration::MAX,
528            pending_steps: u32::MAX,
529            ..TimeControl::default()
530        };
531        control.step();
532        assert_eq!(control.pending_steps, u32::MAX);
533
534        let mut time = FrameTime {
535            frame: u64::MAX,
536            elapsed: Duration::MAX,
537            fixed_tick: u64::MAX,
538            ..FrameTime::default()
539        };
540        assert_eq!(advance(&mut control, &mut time, Duration::MAX), Ok(1));
541        assert_eq!(control.accumulator, Duration::MAX);
542        assert_eq!(control.pending_steps, u32::MAX - 1);
543        assert_eq!(time.frame, u64::MAX);
544        assert_eq!(time.elapsed, Duration::MAX);
545        assert_eq!(time.fixed_tick, u64::MAX);
546    }
547
548    #[test]
549    fn random_seed_repeats_per_seed_tick_and_stream() {
550        let seed = RandomSeed(42);
551        assert_eq!(seed.value(3, 1), RandomSeed(42).value(3, 1));
552        assert_ne!(seed.value(3, 1), seed.value(4, 1));
553        assert_ne!(seed.value(3, 1), seed.value(3, 2));
554        assert_ne!(seed.value(3, 1), RandomSeed(43).value(3, 1));
555        let units: Vec<_> = (0..1000).map(|tick| seed.unit(tick, 0)).collect();
556        assert!(units.iter().all(|unit| (0.0..1.0).contains(unit)));
557        let mean = units.iter().sum::<f32>() / units.len() as f32;
558        assert!((0.45..0.55).contains(&mean), "{mean}");
559    }
560
561    #[test]
562    fn subsystem_streams_are_independent_and_fixed() {
563        let bursts = RandomSeed::stream("bursts", 7);
564        assert_eq!(bursts, RandomSeed::stream("bursts", 7));
565        assert_ne!(bursts, RandomSeed::stream("bursts", 8));
566        assert_ne!(bursts, RandomSeed::stream("spawner", 7));
567        // Pinned so a replay recorded today draws the same values later.
568        assert_eq!(RandomSeed(42).value(3, bursts), 5_142_468_438_960_481_807);
569    }
570}