ferravex_play/gameplay/
progression.rs

1//! Integer experience curves, with at most 1023 promotions per award.
2//!
3//! Awards saturate the stored `u64` XP **before** subtracting promotion costs.
4//! Excess at the level cap is retained within that integer bound. This is not
5//! mathematically unbounded XP: saturation can discard part of a request, and
6//! partitioning a saturating award can change its final remainder.
7//!
8//! Preview is advisory; only a newly accepted game event should call
9//! [`Progression::award_report`] and grant its promotions. Neither preview nor
10//! restore issues rewards. Games own event deduplication and must restore their
11//! reward state consistently with progression, or retain a separate reward ledger
12//! across rollback. This helper cannot undo external effects or prevent a game
13//! from re-awarding a replayed event after loading an older snapshot.
14use super::LoopError;
15
16/// Exact result of applying the legacy saturating-add-then-promote rule.
17///
18/// Preview and commit return the same value if no state changes between them.
19/// Copies of reports are observations, not single-use reward tokens. Only the
20/// report returned by a new accepted award should drive rewards.
21///
22/// Using `u128` arithmetic, `xp_before + accepted_xp == xp_spent + xp_after`.
23/// `accepted_xp` is the delta admitted by the initial saturating addition, not
24/// `xp_after - xp_before`, which may be negative after promotion costs.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct AwardReport {
27    /// XP requested by the caller.
28    pub requested_xp: u64,
29    /// XP admitted before promotion subtraction; at most `u64::MAX - xp_before`.
30    pub accepted_xp: u64,
31    /// Requested XP discarded by saturation, even if promotions free room later.
32    pub discarded_xp: u64,
33    /// Whether any requested XP was discarded. Exactly filling storage is false.
34    pub saturated: bool,
35    /// Level before this award.
36    pub level_before: u16,
37    /// Level after this award.
38    pub level_after: u16,
39    /// New promotions, bounded by 1023; zero when already at the cap.
40    pub promotions: u16,
41    /// Retained XP before the initial addition.
42    pub xp_before: u64,
43    /// Total XP subtracted for newly earned levels (not a lifetime total).
44    pub xp_spent: u64,
45    /// Retained remainder after promotion subtraction; may be large at the cap.
46    pub xp_after: u64,
47    /// Whether `level_after` equals the authored maximum, including maximum 1.
48    pub at_cap: bool,
49}
50
51/// Plain state plus the exact authored curve, with no serialization or wire ABI.
52///
53/// Public fields let a host decode its own format. [`Progression::restore`]
54/// validates every field before replacing state; this type alone is untrusted.
55/// No fingerprint substitutes for equality of `base`, `growth` and `maximum`.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct ProgressionSnapshot {
58    /// Positive initial promotion cost.
59    pub base: u32,
60    /// Per-level additive cost growth, including zero.
61    pub growth: u32,
62    /// Authored level cap, in `1..=1024`.
63    pub maximum: u16,
64    /// Current level, in `1..=maximum`.
65    pub level: u16,
66    /// Remainder, strictly below next cost unless at the cap.
67    pub xp: u64,
68}
69
70/// First failed restore check, in declaration order. Rejection is atomic.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum RestoreError {
73    /// Snapshot has zero base or a maximum outside `1..=1024`.
74    InvalidCurve,
75    /// Any authored value differs from the destination's exact configuration.
76    CurveMismatch,
77    /// Level is zero or above the snapshot's maximum.
78    InvalidLevel,
79    /// XP could already buy a promotion below the cap: state is not normalized.
80    UnsettledXp,
81}
82
83/// State-loading observation, deliberately containing no award/promotions.
84///
85/// An identical repeated restore has `before == after`. An older same-curve
86/// snapshot is valid rollback; there is no timestamp, revision or anti-replay
87/// guarantee. A snapshot from an old *different* curve is rejected.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub struct RestoreReport {
90    /// State before a successful load.
91    pub before: ProgressionSnapshot,
92    /// Validated state installed by the load.
93    pub after: ProgressionSnapshot,
94}
95
96/// Private, normalized progression state with an immutable authored curve.
97#[derive(Clone, Copy, Debug)]
98pub struct Progression {
99    base: u32,
100    growth: u32,
101    maximum: u16,
102    level: u16,
103    xp: u64,
104}
105impl Progression {
106    /// Start at level 1 with no XP. Zero growth and a maximum of 1 are valid.
107    ///
108    /// ```
109    /// use ferravex_play::gameplay::progression::Progression;
110    /// let p = Progression::new(10, 5, 3).unwrap();
111    /// assert_eq!((p.level(), p.xp(), p.next_cost()), (1, 0, Some(10)));
112    /// assert!(Progression::new(0, 5, 3).is_err());
113    /// ```
114    pub fn new(base: u32, growth: u32, maximum: u16) -> Result<Self, LoopError> {
115        if base == 0 || !(1..=1024).contains(&maximum) {
116            return Err(LoopError::Invalid);
117        }
118        Ok(Self {
119            base,
120            growth,
121            maximum,
122            level: 1,
123            xp: 0,
124        })
125    }
126    pub fn level(&self) -> u16 {
127        self.level
128    }
129    pub fn xp(&self) -> u64 {
130        self.xp
131    }
132    pub fn next_cost(&self) -> Option<u64> {
133        (self.level < self.maximum)
134            .then(|| u64::from(self.base) + u64::from(self.growth) * u64::from(self.level - 1))
135    }
136    /// Returns earned promotions; hosts apply rewards once from this result.
137    /// Excess at the level cap is retained for display, never re-awarded.
138    /// Addition saturates at `u64::MAX` before promotion costs are subtracted.
139    /// This is equivalent to [`Self::award_report`]'s `promotions` field.
140    pub fn award(&mut self, amount: u64) -> u16 {
141        self.award_report(amount).promotions
142    }
143
144    /// Compute the exact award without changing state or issuing rewards.
145    ///
146    /// A preview is not a reservation; recompute on commit after other awards or
147    /// restores. At most 1023 iterations, with no allocation or callbacks.
148    ///
149    /// ```
150    /// use ferravex_play::gameplay::progression::Progression;
151    /// let mut p = Progression::new(10, 5, 3).unwrap();
152    /// let preview = p.preview_award(30);
153    /// assert_eq!((p.level(), p.xp()), (1, 0));
154    /// assert_eq!((preview.promotions, preview.xp_spent, preview.xp_after), (2, 25, 5));
155    /// assert!(preview.at_cap);
156    /// assert_eq!(p.award_report(30), preview);
157    /// ```
158    pub fn preview_award(&self, amount: u64) -> AwardReport {
159        let mut next = *self;
160        next.xp = next.xp.saturating_add(amount);
161        let accepted_xp = next.xp - self.xp;
162        let mut xp_spent = 0;
163        while let Some(cost) = next.next_cost() {
164            if next.xp < cost {
165                break;
166            }
167            next.xp -= cost;
168            xp_spent += cost;
169            next.level += 1;
170        }
171        let discarded_xp = amount - accepted_xp;
172        AwardReport {
173            requested_xp: amount,
174            accepted_xp,
175            discarded_xp,
176            saturated: discarded_xp != 0,
177            level_before: self.level,
178            level_after: next.level,
179            promotions: next.level - self.level,
180            xp_before: self.xp,
181            xp_spent,
182            xp_after: next.xp,
183            at_cap: next.level == self.maximum,
184        }
185    }
186
187    /// Commit the same rule as [`Self::preview_award`], returning accepted data.
188    ///
189    /// Caller owns game-event acceptance and deduplication. Reward only this
190    /// call's promotions, once; no lifetime reward ledger is kept here.
191    ///
192    /// ```
193    /// use ferravex_play::gameplay::progression::Progression;
194    /// let mut p = Progression::new(10, 0, 2).unwrap();
195    /// p.award(9);
196    /// let report = p.award_report(u64::MAX);
197    /// assert_eq!((report.accepted_xp, report.discarded_xp), (u64::MAX - 9, 9));
198    /// assert!(report.saturated);
199    /// assert_eq!((report.promotions, p.xp()), (1, u64::MAX - 10));
200    /// ```
201    pub fn award_report(&mut self, amount: u64) -> AwardReport {
202        let report = self.preview_award(amount);
203        self.level = report.level_after;
204        self.xp = report.xp_after;
205        report
206    }
207
208    /// Capture state and every authored value, without normalizing or awarding.
209    /// See [`Self::restore`] for checked loading and an executable example.
210    pub fn snapshot(&self) -> ProgressionSnapshot {
211        ProgressionSnapshot {
212            base: self.base,
213            growth: self.growth,
214            maximum: self.maximum,
215            level: self.level,
216            xp: self.xp,
217        }
218    }
219
220    /// Atomically load validated state for this exact curve; never issue rewards.
221    ///
222    /// Checks authoring, exact configuration, level bounds, then XP normalization.
223    /// At the cap any `u64` remainder is valid. Older same-curve snapshots are
224    /// deliberately accepted for rollback, without undoing external side effects.
225    /// Restore corresponding game-owned reward/event state together, or maintain
226    /// an external deduplication ledger for effects that must survive rollback.
227    ///
228    /// ```
229    /// use ferravex_play::gameplay::progression::{Progression, RestoreError};
230    /// let mut p = Progression::new(10, 5, 3).unwrap();
231    /// let start = p.snapshot();
232    /// p.award_report(12);
233    /// let loaded = p.restore(start).unwrap();
234    /// assert_eq!((loaded.before.level, loaded.after.level), (2, 1));
235    /// let again = p.restore(start).unwrap();
236    /// assert_eq!(again.before, again.after); // No reward to replay.
237    /// let mut invalid = start;
238    /// invalid.xp = 10; // A pending promotion is not normalized saved state.
239    /// assert_eq!(p.restore(invalid), Err(RestoreError::UnsettledXp));
240    /// assert_eq!(p.snapshot(), start);
241    /// ```
242    pub fn restore(
243        &mut self,
244        snapshot: ProgressionSnapshot,
245    ) -> Result<RestoreReport, RestoreError> {
246        let mut next = Self::new(snapshot.base, snapshot.growth, snapshot.maximum)
247            .map_err(|_| RestoreError::InvalidCurve)?;
248        if (next.base, next.growth, next.maximum) != (self.base, self.growth, self.maximum) {
249            return Err(RestoreError::CurveMismatch);
250        }
251        if snapshot.level == 0 || snapshot.level > snapshot.maximum {
252            return Err(RestoreError::InvalidLevel);
253        }
254        next.level = snapshot.level;
255        if next.next_cost().is_some_and(|cost| snapshot.xp >= cost) {
256            return Err(RestoreError::UnsettledXp);
257        }
258        next.xp = snapshot.xp;
259        let report = RestoreReport {
260            before: self.snapshot(),
261            after: snapshot,
262        };
263        *self = next;
264        Ok(report)
265    }
266}
267#[cfg(test)]
268mod tests {
269    use super::*;
270    #[test]
271    fn large_and_partitioned_awards_have_identical_levels_and_remainders() {
272        let mut a = Progression::new(10, 5, 8).unwrap();
273        let mut b = a;
274        assert_eq!(a.award(85), 4);
275        for _ in 0..85 {
276            b.award(1);
277        }
278        assert_eq!((a.level(), a.xp()), (b.level(), b.xp()));
279        assert_eq!((a.level(), a.xp(), a.next_cost()), (5, 15, Some(30)));
280        a.award(u64::MAX);
281        assert_eq!(a.level(), 8);
282        assert_eq!(a.next_cost(), None);
283        assert_eq!(a.award(u64::MAX), 0);
284        assert!(Progression::new(0, 1, 2).is_err());
285    }
286}