repame-sim 0.3.27

headless bevy_ecs sim with fixed-timestep stepping and snapshot-out convention
Documentation
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Headless sim: `bevy_ecs` world stepped without a renderer.
//! Game owns `Sim`, feeds wall time via `Sim::step`,
//! then reads a snapshot for the viewport.
//!
//! Determinism stance: `bevy_ecs` query iteration follows entity allocation
//! history, so a replay with an identical spawn history iterates
//! identically. The sim does NOT sort systems' iteration for you: any
//! gameplay outcome that depends on iteration order (damage application,
//! projectile-vs-multiple-enemies resolution) must sort explicitly in the
//! affected system, or replays diverge the moment allocation history does.
//! Cross-platform float equality (notably `Perlin`/`sin`/`powf` in fx) is
//! additionally *not* guaranteed between native libm and wasm; same-binary
//! replay is the supported claim. [`tape`] is the harness that turns the claim
//! into a check inside one binary (record one intent per tick, hash the world
//! after each tick in a canonical order, replay, diff), and carrying a tape
//! plus its hashes to another target is what makes that target's claim one
//! comparison instead of an argument.

use web_time::Duration;

use bevy_ecs::prelude::*;
use bevy_ecs::schedule::{IntoScheduleConfigs, Schedule};
use bevy_ecs::system::ScheduleSystem;

pub use bevy_ecs;

pub mod hash;
pub mod rng;
pub mod state;
pub mod tape;
pub mod task;
pub mod timer;

pub use hash::Hash64;
pub use rng::{Rng, SimRng, WorldSeed};
pub use state::{NextState, State, States, in_state};
pub use tape::{Divergence, Intent, Setup, Tape, VerifyError, WorldHasher};
pub use task::{Task, TaskPool};
pub use timer::{StepTimer, TimerMode};

/// Fixed-step sim state. Game registers systems,
/// feeds wall time with `step`, reads `world` for the snapshot.
pub struct Sim {
    /// Entity/component store. Game crates add their own components here.
    pub world: World,
    schedule: Schedule,
    /// Per-state transition appliers, run before `schedule` each tick.
    state_appliers: Vec<Box<dyn FnMut(&mut World) + Send + Sync>>,
    accumulator: Duration,
    /// Fixed step size. Default 60 Hz.
    ///
    /// Each tick adds this to `SimTime`. Set before first `step`.
    pub step: Duration,
    /// Sim speed multiplier. Zero or negative pauses the sim; a non-finite
    /// value runs at normal speed.
    pub time_scale: f32,
    /// Max ticks per `step` call. Default `8`.
    ///
    /// Caps catch-up after hitches. Excess wall time is dropped.
    /// Clamped to a minimum of `1` so the sim keeps moving.
    pub max_steps: u32,
}

/// Sim time, advanced once per fixed step.
#[derive(Resource, Clone, Copy, Debug, Default)]
pub struct SimTime {
    /// Total simulated seconds.
    pub elapsed_secs: f64,
    /// Fixed delta of the current step.
    pub delta_secs: f32,
}

impl Sim {
    pub fn new(step: Duration) -> Self {
        let mut world = World::new();
        world.init_resource::<SimTime>();
        Self {
            world,
            schedule: Schedule::default(),
            state_appliers: Vec::new(),
            accumulator: Duration::ZERO,
            step,
            time_scale: 1.0,
            max_steps: 8,
        }
    }

    /// 60 Hz fixed-step sim.
    pub fn with_default_step() -> Self {
        Self::new(Duration::from_secs_f64(1.0 / 60.0))
    }

    /// Register a system into the per-step schedule.
    pub fn add_system<M>(&mut self, system: impl IntoSystem<(), (), M>) -> &mut Self {
        self.schedule.add_systems(system);
        self
    }

    /// Register systems with a fixed execution order.
    ///
    /// Use one `(a, b, c).chain()` tuple for pipelines that need order.
    pub fn add_chained_systems<M>(
        &mut self,
        systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
    ) -> &mut Self {
        self.schedule.add_systems(systems);
        self
    }

    /// Register a state set with its initial value.
    ///
    /// Call once per state type, before `on_enter`/`on_exit`/`on_transition`.
    /// Transitions are applied at the head of each step, before the main
    /// schedule, so gameplay never observes a half-switched state.
    pub fn add_state<S: States>(&mut self, initial: S) -> &mut Self {
        self.world.insert_resource(State::<S>::new(initial));
        self.world.insert_resource(NextState::<S>::new());
        state::init_schedules::<S>(&mut self.world);
        self.state_appliers.push(Box::new(state::apply::<S>));
        self
    }

