Skip to main content

astrelis_winit/
time.rs

1use std::time::{Duration, Instant};
2
3use astrelis_core::profiling::profile_function;
4
5/// Frame timing information for the app lifecycle.
6///
7/// This is a simplified time struct used by the winit app loop.
8/// For more advanced time features (time scale, fixed timestep, etc.),
9/// use the `Time` resource from the main `astrelis` crate.
10///
11/// # Example
12///
13/// ```no_run
14/// use astrelis_winit::app::{App, AppCtx};
15/// use astrelis_winit::{FrameTime, WindowId};
16/// use astrelis_winit::event::EventBatch;
17/// use astrelis_winit::window::WindowBackend;
18///
19/// struct MyApp;
20///
21/// impl App for MyApp {
22///     fn update(&mut self, _ctx: &mut AppCtx, time: &FrameTime) {
23///         let dt = time.delta_seconds();
24///         // Use dt for frame-independent movement
25///         let _ = dt; // silence unused warning
26///     }
27///
28///     fn render(&mut self, _ctx: &mut AppCtx, _window_id: WindowId, _events: &mut EventBatch) {
29///         // rendering
30///     }
31/// }
32/// ```
33#[derive(Debug, Clone)]
34pub struct FrameTime {
35    /// Time elapsed since the last frame
36    pub delta: Duration,
37    /// Total time elapsed since app start
38    pub elapsed: Duration,
39    /// Total number of frames rendered
40    pub frame_count: u64,
41}
42
43impl FrameTime {
44    pub fn new() -> Self {
45        Self {
46            delta: Duration::ZERO,
47            elapsed: Duration::ZERO,
48            frame_count: 0,
49        }
50    }
51
52    /// Returns delta time in seconds (f32)
53    #[inline]
54    pub fn delta_seconds(&self) -> f32 {
55        self.delta.as_secs_f32()
56    }
57
58    /// Returns elapsed time in seconds (f32)
59    #[inline]
60    pub fn elapsed_seconds(&self) -> f32 {
61        self.elapsed.as_secs_f32()
62    }
63}
64
65impl Default for FrameTime {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71/// Tracks time for the app loop
72pub(crate) struct TimeTracker {
73    start_time: Instant,
74    last_frame_time: Instant,
75    frame_count: u64,
76}
77
78impl TimeTracker {
79    pub fn new() -> Self {
80        let now = Instant::now();
81        Self {
82            start_time: now,
83            last_frame_time: now,
84            frame_count: 0,
85        }
86    }
87
88    pub fn tick(&mut self) -> FrameTime {
89        profile_function!();
90        let now = Instant::now();
91        let delta = now.duration_since(self.last_frame_time);
92        let elapsed = now.duration_since(self.start_time);
93
94        self.last_frame_time = now;
95        self.frame_count += 1;
96
97        FrameTime {
98            delta,
99            elapsed,
100            frame_count: self.frame_count,
101        }
102    }
103}