ferravex_play/gameplay/
spawn.rs

1//! Deterministic safe-spawn selection. Hosts supply authoritative occupancy and
2//! line-of-sight eligibility before spending encounter credits.
3//!
4//! The legacy [`SpawnSelector::choose`] keeps its farthest-first callback
5//! pruning. The checked APIs instead explain **every** candidate, rank finite
6//! caller scores, and never turn an unsafe result into a fallback position.
7//! Scores/availability are authoritative host policy, not client authority.
8//!
9//! # Admission recipe
10//!
11//! This uses the real encounter admission gate and one already prepared actor
12//! slot. Selection runs on a copy: failed admission does not rotate the live
13//! selector. No world mutation occurs between the queries and admission. Once
14//! admission spends credits, placing into the prepared slot cannot fail. For a
15//! fallible ECS/pool admission, reserve/validate its capacity first and arrange
16//! explicit rollback if a later gate can fail; selection is not a reservation.
17//!
18//! ```
19//! use ferravex_math::Vec2;
20//! use ferravex_play::{
21//!     encounter::{EncounterConfig, EncounterDirector},
22//!     gameplay::spawn::{SpawnAssessment, SpawnCheckError, SpawnSelector},
23//! };
24//!
25//! fn attempt(selector: &mut SpawnSelector, director: &mut EncounterDirector,
26//!     actor: &mut Option<Vec2>, obstructed: bool) -> Result<bool, SpawnCheckError<()>>
27//! {
28//!     let points = [Vec2::new(20.0, 0.0), Vec2::new(-20.0, 0.0)];
29//!     let mut output = [SpawnAssessment::EMPTY; 2];
30//!     let mut pending = *selector;
31//!     let chosen = pending.choose_checked_into(&points, Vec2::ZERO, &mut output,
32//!         |_| Ok(actor.is_none()), // Prepared storage availability.
33//!         |_, distance_squared| Ok(Some(distance_squared)),
34//!         |_| Ok(!obstructed))?; // Replace with authoritative geometry/LOS query.
35//!     if let Some(index) = chosen {
36//!         if director.admit(1, usize::from(actor.is_some())) {
37//!             *actor = Some(points[index]); // Guaranteed placement in prepared slot.
38//!             *selector = pending;
39//!             return Ok(true); // Emit accepted-event feedback here.
40//!         }
41//!     }
42//!     Ok(false) // Defer; no placement or credits spent when unsafe/rejected.
43//! }
44//! let mut selector = SpawnSelector::new(10.0).unwrap();
45//! let mut director = EncounterDirector::new(EncounterConfig {
46//!     credits: 2, max_alive: 1, interval: 0.5, first_delay: 0.0,
47//!     recovery_seconds: 1.0,
48//! }).unwrap();
49//! let mut actor = None;
50//! assert!(!attempt(&mut selector, &mut director, &mut actor, true).unwrap());
51//! assert_eq!(director.credits(), 2);
52//! assert_eq!(actor, None);
53//! assert!(attempt(&mut selector, &mut director, &mut actor, false).unwrap());
54//! assert_eq!(director.credits(), 1);
55//! assert_eq!(actor.take(), Some(Vec2::new(20.0, 0.0)));
56//! // Pacing rejects another safe selection without accepting its cursor change.
57//! assert!(!attempt(&mut selector, &mut director, &mut actor, false).unwrap());
58//! assert_eq!(director.credits(), 1);
59//! director.advance(0.25, 0.0).unwrap();
60//! director.advance(0.25, 0.0).unwrap();
61//! assert!(attempt(&mut selector, &mut director, &mut actor, false).unwrap());
62//! assert_eq!(actor, Some(Vec2::new(-20.0, 0.0)));
63//! ```
64use super::LoopError;
65use ferravex_math::Vec2;
66/// First exclusion in the checked pipeline; later queries are skipped.
67/// See the module's admission recipe and [`SpawnSelector::assess_into`].
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum SpawnExclusion {
70    /// Nonfinite coordinate or an absolute component greater than 1e6.
71    InvalidGeometry,
72    /// Squared distance is strictly below the configured minimum squared.
73    TooClose,
74    /// The availability query returned false (e.g. an unavailable authored slot).
75    Unavailable,
76    /// The score callback returned `None` under the host's authored policy.
77    Authored,
78    /// The final clearance/line-of-sight query returned false.
79    Obstructed,
80}
81
82/// One candidate's eligibility, with the host's finite score when eligible.
83#[derive(Clone, Copy, Debug, PartialEq)]
84pub enum SpawnOutcome {
85    Excluded(SpawnExclusion),
86    Eligible { score: f32 },
87}
88
89/// Read-only diagnostic stored at the original source index in caller output.
90/// Indices identify this input slice only; reordering candidates changes identity.
91#[derive(Clone, Copy, Debug, PartialEq)]
92pub struct SpawnAssessment {
93    pub index: usize,
94    /// `None` only for invalid candidate geometry; otherwise uses legacy f32
95    /// squared-distance arithmetic in caller-defined logical world units.
96    pub distance_squared: Option<f32>,
97    pub outcome: SpawnOutcome,
98}
99impl SpawnAssessment {
100    /// Storage initializer, not an assessed candidate. Only the first input
101    /// length entries are meaningful after a successful checked call.
102    pub const EMPTY: Self = Self {
103        index: 0,
104        distance_squared: None,
105        outcome: SpawnOutcome::Excluded(SpawnExclusion::InvalidGeometry),
106    };
107}
108
109/// Which external query failed. Query side effects cannot be rolled back.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub enum SpawnQuery {
112    Availability,
113    Score,
114    Obstruction,
115}
116
117/// Request/numeric/query failures, distinct from individual candidate exclusions.
118/// Every reported error preserves the selector and the entire output slice.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub enum SpawnCheckError<E> {
121    EmptyCandidates,
122    CandidateCapacity {
123        count: usize,
124    },
125    InvalidReference,
126    OutputTooSmall {
127        required: usize,
128        provided: usize,
129    },
130    /// A nonfinite score aborts the request, rather than excluding a candidate.
131    InvalidScore {
132        index: usize,
133    },
134    Callback {
135        index: usize,
136        query: SpawnQuery,
137        error: E,
138    },
139}
140
141#[derive(Clone, Copy, Debug)]
142pub struct SpawnSelector {
143    minimum: f32,
144    cursor: usize,
145}
146impl SpawnSelector {
147    /// Maximum input length for both legacy and checked paths.
148    pub const MAX_CANDIDATES: usize = 256;
149
150    pub fn new(minimum: f32) -> Result<Self, LoopError> {
151        if !minimum.is_finite() || !(0. ..=1e6).contains(&minimum) {
152            return Err(LoopError::Invalid);
153        }
154        Ok(Self { minimum, cursor: 0 })
155    }
156    /// Farthest eligible candidate wins, with rotating stable tie breaks.
157    /// At most 256 eligibility queries. None means defer spawning, never fallback
158    /// into an unsafe location. Callbacks should be read-only world queries.
159    pub fn choose(
160        &mut self,
161        positions: &[Vec2],
162        player: Vec2,
163        mut eligible: impl FnMut(usize) -> bool,
164    ) -> Result<Option<usize>, LoopError> {
165        if positions.is_empty()
166            || positions.len() > 256
167            || !valid(player)
168            || positions.iter().any(|p| !valid(*p))
169        {
170            return Err(LoopError::Invalid);
171        }
172        let mut best = None;
173        let mut best_distance = -1.;
174        for offset in 0..positions.len() {
175            let i = (self.cursor + offset) % positions.len();
176            let d = positions[i].distance_squared(player);
177            if d >= self.minimum * self.minimum && d > best_distance && eligible(i) {
178                best = Some(i);
179                best_distance = d;
180            }
181        }
182        if let Some(i) = best {
183            self.cursor = (i + 1) % positions.len();
184        }
185        Ok(best)
186    }
187
188    /// Assess candidates without rotating the selector. Returns the winning
189    /// source index, or `None` when all candidates are excluded (defer spawning).
190    ///
191    /// Requires 1..=256 positions, a valid reference (finite, each absolute
192    /// component <= 1e6), and output capacity >= input length, checked in that
193    /// order **before any callbacks**. Bad individual positions are exclusions,
194    /// unlike the legacy method's whole-request error. The minimum-distance
195    /// boundary is inclusive and uses the same arithmetic as [`Self::choose`].
196    ///
197    /// Starting at the existing cursor modulo input length, visit each source
198    /// index once, wrapping. At each index: geometry, minimum distance,
199    /// `available`, `score`, `unobstructed`, stopping at the first exclusion.
200    /// Each callback is invoked at most once per candidate (at most 256 each,
201    /// 768 total); no obstruction query runs after any prior exclusion or invalid
202    /// score. Unlike legacy `choose`, eligible lower-scored candidates still get
203    /// obstruction queries so that diagnostics describe every candidate.
204    ///
205    /// `score(index, distance_squared)` returns `None` for authored exclusion,
206    /// or a finite score (negative/zero allowed). Higher scores win; exactly equal
207    /// scores keep the first in rotating source order, with no random seed.
208    /// Return the supplied distance for legacy farthest-distance ranking.
209    /// Availability and score callbacks should be cheap read-only checks;
210    /// clearance/LOS stays entirely caller-controlled in `unobstructed`.
211    ///
212    /// On success, output[..positions.len()] is replaced in **source index**
213    /// order and the tail is untouched. Errors (including a later query failure
214    /// or nonfinite score) leave all output and selector state untouched using
215    /// fixed stack scratch storage, with no heap allocation by this method.
216    /// External callback effects/allocations/panics cannot be rolled back; no
217    /// remaining queries run after a reported failure. Diagnostics are a snapshot,
218    /// not a reservation or permission to skip actual admission/revalidation.
219    ///
220    /// ```
221    /// use ferravex_math::Vec2;
222    /// use ferravex_play::gameplay::spawn::{SpawnAssessment, SpawnSelector};
223    /// let selector = SpawnSelector::new(10.0).unwrap();
224    /// let points = [Vec2::new(20.0, 0.0), Vec2::new(-20.0, 0.0)];
225    /// let mut output = [SpawnAssessment::EMPTY; 2];
226    /// for _ in 0..2 {
227    ///     let best = selector.assess_into(&points, Vec2::ZERO, &mut output,
228    ///         |_| Ok::<_, ()>(true), |_, d| Ok(Some(d)), |_| Ok(true)).unwrap();
229    ///     assert_eq!(best, Some(0)); // Reading does not rotate ties.
230    /// }
231    /// ```
232    pub fn assess_into<E>(
233        &self,
234        positions: &[Vec2],
235        reference: Vec2,
236        output: &mut [SpawnAssessment],
237        mut available: impl FnMut(usize) -> Result<bool, E>,
238        mut score: impl FnMut(usize, f32) -> Result<Option<f32>, E>,
239        mut unobstructed: impl FnMut(usize) -> Result<bool, E>,
240    ) -> Result<Option<usize>, SpawnCheckError<E>> {
241        if positions.is_empty() {
242            return Err(SpawnCheckError::EmptyCandidates);
243        }
244        if positions.len() > Self::MAX_CANDIDATES {
245            return Err(SpawnCheckError::CandidateCapacity {
246                count: positions.len(),
247            });
248        }
249        if !valid(reference) {
250            return Err(SpawnCheckError::InvalidReference);
251        }
252        if output.len() < positions.len() {
253            return Err(SpawnCheckError::OutputTooSmall {
254                required: positions.len(),
255                provided: output.len(),
256            });
257        }
258        let mut scratch = [SpawnAssessment::EMPTY; Self::MAX_CANDIDATES];
259        let mut best: Option<(usize, f32)> = None;
260        for offset in 0..positions.len() {
261            let i = (self.cursor + offset) % positions.len();
262            let assessment = &mut scratch[i];
263            assessment.index = i;
264            if !valid(positions[i]) {
265                continue;
266            }
267            let distance = positions[i].distance_squared(reference);
268            assessment.distance_squared = Some(distance);
269            let exclusion = if distance < self.minimum * self.minimum {
270                SpawnExclusion::TooClose
271            } else if !available(i).map_err(|error| SpawnCheckError::Callback {
272                index: i,
273                query: SpawnQuery::Availability,
274                error,
275            })? {
276                SpawnExclusion::Unavailable
277            } else if let Some(value) =
278                score(i, distance).map_err(|error| SpawnCheckError::Callback {
279                    index: i,
280                    query: SpawnQuery::Score,
281                    error,
282                })?
283            {
284                if !value.is_finite() {
285                    return Err(SpawnCheckError::InvalidScore { index: i });
286                }
287                if unobstructed(i).map_err(|error| SpawnCheckError::Callback {
288                    index: i,
289                    query: SpawnQuery::Obstruction,
290                    error,
291                })? {
292                    assessment.outcome = SpawnOutcome::Eligible { score: value };
293                    if best.is_none_or(|(_, previous)| value > previous) {
294                        best = Some((i, value));
295                    }
296                    continue;
297                }
298                SpawnExclusion::Obstructed
299            } else {
300                SpawnExclusion::Authored
301            };
302            assessment.outcome = SpawnOutcome::Excluded(exclusion);
303        }
304        output[..positions.len()].copy_from_slice(&scratch[..positions.len()]);
305        Ok(best.map(|(index, _)| index))
306    }
307
308    /// Assess and accept a selection, rotating only on `Ok(Some(index))`.
309    /// All query, output and failure contracts are those of [`Self::assess_into`].
310    /// This accepts selector state only, not an actor or encounter credit spend.
311    /// Use a copied selector and commit it after actual admission if that can
312    /// fail; see the module's runnable encounter recipe.
313    ///
314    /// ```
315    /// use ferravex_math::Vec2;
316    /// use ferravex_play::gameplay::spawn::{SpawnAssessment, SpawnSelector};
317    /// let mut selector = SpawnSelector::new(0.0).unwrap();
318    /// let points = [Vec2::X, -Vec2::X];
319    /// let mut output = [SpawnAssessment::EMPTY; 2];
320    /// for expected in [0, 1] {
321    ///     assert_eq!(selector.choose_checked_into(&points, Vec2::ZERO, &mut output,
322    ///         |_| Ok::<_, ()>(true), |_, d| Ok(Some(d)), |_| Ok(true)).unwrap(),
323    ///         Some(expected));
324    /// }
325    /// ```
326    pub fn choose_checked_into<E>(
327        &mut self,
328        positions: &[Vec2],
329        reference: Vec2,
330        output: &mut [SpawnAssessment],
331        available: impl FnMut(usize) -> Result<bool, E>,
332        score: impl FnMut(usize, f32) -> Result<Option<f32>, E>,
333        unobstructed: impl FnMut(usize) -> Result<bool, E>,
334    ) -> Result<Option<usize>, SpawnCheckError<E>> {
335        let best =
336            self.assess_into(positions, reference, output, available, score, unobstructed)?;
337        if let Some(i) = best {
338            self.cursor = (i + 1) % positions.len();
339        }
340        Ok(best)
341    }
342
343    /// Reset tie rotation to source index zero, retaining the authored minimum.
344    /// Reset on a new run or when intentionally restarting candidate identity.
345    ///
346    /// ```
347    /// use ferravex_math::Vec2;
348    /// use ferravex_play::gameplay::spawn::SpawnSelector;
349    /// let mut selector = SpawnSelector::new(0.0).unwrap();
350    /// let points = [Vec2::X, -Vec2::X];
351    /// assert_eq!(selector.choose(&points, Vec2::ZERO, |_| true), Ok(Some(0)));
352    /// selector.reset();
353    /// assert_eq!(selector.choose(&points, Vec2::ZERO, |_| true), Ok(Some(0)));
354    /// ```
355    pub fn reset(&mut self) {
356        self.cursor = 0;
357    }
358}
359fn valid(p: Vec2) -> bool {
360    p.is_finite() && p.abs().max_element() <= 1e6
361}
362#[cfg(test)]
363mod tests {
364    use super::*;
365    #[test]
366    fn unsafe_candidates_defer_and_equal_distances_rotate() {
367        let mut s = SpawnSelector::new(10.).unwrap();
368        let p = [Vec2::X * 20., -Vec2::X * 20., Vec2::X];
369        assert_eq!(s.choose(&p, Vec2::ZERO, |_| true).unwrap(), Some(0));
370        assert_eq!(s.choose(&p, Vec2::ZERO, |_| true).unwrap(), Some(1));
371        assert_eq!(s.choose(&p, Vec2::ZERO, |_| false).unwrap(), None);
372        assert_eq!(s.choose(&p, Vec2::ZERO, |i| i == 2).unwrap(), None);
373        assert!(s.choose(&[], Vec2::ZERO, |_| panic!()).is_err());
374    }
375}