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
use std::convert::TryFrom;
use xias::Xias;
use crate::time::{Instant, Time};
use crate::SetupEcs;
pub const SIMULATION_PERIOD: Time = Time(100);
pub const MICROS_PER_TICK: u64 = 10000;
#[derive(Debug, Default, getset::CopyGetters)]
pub struct Clock {
#[getset(get_copy = "pub")]
now: Instant,
#[getset(get_copy = "pub")]
delta: Time,
epoch_instant: Instant,
epoch_micros: i64,
}
impl Clock {
pub fn update_micros(&mut self, micros: i64) {
let delta_micros = (micros - self.epoch_micros).homosign();
let delta_time =
Time(u32::try_from(delta_micros / MICROS_PER_TICK).expect("micros is not monotonic"));
let now = self.epoch_instant + delta_time;
self.delta = now - self.now;
self.now = now;
}
pub fn reset_time(&mut self, now: Instant, micros: i64) {
self.now = now;
self.delta = Time::zero();
self.epoch_instant = now;
self.epoch_micros = micros;
}
}
pub struct SimulationEvent;
#[codegen::system(Schedule)]
fn sim_trigger(
#[publisher] sim_pub: impl FnMut(SimulationEvent),
#[resource] clock: &Clock,
#[state(Instant::default())] last_sim_time: &mut Instant,
) {
let now = clock.now().since_epoch().int_div(SIMULATION_PERIOD);
let last = last_sim_time.since_epoch().int_div(SIMULATION_PERIOD);
if now != last {
sim_pub(SimulationEvent);
*last_sim_time = clock.now();
}
}
pub fn setup_ecs(setup: SetupEcs) -> SetupEcs { setup.uses(sim_trigger_setup) }