Skip to main content

elevator_core/
time.rs

1//! Tick-to-wall-clock time conversion.
2
3use std::time::Duration;
4
5/// Simulation tick rate, exposed as a [`World`](crate::world::World) resource.
6///
7/// Dispatch strategies and other subsystems that only hold a `&World`
8/// need this to convert between tick-denominated elevator fields
9/// (e.g. `door_transition_ticks`) and the second-denominated terms
10/// they combine with (travel time, rider delay). Inserted once during
11/// [`Simulation::new`](crate::sim::Simulation::new) and restored from
12/// snapshots via the same path.
13///
14/// Strategies that miss the resource (e.g. in a bare-bones unit-test
15/// world) should fall back to 60 Hz — the canonical default and the
16/// only value used across the published scenarios.
17#[derive(Debug, Clone, Copy)]
18pub struct TickRate(pub f64);
19
20impl Default for TickRate {
21    fn default() -> Self {
22        Self(60.0)
23    }
24}
25
26/// Converts between simulation ticks and wall-clock time.
27///
28/// The core simulation is purely tick-based for determinism.
29/// Game integrations use `TimeAdapter` to display real-time
30/// values and schedule events in human-readable units.
31#[derive(Debug, Clone, Copy)]
32pub struct TimeAdapter {
33    /// Ticks per real-time second.
34    ticks_per_second: f64,
35}
36
37impl TimeAdapter {
38    /// Create a new adapter with the given tick rate.
39    #[must_use]
40    pub const fn new(ticks_per_second: f64) -> Self {
41        Self { ticks_per_second }
42    }
43
44    /// Convert ticks to seconds.
45    #[must_use]
46    pub fn ticks_to_seconds(&self, ticks: u64) -> f64 {
47        ticks as f64 / self.ticks_per_second
48    }
49
50    /// Convert seconds to ticks, rounded to nearest.
51    #[must_use]
52    pub fn seconds_to_ticks(&self, seconds: f64) -> u64 {
53        (seconds * self.ticks_per_second).round() as u64
54    }
55
56    /// Convert a `Duration` to ticks, rounded to nearest.
57    #[must_use]
58    pub fn duration_to_ticks(&self, duration: Duration) -> u64 {
59        (duration.as_secs_f64() * self.ticks_per_second).round() as u64
60    }
61
62    /// Convert ticks to a `Duration`.
63    #[must_use]
64    pub fn ticks_to_duration(&self, ticks: u64) -> Duration {
65        Duration::from_secs_f64(ticks as f64 / self.ticks_per_second)
66    }
67
68    /// The configured tick rate.
69    #[must_use]
70    pub const fn ticks_per_second(&self) -> f64 {
71        self.ticks_per_second
72    }
73}