    /// Systems that run when `state` is entered.
    ///
    /// Panics if `add_state` was not called for this state set first.
    pub fn on_enter<S, M>(
        &mut self,
        state: S,
        systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
    ) -> &mut Self
    where
        S: States,
    {
        state::add_enter(&mut self.world, state, systems);
        self
    }

    /// Systems that run when `state` is exited.
    pub fn on_exit<S, M>(
        &mut self,
        state: S,
        systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
    ) -> &mut Self
    where
        S: States,
    {
        state::add_exit(&mut self.world, state, systems);
        self
    }

    /// Systems that run on the `exited -> entered` edge.
    pub fn on_transition<S, M>(
        &mut self,
        exited: S,
        entered: S,
        systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
    ) -> &mut Self
    where
        S: States,
    {
        state::add_transition(&mut self.world, exited, entered, systems);
        self
    }

    /// Request a state change, equivalent to writing `NextState<S>` from a
    /// system. Panics if the state set was not registered.
    pub fn set_state<S: States>(&mut self, next: S) -> &mut Self {
        self.world.resource_mut::<NextState<S>>().set(next);
        self
    }

    /// The current value of a state set.
    pub fn state<S: States>(&self) -> &S {
        self.world.resource::<State<S>>().get()
    }

    /// Advance by `dt` wall time. Returns ticks run.
    ///
    /// Small `dt` banks for later. Large `dt` runs up to `max_steps`
    /// ticks, then drops leftover whole steps. Example:
    ///
    /// ```ignore
    /// let steps = sim.step(frame_dt);
    /// ```
    pub fn step(&mut self, dt: Duration) -> u32 {
        self.step_with(dt, |_| {})
    }

    /// Whether the clock is stopped. Zero or negative pauses; a non-finite
    /// value is a mistake, so it runs at normal speed instead of stalling.
    fn paused(&self) -> bool {
        self.time_scale.is_finite() && self.time_scale <= 0.0
    }

    pub fn step_with(&mut self, dt: Duration, mut after_tick: impl FnMut(&mut World)) -> u32 {
        if self.step.is_zero() {
            return 0;
        }
        if self.paused() {
            // Drop the wall-clock time rather than bank it, so resuming after a
            // long pause does not fire a burst of catch-up ticks.
            self.accumulator = Duration::ZERO;
            return 0;
        }
        self.accumulator += dt;
        let mut ran = 0;
        while self.accumulator >= self.step && ran < self.max_steps.max(1) {
            self.accumulator -= self.step;
            self.tick_with(&mut after_tick);
            ran += 1;
        }
        if self.accumulator >= self.step {
            // Hitch: keep only the sub-step fraction for alpha continuity.
            let step_ns = self.step.as_nanos();
            if step_ns > 0 {
                let acc_ns = self.accumulator.as_nanos() % step_ns;
                self.accumulator = Duration::from_nanos(acc_ns as u64);
            } else {
                self.accumulator = Duration::ZERO;
            }
        }
        ran
    }

    /// Unconsumed time carried to the next frame. Below one step.
    pub fn leftover(&self) -> Duration {
        self.accumulator
    }

    /// Blend factor `accumulator / step`, clamped to `0..1`.
    /// Zero step returns `0.0`. For render blending between snapshots: keep
    /// the previous snapshot and lerp toward the current one by this alpha
    /// (NT motion at 30 Hz sim on 144 Hz display needs it; without it every
    /// fast mover judders on 4-5 identical frames then jumps).
    pub fn alpha(&self) -> f32 {
        let step = self.step.as_secs_f64();
        if step <= 0.0 {
            return 0.0;
        }
        (self.accumulator.as_secs_f64() / step).clamp(0.0, 1.0) as f32
    }

    /// Run the schedule once, advancing sim time by one step.
    /// Tick-model games drive this directly instead of `step`.
    pub fn tick(&mut self) {
        self.tick_with(|_| {});
    }

