ferravex_play/ai/
perception.rs

1use super::{AiError, WorkBudget};
2use ferravex_math::Vec3;
3
4pub const MAX_MEMORIES: usize = 256;
5pub const MAX_NOISES: usize = 256;
6/// True means the host's authoritative static/dynamic world permits sight.
7/// Implementations should ignore the observer/target bodies and enforce layers.
8pub trait VisibilityQuery {
9    fn clear(&mut self, from: Vec3, to: Vec3) -> bool;
10}
11pub struct Unoccluded;
12impl VisibilityQuery for Unoccluded {
13    fn clear(&mut self, _: Vec3, _: Vec3) -> bool {
14        true
15    }
16}
17#[derive(Clone, Copy, Debug)]
18pub struct Observer {
19    pub position: Vec3,
20    pub forward: Vec3,
21}
22#[derive(Clone, Copy, Debug)]
23pub struct Candidate {
24    pub id: u64,
25    pub position: Vec3,
26    pub groups: u32,
27}
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum Detection {
30    Detected,
31    Rejected,
32    Deferred,
33}
34#[derive(Clone, Copy, Debug)]
35pub struct Sight {
36    range: f32,
37    cosine: f64,
38    mask: u32,
39}
40impl Sight {
41    /// Full field of view, radians in 0..=TAU. Distance/cone edges are inclusive.
42    pub fn new(range: f32, field_of_view: f32, mask: u32) -> Result<Self, AiError> {
43        if !range.is_finite()
44            || range <= 0.
45            || !field_of_view.is_finite()
46            || !(0. ..=std::f32::consts::TAU).contains(&field_of_view)
47        {
48            return Err(AiError::InvalidConfiguration);
49        }
50        let cosine = if field_of_view == std::f32::consts::TAU {
51            -1.
52        } else {
53            (f64::from(field_of_view) * 0.5).cos()
54        };
55        Ok(Self {
56            range,
57            cosine,
58            mask,
59        })
60    }
61    pub fn test(
62        &self,
63        observer: Observer,
64        target: Candidate,
65        budget: &mut WorkBudget,
66        query: &mut impl VisibilityQuery,
67    ) -> Result<Detection, AiError> {
68        if !observer.position.is_finite()
69            || !observer.forward.is_finite()
70            || !target.position.is_finite()
71        {
72            return Err(AiError::InvalidInput);
73        }
74        let forward = observer.forward.to_array().map(f64::from);
75        let forward_length = forward.into_iter().map(|v| v * v).sum::<f64>().sqrt();
76        if forward_length == 0. {
77            return Err(AiError::InvalidInput);
78        }
79        if !budget.candidate() {
80            return Ok(Detection::Deferred);
81        }
82        if target.groups & self.mask == 0 {
83            return Ok(Detection::Rejected);
84        }
85        let (delta, distance) = delta_distance(observer.position, target.position);
86        if distance > f64::from(self.range) {
87            return Ok(Detection::Rejected);
88        }
89        if distance > 0.
90            && delta
91                .into_iter()
92                .zip(forward)
93                .map(|(a, b)| a * b)
94                .sum::<f64>()
95                / (distance * forward_length)
96                + 1e-7
97                < self.cosine
98        {
99            return Ok(Detection::Rejected);
100        }
101        if distance == 0. {
102            return Ok(Detection::Detected);
103        }
104        if !budget.query() {
105            return Ok(Detection::Deferred);
106        }
107        Ok(if query.clear(observer.position, target.position) {
108            Detection::Detected
109        } else {
110            Detection::Rejected
111        })
112    }
113}
114fn delta_distance(from: Vec3, to: Vec3) -> ([f64; 3], f64) {
115    let a = from.to_array();
116    let b = to.to_array();
117    let delta = std::array::from_fn(|i| f64::from(b[i]) - f64::from(a[i]));
118    (delta, delta.into_iter().map(|v| v * v).sum::<f64>().sqrt())
119}
120#[derive(Clone, Copy, Debug)]
121pub struct Noise {
122    pub source: u64,
123    pub position: Vec3,
124    pub groups: u32,
125    pub radius: f32,
126}
127impl Noise {
128    fn valid(self) -> bool {
129        self.position.is_finite() && self.radius.is_finite() && self.radius > 0.
130    }
131}
132#[derive(Clone, Copy, Debug)]
133pub struct Hearing {
134    range: f32,
135    mask: u32,
136    blocked_scale: f32,
137}
138impl Hearing {
139    /// Occluded sound radius is scaled by blocked_scale. None as query in test
140    /// disables occlusion; this is an explicit host choice, not a failed query.
141    pub fn new(range: f32, mask: u32, blocked_scale: f32) -> Result<Self, AiError> {
142        if !range.is_finite()
143            || range <= 0.
144            || !blocked_scale.is_finite()
145            || !(0. ..=1.).contains(&blocked_scale)
146        {
147            return Err(AiError::InvalidConfiguration);
148        }
149        Ok(Self {
150            range,
151            mask,
152            blocked_scale,
153        })
154    }
155    pub fn test(
156        &self,
157        position: Vec3,
158        noise: Noise,
159        budget: &mut WorkBudget,
160        query: Option<&mut dyn VisibilityQuery>,
161    ) -> Result<Detection, AiError> {
162        if !position.is_finite() || !noise.valid() {
163            return Err(AiError::InvalidInput);
164        }
165        if !budget.candidate() {
166            return Ok(Detection::Deferred);
167        }
168        let (_, distance) = delta_distance(position, noise.position);
169        let radius = f64::from(self.range.min(noise.radius));
170        if noise.groups & self.mask == 0 || distance > radius {
171            return Ok(Detection::Rejected);
172        }
173        if let Some(query) = query {
174            if !budget.query() {
175                return Ok(Detection::Deferred);
176            }
177            if !query.clear(position, noise.position)
178                && distance > radius * f64::from(self.blocked_scale)
179            {
180                return Ok(Detection::Rejected);
181            }
182        }
183        Ok(Detection::Detected)
184    }
185}
186#[derive(Clone, Copy, Debug)]
187pub struct MemorySettings {
188    pub capacity: usize,
189    pub sight_seconds: f32,
190    pub hearing_seconds: f32,
191}
192impl Default for MemorySettings {
193    fn default() -> Self {
194        Self {
195            capacity: 8,
196            sight_seconds: 2.,
197            hearing_seconds: 3.,
198        }
199    }
200}
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202pub enum Sense {
203    Sight,
204    Hearing,
205}
206#[derive(Clone, Copy, Debug)]
207pub struct Track {
208    pub id: u64,
209    pub position: Vec3,
210    pub groups: u32,
211    pub age: f64,
212    pub visible: bool,
213    pub sense: Sense,
214    remaining: f64,
215}
216impl Track {
217    pub fn remaining(&self) -> f64 {
218        self.remaining
219    }
220}
221/// Fixed-capacity memory. Current-tick sight always takes precedence over hearing.
222/// Older hearing can update a remembered position; it never grants current sight.
223pub struct Memory {
224    settings: MemorySettings,
225    tracks: Vec<Track>,
226    dropped: u64,
227}
228impl Memory {
229    pub fn new(settings: MemorySettings) -> Result<Self, AiError> {
230        if settings.capacity > MAX_MEMORIES
231            || ![settings.sight_seconds, settings.hearing_seconds]
232                .into_iter()
233                .all(|v| v.is_finite() && (0.0001..=3600.).contains(&v))
234        {
235            return Err(AiError::InvalidConfiguration);
236        }
237        Ok(Self {
238            settings,
239            tracks: Vec::with_capacity(settings.capacity),
240            dropped: 0,
241        })
242    }
243    pub fn advance(&mut self, dt: f32) -> Result<(), AiError> {
244        if !dt.is_finite() || !(0. ..=60.).contains(&dt) {
245            return Err(AiError::InvalidInput);
246        }
247        for t in &mut self.tracks {
248            t.age += f64::from(dt);
249            t.remaining -= f64::from(dt);
250            t.visible = false;
251        }
252        self.tracks.retain(|t| t.remaining > 1e-9);
253        Ok(())
254    }
255    pub fn observe(&mut self, target: Candidate, sense: Sense) -> Result<bool, AiError> {
256        if !target.position.is_finite() {
257            return Err(AiError::InvalidInput);
258        }
259        if let Some(t) = self.tracks.iter_mut().find(|t| t.id == target.id) {
260            if sense == Sense::Hearing && t.visible {
261                return Ok(true);
262            }
263            *t = Self::track(target, sense, self.settings);
264            return Ok(true);
265        }
266        if self.tracks.len() == self.settings.capacity {
267            self.dropped = self.dropped.saturating_add(1);
268            return Ok(false);
269        }
270        self.tracks.push(Self::track(target, sense, self.settings));
271        Ok(true)
272    }
273    fn track(target: Candidate, sense: Sense, s: MemorySettings) -> Track {
274        Track {
275            id: target.id,
276            position: target.position,
277            groups: target.groups,
278            age: 0.,
279            visible: sense == Sense::Sight,
280            sense,
281            remaining: f64::from(if sense == Sense::Sight {
282                s.sight_seconds
283            } else {
284                s.hearing_seconds
285            }),
286        }
287    }
288    pub fn tracks(&self) -> &[Track] {
289        &self.tracks
290    }
291    pub fn get(&self, id: u64) -> Option<&Track> {
292        self.tracks.iter().find(|t| t.id == id)
293    }
294    pub fn forget(&mut self, id: u64) {
295        self.tracks.retain(|t| t.id != id);
296    }
297    pub fn clear(&mut self) {
298        self.tracks.clear();
299    }
300    pub fn dropped(&self) -> u64 {
301        self.dropped
302    }
303    /// Deterministic: fresh sight first, youngest stimulus, then lowest host ID.
304    pub fn best(&self, mask: u32) -> Option<&Track> {
305        self.tracks
306            .iter()
307            .filter(|t| t.groups & mask != 0)
308            .min_by(|a, b| {
309                b.visible
310                    .cmp(&a.visible)
311                    .then_with(|| a.age.total_cmp(&b.age))
312                    .then_with(|| a.id.cmp(&b.id))
313            })
314    }
315}
316#[derive(Clone, Copy)]
317struct TimedNoise {
318    noise: Noise,
319    remaining: f64,
320}
321/// Retains newest sounds on saturation. Age once per simulation tick, then publish
322/// accepted gameplay sounds. Consumers should exclude their own source ID.
323pub struct NoiseBuffer {
324    items: Vec<TimedNoise>,
325    capacity: usize,
326    dropped: u64,
327}
328impl NoiseBuffer {
329    pub fn new(capacity: usize) -> Result<Self, AiError> {
330        if capacity > MAX_NOISES {
331            return Err(AiError::Capacity);
332        }
333        Ok(Self {
334            items: Vec::with_capacity(capacity),
335            capacity,
336            dropped: 0,
337        })
338    }
339    pub fn push(&mut self, noise: Noise, lifetime: f32) -> Result<bool, AiError> {
340        if !noise.valid() || !lifetime.is_finite() || !(0.0001..=10.).contains(&lifetime) {
341            return Err(AiError::InvalidInput);
342        }
343        if self.capacity == 0 {
344            self.dropped = self.dropped.saturating_add(1);
345            return Ok(false);
346        }
347        if self.items.len() == self.capacity {
348            self.items.remove(0);
349            self.dropped = self.dropped.saturating_add(1);
350        }
351        self.items.push(TimedNoise {
352            noise,
353            remaining: f64::from(lifetime),
354        });
355        Ok(true)
356    }
357    pub fn advance(&mut self, dt: f32) -> Result<(), AiError> {
358        if !dt.is_finite() || !(0. ..=60.).contains(&dt) {
359            return Err(AiError::InvalidInput);
360        }
361        for item in &mut self.items {
362            item.remaining -= f64::from(dt);
363        }
364        self.items.retain(|n| n.remaining > 1e-9);
365        Ok(())
366    }
367    pub fn iter(&self) -> impl DoubleEndedIterator<Item = Noise> + ExactSizeIterator + '_ {
368        self.items.iter().map(|n| n.noise)
369    }
370    pub fn clear(&mut self) {
371        self.items.clear();
372    }
373    pub fn dropped(&self) -> u64 {
374        self.dropped
375    }
376}
377
378#[derive(Clone, Copy, Debug)]
379pub struct TargetSelection {
380    pub target: Option<Candidate>,
381    pub incomplete: bool,
382}
383/// Budgeted deterministic priority selection. Non-finite scores are ignored;
384/// equal scores prefer the lower ID. Stops as soon as work is deferred, so an
385/// unbounded iterator cannot exhaust the frame. All returned targets passed sight.
386pub fn select_target(
387    candidates: impl IntoIterator<Item = Candidate>,
388    observer: Observer,
389    sight: Sight,
390    budget: &mut WorkBudget,
391    query: &mut impl VisibilityQuery,
392    priority: impl FnMut(Candidate) -> f32,
393) -> Result<TargetSelection, AiError> {
394    let (choices, incomplete) =
395        visible_choices(candidates, observer, sight, budget, query, priority, None)?;
396    Ok(TargetSelection {
397        target: choices.best.map(|v| v.target),
398        incomplete,
399    })
400}
401
402/// Why an opt-in [`TargetSelector`] selected or released its target.
403#[derive(Clone, Copy, Debug, PartialEq, Eq)]
404pub enum TargetSelectionReason {
405    /// No eligible, finite-scored target was evaluated. See `incomplete` too.
406    NoEligibleTarget,
407    /// There was no previous target; the best evaluated target was acquired.
408    Acquired,
409    /// The previous target is still the best evaluated target.
410    RetainedBest,
411    /// A challenger did not exceed the previous target's score by the margin.
412    RetainedByHysteresis,
413    /// A challenger's score exceeded the previous target's score by the margin.
414    SwitchMarginExceeded,
415    /// Fresh sight outranks a remembered target, regardless of score margin.
416    SwitchedToVisible,
417    /// The previous target was not eligible in the evaluated set.
418    PreviousIneligible,
419}
420
421/// Constant-size explanation of one selection. Scores describe this call only.
422/// `T` is [`Candidate`] for sight selection and [`Track`] for memory selection.
423#[derive(Clone, Copy, Debug)]
424pub struct TargetSelectionReport<T> {
425    pub target: Option<T>,
426    /// Target ID held before this call, even when it is no longer eligible.
427    pub previous: Option<u64>,
428    pub reason: TargetSelectionReason,
429    /// Sight exhausted its candidate/query allowance before finishing the scan.
430    /// The result describes only the evaluated prefix, never unseen candidates.
431    pub incomplete: bool,
432    pub selected_score: Option<f32>,
433    /// Best eligible target's (ID, score), before applying hysteresis.
434    pub best: Option<(u64, f32)>,
435    /// None when the previous target was absent, rejected, deferred or unscored.
436    pub previous_score: Option<f32>,
437}
438
439/// Opt-in, allocation-free target retention using a finite, nonnegative score
440/// margin. Keep one selector per observer/selection stream and call it after
441/// sensing on actual simulation ticks. Reset it when restarting that stream.
442///
443/// Higher scores win; equal scores prefer the lower host ID on acquisition.
444/// An eligible incumbent is retained until a challenger improves its score by
445/// **strictly more** than the margin. A zero margin still retains equal scores.
446/// Scores are recomputed each call; no stale positions, scores or sight are kept.
447/// [`select_target`] and [`Memory::best`] retain their original behavior.
448///
449/// ```
450/// use ferravex_math::Vec3;
451/// use ferravex_play::ai::{
452///     Candidate, Memory, MemorySettings, Sense, TargetSelector, TargetSelectionReason,
453/// };
454/// let mut memory = Memory::new(MemorySettings::default())?;
455/// let mut selector = TargetSelector::new(0.25)?;
456/// memory.observe(Candidate { id: 9, position: Vec3::Z, groups: 1 }, Sense::Sight)?;
457/// let first = selector.select_memory(&memory, 1, |_| 1.0);
458/// assert_eq!(first.reason, TargetSelectionReason::Acquired);
459/// memory.observe(Candidate { id: 2, position: Vec3::X, groups: 1 }, Sense::Sight)?;
460/// let next = selector.select_memory(&memory, 1, |t| if t.id == 2 { 1.1 } else { 1.0 });
461/// assert_eq!(next.target.unwrap().id, 9);
462/// assert_eq!(next.best, Some((2, 1.1)));
463/// assert_eq!(next.reason, TargetSelectionReason::RetainedByHysteresis);
464/// assert_eq!(selector.current(), Some(9));
465/// selector.reset();
466/// assert_eq!(selector.current(), None);
467/// # Ok::<(), ferravex_play::ai::AiError>(())
468/// ```
469#[derive(Clone, Copy, Debug)]
470pub struct TargetSelector {
471    switch_margin: f32,
472    current: Option<u64>,
473}
474impl TargetSelector {
475    /// Rejects negative, NaN and infinite margins with `InvalidConfiguration`.
476    pub fn new(switch_margin: f32) -> Result<Self, AiError> {
477        if !switch_margin.is_finite() || switch_margin < 0. {
478            return Err(AiError::InvalidConfiguration);
479        }
480        Ok(Self {
481            switch_margin,
482            current: None,
483        })
484    }
485
486    /// Last selected ID, not a claim that the target is still alive or visible.
487    pub fn current(&self) -> Option<u64> {
488        self.current
489    }
490
491    /// Forgets target identity while preserving the configured margin.
492    pub fn reset(&mut self) {
493        self.current = None;
494    }
495
496    /// Applies hysteresis to [`select_target`]'s budgeted sight scan. Every
497    /// returned candidate passed sight **in this call**, including the incumbent.
498    /// No extra query is made to retain an incumbent outside the evaluated prefix;
499    /// hosts can put it first when budgets are small. Rejected/deferred candidates
500    /// never get scored. Non-finite scores are ignored.
501    ///
502    /// Incomplete scans can replace or clear an unevaluated incumbent. Inspect
503    /// `incomplete` before treating absence as a confirmed loss of sight. On an
504    /// input error the selected ID is unchanged, but work/query/callback effects
505    /// already performed are not rolled back. Empty input consumes no work.
506    ///
507    /// ```
508    /// use ferravex_math::Vec3;
509    /// use ferravex_play::ai::{
510    ///     Candidate, Observer, Sight, TargetSelector, Unoccluded, WorkBudget,
511    /// };
512    /// let mut selector = TargetSelector::new(0.5)?;
513    /// let observer = Observer { position: Vec3::ZERO, forward: Vec3::Z };
514    /// let sight = Sight::new(10.0, std::f32::consts::TAU, 1)?;
515    /// let candidates = [Candidate { id: 7, position: Vec3::Z, groups: 1 }];
516    /// let report = selector.select_visible(
517    ///     candidates, observer, sight, &mut WorkBudget::new(1, 1, 0),
518    ///     &mut Unoccluded, |_| 1.0,
519    /// )?;
520    /// assert_eq!(report.target.unwrap().id, 7);
521    /// assert!(!report.incomplete);
522    /// # Ok::<(), ferravex_play::ai::AiError>(())
523    /// ```
524    pub fn select_visible(
525        &mut self,
526        candidates: impl IntoIterator<Item = Candidate>,
527        observer: Observer,
528        sight: Sight,
529        budget: &mut WorkBudget,
530        query: &mut impl VisibilityQuery,
531        priority: impl FnMut(Candidate) -> f32,
532    ) -> Result<TargetSelectionReport<Candidate>, AiError> {
533        let (choices, incomplete) = visible_choices(
534            candidates,
535            observer,
536            sight,
537            budget,
538            query,
539            priority,
540            self.current,
541        )?;
542        Ok(self.finish(choices, incomplete))
543    }
544
545    /// Scores matching tracks in existing bounded memory without observing,
546    /// refreshing expiry or issuing visibility queries. Call [`Memory::advance`]
547    /// once per simulation tick before recording accepted detections and selecting.
548    /// Removed, expired or masked-out tracks cannot be retained.
549    ///
550    /// As in [`Memory::best`], fresh sight outranks remembered sight/hearing.
551    /// Within that tier, finite scores and the switch margin determine selection;
552    /// the callback can use `-(track.age as f32)` for youngest-first priority.
553    /// Each matching track is scored once; non-finite scores exclude it. Returned
554    /// tracks preserve their visibility, age and remaining lifetime. A selected
555    /// memory is awareness, not a new sight detection or permission to attack.
556    pub fn select_memory(
557        &mut self,
558        memory: &Memory,
559        mask: u32,
560        mut priority: impl FnMut(&Track) -> f32,
561    ) -> TargetSelectionReport<Track> {
562        let mut choices = SelectionChoices::new(self.current);
563        for track in memory.tracks().iter().filter(|t| t.groups & mask != 0) {
564            choices.consider(*track, track.id, priority(track), track.visible);
565        }
566        self.finish(choices, false)
567    }
568
569    fn finish<T: Copy>(
570        &mut self,
571        choices: SelectionChoices<T>,
572        incomplete: bool,
573    ) -> TargetSelectionReport<T> {
574        let previous = self.current;
575        let (selected, reason) = match (choices.best, choices.incumbent) {
576            (None, _) => (None, TargetSelectionReason::NoEligibleTarget),
577            (Some(best), None) => (
578                Some(best),
579                if previous.is_some() {
580                    TargetSelectionReason::PreviousIneligible
581                } else {
582                    TargetSelectionReason::Acquired
583                },
584            ),
585            (Some(best), Some(old)) if best.id == old.id => {
586                (Some(best), TargetSelectionReason::RetainedBest)
587            }
588            (Some(best), Some(old)) if best.visible && !old.visible => {
589                (Some(best), TargetSelectionReason::SwitchedToVisible)
590            }
591            (Some(best), Some(old))
592                if f64::from(best.score) - f64::from(old.score) > f64::from(self.switch_margin) =>
593            {
594                (Some(best), TargetSelectionReason::SwitchMarginExceeded)
595            }
596            (_, Some(old)) => (Some(old), TargetSelectionReason::RetainedByHysteresis),
597        };
598        self.current = selected.map(|v| v.id);
599        TargetSelectionReport {
600            target: selected.map(|v| v.target),
601            previous,
602            reason,
603            incomplete,
604            selected_score: selected.map(|v| v.score),
605            best: choices.best.map(|v| (v.id, v.score)),
606            previous_score: choices.incumbent.map(|v| v.score),
607        }
608    }
609}
610
611#[derive(Clone, Copy)]
612struct ScoredTarget<T> {
613    target: T,
614    id: u64,
615    score: f32,
616    visible: bool,
617}
618impl<T> ScoredTarget<T> {
619    fn outranks(&self, old: &Self) -> bool {
620        self.visible && !old.visible
621            || self.visible == old.visible
622                && (self.score > old.score || self.score == old.score && self.id < old.id)
623    }
624}
625struct SelectionChoices<T> {
626    current: Option<u64>,
627    best: Option<ScoredTarget<T>>,
628    incumbent: Option<ScoredTarget<T>>,
629}
630impl<T: Copy> SelectionChoices<T> {
631    fn new(current: Option<u64>) -> Self {
632        Self {
633            current,
634            best: None,
635            incumbent: None,
636        }
637    }
638
639    fn consider(&mut self, target: T, id: u64, score: f32, visible: bool) {
640        if !score.is_finite() {
641            return;
642        }
643        let value = ScoredTarget {
644            target,
645            id,
646            score,
647            visible,
648        };
649        if self.best.is_none_or(|old| value.outranks(&old)) {
650            self.best = Some(value);
651        }
652        if self.current == Some(id) && self.incumbent.is_none_or(|old| value.outranks(&old)) {
653            self.incumbent = Some(value);
654        }
655    }
656}
657
658fn visible_choices(
659    candidates: impl IntoIterator<Item = Candidate>,
660    observer: Observer,
661    sight: Sight,
662    budget: &mut WorkBudget,
663    query: &mut impl VisibilityQuery,
664    mut priority: impl FnMut(Candidate) -> f32,
665    current: Option<u64>,
666) -> Result<(SelectionChoices<Candidate>, bool), AiError> {
667    let mut choices = SelectionChoices::new(current);
668    let mut incomplete = false;
669    for target in candidates {
670        match sight.test(observer, target, budget, query)? {
671            Detection::Deferred => {
672                incomplete = true;
673                break;
674            }
675            Detection::Rejected => {}
676            Detection::Detected => {
677                choices.consider(target, target.id, priority(target), true);
678            }
679        }
680    }
681    Ok((choices, incomplete))
682}