use std::time::{Duration, Instant};
const MAX_SIMULATION_CATCH_UP_STEPS: usize = 100;
const INPUT_POLL_INTERVAL: Duration = Duration::from_millis(10);
pub(super) struct TimingController {
pub(super) next_simulation: Instant,
pub(super) next_render: Instant,
}
impl TimingController {
pub(super) fn new(now: Instant) -> Self {
Self {
next_simulation: now,
next_render: now,
}
}
pub(super) fn take_simulation_steps(&mut self, now: Instant, update_delay: u64) -> usize {
if update_delay == 0 {
self.next_simulation = now;
return 1;
}
if now < self.next_simulation {
return 0;
}
let interval = Duration::from_millis(update_delay.saturating_mul(10));
let mut steps = 0;
while self.next_simulation <= now && steps < MAX_SIMULATION_CATCH_UP_STEPS {
steps += 1;
self.next_simulation += interval;
}
if self.next_simulation <= now {
self.next_simulation = now + interval;
}
steps
}
pub(super) fn take_render_due(&mut self, now: Instant, render_fps: u16) -> bool {
if now < self.next_render {
return false;
}
self.next_render = now + Duration::from_secs_f64(1.0 / f64::from(render_fps));
true
}
pub(super) fn sleep_duration(&self, now: Instant, update_delay: u64) -> Duration {
if update_delay == 0 {
return Duration::ZERO;
}
let simulation_wait = self.next_simulation.saturating_duration_since(now);
let render_wait = self.next_render.saturating_duration_since(now);
INPUT_POLL_INTERVAL.min(simulation_wait).min(render_wait)
}
}
#[cfg(test)]
mod tests;