1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use std::time::Duration;
use crate::Stopwatch;
pub struct Timer {
stop_watch: Stopwatch,
time_since_start: Duration,
current_time: Duration,
previous_time: Duration,
delta_time: Duration,
fixed_interval: Duration,
time_since_last_fixed_update: Duration,
should_fixed: bool,
}
unsafe impl Send for Timer {}
unsafe impl Sync for Timer {}
impl Timer {
pub fn new() -> Self {
Self::default()
}
pub fn time_since_start(&self) -> Duration {
self.time_since_start
}
pub fn update_delta_time(&mut self) {
self.current_time = self.stop_watch.elapsed();
self.delta_time = self.current_time - self.previous_time;
self.previous_time = self.current_time;
self.time_since_start += self.delta_time;
}
pub fn update_fixed_time(&mut self) {
self.time_since_last_fixed_update += self.delta_time;
if self.fixed_interval <= self.time_since_last_fixed_update {
self.time_since_last_fixed_update -= self.fixed_interval;
self.should_fixed = true;
return;
}
self.should_fixed = false;
}
pub fn should_fixed_update(&self) -> bool {
self.should_fixed
}
pub fn set_fixed_interval(&mut self, fixed_interval: Duration) {
self.fixed_interval = fixed_interval;
self.time_since_last_fixed_update = fixed_interval;
}
pub fn delta_time(&self) -> Duration {
self.delta_time
}
pub fn fixed_interval(&self) -> Duration {
self.fixed_interval
}
pub fn time_since_last_fixed(&self) -> Duration {
self.time_since_last_fixed_update
}
}
impl Default for Timer {
fn default() -> Self {
Self {
stop_watch: Stopwatch::new(),
time_since_start: Duration::new(0, 0),
current_time: Duration::new(0, 0),
previous_time: Duration::new(0, 0),
delta_time: Duration::new(0, 0),
fixed_interval: Duration::new(0, 0),
time_since_last_fixed_update: Duration::new(0, 0),
should_fixed: false
}
}
}