ferravex_play/gameplay/loot.rs
1//! Seeded weighted choices with setup-time validation, fixed storage and no floats.
2//!
3//! Single [`RewardTable::choose`] and [`RewardTable::roll`] retain their legacy
4//! mappings. Distinct draws remove **indices**, not caller-defined reward values,
5//! from local scratch weights; authored weights never change. Each call starts
6//! afresh. Persist the accepted prefix for a menu; do not reroll on redraw.
7//!
8//! A headless optional reward recipe, using accepted wave clears, actual earned
9//! promotions and capped upgrades (the existing games' selection policies stay
10//! unchanged). Run with `cargo test -p ferravex-play --doc gameplay::loot
11//! --offline --locked -j 2`. This host confirms a defeat after an admitted spawn;
12//! a game supplies that fact from its combat system on an actual simulation tick.
13//!
14//! ```
15//! use ferravex_play::gameplay::{
16//! loot::{DistinctDrawStatus, RewardRng, RewardTable},
17//! progression::Progression,
18//! upgrades::Upgrades,
19//! waves::{WaveSequence, WaveSpec},
20//! };
21//! let mut waves = WaveSequence::new([WaveSpec {
22//! credits: 1, interval: 0.125, rest: 0.0, reward: 10,
23//! }], 1).unwrap();
24//! let mut xp = Progression::new(10, 0, 4).unwrap();
25//! let caps = [1, 1, 1];
26//! let mut upgrades = Upgrades::new(caps).unwrap();
27//! let mut rng = RewardRng::new(7);
28//! let mut points = 0;
29//! assert!(waves.admit(1, 0));
30//! assert_eq!(waves.advance(0.125, 0.0, 1).unwrap(), None);
31//! // The admitted actor has now been defeated; only the clear earns XP.
32//! let clear = waves.advance(0.125, 0.0, 0).unwrap().unwrap();
33//! points += xp.award(u64::from(clear.reward));
34//! let authored = [3, 2, 1];
35//! let weights: [u32; 3] = std::array::from_fn(|id| {
36//! if upgrades.rank(id).unwrap() < caps[id] { authored[id] } else { 0 }
37//! });
38//! // All-capped pools need no table or entropy. Never spend an unearned point.
39//! if points > 0 && weights.iter().any(|&w| w > 0) {
40//! let table = RewardTable::new(weights).unwrap();
41//! let mut offers = [usize::MAX; 3];
42//! let report = table.roll_distinct_into(&mut rng, 3, &mut offers, 16).unwrap();
43//! assert_eq!(report.status, DistinctDrawStatus::Complete);
44//! // Keep this prefix across redraws. This headless host chooses its first
45//! // offer; an interactive host uses the player's submitted offered index.
46//! let displayed = &offers[..report.written];
47//! let chosen = displayed[0];
48//! if points > 0 && displayed.contains(&chosen)
49//! && upgrades.rank(chosen).unwrap() < caps[chosen]
50//! {
51//! points -= 1;
52//! upgrades.apply(chosen).unwrap();
53//! }
54//! assert_eq!(upgrades.rank(chosen), Some(1));
55//! }
56//! assert_eq!(points, 0);
57//! assert_eq!(xp.level(), 2);
58//! assert_eq!(waves.advance(0.125, 0.0, 0).unwrap(), None);
59//! ```
60use super::LoopError;
61
62/// Maximum request size for either distinct operation, independent of table size.
63pub const MAX_DISTINCT_DRAWS: usize = 256;
64/// Maximum number of SplitMix64 outputs consumed by one distinct roll call.
65pub const MAX_DISTINCT_SAMPLES: usize = 4096;
66
67/// Preflight failures: neither caller output nor RNG is changed.
68///
69/// See [`RewardTable::roll_distinct_into`] for precedence and a usage example.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum DistinctDrawError {
72 /// `requested` exceeds [`MAX_DISTINCT_DRAWS`].
73 RequestTooLarge { requested: usize },
74 /// Output cannot hold `min(requested, positive_weight_entries)` indices.
75 OutputTooSmall { required: usize, provided: usize },
76 /// `sample_budget` exceeds [`MAX_DISTINCT_SAMPLES`]. Zero is valid.
77 SampleBudgetTooLarge { sample_budget: usize },
78}
79
80/// Why a distinct call stopped; completion takes precedence over pool exhaustion,
81/// which takes precedence over input exhaustion. See [`DistinctDrawReport`].
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum DistinctDrawStatus {
84 /// Exactly the requested number of indices were written, including zero.
85 Complete,
86 /// All positive-weight indices were written, fewer than requested.
87 TableExhausted,
88 /// More offers were possible, but the roll's sample budget was consumed.
89 SampleBudgetExhausted,
90 /// More offers were possible, but the deterministic ticket slice ended.
91 TicketsExhausted,
92}
93
94/// Accepted prefix and exact input consumption, including rejected RNG samples.
95///
96/// Only `out[..written]` is changed. The tail retains its previous values on all
97/// outcomes. `samples_used` counts SplitMix64 outputs for rolls, or tickets for
98/// ticket draws. Exhaustion is not an error or a rollback: the prefix is valid,
99/// RNG consumption is retained, and another call starts with the full table.
100/// See the examples on [`RewardTable::roll_distinct_into`] and
101/// [`RewardTable::choose_distinct_into`].
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103#[must_use]
104pub struct DistinctDrawReport {
105 pub written: usize,
106 pub samples_used: usize,
107 pub status: DistinctDrawStatus,
108}
109
110#[derive(Clone, Copy, Debug)]
111pub struct RewardTable<const N: usize> {
112 weights: [u32; N],
113 total: u32,
114}
115#[derive(Clone, Copy, Debug)]
116pub struct RewardRng(u64);
117impl RewardRng {
118 pub fn new(seed: u64) -> Self {
119 Self(seed)
120 }
121 /// SplitMix64; gameplay variety only, never security or matchmaking secrets.
122 pub fn next_u64(&mut self) -> u64 {
123 self.0 = self.0.wrapping_add(0x9e3779b97f4a7c15);
124 let mut z = self.0;
125 z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
126 z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
127 z ^ (z >> 31)
128 }
129}
130impl<const N: usize> RewardTable<N> {
131 pub fn new(weights: [u32; N]) -> Result<Self, LoopError> {
132 if N == 0 || N > 256 {
133 return Err(LoopError::Invalid);
134 }
135 let total = weights
136 .iter()
137 .try_fold(0_u32, |s, w| s.checked_add(*w))
138 .ok_or(LoopError::Invalid)?;
139 if total == 0 {
140 return Err(LoopError::Invalid);
141 }
142 Ok(Self { weights, total })
143 }
144 /// Caller can supply a saved/replayed ticket. Zero weight is never selected.
145 pub fn choose(&self, ticket: u32) -> usize {
146 let mut ticket = ticket % self.total;
147 for (i, w) in self.weights.iter().enumerate() {
148 if ticket < *w {
149 return i;
150 }
151 ticket -= w;
152 }
153 unreachable!("validated nonzero total")
154 }
155 /// Fixed work; multiply-high maps the full 64-bit sample to the weight range.
156 /// This legacy mapping has rounding bias for totals that do not divide 2^64;
157 /// its results and one-output RNG advancement are preserved.
158 pub fn roll(&self, rng: &mut RewardRng) -> usize {
159 self.choose(((u128::from(rng.next_u64()) * u128::from(self.total)) >> 64) as u32)
160 }
161
162 /// Weighted sampling without replacement, into caller storage.
163 ///
164 /// For each attempt, consume exactly one [`RewardRng::next_u64`] output and
165 /// use its upper 32 bits as `x`. For remaining total `W`, reject
166 /// `x < (2^32 mod W)`; otherwise use `x % W` as a cumulative-weight ticket,
167 /// in original index order. Remove the selected index's entire weight before
168 /// the next draw. Zero-weight entries never appear; no duplicate retries occur.
169 /// Even `W == 1` consumes a sample for an accepted draw.
170 ///
171 /// With independent uniform 32-bit samples, rejection leaves equally many
172 /// representatives of every ticket. Conditional on a next draw succeeding,
173 /// its index probability is `weight[index] / W`. A finite budget can censor
174 /// the prefix depending on earlier choices, so conditioning on an entire
175 /// request completing need not retain that distribution. SplitMix64 is a
176 /// deterministic gameplay PRNG, not a claim of independent random entropy or
177 /// security. There is no biased fallback on budget exhaustion.
178 ///
179 /// Preflight checks, in order: `requested <= MAX_DISTINCT_DRAWS`, output has
180 /// at least `min(requested, positive_weight_entries)` slots, then
181 /// `sample_budget <= MAX_DISTINCT_SAMPLES`. Errors consume no RNG and write
182 /// nothing. Zero budget is valid: a nonzero request returns an empty prefix
183 /// with `SampleBudgetExhausted`; a zero request completes without samples.
184 /// Accepted or rejected attempts each consume one budget unit and RNG output.
185 /// Only the accepted prefix is written, including on exhaustion; no rollback.
186 ///
187 /// At most `N <= 256` scratch weights (1024 bytes), `requested <= 256` writes,
188 /// and `sample_budget <= 4096` samples. Work is `O(N + sample_budget +
189 /// N * min(requested, positive_weight_entries))`, without allocation, floating
190 /// point, callbacks, wall clocks or authored-weight mutation. A fresh call
191 /// restarts the pool; do not concatenate partial calls as a continuation.
192 ///
193 /// ```
194 /// use ferravex_play::gameplay::loot::{RewardRng, RewardTable, DistinctDrawStatus};
195 /// let table = RewardTable::new([1, 0, 3]).unwrap();
196 /// let mut rng = RewardRng::new(0);
197 /// let mut out = [99; 3];
198 /// let report = table.roll_distinct_into(&mut rng, 3, &mut out, 8).unwrap();
199 /// assert_eq!(report.status, DistinctDrawStatus::TableExhausted);
200 /// assert_eq!((report.written, report.samples_used), (2, 2));
201 /// assert!(out[..2].contains(&0) && out[..2].contains(&2));
202 /// assert_eq!(out[2], 99);
203 /// ```
204 pub fn roll_distinct_into(
205 &self,
206 rng: &mut RewardRng,
207 requested: usize,
208 out: &mut [usize],
209 sample_budget: usize,
210 ) -> Result<DistinctDrawReport, DistinctDrawError> {
211 self.preflight_distinct(requested, out.len())?;
212 if sample_budget > MAX_DISTINCT_SAMPLES {
213 return Err(DistinctDrawError::SampleBudgetTooLarge { sample_budget });
214 }
215 let mut remaining = RemainingRewards::new(self);
216 let mut written = 0;
217 let mut samples_used = 0;
218 while written < requested && remaining.total > 0 && samples_used < sample_budget {
219 let sample = (rng.next_u64() >> 32) as u32;
220 samples_used += 1;
221 if let Some(ticket) = bounded_ticket(sample, remaining.total) {
222 out[written] = remaining.take(ticket);
223 written += 1;
224 }
225 }
226 Ok(remaining.report(
227 requested,
228 written,
229 samples_used,
230 DistinctDrawStatus::SampleBudgetExhausted,
231 ))
232 }
233
234 /// Deterministic distinct draws from saved/authored tickets, without RNG.
235 ///
236 /// Apply each consumed ticket modulo the **remaining** weight total and
237 /// remove that selected index. No tickets are read after completion or pool
238 /// exhaustion. `samples_used` reports the number consumed, at most 256;
239 /// `TicketsExhausted` preserves the accepted prefix if the slice ends early.
240 /// This is an explicit replay mapping, not an unbiased conversion of arbitrary
241 /// random `u32`s. Independent uniform tickets in each remaining range give
242 /// sequential weight-proportional draws. Tickets depend on weights and order;
243 /// saved indices still depend on order. Hosts own stable reward identities and
244 /// any replay/content versioning.
245 ///
246 /// Request/capacity preflight, tail preservation and fresh-pool semantics
247 /// match [`Self::roll_distinct_into`]. Work is `O(N * (1 + min(requested,
248 /// positive_weight_entries, tickets.len())))`; storage is `N` scratch weights,
249 /// with no allocation. Even an arbitrarily long ticket slice is not scanned.
250 ///
251 /// ```
252 /// use ferravex_play::gameplay::loot::{RewardTable, DistinctDrawStatus};
253 /// let table = RewardTable::new([1, 0, 3]).unwrap();
254 /// let mut out = [99; 4];
255 /// let report = table.choose_distinct_into(&[3, 0, 7], 3, &mut out).unwrap();
256 /// assert_eq!(&out, &[2, 0, 99, 99]);
257 /// assert_eq!((report.written, report.samples_used), (2, 2));
258 /// assert_eq!(report.status, DistinctDrawStatus::TableExhausted);
259 /// ```
260 pub fn choose_distinct_into(
261 &self,
262 tickets: &[u32],
263 requested: usize,
264 out: &mut [usize],
265 ) -> Result<DistinctDrawReport, DistinctDrawError> {
266 self.preflight_distinct(requested, out.len())?;
267 let mut remaining = RemainingRewards::new(self);
268 let mut written = 0;
269 while written < requested && remaining.total > 0 && written < tickets.len() {
270 out[written] = remaining.take(tickets[written] % remaining.total);
271 written += 1;
272 }
273 Ok(remaining.report(
274 requested,
275 written,
276 written,
277 DistinctDrawStatus::TicketsExhausted,
278 ))
279 }
280
281 fn preflight_distinct(
282 &self,
283 requested: usize,
284 capacity: usize,
285 ) -> Result<(), DistinctDrawError> {
286 if requested > MAX_DISTINCT_DRAWS {
287 return Err(DistinctDrawError::RequestTooLarge { requested });
288 }
289 let positive = self.weights.iter().filter(|&&weight| weight > 0).count();
290 let required = requested.min(positive);
291 if capacity < required {
292 return Err(DistinctDrawError::OutputTooSmall {
293 required,
294 provided: capacity,
295 });
296 }
297 Ok(())
298 }
299}
300
301// Discard the incomplete modulo cycle at the bottom of the u32 domain.
302// `total` is nonzero, and may be u32::MAX; never compute 2^32 in a u32.
303fn bounded_ticket(sample: u32, total: u32) -> Option<u32> {
304 let threshold = total.wrapping_neg() % total;
305 (sample >= threshold).then(|| sample % total)
306}
307
308struct RemainingRewards<const N: usize> {
309 weights: [u32; N],
310 total: u32,
311}
312impl<const N: usize> RemainingRewards<N> {
313 fn new(table: &RewardTable<N>) -> Self {
314 Self {
315 weights: table.weights,
316 total: table.total,
317 }
318 }
319
320 // ticket < total; each accepted draw removes one whole positive entry.
321 fn take(&mut self, mut ticket: u32) -> usize {
322 for (index, weight) in self.weights.iter_mut().enumerate() {
323 if ticket < *weight {
324 self.total -= *weight;
325 *weight = 0;
326 return index;
327 }
328 ticket -= *weight;
329 }
330 unreachable!("ticket within remaining nonzero total")
331 }
332
333 fn report(
334 &self,
335 requested: usize,
336 written: usize,
337 samples_used: usize,
338 input_exhausted: DistinctDrawStatus,
339 ) -> DistinctDrawReport {
340 DistinctDrawReport {
341 written,
342 samples_used,
343 status: if written == requested {
344 DistinctDrawStatus::Complete
345 } else if self.total == 0 {
346 DistinctDrawStatus::TableExhausted
347 } else {
348 input_exhausted
349 },
350 }
351 }
352}
353#[cfg(test)]
354mod tests {
355 use super::*;
356 #[test]
357 fn bounded_mapping_rejects_only_the_incomplete_modulo_cycle() {
358 for total in [1, 2, 3, 7, 256, 0x8000_0001, u32::MAX] {
359 let domain = 1_u64 << 32;
360 let threshold = (domain % u64::from(total)) as u32;
361 assert_eq!((domain - u64::from(threshold)) % u64::from(total), 0);
362 if threshold > 0 {
363 assert_eq!(bounded_ticket(0, total), None);
364 assert_eq!(bounded_ticket(threshold - 1, total), None);
365 }
366 assert_eq!(bounded_ticket(threshold, total), Some(threshold % total));
367 assert_eq!(bounded_ticket(u32::MAX, total), Some(u32::MAX % total));
368 }
369 assert_eq!(bounded_ticket(0x7fff_fffe, 0x8000_0001), None);
370 assert_eq!(bounded_ticket(0x7fff_ffff, 0x8000_0001), Some(0x7fff_ffff));
371 assert_eq!(bounded_ticket(0x8000_0001, 0x8000_0001), Some(0));
372 assert_eq!(bounded_ticket(0, u32::MAX), None);
373 assert_eq!(bounded_ticket(u32::MAX, u32::MAX), Some(0));
374 }
375
376 #[test]
377 fn tickets_respect_weights_and_seeds_reproduce_sequences() {
378 let t = RewardTable::new([1, 0, 3]).unwrap();
379 assert_eq!(
380 (0..4).map(|n| t.choose(n)).collect::<Vec<_>>(),
381 [0, 2, 2, 2]
382 );
383 let mut a = RewardRng::new(0);
384 let mut b = a;
385 for _ in 0..100 {
386 assert_eq!(t.roll(&mut a), t.roll(&mut b));
387 }
388 assert!(RewardTable::new([0, 0]).is_err());
389 assert!(RewardTable::new([u32::MAX, 1]).is_err());
390 }
391}