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    #[allow(clippy::cast_precision_loss)] // tick counts within f64 range
46    #[must_use]
47    pub fn ticks_to_seconds(&self, ticks: u64) -> f64 {
48        ticks as f64 / self.ticks_per_second
49    }
50
51    /// Convert seconds to ticks, rounded to nearest.
52    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // intentional rounding
53    #[must_use]
54    pub fn seconds_to_ticks(&self, seconds: f64) -> u64 {
55        (seconds * self.ticks_per_second).round() as u64
56    }
57
58    /// Convert a `Duration` to ticks, rounded to nearest.
59    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // intentional rounding
60    #[must_use]
61    pub fn duration_to_ticks(&self, duration: Duration) -> u64 {
62        (duration.as_secs_f64() * self.ticks_per_second).round() as u64
63    }
64
65    /// Convert ticks to a `Duration`.
66    #[allow(clippy::cast_precision_loss)] // tick counts within f64 range
67    #[must_use]
68    pub fn ticks_to_duration(&self, ticks: u64) -> Duration {
69        Duration::from_secs_f64(ticks as f64 / self.ticks_per_second)
70    }
71
72    /// The configured tick rate.
73    #[must_use]
74    pub const fn ticks_per_second(&self) -> f64 {
75        self.ticks_per_second
76    }
77}