//! Wall-clock pacing for the fixed-step simulation. //! //! The physics step never changes: the wall clock only decides how many whole //! steps to run for the frame and how far behind the simulation has fallen. use std::time::{Duration, Instant}; /// Largest number of physics steps run for one rendered frame. pub(crate) const MAX_STEPS: u32 = 50; const NS_PER_S: u64 = 1_000_000_000; /// Wall time beyond this is treated as a stall and not caught up in full. const MAX_FRAME_NS: u64 = 250_000_000; /// The RTF measurement window, roughly one second. const WINDOW_NS: u64 = NS_PER_S; /// What one frame of wall time asks the simulation to do. #[derive(Debug, Clone, Copy, PartialEq)] pub(crate) struct Frame { /// Whole fixed steps to run before drawing. pub steps: u32, /// Paced wall time of the frame, seconds, capped after a stall. pub elapsed_seconds: f32, /// Simulated-to-wall ratio for the latest window, once one has filled. pub rtf: Option, } /// Whole steps that fit into `elapsed_ns`, capped at `max_steps`. #[must_use] pub(crate) fn steps_for(elapsed_ns: u64, step_ns: u64, max_steps: u32) -> u32 { if step_ns == 0 { return 0; } u32::try_from(elapsed_ns / step_ns) .unwrap_or(max_steps) .min(max_steps) } /// Converts a wall-clock duration to whole nanoseconds without overflowing. fn nanos(duration: Duration) -> u64 { u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX) } /// An accumulator that turns irregular frame time into fixed steps. pub(crate) struct Pacer { last: Instant, accumulator_ns: u64, window_wall_ns: u64, window_sim_ns: u64, } impl Pacer { #[allow( clippy::disallowed_methods, reason = "wall clock only paces the app loop" )] pub(crate) fn new() -> Self { Self { last: Instant::now(), accumulator_ns: 0, window_wall_ns: 0, window_sim_ns: 0, } } /// Consumes the time since the previous call and returns the steps to run. #[allow( clippy::disallowed_methods, reason = "wall clock only paces the app loop" )] pub(crate) fn advance(&mut self, step_ns: u64, max_steps: u32) -> Frame { let now = Instant::now(); let elapsed_ns = nanos(self.last.elapsed()); self.last = now; let paced_ns = elapsed_ns.min(MAX_FRAME_NS); self.accumulator_ns = self.accumulator_ns.saturating_add(paced_ns); let steps = steps_for(self.accumulator_ns, step_ns, max_steps); let consumed_ns = u64::from(steps).saturating_mul(step_ns); self.accumulator_ns = self.accumulator_ns.saturating_sub(consumed_ns); if steps == max_steps && self.accumulator_ns >= step_ns { // Drop the backlog instead of spiralling into ever longer frames. self.accumulator_ns = 0; } self.window_wall_ns = self.window_wall_ns.saturating_add(elapsed_ns); self.window_sim_ns = self.window_sim_ns.saturating_add(consumed_ns); let rtf = if self.window_wall_ns >= WINDOW_NS { let ratio = self.window_sim_ns as f32 / self.window_wall_ns as f32; self.window_wall_ns = 0; self.window_sim_ns = 0; Some(ratio) } else { None }; Frame { steps, elapsed_seconds: paced_ns as f32 / NS_PER_S as f32, rtf, } } }