Skip to main content

three_rs/core/
timer.rs

1//! Port of `three.js/src/core/Timer.js`.
2
3use crate::utils::time::now_ms;
4
5/// `Timer` — three.js' successor to `Clock`, and the only one of the two any
6/// graded example page uses (nine of the thirty-nine construct a
7/// `new THREE.Timer()`; none construct a `Clock`).
8///
9/// Its point over `Clock` is that [`update`](Self::update) is the one place
10/// the clock is read, so [`get_delta`](Self::get_delta) and
11/// [`get_elapsed`](Self::get_elapsed) can be called any number of times in a
12/// simulation step and answer the same thing.
13///
14/// # What is left out
15///
16/// `connect( document )` / `disconnect()` and their Page Visibility handling.
17/// Five of the nine pages call `timer.connect( document )`; all it does is
18/// register a `visibilitychange` listener that calls
19/// [`reset`](Self::reset) when the tab comes back, so that a tab left in the
20/// background does not produce one enormous delta. There is no document here —
21/// the crate is host-agnostic and the browser shell drives frames from
22/// `requestAnimationFrame`, which a hidden tab does not fire — so a host that
23/// wants that behaviour calls [`reset`](Self::reset) itself. Nothing about
24/// `update`/`getDelta`/`getElapsed` differs.
25#[derive(Debug, Clone)]
26pub struct Timer {
27    previous_time: f64,
28    current_time: f64,
29    start_time: f64,
30    delta: f64,
31    elapsed: f64,
32    timescale: f64,
33}
34
35impl Default for Timer {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl Timer {
42    /// `new Timer()`. `_startTime = performance.now()`, so the first
43    /// `update()` after construction has a delta of "however long init took",
44    /// exactly as on the page.
45    pub fn new() -> Self {
46        Self {
47            previous_time: 0.0,
48            current_time: 0.0,
49            start_time: now_ms(),
50            delta: 0.0,
51            elapsed: 0.0,
52            timescale: 1.0,
53        }
54    }
55
56    /// `getDelta()` — the last step's length, in seconds.
57    pub fn get_delta(&self) -> f64 {
58        self.delta / 1000.0
59    }
60
61    /// `getElapsed()` — the sum of every delta so far, in seconds.
62    pub fn get_elapsed(&self) -> f64 {
63        self.elapsed / 1000.0
64    }
65
66    /// `getTimescale()`.
67    pub fn get_timescale(&self) -> f64 {
68        self.timescale
69    }
70
71    /// `setTimescale( timescale )` — scales the delta `update()` computes.
72    pub fn set_timescale(&mut self, timescale: f64) -> &mut Self {
73        self.timescale = timescale;
74        self
75    }
76
77    /// `reset()` — forget the gap since the last `update()`, so the next step
78    /// is short rather than however long the timer was ignored for.
79    pub fn reset(&mut self) -> &mut Self {
80        self.current_time = now_ms() - self.start_time;
81        self
82    }
83
84    /// `update()` with no `timestamp`: read the clock.
85    pub fn update(&mut self) -> &mut Self {
86        self.update_with(None)
87    }
88
89    /// `update( timestamp )` — the `requestAnimationFrame` argument, in
90    /// milliseconds on the same origin as `performance.now()`.
91    ///
92    /// A host that wants a fixed simulation step passes
93    /// `start + n * step` here; there is no separate fixed-delta mode in
94    /// r186's `Timer`.
95    pub fn update_with(&mut self, timestamp: Option<f64>) -> &mut Self {
96        self.previous_time = self.current_time;
97        self.current_time = timestamp.unwrap_or_else(now_ms) - self.start_time;
98
99        self.delta = (self.current_time - self.previous_time) * self.timescale;
100        // `_elapsed is the accumulation of all previous deltas`.
101        self.elapsed += self.delta;
102
103        self
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::testing::pin_time;
111
112    #[test]
113    fn a_pinned_clock_gives_a_zero_delta_forever() {
114        pin_time(Some(0.0));
115        let mut timer = Timer::new();
116        for _ in 0..4 {
117            timer.update();
118            assert_eq!(timer.get_delta(), 0.0);
119            assert_eq!(timer.get_elapsed(), 0.0);
120        }
121        pin_time(None);
122    }
123
124    #[test]
125    fn deltas_accumulate_into_elapsed() {
126        pin_time(Some(1000.0));
127        let mut timer = Timer::new();
128
129        pin_time(Some(1016.0));
130        timer.update();
131        assert!((timer.get_delta() - 0.016).abs() < 1e-12);
132        assert!((timer.get_elapsed() - 0.016).abs() < 1e-12);
133
134        pin_time(Some(1048.0));
135        timer.update();
136        assert!((timer.get_delta() - 0.032).abs() < 1e-12);
137        assert!((timer.get_elapsed() - 0.048).abs() < 1e-12);
138
139        pin_time(None);
140    }
141
142    #[test]
143    fn timescale_scales_the_delta() {
144        pin_time(Some(0.0));
145        let mut timer = Timer::new();
146        timer.set_timescale(0.5);
147
148        pin_time(Some(100.0));
149        timer.update();
150        assert!((timer.get_delta() - 0.05).abs() < 1e-12);
151
152        pin_time(None);
153    }
154
155    #[test]
156    fn reset_drops_the_gap_since_the_last_update() {
157        pin_time(Some(0.0));
158        let mut timer = Timer::new();
159
160        // A long pause the host does not want charged to the next step.
161        pin_time(Some(10_000.0));
162        timer.reset();
163        pin_time(Some(10_016.0));
164        timer.update();
165        assert!((timer.get_delta() - 0.016).abs() < 1e-12);
166
167        pin_time(None);
168    }
169
170    #[test]
171    fn an_explicit_timestamp_replaces_the_clock() {
172        pin_time(Some(0.0));
173        let mut timer = Timer::new();
174        timer.update_with(Some(500.0));
175        assert!((timer.get_delta() - 0.5).abs() < 1e-12);
176        pin_time(None);
177    }
178}