ferravex_play/gameplay/upgrades.rs
1//! Capped upgrade ranks and distinct seeded offers. The host defines rank effects.
2//!
3//! [`Upgrades`] retains the original host-managed spending policy.
4//! [`UpgradeChoices`] optionally owns ranks, earned points and one cached offer
5//! together. Existing games, including Neon's automatic upgrade, are unchanged.
6use super::{LoopError, loot::RewardRng};
7#[derive(Clone, Copy, Debug)]
8pub struct Upgrades<const N: usize> {
9 ranks: [u8; N],
10 caps: [u8; N],
11}
12/// Identity within one caller-scoped choice-session namespace.
13///
14/// Only a session can issue tokens. Copying a token/snapshot does not reserve a
15/// point or make it reusable after acceptance, abandonment or reset. Namespaces
16/// are caller-assigned nonzero values, not global uniqueness or security: two
17/// sessions created with the same namespace can issue equal tokens. Use a fresh
18/// namespace whenever recreating a session whose old callbacks may survive.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct UpgradeOfferId {
21 namespace: u64,
22 serial: u64,
23}
24
25impl UpgradeOfferId {
26 /// Caller-assigned namespace; see [`UpgradeChoices::new`].
27 pub fn namespace(self) -> u64 {
28 self.namespace
29 }
30
31 /// Monotonic serial in `1..=u64::MAX`, never reused by a live session.
32 pub fn serial(self) -> u64 {
33 self.serial
34 }
35}
36
37/// Read-only fixed-storage offer snapshot. Only its session can accept it.
38///
39/// Choices are upgrade indices, with trailing `None` for a short eligible pool.
40/// Keep the snapshot across redraws and submit its identity with the chosen ID.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct UpgradeOffer<const K: usize> {
43 id: UpgradeOfferId,
44 choices: [Option<usize>; K],
45}
46
47impl<const K: usize> UpgradeOffer<K> {
48 /// Stable identity, including across repeated [`UpgradeChoices::open`] calls.
49 pub fn id(&self) -> UpgradeOfferId {
50 self.id
51 }
52
53 /// Borrow the fixed array without rerolling, allocating or consuming points.
54 pub fn choices(&self) -> &[Option<usize>; K] {
55 &self.choices
56 }
57}
58
59/// Choice-session failures, each leaving ranks, points and pending offer intact.
60///
61/// These are additive; the legacy [`LoopError`] and upgrade APIs are unchanged.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum UpgradeChoiceError {
64 /// Zero namespace, invalid upgrade state, or `K > N` at construction.
65 Invalid,
66 /// Explicit credit would exceed `u32::MAX`; no partial credit is admitted.
67 BalanceOverflow,
68 /// All `u64::MAX` offer serials were issued. Reset cannot rewind this limit.
69 SerialExhausted,
70 /// No pending offer, or the namespace/serial differs from its identity.
71 StaleOffer,
72 /// No earned point is available.
73 NoPoints,
74 /// The chosen upgrade index is absent from the pending offer.
75 NotOffered,
76 /// The offered upgrade is already at its cap.
77 Capped,
78}
79
80/// Observation of one committed rank and one spent point, not a reward token.
81///
82/// Emit feedback only from this accepted result. Copying/replaying this receipt
83/// grants no additional rank or credit; it has no persistence or wire format.
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85#[must_use]
86pub struct AcceptedUpgrade {
87 /// Consumed offer identity; subsequent choices using it are stale.
88 pub offer: UpgradeOfferId,
89 /// Chosen upgrade index.
90 pub upgrade: usize,
91 /// Rank immediately before acceptance.
92 pub rank_before: u8,
93 /// Rank immediately after acceptance, exactly one higher.
94 pub rank_after: u8,
95 /// Earned balance immediately before acceptance.
96 pub points_before: u32,
97 /// Earned balance immediately after acceptance, exactly one lower.
98 pub points_after: u32,
99}
100
101/// Discarded state returned by [`UpgradeChoices::reset`], never an award.
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103#[must_use]
104pub struct UpgradeReset<const K: usize> {
105 /// Points deliberately discarded by the reset.
106 pub discarded_points: u32,
107 /// Abandoned offer, if any, for host UI/callback cleanup.
108 pub pending: Option<UpgradeOffer<K>>,
109}
110
111/// Optional bounded owner of ranks, earned points and one active choice set.
112///
113/// No `Clone`/`Copy`, mutable rank access, callbacks, event queue or storage I/O.
114/// Acceptance commits solely owned state under `&mut self`; it is not an
115/// external transaction. Snapshots and [`Self::upgrades`] are observations.
116/// The host owns award authority/deduplication: credit only a newly accepted
117/// award's promotions, never preview/restore/replayed reports. Check balance
118/// capacity before committing an external award, or retain an explicit owed
119/// award if credit fails; this adapter cannot roll back external progression.
120///
121/// Storage is `O(N + K)` with `1 <= N <= 256` and `0 <= K <= N`. Operations
122/// allocate nothing. Opening delegates to the existing [`Upgrades::offers`]
123/// (at most `N` eligibility visits and `K` draws); it adds no weighted algorithm.
124/// Caller-supplied RNG, clocks and event IDs remain outside the session.
125///
126/// ```
127/// use ferravex_play::gameplay::{
128/// loot::RewardRng,
129/// upgrades::{UpgradeChoices, UpgradeChoiceError, Upgrades},
130/// };
131/// let mut choices = UpgradeChoices::<3, 2>::new(Upgrades::new([2, 1, 1]).unwrap(), 7)
132/// .unwrap();
133/// let mut rng = RewardRng::new(42);
134/// assert_eq!(choices.open(&mut rng).unwrap(), None); // No earned point.
135/// assert_eq!(choices.credit(2).unwrap(), 2); // Host accepted a new award.
136/// let offer = choices.open(&mut rng).unwrap().unwrap();
137/// assert_eq!(choices.pending(), Some(&offer));
138/// assert_eq!(choices.open(&mut rng).unwrap(), Some(offer)); // Redraw, no RNG.
139/// assert_eq!((offer.id().namespace(), offer.id().serial()), (7, 1));
140/// let id = offer.choices()[0].unwrap();
141/// let accepted = choices.choose(offer.id(), id).unwrap();
142/// assert_eq!((accepted.rank_before, accepted.rank_after), (0, 1));
143/// assert_eq!((accepted.points_before, accepted.points_after), (2, 1));
144/// assert_eq!(choices.upgrades().rank(id), Some(1));
145/// assert_eq!(choices.choose(offer.id(), id), Err(UpgradeChoiceError::StaleOffer));
146/// let next = choices.open(&mut rng).unwrap().unwrap();
147/// assert_eq!(choices.abandon(), Some(next)); // Point retained, serial consumed.
148/// let pending = choices.open(&mut rng).unwrap().unwrap();
149/// let reset = choices.reset();
150/// assert_eq!((reset.discarded_points, reset.pending), (1, Some(pending)));
151/// assert_eq!((choices.points(), choices.upgrades().rank(id)), (0, Some(0)));
152/// choices.credit(1).unwrap();
153/// let fresh = choices.open(&mut rng).unwrap().unwrap();
154/// assert!(fresh.id().serial() > pending.id().serial());
155/// assert_eq!(choices.choose(pending.id(), id), Err(UpgradeChoiceError::StaleOffer));
156/// ```
157#[derive(Debug)]
158pub struct UpgradeChoices<const N: usize, const K: usize> {
159 upgrades: Upgrades<N>,
160 points: u32,
161 namespace: u64,
162 next_serial: Option<u64>,
163 pending: Option<UpgradeOffer<K>>,
164}
165
166impl<const N: usize, const K: usize> UpgradeChoices<N, K> {
167 /// Own an existing valid rank set with zero points and serial 1 next.
168 ///
169 /// Validate `N`, caps/ranks, `K`, and a nonzero namespace before construction.
170 /// A namespace must be fresh relative to any surviving callbacks from other
171 /// sessions. Reusing it is safe only after all old tokens are unreachable.
172 /// No global registry, authenticated token or save/replay format is implied.
173 pub fn new(upgrades: Upgrades<N>, namespace: u64) -> Result<Self, UpgradeChoiceError> {
174 if N == 0
175 || N > 256
176 || K > N
177 || namespace == 0
178 || upgrades.caps.contains(&0)
179 || upgrades
180 .ranks
181 .iter()
182 .zip(upgrades.caps)
183 .any(|(&r, c)| r > c)
184 {
185 return Err(UpgradeChoiceError::Invalid);
186 }
187 Ok(Self {
188 upgrades,
189 points: 0,
190 namespace,
191 next_serial: Some(1),
192 pending: None,
193 })
194 }
195
196 /// Observe ranks; no mutable reference or live ownership copy is exposed.
197 pub fn upgrades(&self) -> &Upgrades<N> {
198 &self.upgrades
199 }
200
201 /// Unspent explicitly credited points.
202 pub fn points(&self) -> u32 {
203 self.points
204 }
205
206 /// Inspect the existing offer without touching RNG or balance.
207 pub fn pending(&self) -> Option<&UpgradeOffer<K>> {
208 self.pending.as_ref()
209 }
210
211 /// Explicit checked earned-point credit, returning the new total.
212 ///
213 /// Zero is a no-op; overflow changes nothing, including the offer. There is
214 /// no award deduplication: repeated successful credits intentionally add
215 /// again. Authority, replay/rollback consistency and event identity belong
216 /// to the caller. Credit never rerolls or replaces a pending offer.
217 pub fn credit(&mut self, points: u32) -> Result<u32, UpgradeChoiceError> {
218 let total = self
219 .points
220 .checked_add(points)
221 .ok_or(UpgradeChoiceError::BalanceOverflow)?;
222 self.points = total;
223 Ok(total)
224 }
225
226 /// Return the cached offer or generate one using [`Upgrades::offers`].
227 ///
228 /// Exact order: cached offer first; then zero points, `K == 0` or all ranks
229 /// capped return `Ok(None)`; then check serial exhaustion; then select and
230 /// publish. Every earlier return consumes zero RNG outputs and no serial.
231 /// A new offer consumes exactly `min(K, eligible_count)` existing RNG
232 /// outputs (including a sole eligible choice), and exactly one serial.
233 /// Short offers have trailing `None`; empty offers are never published.
234 /// Errors leave RNG and session intact. Constructor rejection of `K > N`
235 /// occurs before any RNG can be supplied. Redraws must retain this offer;
236 /// explicit [`Self::abandon`] permits a new draw on the next open.
237 pub fn open(
238 &mut self,
239 rng: &mut RewardRng,
240 ) -> Result<Option<UpgradeOffer<K>>, UpgradeChoiceError> {
241 if let Some(offer) = self.pending {
242 return Ok(Some(offer));
243 }
244 if self.points == 0 || K == 0 || self.upgrades.ranks == self.upgrades.caps {
245 return Ok(None);
246 }
247 let serial = self
248 .next_serial
249 .ok_or(UpgradeChoiceError::SerialExhausted)?;
250 let choices = self
251 .upgrades
252 .offers(rng)
253 .map_err(|_| UpgradeChoiceError::Invalid)?;
254 let offer = UpgradeOffer {
255 id: UpgradeOfferId {
256 namespace: self.namespace,
257 serial,
258 },
259 choices,
260 };
261 self.next_serial = serial.checked_add(1);
262 self.pending = Some(offer);
263 Ok(Some(offer))
264 }
265
266 /// Accept an offered upgrade, spending one point and adding one rank.
267 ///
268 /// Check identity (including no offer), point balance, membership, then cap,
269 /// in that order. Every rejection changes nothing. On acceptance the entire
270 /// offer is consumed, even with points/other choices left. Repeated clicks,
271 /// keypresses and delayed callbacks must submit the original token; they
272 /// then fail stale, even after a new offer opens. No implicit next draw.
273 /// Owned ranks cannot concurrently change through the public session API.
274 pub fn choose(
275 &mut self,
276 offer: UpgradeOfferId,
277 upgrade: usize,
278 ) -> Result<AcceptedUpgrade, UpgradeChoiceError> {
279 let pending = self
280 .pending
281 .as_ref()
282 .filter(|pending| pending.id == offer)
283 .ok_or(UpgradeChoiceError::StaleOffer)?;
284 let points_after = self
285 .points
286 .checked_sub(1)
287 .ok_or(UpgradeChoiceError::NoPoints)?;
288 if !pending.choices.contains(&Some(upgrade)) {
289 return Err(UpgradeChoiceError::NotOffered);
290 }
291 let rank_before = self
292 .upgrades
293 .rank(upgrade)
294 .ok_or(UpgradeChoiceError::NotOffered)?;
295 let rank_after = self
296 .upgrades
297 .apply(upgrade)
298 .map_err(|_| UpgradeChoiceError::Capped)?;
299 let accepted = AcceptedUpgrade {
300 offer,
301 upgrade,
302 rank_before,
303 rank_after,
304 points_before: self.points,
305 points_after,
306 };
307 self.points = points_after;
308 self.pending = None;
309 Ok(accepted)
310 }
311
312 /// Explicitly abandon the offer, returning it for host cleanup.
313 ///
314 /// No point is spent/refunded and the serial is never rewound. Any later
315 /// open is a deliberate new draw; old callbacks are stale.
316 pub fn abandon(&mut self) -> Option<UpgradeOffer<K>> {
317 self.pending.take()
318 }
319
320 /// Reset all ranks and points, returning discarded points and pending offer.
321 ///
322 /// Retains caps, namespace and monotonic serial state, including exhaustion.
323 /// It neither resets the caller's RNG nor credits a reward. A deterministic
324 /// restart reseeds the caller RNG separately; reproduced choices still get
325 /// fresh serials. Recreate with a fresh namespace to recover from exhaustion.
326 pub fn reset(&mut self) -> UpgradeReset<K> {
327 let reset = UpgradeReset {
328 discarded_points: self.points,
329 pending: self.pending.take(),
330 };
331 self.points = 0;
332 self.upgrades.ranks = [0; N];
333 reset
334 }
335}
336impl<const N: usize> Upgrades<N> {
337 pub fn new(caps: [u8; N]) -> Result<Self, LoopError> {
338 if N == 0 || N > 256 || caps.contains(&0) {
339 return Err(LoopError::Invalid);
340 }
341 Ok(Self {
342 ranks: [0; N],
343 caps,
344 })
345 }
346 pub fn rank(&self, id: usize) -> Option<u8> {
347 self.ranks.get(id).copied()
348 }
349 /// Only call after spending the host's earned upgrade point.
350 pub fn apply(&mut self, id: usize) -> Result<u8, LoopError> {
351 let cap = *self.caps.get(id).ok_or(LoopError::Invalid)?;
352 if self.ranks[id] >= cap {
353 return Err(LoopError::Unavailable);
354 }
355 self.ranks[id] += 1;
356 Ok(self.ranks[id])
357 }
358 /// Fixed scratch, no duplicate or maxed offers. Fewer eligible choices leave
359 /// trailing None entries. Persist chosen IDs, not RNG state, in run records.
360 pub fn offers<const K: usize>(
361 &self,
362 rng: &mut RewardRng,
363 ) -> Result<[Option<usize>; K], LoopError> {
364 if K > N {
365 return Err(LoopError::Invalid);
366 }
367 let mut eligible = [0; N];
368 let mut count = 0;
369 for id in 0..N {
370 if self.ranks[id] < self.caps[id] {
371 eligible[count] = id;
372 count += 1;
373 }
374 }
375 let mut offers = [None; K];
376 for slot in &mut offers {
377 if count == 0 {
378 break;
379 }
380 let index = (rng.next_u64() % count as u64) as usize;
381 *slot = Some(eligible[index]);
382 count -= 1;
383 eligible[index] = eligible[count];
384 }
385 Ok(offers)
386 }
387}
388#[cfg(test)]
389mod tests {
390 use super::*;
391 #[test]
392 fn offers_exclude_maxed_ranks_and_never_duplicate() {
393 let mut u = Upgrades::new([1, 2, 1]).unwrap();
394 u.apply(0).unwrap();
395 let offers = u.offers::<3>(&mut RewardRng::new(7)).unwrap();
396 assert_eq!(offers[2], None);
397 assert_ne!(offers[0], offers[1]);
398 assert!(!offers.contains(&Some(0)));
399 assert_eq!(u.apply(0), Err(LoopError::Unavailable));
400 u.apply(1).unwrap();
401 u.apply(1).unwrap();
402 u.apply(2).unwrap();
403 assert_eq!(u.offers::<2>(&mut RewardRng::new(1)).unwrap(), [None, None]);
404 }
405
406 #[test]
407 fn choice_constructor_rejects_invalid_private_state_and_configuration() {
408 assert!(matches!(
409 UpgradeChoices::<0, 0>::new(
410 Upgrades {
411 ranks: [],
412 caps: []
413 },
414 1
415 ),
416 Err(UpgradeChoiceError::Invalid)
417 ));
418 assert!(matches!(
419 UpgradeChoices::<257, 0>::new(
420 Upgrades {
421 ranks: [0; 257],
422 caps: [1; 257]
423 },
424 1
425 ),
426 Err(UpgradeChoiceError::Invalid)
427 ));
428 for (ranks, caps) in [([0], [0]), ([2], [1])] {
429 assert!(matches!(
430 UpgradeChoices::<1, 1>::new(Upgrades { ranks, caps }, 1),
431 Err(UpgradeChoiceError::Invalid)
432 ));
433 }
434 assert!(matches!(
435 UpgradeChoices::<1, 2>::new(Upgrades::new([1]).unwrap(), 1),
436 Err(UpgradeChoiceError::Invalid)
437 ));
438 assert!(matches!(
439 UpgradeChoices::<1, 1>::new(Upgrades::new([1]).unwrap(), 0),
440 Err(UpgradeChoiceError::Invalid)
441 ));
442 }
443
444 #[test]
445 fn defensive_choice_preflight_order_and_atomicity() {
446 let mut choices = UpgradeChoices::<2, 1>::new(Upgrades::new([1, 1]).unwrap(), 1).unwrap();
447 choices.credit(1).unwrap();
448 let offer = choices.open(&mut RewardRng::new(7)).unwrap().unwrap();
449 let id = offer.choices()[0].unwrap();
450 // Public ownership forbids concurrent rank edits and point debits. Fault
451 // injection here verifies the final guards without exposing such edits.
452 choices.upgrades.apply(id).unwrap();
453 choices.points = 0;
454 let stale = UpgradeOfferId {
455 namespace: 2,
456 serial: offer.id().serial(),
457 };
458 assert_eq!(
459 choices.choose(stale, usize::MAX),
460 Err(UpgradeChoiceError::StaleOffer)
461 );
462 assert_eq!(
463 choices.choose(offer.id(), usize::MAX),
464 Err(UpgradeChoiceError::NoPoints)
465 );
466 assert_eq!(
467 choices.choose(offer.id(), id),
468 Err(UpgradeChoiceError::NoPoints)
469 );
470 assert_eq!(choices.points(), 0);
471 assert_eq!(choices.pending(), Some(&offer));
472 assert_eq!(
473 choices.upgrades().ranks,
474 [u8::from(id == 0), u8::from(id == 1)]
475 );
476 choices.credit(1).unwrap();
477 assert_eq!(
478 choices.choose(offer.id(), usize::MAX),
479 Err(UpgradeChoiceError::NotOffered)
480 );
481 assert_eq!(
482 choices.choose(offer.id(), id),
483 Err(UpgradeChoiceError::Capped)
484 );
485 assert_eq!(choices.points(), 1);
486 assert_eq!(choices.pending(), Some(&offer));
487 assert_eq!(choices.upgrades().rank(id), Some(1));
488 }
489
490 #[test]
491 fn last_serial_is_usable_once_and_reset_never_rewinds_exhaustion() {
492 let mut choices = UpgradeChoices::<1, 1>::new(Upgrades::new([2]).unwrap(), 11).unwrap();
493 choices.next_serial = Some(u64::MAX);
494 choices.credit(2).unwrap();
495 let mut rng = RewardRng::new(7);
496 let last = choices.open(&mut rng).unwrap().unwrap();
497 assert_eq!(last.id().serial(), u64::MAX);
498 let mut untouched = rng;
499 assert_eq!(choices.open(&mut rng), Ok(Some(last))); // Cached beats exhausted.
500 assert_eq!(rng.next_u64(), untouched.next_u64());
501 let accepted = choices.choose(last.id(), 0).unwrap();
502 assert_eq!((accepted.rank_after, accepted.points_after), (1, 1));
503 let mut untouched = rng;
504 assert_eq!(
505 choices.open(&mut rng),
506 Err(UpgradeChoiceError::SerialExhausted)
507 );
508 assert_eq!(rng.next_u64(), untouched.next_u64());
509 assert_eq!(choices.points(), 1);
510 assert_eq!(choices.upgrades().rank(0), Some(1));
511 let discarded = choices.reset();
512 assert_eq!(discarded.discarded_points, 1);
513 assert_eq!(choices.open(&mut rng), Ok(None)); // No points precedes exhaustion.
514 choices.credit(1).unwrap();
515 assert_eq!(
516 choices.open(&mut rng),
517 Err(UpgradeChoiceError::SerialExhausted)
518 );
519 assert_eq!(
520 choices.choose(last.id(), 0),
521 Err(UpgradeChoiceError::StaleOffer)
522 );
523
524 let mut fresh = UpgradeChoices::<1, 1>::new(Upgrades::new([2]).unwrap(), 12).unwrap();
525 fresh.credit(1).unwrap();
526 let offer = fresh.open(&mut rng).unwrap().unwrap();
527 assert_eq!(offer.id().serial(), 1);
528 assert_eq!(
529 fresh.choose(last.id(), 0),
530 Err(UpgradeChoiceError::StaleOffer)
531 );
532 assert_eq!(fresh.pending(), Some(&offer));
533 }
534
535 #[test]
536 fn exhausted_but_empty_or_zero_width_open_does_not_touch_entropy() {
537 let mut ranks = Upgrades::new([1]).unwrap();
538 ranks.apply(0).unwrap();
539 let mut capped = UpgradeChoices::<1, 1>::new(ranks, 1).unwrap();
540 let mut zero = UpgradeChoices::<1, 0>::new(Upgrades::new([1]).unwrap(), 2).unwrap();
541 capped.next_serial = None;
542 zero.next_serial = None;
543 capped.credit(1).unwrap();
544 zero.credit(1).unwrap();
545 let mut rng = RewardRng::new(9);
546 let mut untouched = rng;
547 assert_eq!(capped.open(&mut rng), Ok(None));
548 assert_eq!(zero.open(&mut rng), Ok(None));
549 assert_eq!(rng.next_u64(), untouched.next_u64());
550 assert_eq!((capped.points(), zero.points()), (1, 1));
551 }
552}