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`], with any
117/// remaining accumulated time retained for later updates. A queued step is
118/// consumed only while paused and advances elapsed time by exactly one fixed
119/// timestep without consuming the accumulator.
120///
121/// # Errors
122///
123/// Returns [`TimeAdvanceError::InvalidFixedDelta`] when `control.fixed_delta`
124/// is zero, before mutating either the supplied [`TimeControl`] or
125/// [`FrameTime`].
126///
127/// # Panics
128///
129/// After fixed-delta validation, when the simulation is not paused, this may
130/// panic if `control.time_scale` is positive and non-finite, or if scaling
131/// `real_delta` by the non-negative time scale cannot be represented by
132/// [`Duration::mul_f64`]. Negative and `NaN` time scales are clamped to zero
133/// and do not panic.
134pub fn advance(
135    control: &mut TimeControl,
136    time: &mut FrameTime,
137    real_delta: Duration,
138) -> Result<u32, TimeAdvanceError> {
139    if control.fixed_delta.is_zero() {
140        return Err(TimeAdvanceError::InvalidFixedDelta);
141    }
142
143    let scaled_delta = if control.paused {
144        Duration::ZERO
145    } else {
146        real_delta.mul_f64(control.time_scale.max(0.0))
147    };
148    control.accumulator = control.accumulator.saturating_add(scaled_delta);
149
150    let mut fixed_steps = 0;
151    let fixed_delta = control.fixed_delta;
152    while control.accumulator >= fixed_delta
153        && fixed_steps < control.max_fixed_steps
154        && !control.paused
155    {
156        control.accumulator -= fixed_delta;
157        fixed_steps += 1;
158    }
159    let stepped_while_paused = control.paused && control.pending_steps > 0;
160    if stepped_while_paused {
161        control.pending_steps -= 1;
162        fixed_steps = 1;
163    }
164    let elapsed_delta = if stepped_while_paused {
165        fixed_delta
166    } else {
167        scaled_delta
168    };
169
170    time.frame = time.frame.saturating_add(1);
171    time.real_delta = real_delta;
172    time.delta = scaled_delta;
173    time.elapsed = time.elapsed.saturating_add(elapsed_delta);
174    time.fixed_delta = fixed_delta;
175    time.fixed_tick = time.fixed_tick.saturating_add(u64::from(fixed_steps));
176    Ok(fixed_steps)
177}
178
179#[cfg(test)]
180mod tests {
181    use std::time::Duration;
182
183    use bevy_ecs::prelude::Resource;
184
185    use super::{advance, FrameTime, TimeAdvanceError, TimeControl};
186
187    #[test]
188    fn default_starts_at_frame_zero_with_sixty_hz_fixed_delta() {
189        let time = FrameTime::default();
190
191        assert_eq!(time.frame, 0);
192        assert_eq!(time.real_delta, Duration::ZERO);
193        assert_eq!(time.delta, Duration::ZERO);
194        assert_eq!(time.elapsed, Duration::ZERO);
195        assert_eq!(time.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
196        assert_eq!(time.fixed_tick, 0);
197    }
198
199    #[test]
200    fn duration_accessors_return_seconds() {
201        let time = FrameTime {
202            delta: Duration::from_millis(125),
203            elapsed: Duration::from_millis(2_500),
204            ..FrameTime::default()
205        };
206
207        assert_eq!(time.delta_seconds(), 0.125);
208        assert_eq!(time.elapsed_seconds(), 2.5);
209    }
210
211    #[test]
212    fn frame_time_is_an_ecs_resource() {
213        fn assert_resource<T: Resource>() {}
214
215        assert_resource::<FrameTime>();
216    }
217
218    #[test]
219    fn frame_time_is_clone_and_copy() {
220        fn assert_clone_copy<T: Clone + Copy>() {}
221
222        assert_clone_copy::<FrameTime>();
223    }
224
225    #[test]
226    fn time_control_defaults_and_public_traits_are_stable() {
227        fn assert_resource_clone_debug<
228            T: Resource + Clone + std::fmt::Debug,
229        >() {
230        }
231        fn assert_error_traits<T: std::error::Error + Clone + Copy + Eq>() {}
232
233        assert_resource_clone_debug::<TimeControl>();
234        assert_error_traits::<TimeAdvanceError>();
235
236        let control = TimeControl::default();
237        assert!(!control.paused);
238        assert_eq!(control.time_scale, 1.0);
239        assert_eq!(control.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
240        assert_eq!(control.max_fixed_steps, 8);
241        assert_eq!(control.accumulator, Duration::ZERO);
242        assert_eq!(control.pending_steps, 0);
243        assert_eq!(
244            TimeAdvanceError::InvalidFixedDelta.to_string(),
245            "fixed delta must be greater than zero"
246        );
247    }
248
249    #[test]
250    fn normal_scaled_advance_updates_all_bookkeeping() {
251        let mut control = TimeControl {
252            time_scale: 0.5,
253            fixed_delta: Duration::from_millis(10),
254            ..TimeControl::default()
255        };
256        let mut time = FrameTime::default();
257
258        assert_eq!(
259            advance(&mut control, &mut time, Duration::from_millis(25)),
260            Ok(1)
261        );
262        assert_eq!(control.accumulator, Duration::from_micros(2_500));
263        assert_eq!(time.frame, 1);
264        assert_eq!(time.real_delta, Duration::from_millis(25));
265        assert_eq!(time.delta, Duration::from_micros(12_500));
266        assert_eq!(time.elapsed, Duration::from_micros(12_500));
267        assert_eq!(time.fixed_delta, Duration::from_millis(10));
268        assert_eq!(time.fixed_tick, 1);
269    }
270
271    #[test]
272    fn catch_up_cap_retains_backlog_for_later_frames() {
273        let mut control = TimeControl {
274            fixed_delta: Duration::from_millis(10),
275            max_fixed_steps: 2,
276            ..TimeControl::default()
277        };
278        let mut time = FrameTime::default();
279
280        assert_eq!(
281            advance(&mut control, &mut time, Duration::from_millis(35)),
282            Ok(2)
283        );
284        assert_eq!(control.accumulator, Duration::from_millis(15));
285        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
286        assert_eq!(control.accumulator, Duration::from_millis(5));
287        assert_eq!(time.fixed_tick, 3);
288        assert_eq!(time.elapsed, Duration::from_millis(35));
289    }
290
291    #[test]
292    fn pause_drains_one_queued_step_per_update_and_resume_restores_time() {
293        let mut control = TimeControl {
294            fixed_delta: Duration::from_millis(10),
295            ..TimeControl::default()
296        };
297        let mut time = FrameTime::default();
298        control.pause();
299        control.step();
300        control.step();
301
302        assert_eq!(
303            advance(&mut control, &mut time, Duration::from_secs(1)),
304            Ok(1)
305        );
306        assert_eq!(time.delta, Duration::ZERO);
307        assert_eq!(time.elapsed, Duration::from_millis(10));
308        assert_eq!(control.pending_steps, 1);
309        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
310        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(0));
311
312        control.resume();
313        assert_eq!(
314            advance(&mut control, &mut time, Duration::from_millis(10)),
315            Ok(1)
316        );
317        assert_eq!(time.elapsed, Duration::from_millis(30));
318        assert_eq!(time.fixed_tick, 3);
319    }
320
321    #[test]
322    fn steps_queued_while_running_persist_until_paused() {
323        let mut control = TimeControl {
324            fixed_delta: Duration::from_millis(10),
325            ..TimeControl::default()
326        };
327        let mut time = FrameTime::default();
328        control.step();
329
330        assert_eq!(
331            advance(&mut control, &mut time, Duration::from_millis(10)),
332            Ok(1)
333        );
334        assert_eq!(control.pending_steps, 1);
335        control.pause();
336        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
337        assert_eq!(control.pending_steps, 0);
338    }
339
340    #[test]
341    fn negative_and_nan_time_scales_clamp_to_zero() {
342        for scale in [-1.0, f64::NAN] {
343            let mut control = TimeControl {
344                time_scale: scale,
345                fixed_delta: Duration::from_millis(10),
346                ..TimeControl::default()
347            };
348            let mut time = FrameTime::default();
349
350            assert_eq!(
351                advance(&mut control, &mut time, Duration::from_secs(1)),
352                Ok(0)
353            );
354            assert_eq!(control.accumulator, Duration::ZERO);
355            assert_eq!(time.delta, Duration::ZERO);
356            assert_eq!(time.elapsed, Duration::ZERO);
357        }
358    }
359
360    #[test]
361    #[should_panic]
362    fn positive_infinite_time_scale_panics_while_running() {
363        let mut control = TimeControl {
364            time_scale: f64::INFINITY,
365            ..TimeControl::default()
366        };
367        let mut time = FrameTime::default();
368
369        let _ = advance(&mut control, &mut time, Duration::from_secs(1));
370    }
371
372    #[test]
373    fn zero_max_fixed_steps_retains_the_entire_backlog() {
374        let mut control = TimeControl {
375            fixed_delta: Duration::from_millis(10),
376            max_fixed_steps: 0,
377            ..TimeControl::default()
378        };
379        let mut time = FrameTime::default();
380
381        assert_eq!(
382            advance(&mut control, &mut time, Duration::from_millis(25)),
383            Ok(0)
384        );
385        assert_eq!(control.accumulator, Duration::from_millis(25));
386        assert_eq!(time.elapsed, Duration::from_millis(25));
387        assert_eq!(time.fixed_tick, 0);
388    }
389
390    #[test]
391    fn zero_fixed_delta_errors_before_mutating_either_resource() {
392        let mut control = TimeControl {
393            paused: true,
394            time_scale: 2.0,
395            fixed_delta: Duration::ZERO,
396            max_fixed_steps: 3,
397            accumulator: Duration::from_millis(7),
398            pending_steps: 2,
399        };
400        let mut time = FrameTime {
401            frame: 4,
402            real_delta: Duration::from_millis(1),
403            delta: Duration::from_millis(2),
404            elapsed: Duration::from_millis(3),
405            fixed_delta: Duration::from_millis(4),
406            fixed_tick: 5,
407        };
408
409        assert_eq!(
410            advance(&mut control, &mut time, Duration::from_secs(1)),
411            Err(TimeAdvanceError::InvalidFixedDelta)
412        );
413        assert!(control.paused);
414        assert_eq!(control.time_scale, 2.0);
415        assert_eq!(control.fixed_delta, Duration::ZERO);
416        assert_eq!(control.max_fixed_steps, 3);
417        assert_eq!(control.accumulator, Duration::from_millis(7));
418        assert_eq!(control.pending_steps, 2);
419        assert_eq!(time.frame, 4);
420        assert_eq!(time.real_delta, Duration::from_millis(1));
421        assert_eq!(time.delta, Duration::from_millis(2));
422        assert_eq!(time.elapsed, Duration::from_millis(3));
423        assert_eq!(time.fixed_delta, Duration::from_millis(4));
424        assert_eq!(time.fixed_tick, 5);
425    }
426
427    #[test]
428    fn paused_updates_and_steps_preserve_accumulated_partial_time() {
429        let mut control = TimeControl {
430            fixed_delta: Duration::from_millis(10),
431            ..TimeControl::default()
432        };
433        let mut time = FrameTime::default();
434        advance(&mut control, &mut time, Duration::from_millis(6)).unwrap();
435        control.pause();
436        advance(&mut control, &mut time, Duration::from_secs(1)).unwrap();
437        control.step();
438        advance(&mut control, &mut time, Duration::ZERO).unwrap();
439        assert_eq!(control.accumulator, Duration::from_millis(6));
440
441        control.resume();
442        assert_eq!(
443            advance(&mut control, &mut time, Duration::from_millis(4)),
444            Ok(1)
445        );
446        assert_eq!(control.accumulator, Duration::ZERO);
447    }
448
449    #[test]
450    fn counters_durations_and_step_queue_saturate() {
451        let mut control = TimeControl {
452            paused: true,
453            fixed_delta: Duration::from_nanos(1),
454            accumulator: Duration::MAX,
455            pending_steps: u32::MAX,
456            ..TimeControl::default()
457        };
458        control.step();
459        assert_eq!(control.pending_steps, u32::MAX);
460
461        let mut time = FrameTime {
462            frame: u64::MAX,
463            elapsed: Duration::MAX,
464            fixed_tick: u64::MAX,
465            ..FrameTime::default()
466        };
467        assert_eq!(advance(&mut control, &mut time, Duration::MAX), Ok(1));
468        assert_eq!(control.accumulator, Duration::MAX);
469        assert_eq!(control.pending_steps, u32::MAX - 1);
470        assert_eq!(time.frame, u64::MAX);
471        assert_eq!(time.elapsed, Duration::MAX);
472        assert_eq!(time.fixed_tick, u64::MAX);
473    }
474}