Skip to main content

repame_sim/
lib.rs

1//! Headless sim: `bevy_ecs` world stepped without a renderer.
2//! Game owns `Sim`, feeds wall time via `Sim::step`,
3//! then reads a snapshot for the viewport.
4//!
5//! [`rng`] is the one random source a game should draw from: [`SimRng`] is
6//! xoshiro256\*\* seeded through SplitMix64, and [`WorldSeed`] derives a
7//! stream per system or per entity from `(seed, tag)`, so adding a system
8//! does not shift the others' streams. [`hash`] hashes a world in a canonical
9//! order, and [`tape`] records and replays a session against those hashes.
10//!
11//! Determinism stance: `bevy_ecs` query iteration follows entity allocation
12//! history, so a replay with an identical spawn history iterates
13//! identically. The sim does NOT sort systems' iteration for you: any
14//! gameplay outcome that depends on iteration order (damage application,
15//! projectile-vs-multiple-enemies resolution) must sort explicitly in the
16//! affected system, or replays diverge the moment allocation history does.
17//! Cross-platform float equality (notably `Perlin`/`sin`/`powf` in fx) is
18//! additionally *not* guaranteed between native libm and wasm; same-binary
19//! replay is the supported claim. [`tape`] is the harness that turns the claim
20//! into a check inside one binary (record one intent per tick, hash the world
21//! after each tick in a canonical order, replay, diff), and carrying a tape
22//! plus its hashes to another target is what makes that target's claim one
23//! comparison instead of an argument.
24
25use 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
47/// Fixed-step sim state. Game registers systems,
48/// feeds wall time with `step`, reads `world` for the snapshot.
49pub struct Sim {
50    /// Entity/component store. Game crates add their own components here.
51    pub world: World,
52    schedule: Schedule,
53    /// Per-state transition appliers, run before `schedule` each tick.
54    state_appliers: Vec<Box<dyn FnMut(&mut World) + Send + Sync>>,
55    accumulator: Duration,
56    /// Fixed step size. Default 60 Hz.
57    ///
58    /// Each tick adds this to `SimTime`. Set before first `step`.
59    pub step: Duration,
60    /// Sim speed multiplier. Zero or negative pauses the sim; a non-finite
61    /// value runs at normal speed.
62    pub time_scale: f32,
63    /// Max ticks per `step` call. Default `8`.
64    ///
65    /// Caps catch-up after hitches. Excess wall time is dropped.
66    /// Clamped to a minimum of `1` so the sim keeps moving.
67    pub max_steps: u32,
68}
69
70/// Sim time, advanced once per fixed step.
71#[derive(Resource, Clone, Copy, Debug, Default)]
72pub struct SimTime {
73    /// Total simulated seconds.
74    pub elapsed_secs: f64,
75    /// Fixed delta of the current step.
76    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    /// 60 Hz fixed-step sim.
95    pub fn with_default_step() -> Self {
96        Self::new(Duration::from_secs_f64(1.0 / 60.0))
97    }
98
99    /// Register a system into the per-step schedule.
100    pub fn add_system<M>(&mut self, system: impl IntoSystem<(), (), M>) -> &mut Self {
101        self.schedule.add_systems(system);
102        self
103    }
104
105    /// Register systems with a fixed execution order.
106    ///
107    /// Use one `(a, b, c).chain()` tuple for pipelines that need order.
108    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    /// Register a state set with its initial value.
117    ///
118    /// Call once per state type, before `on_enter`/`on_exit`/`on_transition`.
119    /// Transitions are applied at the head of each step, before the main
120    /// schedule, so gameplay never observes a half-switched state.
121    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    /// Systems that run when `state` is entered.
130    ///
131    /// Panics if `add_state` was not called for this state set first.
132    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    /// Systems that run when `state` is exited.
145    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    /// Systems that run on the `exited -> entered` edge.
158    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    /// Request a state change, equivalent to writing `NextState<S>` from a
172    /// system. Panics if the state set was not registered.
173    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    /// The current value of a state set.
179    pub fn state<S: States>(&self) -> &S {
180        self.world.resource::<State<S>>().get()
181    }
182
183    /// Advance by `dt` wall time. Returns ticks run.
184    ///
185    /// Small `dt` banks for later. Large `dt` runs up to `max_steps`
186    /// ticks, then drops leftover whole steps. Example:
187    ///
188    /// ```ignore
189    /// let steps = sim.step(frame_dt);
190    /// ```
191    pub fn step(&mut self, dt: Duration) -> u32 {
192        self.step_with(dt, |_| {})
193    }
194
195    /// Whether the clock is stopped. Zero or negative pauses; a non-finite
196    /// value is a mistake, so it runs at normal speed instead of stalling.
197    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            // Drop the wall-clock time rather than bank it, so resuming after a
207            // long pause does not fire a burst of catch-up ticks.
208            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            // Hitch: keep only the sub-step fraction for alpha continuity.
220            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    /// Unconsumed time carried to the next frame. Below one step.
232    pub fn leftover(&self) -> Duration {
233        self.accumulator
234    }
235
236    /// Blend factor `accumulator / step`, clamped to `0..1`.
237    /// Zero step returns `0.0`. For render blending between snapshots: keep
238    /// the previous snapshot and lerp toward the current one by this alpha
239    /// (NT motion at 30 Hz sim on 144 Hz display needs it; without it every
240    /// fast mover judders on 4-5 identical frames then jumps).
241    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    /// Run the schedule once, advancing sim time by one step.
250    /// Tick-model games drive this directly instead of `step`.
251    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}