    fn tick_with(&mut self, after_tick: impl FnOnce(&mut World)) {
        if self.paused() {
            return;
        }
        let time_scale = if self.time_scale.is_finite() {
            self.time_scale
        } else {
            1.0
        };
        {
            let mut time = self.world.resource_mut::<SimTime>();
            time.delta_secs = self.step.as_secs_f32() * time_scale;
            time.elapsed_secs += self.step.as_secs_f64() * time_scale as f64;
        }
        let Sim {
            state_appliers,
            world,
            schedule,
            ..
        } = self;
        for apply in state_appliers.iter_mut() {
            apply(world);
        }
        schedule.run(world);
        after_tick(world);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fixed_steps_accumulate() {
        let mut sim = Sim::with_default_step();
        let ran = sim.step(Duration::from_nanos(50_000_001));
        assert_eq!(ran, 3);
        let time = sim.world.resource::<SimTime>();
        assert!((time.elapsed_secs - 3.0 / 60.0).abs() < 1e-9);
    }

    #[test]
    fn zero_time_scale_pauses_without_banking_wall_time() {
        let per_frame = Sim::with_default_step().step(Duration::from_millis(50));
        assert!(per_frame > 0);

        let mut sim = Sim::with_default_step();
        sim.step(Duration::from_millis(50));
        let before = sim.world.resource::<SimTime>().elapsed_secs;

        sim.time_scale = 0.0;
        assert_eq!(
            sim.step(Duration::from_secs(5)),
            0,
            "paused sim runs no ticks"
        );
        sim.tick();
        assert_eq!(
            sim.world.resource::<SimTime>().elapsed_secs,
            before,
            "paused sim does not advance its clock"
        );

        sim.time_scale = 1.0;
        assert_eq!(
            sim.step(Duration::from_millis(50)),
            per_frame,
            "resuming must not fire a catch-up burst"
        );
    }

    #[test]
    fn non_finite_time_scale_runs_at_normal_speed() {
        let mut sim = Sim::with_default_step();
        sim.time_scale = f32::NAN;
        sim.step(Duration::from_millis(51));
        let time = sim.world.resource::<SimTime>();
        assert!(
            (time.delta_secs - 1.0 / 60.0).abs() < 1e-6,
            "a non-finite scale must not stall the delta, got {}",
            time.delta_secs
        );
        assert!(time.elapsed_secs > 0.0, "the clock still advances");
    }

    #[test]
    fn post_tick_runs_after_each_fixed_step() {
        use std::sync::{Arc, Mutex};

        let log = Arc::new(Mutex::new(Vec::new()));
        let sim_log = log.clone();
        let mut sim = Sim::with_default_step();
        sim.add_system(move || sim_log.lock().unwrap().push("sim"));
        let post_log = log.clone();

        let ran = sim.step_with(Duration::from_millis(51), move |_| {
            post_log.lock().unwrap().push("post");
        });

        assert_eq!(ran, 3);
        assert_eq!(
            *log.lock().unwrap(),
            ["sim", "post", "sim", "post", "sim", "post"]
        );
    }

    #[test]
    fn zero_step_never_ticks() {
        let mut sim = Sim::new(Duration::ZERO);
        let ran = sim.step(Duration::from_secs(10));
        assert_eq!(ran, 0);
        let time = sim.world.resource::<SimTime>();
        assert_eq!(time.elapsed_secs, 0.0);
    }

    #[test]
    fn spiral_of_death_is_capped() {
        let mut sim = Sim::with_default_step();
        sim.max_steps = 4;
        let ran = sim.step(Duration::from_secs(10));
        assert_eq!(ran, 4);
        assert!(
            sim.leftover() < sim.step,
            "keeps only fraction, got {:?}",
            sim.leftover()
        );
    }

    #[test]
    fn alpha_is_interpolation_fraction() {
        let mut sim = Sim::new(Duration::from_millis(16));
        sim.step(Duration::from_millis(8));
        assert!((sim.alpha() - 0.5).abs() < 1e-6, "got {}", sim.alpha());
        sim.step(Duration::from_millis(8));
        assert!(sim.alpha() < 1e-6, "step boundary, got {}", sim.alpha());
    }

    #[test]
    fn time_scale_changes_simulated_delta_without_changing_wall_accumulation() {
        let mut sim = Sim::with_default_step();
        sim.time_scale = 0.25;
        let ran = sim.step(Duration::from_nanos(16_666_667));
        let time = sim.world.resource::<SimTime>();
        assert_eq!(ran, 1);
        assert!((time.delta_secs - 1.0 / 240.0).abs() < 1e-6);
        assert!((time.elapsed_secs - 1.0 / 240.0).abs() < 1e-9);
    }

    #[test]
    fn chained_systems_run_in_order() {
        use std::sync::{Arc, Mutex};
        let log: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
        let (a_log, b_log, c_log) = (log.clone(), log.clone(), log.clone());
        let mut sim = Sim::with_default_step();
        sim.add_chained_systems(
            (
                move || a_log.lock().unwrap().push("a"),
                move || b_log.lock().unwrap().push("b"),
                move || c_log.lock().unwrap().push("c"),
            )
                .chain(),
        );
        sim.tick();
        assert_eq!(*log.lock().unwrap(), vec!["a", "b", "c"]);
    }
}