nadir/replay.rs
1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Replays: the game's actions played from a recording in place of the live
16//! input ([`App::play_replay`](crate::App::play_replay)), and [`Replay`], how
17//! far one got.
18
19use nadir_ecs::World;
20use nadir_input::{ActionSet, ActionState, Input, InputError, InputPlayer};
21use nadir_scene::TypeRegistry;
22
23use crate::app::LatchFn;
24
25/// A hash of every reflected component of `world`, as
26/// [`TypeRegistry::hash_world`] takes it, with the context the engine gives
27/// it. Determinism tests compare it run against run, tick after tick.
28///
29/// It is the same after the same ticks of the same replay, from the same
30/// start, whatever the frames were, as long as the game's frame systems
31/// change no reflected component and spawn or despawn nothing, and no tick
32/// system reads what frames set (an [`Animator`](crate::Animator)'s time,
33/// the `Sprite` fields that `nadir::animate` writes, [`TickStats`](crate::TickStats)),
34/// whether an asset has loaded, or the pointer or the wheel (ADR-0025).
35///
36/// # Panics
37///
38/// If the world has no [`TypeRegistry`] (every [`App`](crate::App)'s has
39/// one), or a reflected type's components, the registry, or the
40/// [`AssetServer`](nadir_assets::AssetServer), [`Clips`](crate::Clips) or
41/// [`CollisionLayers`](crate::CollisionLayers) resource are borrowed
42/// mutably elsewhere, as [`reflect_context`](crate::reflect_context)
43/// borrows them.
44pub fn world_hash(world: &World) -> u64 {
45 let registry = world.resource::<TypeRegistry>();
46 crate::reflect_context(world, "nadir::world_hash", |cx| {
47 registry.hash_world(world, &mut cx.hashing())
48 })
49}
50
51/// How the replay that [`App::play_replay`](crate::App::play_replay) plays
52/// is going: a resource that it adds.
53///
54/// `ticks` counts the replay's ticks that fed the actions so far. While a
55/// tick's systems run, it counts that tick.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum Replay {
58 /// Its ticks feed the actions.
59 Playing {
60 /// The ticks played, this one included.
61 ticks: u64,
62 },
63 /// It ended with its last tick, the `ticks`-th. The ticks after it are
64 /// latched from the live input.
65 Ended {
66 /// The ticks it held.
67 ticks: u64,
68 },
69 /// After `ticks` ticks, the next could not be read. The ticks after
70 /// the last played are latched from the live input.
71 Failed {
72 /// The ticks played before the one that could not be read.
73 ticks: u64,
74 /// Why it could not be read.
75 error: InputError,
76 },
77}
78
79/// A replay that is playing, whatever its action set.
80pub(crate) trait PlayReplay {
81 /// Starts a tick: latches the live input into a set of its own, so that
82 /// [`Input`] keeps its ticks and nothing of it reaches the actions, and
83 /// puts the replay's next tick into the game's [`ActionState`]. Returns
84 /// the ticks played, this one included.
85 fn latch(&mut self, input: &mut Input, world: &World) -> u64;
86
87 /// The ticks played so far.
88 fn ticks(&self) -> u64;
89
90 /// What reading ahead found after the tick just latched: `Ok(true)` if
91 /// another tick follows, `Ok(false)` at the end, or why the next tick
92 /// cannot be read.
93 fn ahead(&self) -> &Result<bool, InputError>;
94}
95
96/// A replay of the action set `A`, one tick read ahead of the actions, so
97/// that its end is known as its last tick ends.
98pub(crate) struct ReplayInput<A: ActionSet> {
99 player: InputPlayer<'static, A>,
100 /// The next tick's state.
101 next: ActionState<A>,
102 ahead: Result<bool, InputError>,
103 ticks: u64,
104 /// The live input's latch, into a set of its own.
105 live: LatchFn,
106}
107
108impl<A: ActionSet> ReplayInput<A> {
109 /// Reads `player`'s first tick ahead. `live` latches the live input
110 /// into a set of its own.
111 pub(crate) fn new(mut player: InputPlayer<'static, A>, live: LatchFn) -> Self {
112 let mut next = ActionState::new();
113 let ahead = player.next_tick(&mut next);
114 Self {
115 player,
116 next,
117 ahead,
118 ticks: 0,
119 live,
120 }
121 }
122}
123
124impl<A: ActionSet> PlayReplay for ReplayInput<A> {
125 fn latch(&mut self, input: &mut Input, world: &World) -> u64 {
126 (self.live)(input, world);
127 // `next_tick` fills every action, so the state swapped out is
128 // overwritten whole.
129 std::mem::swap(&mut *world.resource_mut::<ActionState<A>>(), &mut self.next);
130 self.ticks += 1;
131 self.ahead = self.player.next_tick(&mut self.next);
132 self.ticks
133 }
134
135 fn ticks(&self) -> u64 {
136 self.ticks
137 }
138
139 fn ahead(&self) -> &Result<bool, InputError> {
140 &self.ahead
141 }
142}