ferravex_play/gameplay/
buffer.rs

1//! One pending command, consumed only when the host can execute it.
2//!
3//! Push only fresh gameplay input edges inside executed simulation ticks. Advance
4//! once per executed tick, not per render frame or per issued-but-skipped update.
5//! Outcome methods never invoke game code: `Executed` means the command was handed
6//! to the caller, which must apply its game rules before emitting accepted feedback.
7//!
8//! ```
9//! use ferravex_play::gameplay::buffer::{
10//!     AdvanceOutcome, CommandBuffer, ConsumeOutcome, PushOutcome,
11//! };
12//! let mut commands = CommandBuffer::new(0.125)?;
13//! assert_eq!(commands.push_checked(1), PushOutcome::Queued);
14//! assert_eq!(commands.push_checked(2), PushOutcome::Replaced(1));
15//! assert_eq!(commands.remaining_life(), Some(0.125));
16//! assert_eq!(commands.take_if_checked(false), ConsumeOutcome::Gated);
17//! assert_eq!(commands.advance_checked(0.0625)?, AdvanceOutcome::Pending);
18//! assert_eq!(commands.pending(), Some(2)); // Inspection does not consume.
19//! assert_eq!(commands.remaining_life(), Some(0.0625));
20//! assert_eq!(commands.take_if_checked(true), ConsumeOutcome::Executed(2));
21//! assert_eq!(commands.take_if_checked(true), ConsumeOutcome::Empty);
22//! assert_eq!(commands.push_checked(3), PushOutcome::Queued);
23//! assert_eq!(commands.advance_checked(0.125)?, AdvanceOutcome::Expired(3));
24//! assert_eq!(commands.advance_checked(0.0)?, AdvanceOutcome::Empty);
25//! assert_eq!(commands.remaining_life(), None);
26//! # Ok::<(), ferravex_play::gameplay::LoopError>(())
27//! ```
28use super::{LoopError, seconds};
29
30/// Result of admitting a fresh edge into the single command slot.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum PushOutcome<T: Copy> {
33    /// The empty slot now holds the supplied command for a full lifetime.
34    Queued,
35    /// The supplied command replaced this old value and reset the lifetime.
36    Replaced(T),
37}
38
39/// Result of advancing the command lifetime by a validated simulation delta.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum AdvanceOutcome<T: Copy> {
42    /// There was no pending command.
43    Empty,
44    /// The command remains pending; inspect it without consuming via the buffer.
45    Pending,
46    /// This value expired and was removed by this operation.
47    Expired(T),
48}
49
50/// Result of asking for a command with a caller-supplied execution gate.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum ConsumeOutcome<T: Copy> {
53    /// No command was pending, regardless of the gate.
54    Empty,
55    /// The closed gate retained the command and its exact remaining lifetime.
56    Gated,
57    /// This value was removed for execution by the caller, exactly once.
58    Executed(T),
59}
60
61/// Allocation-free storage for one pending input edge with a fixed lifetime.
62///
63/// A new edge always replaces the occupied slot; holding a button must not push
64/// again. Expiry occurs only on advancement, including zero-delta advancement:
65/// the historical `remaining <= 1e-9` seconds boundary is preserved. Thus a
66/// positive lifetime at or below that boundary can be consumed before its first
67/// advance, just as with the legacy methods. See the module example for outcomes.
68/// Commands need only be `Copy`: admission and outcomes never compare payloads
69/// or require them to implement `Debug` or equality traits.
70#[derive(Clone, Copy, Debug)]
71pub struct CommandBuffer<T: Copy> {
72    command: Option<T>,
73    remaining: f64,
74    lifetime: f64,
75}
76impl<T: Copy> CommandBuffer<T> {
77    pub fn new(lifetime: f32) -> Result<Self, LoopError> {
78        let lifetime = seconds(lifetime)?;
79        if lifetime == 0. {
80            return Err(LoopError::Invalid);
81        }
82        Ok(Self {
83            command: None,
84            remaining: 0.,
85            lifetime,
86        })
87    }
88    /// A new edge replaces the previous command. Holding a button is not an edge.
89    pub fn push(&mut self, command: T) {
90        let _ = self.push_checked(command);
91    }
92    /// Admit a fresh edge, returning the displaced value only on replacement.
93    ///
94    /// The one-slot capacity is deliberate: insertion cannot fail after checked
95    /// construction. Even an equal-valued edge replaces and refreshes the slot.
96    /// See the module example; this is the implementation used by [`Self::push`].
97    pub fn push_checked(&mut self, command: T) -> PushOutcome<T> {
98        let previous = self.command.replace(command);
99        self.remaining = self.lifetime;
100        match previous {
101            Some(previous) => PushOutcome::Replaced(previous),
102            None => PushOutcome::Queued,
103        }
104    }
105    /// Advance simulation time, discarding the detailed expiry outcome.
106    pub fn advance(&mut self, dt: f32) -> Result<(), LoopError> {
107        self.advance_checked(dt).map(|_| ())
108    }
109    /// Advance once per executed tick, reporting a removed expired value once.
110    ///
111    /// `dt` must be finite and in `0..=3600` seconds, even for an empty buffer.
112    /// Invalid input returns [`LoopError::Invalid`] without changing any state.
113    /// Expiry uses the existing inclusive `1e-9` seconds boundary, not a rounded
114    /// inspection value. No expiry is cached for a later call to report again.
115    /// See the module example; [`Self::advance`] shares this implementation.
116    pub fn advance_checked(&mut self, dt: f32) -> Result<AdvanceOutcome<T>, LoopError> {
117        let dt = seconds(dt)?;
118        self.remaining = (self.remaining - dt).max(0.);
119        if self.remaining <= 1e-9 {
120            let expired = self.command.take();
121            self.remaining = 0.;
122            return Ok(match expired {
123                Some(command) => AdvanceOutcome::Expired(command),
124                None => AdvanceOutcome::Empty,
125            });
126        }
127        Ok(AdvanceOutcome::Pending)
128    }
129    /// Consume if ready, discarding the distinction between empty and gated.
130    pub fn take_if(&mut self, ready: bool) -> Option<T> {
131        match self.take_if_checked(ready) {
132            ConsumeOutcome::Executed(command) => Some(command),
133            ConsumeOutcome::Empty | ConsumeOutcome::Gated => None,
134        }
135    }
136    /// Hand off a pending command only when the caller's execution gate is open.
137    ///
138    /// An empty slot reports `Empty` even for a closed gate. `Gated` changes no
139    /// state and invokes no speculative callback. `Executed` clears the command
140    /// and remaining life; it does not establish that the caller's game rules
141    /// accepted the action. See the module example and [`Self::take_if`].
142    pub fn take_if_checked(&mut self, ready: bool) -> ConsumeOutcome<T> {
143        match self.command {
144            None => ConsumeOutcome::Empty,
145            Some(_) if !ready => ConsumeOutcome::Gated,
146            Some(command) => {
147                self.clear();
148                ConsumeOutcome::Executed(command)
149            }
150        }
151    }
152    /// Discard any pending command and life, retaining the configured lifetime.
153    pub fn clear(&mut self) {
154        self.command = None;
155        self.remaining = 0.;
156    }
157    pub fn pending(&self) -> Option<T> {
158        self.command
159    }
160    /// Read remaining seconds without consuming, advancing or checking expiry.
161    ///
162    /// `None` means the slot is empty. `Some` preserves the internal `f64`
163    /// precision used by expiry, including a just-pushed sub-epsilon lifetime.
164    /// Repeated inspection and closed gates cannot refresh the lifetime.
165    /// See the module example for inspection before and after execution/expiry.
166    pub fn remaining_life(&self) -> Option<f64> {
167        self.command.map(|_| self.remaining)
168    }
169}
170#[cfg(test)]
171mod tests {
172    use super::*;
173    #[test]
174    fn unavailable_commands_survive_then_execute_once_or_expire() {
175        let mut b = CommandBuffer::new(0.12).unwrap();
176        b.push(7);
177        assert_eq!(b.take_if(false), None);
178        b.advance(0.1).unwrap();
179        assert_eq!(b.take_if(true), Some(7));
180        assert_eq!(b.take_if(true), None);
181        b.push(9);
182        b.advance(0.2).unwrap();
183        assert_eq!(b.take_if(true), None);
184        b.push(2);
185        assert_eq!(b.advance(f32::NAN), Err(LoopError::Invalid));
186        assert_eq!(b.pending(), Some(2));
187        b.push(3);
188        assert_eq!(b.take_if(true), Some(3));
189    }
190
191    #[test]
192    fn replacement_returns_only_the_displaced_value_and_refreshes_one_slot() {
193        let mut b = CommandBuffer::new(0.125).unwrap();
194        assert_eq!(b.push_checked(1), PushOutcome::Queued);
195        assert_eq!(b.advance_checked(0.0625), Ok(AdvanceOutcome::Pending));
196        assert_eq!(b.push_checked(2), PushOutcome::Replaced(1));
197        assert_eq!(b.remaining_life(), Some(0.125));
198        assert_eq!(b.push_checked(2), PushOutcome::Replaced(2));
199        for next in 3..1000 {
200            assert_eq!(b.push_checked(next), PushOutcome::Replaced(next - 1));
201        }
202        assert_eq!(b.take_if_checked(true), ConsumeOutcome::Executed(999));
203        assert_eq!(b.take_if_checked(true), ConsumeOutcome::Empty);
204        assert_eq!(b.advance_checked(0.125), Ok(AdvanceOutcome::Empty));
205        assert_eq!(b.remaining_life(), None);
206        assert_eq!(b.push_checked(1000), PushOutcome::Queued);
207    }
208
209    #[test]
210    fn inspection_and_gates_preserve_the_exact_command_and_life() {
211        let mut b = CommandBuffer::new(0.125).unwrap();
212        assert_eq!(b.take_if_checked(false), ConsumeOutcome::<u8>::Empty);
213        b.push(7);
214        b.advance(0.03125).unwrap();
215        for _ in 0..10 {
216            assert_eq!(b.pending(), Some(7));
217            assert_eq!(b.remaining_life(), Some(0.09375));
218            assert_eq!(b.take_if_checked(false), ConsumeOutcome::Gated);
219            assert_eq!(b.advance_checked(0.), Ok(AdvanceOutcome::Pending));
220        }
221        assert_eq!(b.advance_checked(0.09375), Ok(AdvanceOutcome::Expired(7)));
222        assert_eq!(b.advance_checked(0.), Ok(AdvanceOutcome::Empty));
223        assert_eq!(b.take_if_checked(false), ConsumeOutcome::Empty);
224        assert_eq!(b.take_if_checked(true), ConsumeOutcome::Empty);
225    }
226
227    #[test]
228    fn zero_and_public_epsilon_neighbors_keep_legacy_expiry() {
229        assert!(matches!(
230            CommandBuffer::<u8>::new(0.),
231            Err(LoopError::Invalid)
232        ));
233        // 1e-9 rounds down as f32; its next representable neighbor rounds up.
234        let below = 1e-9_f32;
235        let above = f32::from_bits(below.to_bits() + 1);
236        assert!(f64::from(below) < 1e-9);
237        assert!(f64::from(above) > 1e-9);
238        for lifetime in [f32::from_bits(1), below] {
239            let mut b = CommandBuffer::new(lifetime).unwrap();
240            b.push(1);
241            assert_eq!(b.remaining_life(), Some(f64::from(lifetime)));
242            assert_eq!(b.take_if_checked(false), ConsumeOutcome::Gated);
243            assert_eq!(b.take_if_checked(true), ConsumeOutcome::Executed(1));
244            b.push(2);
245            assert_eq!(b.advance_checked(0.), Ok(AdvanceOutcome::Expired(2)));
246            assert_eq!(b.remaining_life(), None);
247        }
248        let mut b = CommandBuffer::new(above).unwrap();
249        b.push(3);
250        assert_eq!(b.advance_checked(0.), Ok(AdvanceOutcome::Pending));
251        // Subtracting a valid small delta crosses the existing epsilon boundary.
252        assert_eq!(b.advance_checked(below), Ok(AdvanceOutcome::Expired(3)));
253        b.push(4);
254        assert_eq!(b.advance_checked(above), Ok(AdvanceOutcome::Expired(4)));
255    }
256
257    #[test]
258    fn exact_internal_epsilon_is_inclusive_and_inspection_does_not_expire_it() {
259        let mut b = CommandBuffer::new(0.125).unwrap();
260        b.push(8);
261        // Pin the exact internal comparison separately from f32 input rounding.
262        b.remaining = 1e-9;
263        assert_eq!(b.remaining_life(), Some(1e-9));
264        assert_eq!(b.pending(), Some(8));
265        assert_eq!(b.take_if_checked(false), ConsumeOutcome::Gated);
266        assert_eq!(b.advance_checked(0.), Ok(AdvanceOutcome::Expired(8)));
267        assert_eq!(b.advance_checked(0.), Ok(AdvanceOutcome::Empty));
268    }
269
270    #[test]
271    fn invalid_deltas_preserve_all_state_in_empty_and_occupied_buffers() {
272        let mut b = CommandBuffer::new(3600.).unwrap();
273        for occupied in [false, true] {
274            if occupied {
275                b.push(9);
276                b.advance(0.125).unwrap();
277            }
278            let before = (b.command, b.remaining, b.lifetime);
279            for invalid in [
280                f32::NAN,
281                f32::INFINITY,
282                f32::NEG_INFINITY,
283                -0.001,
284                f32::from_bits(3600_f32.to_bits() + 1),
285            ] {
286                assert_eq!(b.advance_checked(invalid), Err(LoopError::Invalid));
287                assert_eq!((b.command, b.remaining, b.lifetime), before);
288                assert_eq!(b.advance(invalid), Err(LoopError::Invalid));
289                assert_eq!((b.command, b.remaining, b.lifetime), before);
290                assert!(matches!(
291                    CommandBuffer::<u8>::new(invalid),
292                    Err(LoopError::Invalid)
293                ));
294            }
295        }
296        assert_eq!(b.advance_checked(3600.), Ok(AdvanceOutcome::Expired(9)));
297        assert_eq!(b.advance_checked(-0.), Ok(AdvanceOutcome::Empty));
298    }
299
300    #[test]
301    fn clear_resets_pending_life_but_retains_authored_configuration() {
302        let mut b = CommandBuffer::new(0.125).unwrap();
303        for command in 0..3 {
304            b.push(command);
305            b.advance(0.0625).unwrap();
306            b.clear();
307            b.clear();
308            assert_eq!(b.pending(), None);
309            assert_eq!(b.remaining_life(), None);
310            assert_eq!(b.take_if_checked(false), ConsumeOutcome::Empty);
311            assert_eq!(b.advance_checked(0.), Ok(AdvanceOutcome::Empty));
312            assert_eq!(b.push_checked(command + 1), PushOutcome::Queued);
313            assert_eq!(b.remaining_life(), Some(0.125));
314        }
315    }
316
317    #[test]
318    fn legacy_wrappers_share_checked_state_transitions() {
319        let mut old = CommandBuffer::new(0.125).unwrap();
320        let mut checked = old;
321        for command in 0..3 {
322            old.push(command);
323            checked.push_checked(command);
324            assert_eq!(old.advance(0.03125), Ok(()));
325            assert_eq!(
326                checked.advance_checked(0.03125),
327                Ok(AdvanceOutcome::Pending)
328            );
329            assert_eq!(old.take_if(false), None);
330            assert_eq!(checked.take_if_checked(false), ConsumeOutcome::Gated);
331            assert_eq!(old.pending(), checked.pending());
332            assert_eq!(old.remaining_life(), checked.remaining_life());
333        }
334        assert_eq!(old.take_if(true), Some(2));
335        assert_eq!(checked.take_if_checked(true), ConsumeOutcome::Executed(2));
336        old.push(3);
337        checked.push_checked(3);
338        old.advance(0.125).unwrap();
339        assert_eq!(
340            checked.advance_checked(0.125),
341            Ok(AdvanceOutcome::Expired(3))
342        );
343        assert_eq!(
344            (old.command, old.remaining),
345            (checked.command, checked.remaining)
346        );
347    }
348
349    #[test]
350    fn tick_input_edges_refresh_only_on_actual_new_presses() {
351        use crate::input::{ActionMap, Binding, InputCode};
352
353        let mut input = ActionMap::default();
354        let code = InputCode::Key(32);
355        let jump = input.try_action(vec![Binding::digital(code)]).unwrap();
356        let mut b = CommandBuffer::new(0.0625).unwrap();
357        input.feed(code, 1.);
358        assert!(input.peek(jump).pressed); // A zero-tick frame consumes nothing.
359        assert_eq!(b.pending(), None);
360        assert!(input.consume_tick(jump).pressed);
361        assert_eq!(b.push_checked(1), PushOutcome::Queued);
362        assert_eq!(b.advance_checked(0.015625), Ok(AdvanceOutcome::Pending));
363        assert_eq!(b.take_if_checked(false), ConsumeOutcome::Gated);
364        assert!(!input.consume_tick(jump).pressed); // Held in a catch-up update.
365        assert_eq!(b.advance_checked(0.015625), Ok(AdvanceOutcome::Pending));
366        assert_eq!(b.remaining_life(), Some(0.03125));
367        input.feed(code, 0.);
368        input.feed(code, 1.);
369        assert!(input.consume_tick(jump).pressed);
370        assert_eq!(b.push_checked(2), PushOutcome::Replaced(1));
371        assert_eq!(b.remaining_life(), Some(0.0625));
372        assert_eq!(b.take_if_checked(true), ConsumeOutcome::Executed(2));
373    }
374}