1use web_time::Duration;
26
27use bevy_ecs::prelude::*;
28use bevy_ecs::schedule::{IntoScheduleConfigs, Schedule};
29use bevy_ecs::system::ScheduleSystem;
30
31pub use bevy_ecs;
32
33pub mod hash;
34pub mod rng;
35pub mod state;
36pub mod tape;
37pub mod task;
38pub mod timer;
39
40pub use hash::Hash64;
41pub use rng::{Rng, SimRng, WorldSeed};
42pub use state::{NextState, State, States, in_state};
43pub use tape::{Divergence, Intent, Setup, Tape, VerifyError, WorldHasher};
44pub use task::{Task, TaskPool};
45pub use timer::{StepTimer, TimerMode};
46
47pub struct Sim {
50 pub world: World,
52 schedule: Schedule,
53 state_appliers: Vec<Box<dyn FnMut(&mut World) + Send + Sync>>,
55 accumulator: Duration,
56 pub step: Duration,
60 pub time_scale: f32,
63 pub max_steps: u32,
68}
69
70#[derive(Resource, Clone, Copy, Debug, Default)]
72pub struct SimTime {
73 pub elapsed_secs: f64,
75 pub delta_secs: f32,
77}
78
79impl Sim {
80 pub fn new(step: Duration) -> Self {
81 let mut world = World::new();
82 world.init_resource::<SimTime>();
83 Self {
84 world,
85 schedule: Schedule::default(),
86 state_appliers: Vec::new(),
87 accumulator: Duration::ZERO,
88 step,
89 time_scale: 1.0,
90 max_steps: 8,
91 }
92 }
93
94 pub fn with_default_step() -> Self {
96 Self::new(Duration::from_secs_f64(1.0 / 60.0))
97 }
98
99 pub fn add_system<M>(&mut self, system: impl IntoSystem<(), (), M>) -> &mut Self {
101 self.schedule.add_systems(system);
102 self
103 }
104
105 pub fn add_chained_systems<M>(
109 &mut self,
110 systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
111 ) -> &mut Self {
112 self.schedule.add_systems(systems);
113 self
114 }
115
116 pub fn add_state<S: States>(&mut self, initial: S) -> &mut Self {
122 self.world.insert_resource(State::<S>::new(initial));
123 self.world.insert_resource(NextState::<S>::new());
124 state::init_schedules::<S>(&mut self.world);
125 self.state_appliers.push(Box::new(state::apply::<S>));
126 self
127 }
128
129 pub fn on_enter<S, M>(
133 &mut self,
134 state: S,
135 systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
136 ) -> &mut Self
137 where
138 S: States,
139 {
140 state::add_enter(&mut self.world, state, systems);
141 self
142 }
143
144 pub fn on_exit<S, M>(
146 &mut self,
147 state: S,
148 systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
149 ) -> &mut Self
150 where
151 S: States,
152 {
153 state::add_exit(&mut self.world, state, systems);
154 self
155 }
156
157 pub fn on_transition<S, M>(
159 &mut self,
160 exited: S,
161 entered: S,
162 systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
163 ) -> &mut Self
164 where
165 S: States,
166 {
167 state::add_transition(&mut self.world, exited, entered, systems);
168 self
169 }
170
171 pub fn set_state<S: States>(&mut self, next: S) -> &mut Self {
174 self.world.resource_mut::<NextState<S>>().set(next);
175 self
176 }
177
178 pub fn state<S: States>(&self) -> &S {
180 self.world.resource::<State<S>>().get()
181 }
182
183 pub fn step(&mut self, dt: Duration) -> u32 {
192 self.step_with(dt, |_| {})
193 }
194
195 fn paused(&self) -> bool {
198 self.time_scale.is_finite() && self.time_scale <= 0.0
199 }
200
201 pub fn step_with(&mut self, dt: Duration, mut after_tick: impl FnMut(&mut World)) -> u32 {
202 if self.step.is_zero() {
203 return 0;
204 }
205 if self.paused() {
206 self.accumulator = Duration::ZERO;
209 return 0;
210 }
211 self.accumulator += dt;
212 let mut ran = 0;
213 while self.accumulator >= self.step && ran < self.max_steps.max(1) {
214 self.accumulator -= self.step;
215 self.tick_with(&mut after_tick);
216 ran += 1;
217 }
218 if self.accumulator >= self.step {
219 let step_ns = self.step.as_nanos();
221 if step_ns > 0 {
222 let acc_ns = self.accumulator.as_nanos() % step_ns;
223 self.accumulator = Duration::from_nanos(acc_ns as u64);
224 } else {
225 self.accumulator = Duration::ZERO;
226 }
227 }
228 ran
229 }
230
231 pub fn leftover(&self) -> Duration {
233 self.accumulator
234 }
235
236 pub fn alpha(&self) -> f32 {
242 let step = self.step.as_secs_f64();
243 if step <= 0.0 {
244 return 0.0;
245 }
246 (self.accumulator.as_secs_f64() / step).clamp(0.0, 1.0) as f32
247 }
248
249 pub fn tick(&mut self) {
252 self.tick_with(|_| {});
253 }
254
255 fn tick_with(&mut self, after_tick: impl FnOnce(&mut World)) {
256 if self.paused() {
257 return;
258 }
259 let time_scale = if self.time_scale.is_finite() {
260 self.time_scale
261 } else {
262 1.0
263 };
264 {
265 let mut time = self.world.resource_mut::<SimTime>();
266 time.delta_secs = self.step.as_secs_f32() * time_scale;
267 time.elapsed_secs += self.step.as_secs_f64() * time_scale as f64;
268 }
269 let Sim {
270 state_appliers,
271 world,
272 schedule,
273 ..
274 } = self;
275 for apply in state_appliers.iter_mut() {
276 apply(world);
277 }
278 schedule.run(world);
279 after_tick(world);
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn fixed_steps_accumulate() {
289 let mut sim = Sim::with_default_step();
290 let ran = sim.step(Duration::from_nanos(50_000_001));
291 assert_eq!(ran, 3);
292 let time = sim.world.resource::<SimTime>();
293 assert!((time.elapsed_secs - 3.0 / 60.0).abs() < 1e-9);
294 }
295
296 #[test]
297 fn zero_time_scale_pauses_without_banking_wall_time() {
298 let per_frame = Sim::with_default_step().step(Duration::from_millis(50));
299 assert!(per_frame > 0);
300
301 let mut sim = Sim::with_default_step();
302 sim.step(Duration::from_millis(50));
303 let before = sim.world.resource::<SimTime>().elapsed_secs;
304
305 sim.time_scale = 0.0;
306 assert_eq!(
307 sim.step(Duration::from_secs(5)),
308 0,
309 "paused sim runs no ticks"
310 );
311 sim.tick();
312 assert_eq!(
313 sim.world.resource::<SimTime>().elapsed_secs,
314 before,
315 "paused sim does not advance its clock"
316 );
317
318 sim.time_scale = 1.0;
319 assert_eq!(
320 sim.step(Duration::from_millis(50)),
321 per_frame,
322 "resuming must not fire a catch-up burst"
323 );
324 }
325
326 #[test]
327 fn non_finite_time_scale_runs_at_normal_speed() {
328 let mut sim = Sim::with_default_step();
329 sim.time_scale = f32::NAN;
330 sim.step(Duration::from_millis(51));
331 let time = sim.world.resource::<SimTime>();
332 assert!(
333 (time.delta_secs - 1.0 / 60.0).abs() < 1e-6,
334 "a non-finite scale must not stall the delta, got {}",
335 time.delta_secs
336 );
337 assert!(time.elapsed_secs > 0.0, "the clock still advances");
338 }
339
340 #[test]
341 fn post_tick_runs_after_each_fixed_step() {
342 use std::sync::{Arc, Mutex};
343
344 let log = Arc::new(Mutex::new(Vec::new()));
345 let sim_log = log.clone();
346 let mut sim = Sim::with_default_step();
347 sim.add_system(move || sim_log.lock().unwrap().push("sim"));
348 let post_log = log.clone();
349
350 let ran = sim.step_with(Duration::from_millis(51), move |_| {
351 post_log.lock().unwrap().push("post");
352 });
353
354 assert_eq!(ran, 3);
355 assert_eq!(
356 *log.lock().unwrap(),
357 ["sim", "post", "sim", "post", "sim", "post"]
358 );
359 }
360
361 #[test]
362 fn zero_step_never_ticks() {
363 let mut sim = Sim::new(Duration::ZERO);
364 let ran = sim.step(Duration::from_secs(10));
365 assert_eq!(ran, 0);
366 let time = sim.world.resource::<SimTime>();
367 assert_eq!(time.elapsed_secs, 0.0);
368 }
369
370 #[test]
371 fn spiral_of_death_is_capped() {
372 let mut sim = Sim::with_default_step();
373 sim.max_steps = 4;
374 let ran = sim.step(Duration::from_secs(10));
375 assert_eq!(ran, 4);
376 assert!(
377 sim.leftover() < sim.step,
378 "keeps only fraction, got {:?}",
379 sim.leftover()
380 );
381 }
382
383 #[test]
384 fn alpha_is_interpolation_fraction() {
385 let mut sim = Sim::new(Duration::from_millis(16));
386 sim.step(Duration::from_millis(8));
387 assert!((sim.alpha() - 0.5).abs() < 1e-6, "got {}", sim.alpha());
388 sim.step(Duration::from_millis(8));
389 assert!(sim.alpha() < 1e-6, "step boundary, got {}", sim.alpha());
390 }
391
392 #[test]
393 fn time_scale_changes_simulated_delta_without_changing_wall_accumulation() {
394 let mut sim = Sim::with_default_step();
395 sim.time_scale = 0.25;
396 let ran = sim.step(Duration::from_nanos(16_666_667));
397 let time = sim.world.resource::<SimTime>();
398 assert_eq!(ran, 1);
399 assert!((time.delta_secs - 1.0 / 240.0).abs() < 1e-6);
400 assert!((time.elapsed_secs - 1.0 / 240.0).abs() < 1e-9);
401 }
402
403 #[test]
404 fn chained_systems_run_in_order() {
405 use std::sync::{Arc, Mutex};
406 let log: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
407 let (a_log, b_log, c_log) = (log.clone(), log.clone(), log.clone());
408 let mut sim = Sim::with_default_step();
409 sim.add_chained_systems(
410 (
411 move || a_log.lock().unwrap().push("a"),
412 move || b_log.lock().unwrap().push("b"),
413 move || c_log.lock().unwrap().push("c"),
414 )
415 .chain(),
416 );
417 sim.tick();
418 assert_eq!(*log.lock().unwrap(), vec!["a", "b", "c"]);
419 }
420}