Skip to main content

furmint_runtime/
time.rs

1use std::ops::AddAssign;
2
3/// Nanoseconds in a second
4pub const NANOS_PER_SECOND: f64 = 1_000_000_000.0;
5
6/// A struct representing game ticks
7#[derive(Debug)]
8pub struct Time {
9    /// Amount of ticks ran since the game start
10    pub ticks: u64,
11    /// The tick rate in nanoseconds per tick
12    pub tick_period: u64,
13    /// Total elapsed time in seconds
14    pub total_elapsed_time: f64,
15    /// The duration of the last completed tick in seconds
16    pub delta_seconds: f64,
17}
18
19impl AddAssign<u64> for Time {
20    fn add_assign(&mut self, rhs: u64) {
21        self.ticks += rhs;
22    }
23}
24
25impl Time {
26    /// Get the current ticks-per-second rate
27    ///
28    /// This function divides total ticks amount by total elapsed time, or if the elapsed time is
29    /// zero it returns 0.0 to avoid division by zero
30    pub fn tps(&self) -> f64 {
31        if self.total_elapsed_time > 0.0 {
32            self.ticks as f64 / self.total_elapsed_time
33        } else {
34            0.0
35        }
36    }
37
38    /// Get target TPS
39    pub const fn target_tick_rate(&self) -> f64 {
40        NANOS_PER_SECOND / self.total_elapsed_time
41    }
42}