ferravex_play/gameplay/
checkpoint.rs

1//! Ordered, authored respawn anchors with rules-checked compact snapshots.
2//!
3//! [`Checkpoints::recovery`] describes where a host can respawn and which
4//! checkpoint comes next. It does not teleport entities or reset world state.
5//! Activation is monotonic; trusted save restoration may deliberately rewind.
6use super::LoopError;
7
8/// Compact save state. The host owns the fingerprint of the authored rules.
9///
10/// There is no timestamp or generation: two saves with the same rules and index
11/// are indistinguishable. A host that needs freshness checks must store them in
12/// its own save envelope.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct CheckpointSnapshot {
15    pub rules: u64,
16    pub index: usize,
17}
18
19/// An authored anchor paired with its route index.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct CheckpointAnchor<T> {
22    pub index: usize,
23    pub anchor: T,
24}
25
26/// A recovery target and the next eligible checkpoint, without changing state.
27///
28/// `next == None` means the current anchor is the last authored anchor. It does
29/// not declare the game won or prevent respawning there. Hosts apply the actual
30/// recovery and emit feedback only after accepting it.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct CheckpointRecovery<T> {
33    pub current: CheckpointAnchor<T>,
34    pub next: Option<CheckpointAnchor<T>>,
35}
36
37/// The result of an in-order checkpoint trigger.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum CheckpointActivation {
40    /// The next authored anchor became current; checkpoint feedback is eligible.
41    Activated { previous_index: usize, index: usize },
42    /// A duplicate trigger at the current anchor made no change.
43    Current { index: usize },
44    /// A trigger behind the current anchor made no change.
45    Stale { index: usize, current_index: usize },
46}
47
48/// How a successful trusted restore changed checkpoint progress.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum CheckpointRestore {
51    /// The save already identifies the current anchor.
52    Unchanged { index: usize },
53    /// An earlier anchor was restored, intentionally discarding later progress.
54    Rewound { previous_index: usize, index: usize },
55    /// A later saved anchor was restored, possibly beyond the next trigger.
56    Advanced { previous_index: usize, index: usize },
57}
58
59/// A rejected restore. Neither error changes the current checkpoint.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum CheckpointRestoreError {
62    /// Rules are checked before the saved index, including when both are invalid.
63    RulesMismatch { expected: u64, actual: u64 },
64    /// The rules match, but the saved index is outside the authored route.
65    InvalidIndex { index: usize, anchor_count: usize },
66}
67
68#[derive(Clone, Copy, Debug)]
69pub struct Checkpoints<T: Copy, const N: usize> {
70    anchors: [T; N],
71    index: usize,
72    rules: u64,
73}
74impl<T: Copy, const N: usize> Checkpoints<T, N> {
75    /// Hosts validate anchor geometry and supply a stable nonzero rules ID.
76    /// Change that ID whenever the route's anchors, order or recovery rules change;
77    /// this generic container cannot derive a fingerprint from arbitrary `T`.
78    pub fn new(rules: u64, anchors: [T; N]) -> Result<Self, LoopError> {
79        if N == 0 || N > 256 || rules == 0 {
80            return Err(LoopError::Invalid);
81        }
82        Ok(Self {
83            anchors,
84            index: 0,
85            rules,
86        })
87    }
88    pub fn index(&self) -> usize {
89        self.index
90    }
91    pub fn respawn(&self) -> T {
92        self.anchors[self.index]
93    }
94
95    /// Inspect the current respawn anchor with its authored index.
96    ///
97    /// ```
98    /// use ferravex_play::gameplay::checkpoint::{CheckpointAnchor, Checkpoints};
99    /// let checkpoints = Checkpoints::new(4, [10, 20]).unwrap();
100    /// assert_eq!(checkpoints.current_anchor(), CheckpointAnchor { index: 0, anchor: 10 });
101    /// ```
102    pub fn current_anchor(&self) -> CheckpointAnchor<T> {
103        CheckpointAnchor {
104            index: self.index,
105            anchor: self.respawn(),
106        }
107    }
108
109    /// Inspect the next eligible anchor, or `None` at the last authored anchor.
110    /// This never wraps to the start or advances progress.
111    ///
112    /// ```
113    /// use ferravex_play::gameplay::checkpoint::{CheckpointAnchor, Checkpoints};
114    /// let mut checkpoints = Checkpoints::new(4, [10, 20]).unwrap();
115    /// assert_eq!(checkpoints.next_anchor(), Some(CheckpointAnchor { index: 1, anchor: 20 }));
116    /// checkpoints.activate(1).unwrap();
117    /// assert_eq!(checkpoints.next_anchor(), None);
118    /// ```
119    pub fn next_anchor(&self) -> Option<CheckpointAnchor<T>> {
120        let index = self.index + 1;
121        self.anchors
122            .get(index)
123            .copied()
124            .map(|anchor| CheckpointAnchor { index, anchor })
125    }
126
127    /// Describe recovery without consuming it or mutating checkpoint/world state.
128    /// Repeated recovery remains available, including at a terminal anchor.
129    /// The host decides whether to respawn and resets entities, velocity, camera
130    /// history and any other world state in its own recovery transaction.
131    ///
132    /// ```
133    /// use ferravex_play::gameplay::checkpoint::{CheckpointRecovery, Checkpoints};
134    /// let checkpoints = Checkpoints::new(4, [(10, 5)]).unwrap();
135    /// let recovery: CheckpointRecovery<(i32, i32)> = checkpoints.recovery();
136    /// assert_eq!(recovery.current.index, 0);
137    /// assert_eq!(recovery.current.anchor, (10, 5));
138    /// assert_eq!(recovery.next, None);
139    /// assert_eq!(checkpoints.recovery(), recovery);
140    /// ```
141    pub fn recovery(&self) -> CheckpointRecovery<T> {
142        CheckpointRecovery {
143            current: self.current_anchor(),
144            next: self.next_anchor(),
145        }
146    }
147
148    /// Old/duplicate checkpoints cannot move the respawn backward. Skipping an
149    /// authored checkpoint fails, preventing exit triggers from bypassing a route.
150    pub fn activate(&mut self, index: usize) -> Result<bool, LoopError> {
151        self.activate_with_outcome(index)
152            .map(|outcome| matches!(outcome, CheckpointActivation::Activated { .. }))
153    }
154
155    /// Activate the next anchor, distinguishing accepted, duplicate and stale
156    /// triggers. Only `Activated` changes state or warrants checkpoint feedback.
157    /// Out-of-range indices return `Invalid`; skipping ahead returns `Unavailable`.
158    /// Both errors leave progress unchanged.
159    ///
160    /// ```
161    /// use ferravex_play::gameplay::checkpoint::{CheckpointActivation, Checkpoints};
162    /// let mut checkpoints = Checkpoints::new(4, [10, 20, 30]).unwrap();
163    /// assert_eq!(checkpoints.activate_with_outcome(1), Ok(CheckpointActivation::Activated {
164    ///     previous_index: 0, index: 1,
165    /// }));
166    /// assert_eq!(checkpoints.activate_with_outcome(1), Ok(CheckpointActivation::Current { index: 1 }));
167    /// assert_eq!(checkpoints.activate_with_outcome(0), Ok(CheckpointActivation::Stale {
168    ///     index: 0, current_index: 1,
169    /// }));
170    /// ```
171    pub fn activate_with_outcome(
172        &mut self,
173        index: usize,
174    ) -> Result<CheckpointActivation, LoopError> {
175        if index >= N {
176            return Err(LoopError::Invalid);
177        }
178        if index < self.index {
179            return Ok(CheckpointActivation::Stale {
180                index,
181                current_index: self.index,
182            });
183        }
184        if index == self.index {
185            return Ok(CheckpointActivation::Current { index });
186        }
187        if index != self.index + 1 {
188            return Err(LoopError::Unavailable);
189        }
190        let previous_index = self.index;
191        self.index = index;
192        Ok(CheckpointActivation::Activated {
193            previous_index,
194            index,
195        })
196    }
197    pub fn snapshot(&self) -> CheckpointSnapshot {
198        CheckpointSnapshot {
199            rules: self.rules,
200            index: self.index,
201        }
202    }
203    /// Trusted save restoration only. This changes respawn state, not world state;
204    /// the host restores inventory/objectives with its existing save transaction.
205    pub fn restore(&mut self, saved: CheckpointSnapshot) -> Result<(), LoopError> {
206        self.restore_with_outcome(saved)
207            .map(|_| ())
208            .map_err(|_| LoopError::Invalid)
209    }
210
211    /// Restore a trusted snapshot, reporting a rewind, advance or unchanged index.
212    /// Rules and index are validated before mutation; either error preserves all
213    /// checkpoint state. A matching old save may rewind and a later save may skip
214    /// anchors, as with [`Self::restore`]. This is not a gameplay trigger or a
215    /// network freshness check; [`CheckpointSnapshot`] has no generation field.
216    ///
217    /// Only checkpoint progress is restored. The host must coordinate its world
218    /// transaction before using [`Self::recovery`] to apply the resulting anchor.
219    ///
220    /// ```
221    /// use ferravex_play::gameplay::checkpoint::{
222    ///     CheckpointRestore, CheckpointRestoreError, CheckpointSnapshot, Checkpoints,
223    /// };
224    /// let mut checkpoints = Checkpoints::new(4, [10, 20, 30]).unwrap();
225    /// let start = checkpoints.snapshot();
226    /// checkpoints.activate(1).unwrap();
227    /// assert_eq!(checkpoints.restore_with_outcome(start), Ok(CheckpointRestore::Rewound {
228    ///     previous_index: 1, index: 0,
229    /// }));
230    /// let bad = CheckpointSnapshot { rules: 5, index: 2 };
231    /// assert_eq!(checkpoints.restore_with_outcome(bad), Err(CheckpointRestoreError::RulesMismatch {
232    ///     expected: 4, actual: 5,
233    /// }));
234    /// assert_eq!(checkpoints.snapshot(), start);
235    /// ```
236    pub fn restore_with_outcome(
237        &mut self,
238        saved: CheckpointSnapshot,
239    ) -> Result<CheckpointRestore, CheckpointRestoreError> {
240        if saved.rules != self.rules {
241            return Err(CheckpointRestoreError::RulesMismatch {
242                expected: self.rules,
243                actual: saved.rules,
244            });
245        }
246        if saved.index >= N {
247            return Err(CheckpointRestoreError::InvalidIndex {
248                index: saved.index,
249                anchor_count: N,
250            });
251        }
252        let previous_index = self.index;
253        let index = saved.index;
254        let outcome = match index.cmp(&previous_index) {
255            std::cmp::Ordering::Less => CheckpointRestore::Rewound {
256                previous_index,
257                index,
258            },
259            std::cmp::Ordering::Equal => CheckpointRestore::Unchanged { index },
260            std::cmp::Ordering::Greater => CheckpointRestore::Advanced {
261                previous_index,
262                index,
263            },
264        };
265        self.index = saved.index;
266        Ok(outcome)
267    }
268}
269#[cfg(test)]
270mod tests {
271    use super::*;
272    #[test]
273    fn checkpoints_are_ordered_and_snapshots_validate_before_mutation() {
274        let mut c = Checkpoints::new(4, [10, 20, 30]).unwrap();
275        assert_eq!(c.respawn(), 10);
276        assert_eq!(c.activate(2), Err(LoopError::Unavailable));
277        assert!(c.activate(1).unwrap());
278        assert!(!c.activate(0).unwrap());
279        let saved = c.snapshot();
280        assert!(c.activate(2).unwrap());
281        c.restore(saved).unwrap();
282        assert_eq!(c.respawn(), 20);
283        assert!(
284            c.restore(CheckpointSnapshot { rules: 5, index: 0 })
285                .is_err()
286        );
287        assert_eq!(c.index(), 1);
288        assert!(
289            c.restore(CheckpointSnapshot { rules: 4, index: 3 })
290                .is_err()
291        );
292        assert_eq!(c.index(), 1);
293    }
294
295    #[test]
296    fn recovery_inspects_current_and_next_without_consuming_or_advancing() {
297        // Equal values remain distinguishable by authored index.
298        let mut c = Checkpoints::new(4, [10, 10, 30]).unwrap();
299        for index in 0..3 {
300            c.activate(index).unwrap();
301            let before = c.snapshot();
302            let current = CheckpointAnchor {
303                index,
304                anchor: [10, 10, 30][index],
305            };
306            let next = [10, 10, 30]
307                .get(index + 1)
308                .copied()
309                .map(|anchor| CheckpointAnchor {
310                    index: index + 1,
311                    anchor,
312                });
313            let expected = CheckpointRecovery { current, next };
314            assert_eq!(c.current_anchor(), current);
315            assert_eq!(c.next_anchor(), next);
316            assert_eq!(c.recovery(), expected);
317            assert_eq!(c.recovery(), expected);
318            assert_eq!(c.respawn(), current.anchor);
319            assert_eq!(c.snapshot(), before);
320        }
321        assert_eq!(c.recovery().current.anchor, 30);
322        assert_eq!(c.recovery().next, None);
323    }
324
325    #[test]
326    fn activation_outcomes_cover_stale_duplicate_skipped_and_terminal_triggers() {
327        for current_index in 0..4 {
328            for index in [0, 1, 2, 3, 4, usize::MAX] {
329                let mut c = Checkpoints::new(4, [10, 20, 30, 40]).unwrap();
330                c.restore(CheckpointSnapshot {
331                    rules: 4,
332                    index: current_index,
333                })
334                .unwrap();
335                let mut legacy = c;
336                let before = c.snapshot();
337                let expected = if index >= 4 {
338                    Err(LoopError::Invalid)
339                } else if index < current_index {
340                    Ok(CheckpointActivation::Stale {
341                        index,
342                        current_index,
343                    })
344                } else if index == current_index {
345                    Ok(CheckpointActivation::Current { index })
346                } else if index == current_index + 1 {
347                    Ok(CheckpointActivation::Activated {
348                        previous_index: current_index,
349                        index,
350                    })
351                } else {
352                    Err(LoopError::Unavailable)
353                };
354                let accepted = expected
355                    .map(|outcome| matches!(outcome, CheckpointActivation::Activated { .. }));
356                assert_eq!(c.activate_with_outcome(index), expected);
357                assert_eq!(legacy.activate(index), accepted);
358                assert_eq!(c.snapshot(), legacy.snapshot());
359                if accepted == Ok(true) {
360                    assert_eq!(c.index(), index);
361                    assert_eq!(c.respawn(), [10, 20, 30, 40][index]);
362                } else {
363                    assert_eq!(c.snapshot(), before);
364                }
365            }
366        }
367    }
368
369    #[test]
370    fn trusted_restore_reports_rewinds_advances_and_unchanged_including_terminal() {
371        for previous_index in 0..4 {
372            for index in 0..4 {
373                let mut c = Checkpoints::new(4, [10, 20, 30, 40]).unwrap();
374                c.restore(CheckpointSnapshot {
375                    rules: 4,
376                    index: previous_index,
377                })
378                .unwrap();
379                let mut legacy = c;
380                let saved = CheckpointSnapshot { rules: 4, index };
381                let expected = if index < previous_index {
382                    CheckpointRestore::Rewound {
383                        previous_index,
384                        index,
385                    }
386                } else if index == previous_index {
387                    CheckpointRestore::Unchanged { index }
388                } else {
389                    CheckpointRestore::Advanced {
390                        previous_index,
391                        index,
392                    }
393                };
394                assert_eq!(c.restore_with_outcome(saved), Ok(expected));
395                assert_eq!(legacy.restore(saved), Ok(()));
396                assert_eq!(c.snapshot(), saved);
397                assert_eq!(legacy.snapshot(), saved);
398                assert_eq!(c.recovery(), legacy.recovery());
399                assert_eq!(c.current_anchor().anchor, [10, 20, 30, 40][index]);
400                assert_eq!(
401                    c.next_anchor().map(|a| a.index),
402                    (index < 3).then_some(index + 1)
403                );
404                assert_eq!(
405                    c.restore_with_outcome(saved),
406                    Ok(CheckpointRestore::Unchanged { index })
407                );
408            }
409        }
410    }
411
412    #[test]
413    fn restore_errors_preserve_progress_anchors_and_fingerprint() {
414        for current_index in 0..3 {
415            let mut c = Checkpoints::new(4, [10, 20, 30]).unwrap();
416            c.restore(CheckpointSnapshot {
417                rules: 4,
418                index: current_index,
419            })
420            .unwrap();
421            let before = c.snapshot();
422            let recovery = c.recovery();
423            for saved in [
424                CheckpointSnapshot { rules: 0, index: 0 },
425                CheckpointSnapshot { rules: 5, index: 2 },
426                CheckpointSnapshot {
427                    rules: 5,
428                    index: usize::MAX,
429                },
430                CheckpointSnapshot { rules: 4, index: 3 },
431                CheckpointSnapshot {
432                    rules: 4,
433                    index: usize::MAX,
434                },
435            ] {
436                let expected = if saved.rules == 4 {
437                    CheckpointRestoreError::InvalidIndex {
438                        index: saved.index,
439                        anchor_count: 3,
440                    }
441                } else {
442                    CheckpointRestoreError::RulesMismatch {
443                        expected: 4,
444                        actual: saved.rules,
445                    }
446                };
447                assert_eq!(c.restore_with_outcome(saved), Err(expected));
448                assert_eq!(c.snapshot(), before);
449                assert_eq!(c.recovery(), recovery);
450                assert_eq!(c.restore(saved), Err(LoopError::Invalid));
451                assert_eq!(c.snapshot(), before);
452                assert_eq!(c.recovery(), recovery);
453            }
454        }
455    }
456
457    #[test]
458    fn restoring_an_earlier_save_reopens_the_next_anchor() {
459        let mut c = Checkpoints::new(4, [10, 20, 30]).unwrap();
460        c.activate(1).unwrap();
461        let old_save = c.snapshot();
462        c.activate(2).unwrap();
463        assert_eq!(c.next_anchor(), None);
464        assert_eq!(
465            c.activate_with_outcome(old_save.index),
466            Ok(CheckpointActivation::Stale {
467                index: 1,
468                current_index: 2,
469            })
470        );
471        assert_eq!(c.index(), 2);
472        assert_eq!(
473            c.restore_with_outcome(old_save),
474            Ok(CheckpointRestore::Rewound {
475                previous_index: 2,
476                index: 1,
477            })
478        );
479        assert_eq!(
480            c.next_anchor(),
481            Some(CheckpointAnchor {
482                index: 2,
483                anchor: 30
484            })
485        );
486        assert_eq!(
487            c.activate_with_outcome(2),
488            Ok(CheckpointActivation::Activated {
489                previous_index: 1,
490                index: 2,
491            })
492        );
493    }
494
495    #[test]
496    fn single_anchor_and_maximum_route_recover_at_terminal_without_wraparound() {
497        let mut single = Checkpoints::new(4, [10]).unwrap();
498        assert_eq!(single.next_anchor(), None);
499        assert_eq!(
500            single.recovery().current,
501            CheckpointAnchor {
502                index: 0,
503                anchor: 10
504            }
505        );
506        assert_eq!(
507            single.activate_with_outcome(0),
508            Ok(CheckpointActivation::Current { index: 0 })
509        );
510        assert_eq!(single.activate_with_outcome(1), Err(LoopError::Invalid));
511        assert_eq!(
512            single.restore_with_outcome(single.snapshot()),
513            Ok(CheckpointRestore::Unchanged { index: 0 })
514        );
515
516        let mut maximum = Checkpoints::new(4, std::array::from_fn::<_, 256, _>(|i| i)).unwrap();
517        for index in 1..256 {
518            assert_eq!(
519                maximum.next_anchor(),
520                Some(CheckpointAnchor {
521                    index,
522                    anchor: index
523                })
524            );
525            assert!(maximum.activate(index).unwrap());
526        }
527        assert_eq!(maximum.recovery().current.index, 255);
528        assert_eq!(maximum.respawn(), 255);
529        assert_eq!(maximum.next_anchor(), None);
530        assert_eq!(maximum.activate_with_outcome(256), Err(LoopError::Invalid));
531        assert_eq!(maximum.index(), 255);
532        assert!(matches!(
533            Checkpoints::<u8, 0>::new(4, []),
534            Err(LoopError::Invalid)
535        ));
536        assert!(matches!(
537            Checkpoints::new(4, [0; 257]),
538            Err(LoopError::Invalid)
539        ));
540        assert!(matches!(Checkpoints::new(0, [10]), Err(LoopError::Invalid)));
541    }
542}