Skip to main content

synctick_bevy/
simulation.rs

1//! Worker-owned Bevy simulation and deterministic schedule.
2use bevy_app::App;
3use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
4use std::time::Duration;
5use synctick::{Game, Input, SessionResult, Simulation, Tick};
6
7/// Framework-assigned tick currently being simulated; zero before the first tick.
8#[derive(Resource, Debug, Default, Clone, Copy)]
9pub struct TickNumber(pub u64);
10/// Fixed simulation interval recorded in the session metadata.
11#[derive(Resource, Debug, Clone, Copy)]
12pub struct TickDuration(pub Duration);
13/// Participant-tagged commands in authoritative order for the current tick.
14///
15/// Inputs remain available through publication and the game's cleanup hook.
16#[derive(Resource)]
17pub struct TickInputs<C: Send + Sync + 'static>(pub Vec<Input<C>>);
18impl<C: Send + Sync + 'static> Default for TickInputs<C> {
19    fn default() -> Self {
20        Self(Vec::new())
21    }
22}
23/// Deterministic gameplay schedule, run once per live or replayed tick.
24#[derive(ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
25pub struct SimStep;
26
27/// A game's Bevy simulation construction and presentation hooks.
28///
29/// `build` must
30/// fully initialize deterministic state; ordinary Startup/Update schedules are
31/// not run on the worker. Register gameplay systems on [`SimStep`].
32pub trait BevyGame: Clone + Send + Sync + 'static {
33    type Command: synctick::codec::Wire + Send + Sync + 'static;
34    type Initialization: synctick::codec::Wire + Send + 'static;
35    const ID: [u8; 16];
36    const VERSION: u32;
37    /// # Errors
38    /// Reject unsupported initialization or failed world construction.
39    fn build(&self, initialization: Self::Initialization, app: &mut App) -> SessionResult;
40    /// Include `TickNumber` and every future-affecting game resource/component.
41    fn state_hash(&self, world: &mut World) -> u64;
42    /// Publish complete state before Live and after valid live ticks, never during replay.
43    /// Must not change deterministic state. Inputs and transient effects remain
44    /// available until `finish_tick`; initial publication has no pending effects.
45    /// # Errors
46    /// Return terminal presentation-publication failures.
47    fn publish(&self, _world: &mut World) -> SessionResult {
48        Ok(())
49    }
50    /// Discard per-tick presentation effects after publication, or directly after
51    /// a replay tick. Runs before the adapter clears inputs and world trackers.
52    /// Must not change deterministic state or fail. Also runs after returned tick
53    /// or publication errors; panics terminate the worker without guaranteed cleanup.
54    fn finish_tick(&self, _world: &mut World) {}
55}
56
57/// Adapt a [`BevyGame`] to the engine-independent [`Game`] session API.
58#[derive(Clone)]
59pub struct GameAdapter<G>(pub G);
60/// Worker-owned simulation constructed by [`GameAdapter`].
61pub struct BevySimulation<G> {
62    app: App,
63    game: G,
64}
65impl<G: BevyGame> Game for GameAdapter<G> {
66    type Command = G::Command;
67    type Initialization = G::Initialization;
68    type Simulation = BevySimulation<G>;
69    const ID: [u8; 16] = G::ID;
70    const VERSION: u32 = G::VERSION;
71    fn create(
72        &self,
73        initialization: G::Initialization,
74        tick_duration: Duration,
75    ) -> SessionResult<Self::Simulation> {
76        let mut app = App::new();
77        app.init_resource::<TickNumber>();
78        app.init_resource::<TickInputs<G::Command>>();
79        app.insert_resource(TickDuration(tick_duration));
80        app.init_schedule(SimStep);
81        self.0.build(initialization, &mut app)?;
82        Ok(BevySimulation {
83            app,
84            game: self.0.clone(),
85        })
86    }
87}
88impl<G: BevyGame> Simulation<G::Command> for BevySimulation<G> {
89    fn current_tick(&self) -> u64 {
90        self.app.world().resource::<TickNumber>().0
91    }
92    fn state_hash(&mut self) -> u64 {
93        self.game.state_hash(self.app.world_mut())
94    }
95    fn advance(&mut self, tick: Tick<G::Command>) -> SessionResult {
96        let world = self.app.world_mut();
97        world.resource_mut::<TickNumber>().0 = tick.number;
98        world.resource_mut::<TickInputs<G::Command>>().0 = tick.inputs;
99        world.run_schedule(SimStep);
100        Ok(())
101    }
102    fn finish_tick(&mut self) {
103        let world = self.app.world_mut();
104        self.game.finish_tick(world);
105        world.resource_mut::<TickInputs<G::Command>>().0.clear();
106        world.clear_trackers();
107    }
108    fn publish(&mut self) -> SessionResult {
109        self.game.publish(self.app.world_mut())
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use crate::test_game::Example;
117    use std::sync::atomic::Ordering;
118    #[test]
119    fn factory_and_publication_share_the_same_tick_contract() {
120        let game = Example::default();
121        let observed = game.published.clone();
122        let mut sim = GameAdapter(game)
123            .create((), Duration::from_millis(10))
124            .unwrap();
125        assert_eq!(
126            sim.app.world().resource::<TickDuration>().0,
127            Duration::from_millis(10)
128        );
129        sim.advance(Tick {
130            number: 1,
131            inputs: vec![Input {
132                participant: synctick::ParticipantId::Host,
133                command: (),
134            }],
135        })
136        .unwrap();
137        assert_eq!(observed.load(Ordering::Acquire), 0);
138        sim.finish_tick();
139        assert_eq!(sim.game.cleaned_inputs.load(Ordering::Acquire), 1);
140        assert!(sim.app.world().resource::<TickInputs<()>>().0.is_empty());
141        sim.publish().unwrap();
142        assert_eq!(sim.game.published_inputs.load(Ordering::Acquire), 0);
143        assert_eq!(observed.load(Ordering::Acquire), 2);
144        sim.advance(Tick {
145            number: 2,
146            inputs: vec![Input {
147                participant: synctick::ParticipantId::Host,
148                command: (),
149            }],
150        })
151        .unwrap();
152        sim.publish().unwrap();
153        assert_eq!(sim.game.published_inputs.load(Ordering::Acquire), 1);
154        sim.finish_tick();
155        assert_eq!(sim.game.cleaned_inputs.load(Ordering::Acquire), 1);
156        assert_eq!(observed.load(Ordering::Acquire), 3);
157        assert!(sim.app.world().resource::<TickInputs<()>>().0.is_empty());
158    }
159}