Skip to main content

euv_core/game/clock/
impl.rs

1use super::*;
2
3/// Default 60Hz integer-nanosecond fixed-timestep `FrameClock` with 8-substep safety cap.
4impl Default for FrameClock {
5    /// Creates a `FrameClock` configured for 60Hz (`16_666_667 ns`) fixed simulation steps.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default 60Hz game clock.
10    fn default() -> Self {
11        Self::from_fixed_step_ns(CLOCK_DEFAULT_FIXED_STEP_NS, CLOCK_DEFAULT_MAX_SUBSTEPS)
12    }
13}
14
15/// Nanosecond fixed-step accumulation, VSync hysteresis snapping, and dt-invariant FPS telemetry for `FrameClock`.
16impl FrameClock {
17    /// Constructs a `FrameClock` from a fixed timestep in seconds and substep cap.
18    ///
19    /// # Arguments
20    ///
21    /// - `f32` - Fixed simulation timestep in seconds (e.g. `1.0 / 60.0`).
22    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - Configured integer-nanosecond frame clock.
27    #[must_use]
28    pub fn new(fixed_dt: f32, max_substeps: u32) -> Self {
29        let safe_dt: f32 = if fixed_dt.is_finite() {
30            fixed_dt.max(0.000_1)
31        } else {
32            1.0 / 60.0
33        };
34        let step_ns: u64 = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
35            .round()
36            .max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
37        Self::from_fixed_step_ns(step_ns, max_substeps)
38    }
39
40    /// Constructs a `FrameClock` directly from an exact integer-nanosecond simulation period.
41    ///
42    /// # Arguments
43    ///
44    /// - `u64` - Fixed simulation step duration in nanoseconds (`16_666_667` for 60Hz, `8_333_333` for 120Hz).
45    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
46    ///
47    /// # Returns
48    ///
49    /// - `Self` - Configured integer-nanosecond frame clock.
50    #[must_use]
51    pub fn from_fixed_step_ns(fixed_step_ns: u64, max_substeps: u32) -> Self {
52        let safe_ns: u64 = fixed_step_ns.max(CLOCK_MIN_FIXED_STEP_NS);
53        Self {
54            fixed_dt: ((safe_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
55            fixed_step_ns: safe_ns,
56            max_substeps: max_substeps.max(1),
57            accumulator_ns: 0,
58            accumulator: 0.0,
59            delta_ns: 0,
60            delta_secs: 0.0,
61            elapsed_ns: 0,
62            elapsed_secs: 0.0,
63            alpha: 0.0,
64            fps: 0.0,
65            frame_count: 0,
66            fixed_step_count: 0,
67        }
68    }
69
70    /// Constructs a `FrameClock` for an integer simulation frequency in Hertz (e.g. `60` or `120`).
71    ///
72    /// # Arguments
73    ///
74    /// - `u32` - Simulation tick frequency in Hertz (`1..=1000`).
75    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
76    ///
77    /// # Returns
78    ///
79    /// - `Self` - Configured integer-nanosecond frame clock.
80    #[must_use]
81    pub fn for_sim_hz(sim_hz: u32, max_substeps: u32) -> Self {
82        let clamped_hz: u64 = (sim_hz.clamp(1, 1000)) as u64;
83        let step_ns: u64 = (CLOCK_NS_PER_SEC + clamped_hz / 2) / clamped_hz;
84        Self::from_fixed_step_ns(step_ns, max_substeps)
85    }
86
87    /// Returns the ±0.5% VSync-boundary hysteresis snap window in nanoseconds (`±83_333 ns` at 60Hz).
88    ///
89    /// # Arguments
90    ///
91    /// - `&Self` - Frame clock reference.
92    ///
93    /// # Returns
94    ///
95    /// - `u64` - Hysteresis tolerance window in nanoseconds.
96    #[must_use]
97    pub fn hysteresis_window_ns(&self) -> u64 {
98        let safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
99        (safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1)
100    }
101
102    /// Advances the clock by `raw_dt_ns` nanoseconds using ±0.5% VSync-boundary hysteresis snapping and dt-invariant FPS smoothing.
103    ///
104    /// # Arguments
105    ///
106    /// - `&Self` - Mutable frame clock.
107    /// - `u64` - Unclamped elapsed nanoseconds since the previous frame.
108    ///
109    /// # Returns
110    ///
111    /// - `u32` - Number of fixed-timestep simulation updates to execute this frame.
112    pub fn tick_ns(&mut self, raw_dt_ns: u64) -> u32 {
113        let mut safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
114        let expected_dt_f32: f32 = ((safe_fixed_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
115        if (self.get_fixed_dt() - expected_dt_f32).abs() > 1e-5 && self.get_fixed_dt().is_finite() {
116            let safe_dt: f32 = self.get_fixed_dt().max(0.000_1);
117            safe_fixed_ns = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
118                .round()
119                .max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
120            self.set_fixed_step_ns(safe_fixed_ns);
121        }
122        let dt_ns: u64 = raw_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
123        let dt_secs: f32 = ((dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
124        self.set_delta_ns(dt_ns);
125        self.set_delta_secs(dt_secs);
126        let next_elapsed_ns: u64 = self.get_elapsed_ns().saturating_add(dt_ns);
127        self.set_elapsed_ns(next_elapsed_ns);
128        self.set_elapsed_secs((next_elapsed_ns as f64) / CLOCK_NS_PER_SEC_F64);
129        self.set_frame_count(self.get_frame_count().saturating_add(1));
130        if dt_ns > 0 {
131            let inst_fps: f32 = (CLOCK_NS_PER_SEC_F64 / (dt_ns as f64)) as f32;
132            let prev_fps: f32 = self.get_fps();
133            let smoothed: f32 = if prev_fps <= 0.0 {
134                inst_fps
135            } else {
136                let ema_alpha: f32 =
137                    (1.0 - (-dt_secs / CLOCK_FPS_EMA_TAU_SECS).exp()).clamp(0.0, 1.0);
138                prev_fps + (inst_fps - prev_fps) * ema_alpha
139            };
140            self.set_fps(smoothed);
141        }
142        let snap_window_ns: u64 = (safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1);
143        let mut acc_ns: u64 = self.get_accumulator_ns().saturating_add(dt_ns);
144        let rem_before: u64 = acc_ns % safe_fixed_ns;
145        if rem_before > 0 && safe_fixed_ns - rem_before <= snap_window_ns {
146            acc_ns = acc_ns.saturating_add(safe_fixed_ns - rem_before);
147        }
148        let max_steps: u32 = self.get_max_substeps().max(1);
149        let mut steps: u32 = 0;
150        while acc_ns >= safe_fixed_ns && steps < max_steps {
151            acc_ns -= safe_fixed_ns;
152            steps += 1;
153        }
154        if (steps == max_steps && acc_ns >= safe_fixed_ns)
155            || (steps > 0 && acc_ns <= snap_window_ns)
156        {
157            acc_ns = 0;
158        }
159        self.set_accumulator_ns(acc_ns);
160        self.set_accumulator(((acc_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32);
161        self.set_alpha(((acc_ns as f64) / (safe_fixed_ns as f64)).clamp(0.0, 1.0) as f32);
162        self.set_fixed_step_count(self.get_fixed_step_count().saturating_add(steps as u64));
163        steps
164    }
165
166    /// Advances the clock by `raw_dt_secs` seconds (converted to integer nanoseconds) and returns how many fixed simulation steps to execute.
167    ///
168    /// # Arguments
169    ///
170    /// - `&Self` - Mutable frame clock.
171    /// - `f32` - Unclamped elapsed seconds since the previous frame.
172    ///
173    /// # Returns
174    ///
175    /// - `u32` - Number of fixed-timestep updates to run this frame.
176    pub fn tick(&mut self, raw_dt_secs: f32) -> u32 {
177        let dt_ns: u64 = if raw_dt_secs.is_finite() && raw_dt_secs > 0.0 {
178            ((raw_dt_secs.clamp(0.0, 0.25) as f64) * CLOCK_NS_PER_SEC_F64).round() as u64
179        } else {
180            0
181        };
182        self.tick_ns(dt_ns)
183    }
184}
185
186/// Default 60Hz fixed simulation / 60Hz presentation `FixedTimestep3DSession`.
187impl Default for FixedTimestep3DSession {
188    /// Creates a `FixedTimestep3DSession` with 60Hz fixed simulation, 8 max substeps, and 60Hz presentation cadence.
189    ///
190    /// # Returns
191    ///
192    /// - `Self` - Default decoupled 3D simulation session.
193    fn default() -> Self {
194        Self::new(60, CLOCK_DEFAULT_MAX_SUBSTEPS, 60.0)
195    }
196}
197
198/// Decoupled fixed-timestep simulation stepping and render interpolation helpers for `FixedTimestep3DSession`.
199impl FixedTimestep3DSession {
200    /// Constructs a `FixedTimestep3DSession` with explicit fixed simulation frequency, substep cap, and presentation cadence.
201    ///
202    /// # Arguments
203    ///
204    /// - `u32` - Fixed simulation frequency in Hertz (`1..=1000`).
205    /// - `u32` - Maximum fixed substeps allowed per presentation frame to prevent spiral-of-death stalls.
206    /// - `f32` - Display presentation cadence in Hertz (e.g. `60.0`, `120.0`, `144.0`, `240.0`).
207    ///
208    /// # Returns
209    ///
210    /// - `Self` - Configured decoupled 3D simulation session.
211    #[must_use]
212    pub fn new(sim_hz: u32, max_substeps: u32, present_hz: f32) -> Self {
213        let safe_present_hz: f32 = if present_hz.is_finite() {
214            present_hz.clamp(1.0, 1000.0)
215        } else {
216            60.0
217        };
218        Self {
219            clock: FrameClock::for_sim_hz(sim_hz, max_substeps),
220            present_hz: safe_present_hz,
221            sim_steps_total: 0,
222            present_frames_total: 0,
223            interpolated_only_frames: 0,
224            clamped_stall_frames: 0,
225            last_alpha: 0.0,
226            last_steps: 0,
227        }
228    }
229
230    /// Updates the display presentation cadence in Hertz without altering the fixed simulation timestep or accumulator.
231    ///
232    /// # Arguments
233    ///
234    /// - `&Self` - Mutable simulation session.
235    /// - `f32` - New presentation cadence in Hertz (`1.0..=1000.0`).
236    pub fn set_present_cadence_hz(&mut self, present_hz: f32) {
237        if present_hz.is_finite() {
238            self.set_present_hz(present_hz.clamp(1.0, 1000.0));
239        }
240    }
241
242    /// Advances the decoupled loop by `present_dt_ns` nanoseconds, executing only the required fixed simulation steps and returning render interpolation `alpha`.
243    ///
244    /// # Arguments
245    ///
246    /// - `&Self` - Mutable simulation session.
247    /// - `u64` - Elapsed presentation interval in integer nanoseconds.
248    /// - `CallbackFn` - Fixed-timestep simulation callback invoked once per fixed substep with `fixed_dt_secs`.
249    ///
250    /// # Returns
251    ///
252    /// - `SimPresentFrame` - Per-present step count, interpolation alpha, and clamp flags.
253    pub fn advance_present_ns<CallbackFn>(
254        &mut self,
255        present_dt_ns: u64,
256        mut step_sim: CallbackFn,
257    ) -> SimPresentFrame
258    where
259        CallbackFn: FnMut(f32),
260    {
261        let fixed_ns: u64 = self
262            .get_clock()
263            .get_fixed_step_ns()
264            .max(CLOCK_MIN_FIXED_STEP_NS);
265        let max_substeps: u32 = self.get_clock().get_max_substeps().max(1);
266        let pre_acc_ns: u64 = self.get_clock().get_accumulator_ns();
267        let clamped_dt_ns: u64 = present_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
268        let uncapped_steps: u64 = pre_acc_ns.saturating_add(clamped_dt_ns) / fixed_ns;
269        let hit_clamp: bool =
270            present_dt_ns > CLOCK_MAX_FRAME_DT_NS || uncapped_steps > (max_substeps as u64);
271        let steps: u32 = self.get_mut_clock().tick_ns(present_dt_ns);
272        let fixed_dt: f32 = self.get_clock().get_fixed_dt();
273        let alpha: f32 = self.get_clock().get_alpha();
274        let present_dt_secs: f32 = self.get_clock().get_delta_secs();
275        for _ in 0..steps {
276            step_sim(fixed_dt);
277        }
278        let interpolated_only: bool = steps == 0;
279        self.set_sim_steps_total(self.get_sim_steps_total().saturating_add(steps as u64));
280        self.set_present_frames_total(self.get_present_frames_total().saturating_add(1));
281        if interpolated_only {
282            self.set_interpolated_only_frames(
283                self.get_interpolated_only_frames().saturating_add(1),
284            );
285        }
286        if hit_clamp {
287            self.set_clamped_stall_frames(self.get_clamped_stall_frames().saturating_add(1));
288        }
289        self.set_last_alpha(alpha);
290        self.set_last_steps(steps);
291        SimPresentFrame::new(
292            steps,
293            alpha,
294            fixed_dt,
295            present_dt_secs,
296            interpolated_only,
297            hit_clamp,
298        )
299    }
300
301    /// Advances the decoupled loop by `present_dt_secs` seconds (converted to integer nanoseconds) and returns render interpolation metadata.
302    ///
303    /// # Arguments
304    ///
305    /// - `&Self` - Mutable simulation session.
306    /// - `f32` - Elapsed presentation interval in seconds.
307    /// - `CallbackFn` - Fixed-timestep simulation callback invoked once per fixed substep with `fixed_dt_secs`.
308    ///
309    /// # Returns
310    ///
311    /// - `SimPresentFrame` - Per-present step count, interpolation alpha, and clamp flags.
312    pub fn advance_present<CallbackFn>(
313        &mut self,
314        present_dt_secs: f32,
315        step_sim: CallbackFn,
316    ) -> SimPresentFrame
317    where
318        CallbackFn: FnMut(f32),
319    {
320        let dt_ns: u64 = if present_dt_secs.is_finite() && present_dt_secs > 0.0 {
321            ((present_dt_secs.min(1.0) as f64) * CLOCK_NS_PER_SEC_F64).round() as u64
322        } else {
323            0
324        };
325        self.advance_present_ns(dt_ns, step_sim)
326    }
327
328    /// Linearly interpolates between `prev` and `next` simulation scalar values using `alpha` clamped to `[0.0, 1.0]`.
329    ///
330    /// # Arguments
331    ///
332    /// - `f32` - Previous fixed simulation scalar value.
333    /// - `f32` - Latest fixed simulation scalar value.
334    /// - `f32` - Render interpolation factor in `[0.0, 1.0]`.
335    ///
336    /// # Returns
337    ///
338    /// - `f32` - Smoothly interpolated render scalar value.
339    #[must_use]
340    pub fn interpolate_scalar(prev: f32, next: f32, alpha: f32) -> f32 {
341        let blend_factor: f32 = if alpha.is_finite() {
342            alpha.clamp(0.0, 1.0)
343        } else {
344            1.0
345        };
346        prev + (next - prev) * blend_factor
347    }
348}