Skip to main content

euv_core/game/algorithms/ai/
impl.rs

1use super::*;
2
3/// Typed blackboard storage and retrieval methods for `Blackboard`.
4impl Blackboard {
5    /// Creates a new empty `Blackboard`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Empty typed blackboard.
10    #[must_use]
11    pub fn new() -> Self {
12        Self::default()
13    }
14
15    /// Inserts or replaces a boolean entry under `key`.
16    ///
17    /// # Arguments
18    ///
19    /// - `&str` - Blackboard key name.
20    /// - `bool` - Boolean value.
21    pub fn set_bool(&mut self, key: &str, value: bool) {
22        let _: Option<BtValue> = self
23            .get_mut_entries()
24            .insert(key.to_owned(), BtValue::Bool(value));
25    }
26
27    /// Reads a boolean entry by `key`, returning `None` if absent or mismatched in type.
28    ///
29    /// # Arguments
30    ///
31    /// - `&str` - Blackboard key name.
32    ///
33    /// # Returns
34    ///
35    /// - `Option<bool>` - Stored boolean if present.
36    #[must_use]
37    pub fn get_bool(&self, key: &str) -> Option<bool> {
38        match self.get_entries().get(key) {
39            Some(BtValue::Bool(val)) => Some(*val),
40            _ => None,
41        }
42    }
43
44    /// Inserts or replaces a signed 64-bit integer entry under `key`.
45    ///
46    /// # Arguments
47    ///
48    /// - `&str` - Blackboard key name.
49    /// - `i64` - Integer value.
50    pub fn set_int(&mut self, key: &str, value: i64) {
51        let _: Option<BtValue> = self
52            .get_mut_entries()
53            .insert(key.to_owned(), BtValue::Int(value));
54    }
55
56    /// Reads a signed integer entry by `key`.
57    ///
58    /// # Arguments
59    ///
60    /// - `&str` - Blackboard key name.
61    ///
62    /// # Returns
63    ///
64    /// - `Option<i64>` - Stored integer if present.
65    #[must_use]
66    pub fn get_int(&self, key: &str) -> Option<i64> {
67        match self.get_entries().get(key) {
68            Some(BtValue::Int(val)) => Some(*val),
69            _ => None,
70        }
71    }
72
73    /// Inserts or replaces an `f32` entry under `key`.
74    ///
75    /// # Arguments
76    ///
77    /// - `&str` - Blackboard key name.
78    /// - `f32` - Floating-point value.
79    pub fn set_float(&mut self, key: &str, value: f32) {
80        let _: Option<BtValue> = self
81            .get_mut_entries()
82            .insert(key.to_owned(), BtValue::Float(value));
83    }
84
85    /// Reads an `f32` entry by `key`.
86    ///
87    /// # Arguments
88    ///
89    /// - `&str` - Blackboard key name.
90    ///
91    /// # Returns
92    ///
93    /// - `Option<f32>` - Stored scalar if present.
94    #[must_use]
95    pub fn get_float(&self, key: &str) -> Option<f32> {
96        match self.get_entries().get(key) {
97            Some(BtValue::Float(val)) => Some(*val),
98            _ => None,
99        }
100    }
101
102    /// Inserts or replaces a `Vec2` entry under `key`.
103    ///
104    /// # Arguments
105    ///
106    /// - `&str` - Blackboard key name.
107    /// - `Vec2` - 2D vector value.
108    pub fn set_vec2(&mut self, key: &str, value: Vec2) {
109        let _: Option<BtValue> = self
110            .get_mut_entries()
111            .insert(key.to_owned(), BtValue::Vec2(value));
112    }
113
114    /// Reads a `Vec2` entry by `key`.
115    ///
116    /// # Arguments
117    ///
118    /// - `&str` - Blackboard key name.
119    ///
120    /// # Returns
121    ///
122    /// - `Option<Vec2>` - Stored 2D vector if present.
123    #[must_use]
124    pub fn get_vec2(&self, key: &str) -> Option<Vec2> {
125        match self.get_entries().get(key) {
126            Some(BtValue::Vec2(val)) => Some(*val),
127            _ => None,
128        }
129    }
130
131    /// Inserts or replaces a `Vec3` entry under `key`.
132    ///
133    /// # Arguments
134    ///
135    /// - `&str` - Blackboard key name.
136    /// - `Vec3` - 3D vector value.
137    pub fn set_vec3(&mut self, key: &str, value: Vec3) {
138        let _: Option<BtValue> = self
139            .get_mut_entries()
140            .insert(key.to_owned(), BtValue::Vec3(value));
141    }
142
143    /// Reads a `Vec3` entry by `key`.
144    ///
145    /// # Arguments
146    ///
147    /// - `&str` - Blackboard key name.
148    ///
149    /// # Returns
150    ///
151    /// - `Option<Vec3>` - Stored 3D vector if present.
152    #[must_use]
153    pub fn get_vec3(&self, key: &str) -> Option<Vec3> {
154        match self.get_entries().get(key) {
155            Some(BtValue::Vec3(val)) => Some(*val),
156            _ => None,
157        }
158    }
159
160    /// Inserts or replaces a text entry under `key`.
161    ///
162    /// # Arguments
163    ///
164    /// - `&str` - Blackboard key name.
165    /// - `&str` - Text string value.
166    pub fn set_text(&mut self, key: &str, value: &str) {
167        let _: Option<BtValue> = self
168            .get_mut_entries()
169            .insert(key.to_owned(), BtValue::Text(value.to_owned()));
170    }
171
172    /// Reads a text entry by `key`.
173    ///
174    /// # Arguments
175    ///
176    /// - `&str` - Blackboard key name.
177    ///
178    /// # Returns
179    ///
180    /// - `Option<&str>` - Stored string slice if present.
181    #[must_use]
182    pub fn get_text(&self, key: &str) -> Option<&str> {
183        match self.get_entries().get(key) {
184            Some(BtValue::Text(val)) => Some(val.as_str()),
185            _ => None,
186        }
187    }
188}
189
190/// Tree construction, reset, and tick execution for `BehaviorTree`.
191impl BehaviorTree {
192    /// Creates an empty `BehaviorTree`.
193    ///
194    /// # Returns
195    ///
196    /// - `Self` - Empty arena-backed behavior tree.
197    #[must_use]
198    pub fn new() -> Self {
199        Self::default()
200    }
201
202    /// Appends a node to the arena and returns its stable node handle.
203    ///
204    /// # Arguments
205    ///
206    /// - `BtNodeKind` - Node descriptor.
207    ///
208    /// # Returns
209    ///
210    /// - `usize` - Handle of the added node.
211    pub fn add_node(&mut self, kind: BtNodeKind) -> usize {
212        let idx: usize = self.get_nodes().len();
213        self.get_mut_nodes().push(kind);
214        self.get_mut_states().push(BtNodeState::default());
215        idx
216    }
217
218    /// Resets running child offsets, repeat counters, and active cooldowns across all nodes.
219    pub fn reset(&mut self) {
220        for state in self.get_mut_states() {
221            *state = BtNodeState::default();
222        }
223    }
224
225    /// Advances cooldown timers by `dt` and executes the tree from `root` with zero heap allocations.
226    ///
227    /// # Arguments
228    ///
229    /// - `f32` - Delta time in seconds (clamped to `>= 0.0`).
230    /// - `&mut Blackboard` - Shared typed blackboard.
231    /// - `C` - Condition evaluator callback.
232    /// - `A` - Action executor callback.
233    ///
234    /// # Returns
235    ///
236    /// - `BtStatus` - Root evaluation status for this tick.
237    pub fn tick<C, A>(
238        &mut self,
239        dt: f32,
240        blackboard: &mut Blackboard,
241        mut eval_condition: C,
242        mut run_action: A,
243    ) -> BtStatus
244    where
245        C: FnMut(u32, &mut Blackboard) -> bool,
246        A: FnMut(u32, f32, &mut Blackboard) -> BtStatus,
247    {
248        if self.get_nodes().is_empty() {
249            return BtStatus::Failure;
250        }
251        let safe_dt: f32 = if dt.is_finite() && dt > 0.0 { dt } else { 0.0 };
252        let root_idx: usize = self.get_root();
253        let mut states: Vec<BtNodeState> = take(self.get_mut_states());
254        if states.len() != self.get_nodes().len() {
255            states.resize(self.get_nodes().len(), BtNodeState::default());
256        }
257        for state in &mut states {
258            if state.cooldown_remaining > 0.0 {
259                state.cooldown_remaining = (state.cooldown_remaining - safe_dt).max(0.0);
260            }
261        }
262        let status: BtStatus = bt_tick_node(
263            self.get_nodes(),
264            &mut states,
265            root_idx,
266            safe_dt,
267            blackboard,
268            &mut eval_condition,
269            &mut run_action,
270        );
271        self.set_states(states);
272        status
273    }
274}
275
276/// Safe option accessors for `HfsmStateDef`.
277impl HfsmStateDef {
278    /// Constructs a new `HfsmStateDef`.
279    ///
280    /// # Arguments
281    ///
282    /// - `u32` - Unique state identifier.
283    /// - `Option<u32>` - Optional parent state identifier.
284    /// - `Option<u32>` - Optional default child state identifier.
285    ///
286    /// # Returns
287    ///
288    /// - `Self` - State definition.
289    #[must_use]
290    pub const fn new(id: u32, parent: Option<u32>, initial_child: Option<u32>) -> Self {
291        Self {
292            id,
293            parent,
294            initial_child,
295        }
296    }
297
298    /// Returns the optional parent state identifier.
299    ///
300    /// # Returns
301    ///
302    /// - `Option<u32>` - Parent state ID if nested.
303    #[must_use]
304    pub fn try_get_parent(&self) -> Option<u32> {
305        self.parent
306    }
307
308    /// Returns the optional initial child state identifier.
309    ///
310    /// # Returns
311    ///
312    /// - `Option<u32>` - Initial sub-state ID if composite.
313    #[must_use]
314    pub fn try_get_initial_child(&self) -> Option<u32> {
315        self.initial_child
316    }
317}
318
319/// Safe option accessors for `HfsmTransition`.
320impl HfsmTransition {
321    /// Constructs a new `HfsmTransition`.
322    ///
323    /// # Arguments
324    ///
325    /// - `u32` - Source state identifier.
326    /// - `u32` - Destination state identifier.
327    /// - `Option<u32>` - Optional triggering event identifier (`None` for automatic transitions).
328    /// - `Option<u32>` - Optional guard predicate identifier.
329    /// - `i32` - Transition priority (higher evaluated first).
330    ///
331    /// # Returns
332    ///
333    /// - `Self` - Transition rule.
334    #[must_use]
335    pub const fn new(
336        from_state: u32,
337        to_state: u32,
338        event_id: Option<u32>,
339        guard_id: Option<u32>,
340        priority: i32,
341    ) -> Self {
342        Self {
343            from_state,
344            to_state,
345            event_id,
346            guard_id,
347            priority,
348        }
349    }
350
351    /// Returns the optional triggering event identifier.
352    ///
353    /// # Returns
354    ///
355    /// - `Option<u32>` - Event ID, or `None` for automatic polled transitions.
356    #[must_use]
357    pub fn try_get_event_id(&self) -> Option<u32> {
358        self.event_id
359    }
360
361    /// Returns the optional guard predicate identifier.
362    ///
363    /// # Returns
364    ///
365    /// - `Option<u32>` - Guard ID if guarded.
366    #[must_use]
367    pub fn try_get_guard_id(&self) -> Option<u32> {
368        self.guard_id
369    }
370}
371
372/// Nested state lifecycle, LCA transitions, and parent fallback for `HierarchicalFsm`.
373impl HierarchicalFsm {
374    /// Creates an empty `HierarchicalFsm`.
375    ///
376    /// # Returns
377    ///
378    /// - `Self` - Unstarted hierarchical state machine.
379    #[must_use]
380    pub fn new() -> Self {
381        Self::default()
382    }
383
384    /// Registers a state definition with optional parent and initial child.
385    ///
386    /// # Arguments
387    ///
388    /// - `u32` - Unique state identifier.
389    /// - `Option<u32>` - Optional parent state identifier.
390    /// - `Option<u32>` - Optional default child state identifier.
391    pub fn add_state(&mut self, id: u32, parent: Option<u32>, initial_child: Option<u32>) {
392        self.get_mut_states()
393            .push(HfsmStateDef::new(id, parent, initial_child));
394    }
395
396    /// Registers a guarded transition rule.
397    ///
398    /// # Arguments
399    ///
400    /// - `HfsmTransition` - Transition definition.
401    pub fn add_transition(&mut self, transition: HfsmTransition) {
402        self.get_mut_transitions().push(transition);
403    }
404
405    /// Finds a state definition by `state_id`.
406    ///
407    /// # Arguments
408    ///
409    /// - `&[HfsmStateDef]` - Registered state definitions.
410    /// - `u32` - State identifier to locate.
411    ///
412    /// # Returns
413    ///
414    /// - `Option<HfsmStateDef>` - Matching definition if registered.
415    fn find_state_def(states: &[HfsmStateDef], state_id: u32) -> Option<HfsmStateDef> {
416        states
417            .iter()
418            .copied()
419            .find(|def: &HfsmStateDef| def.get_id() == state_id)
420    }
421
422    /// Resolves the full top-down chain `[root, ..., target, ..., leaf]` into `out_chain`.
423    ///
424    /// # Arguments
425    ///
426    /// - `&[HfsmStateDef]` - Registered state definitions.
427    /// - `u32` - Target state identifier.
428    /// - `&mut Vec<u32>` - Output chain buffer populated from root to leaf.
429    fn resolve_chain(states: &[HfsmStateDef], target: u32, out_chain: &mut Vec<u32>) {
430        out_chain.clear();
431        let mut cursor: Option<u32> = Some(target);
432        let mut guard_steps: usize = 0;
433        while let Some(id) = cursor {
434            if guard_steps > states.len() {
435                break;
436            }
437            guard_steps += 1;
438            out_chain.push(id);
439            cursor =
440                Self::find_state_def(states, id).and_then(|def: HfsmStateDef| def.try_get_parent());
441        }
442        out_chain.reverse();
443        let mut child_cursor: Option<u32> = Self::find_state_def(states, target)
444            .and_then(|def: HfsmStateDef| def.try_get_initial_child());
445        let mut child_steps: usize = 0;
446        while let Some(child_id) = child_cursor {
447            if child_steps > states.len() || out_chain.contains(&child_id) {
448                break;
449            }
450            child_steps += 1;
451            out_chain.push(child_id);
452            child_cursor = Self::find_state_def(states, child_id)
453                .and_then(|def: HfsmStateDef| def.try_get_initial_child());
454        }
455    }
456
457    /// Enters `initial_state` (descending any `initial_child` chain) and emits top-down `Enter` events.
458    ///
459    /// # Arguments
460    ///
461    /// - `u32` - Initial state identifier.
462    /// - `H` - Lifecycle event callback.
463    pub fn start<H>(&mut self, initial_state: u32, mut on_event: H)
464    where
465        H: FnMut(HfsmLifecycleEvent),
466    {
467        let mut target_chain: Vec<u32> = take(self.get_mut_target_chain_scratch());
468        Self::resolve_chain(self.get_states(), initial_state, &mut target_chain);
469        for &state_id in &target_chain {
470            on_event(HfsmLifecycleEvent::Enter(state_id));
471        }
472        let active: &mut Vec<u32> = self.get_mut_active_chain();
473        active.clear();
474        active.extend_from_slice(&target_chain);
475        self.set_target_chain_scratch(target_chain);
476    }
477
478    /// Returns the currently active leaf state identifier, if started.
479    ///
480    /// # Returns
481    ///
482    /// - `Option<u32>` - Active leaf state identifier.
483    #[must_use]
484    pub fn current_state(&self) -> Option<u32> {
485        self.get_active_chain().last().copied()
486    }
487
488    /// Returns `true` if `state_id` is currently active as either leaf or enclosing parent state.
489    ///
490    /// # Arguments
491    ///
492    /// - `u32` - State identifier to query.
493    ///
494    /// # Returns
495    ///
496    /// - `bool` - `true` when `state_id` is in the active hierarchy.
497    #[must_use]
498    pub fn is_in_state(&self, state_id: u32) -> bool {
499        self.get_active_chain().contains(&state_id)
500    }
501
502    /// Finds the highest-priority valid transition matching `event_id` walking leaf-to-root for parent fallback.
503    ///
504    /// # Arguments
505    ///
506    /// - `Option<u32>` - Triggering event (`None` for automatic update transitions).
507    /// - `&mut G` - Guard evaluator callback.
508    ///
509    /// # Returns
510    ///
511    /// - `Option<u32>` - Destination state identifier if a transition fires.
512    fn pick_transition<G>(&self, event_id: Option<u32>, eval_guard: &mut G) -> Option<u32>
513    where
514        G: FnMut(u32) -> bool,
515    {
516        let transitions: &[HfsmTransition] = self.get_transitions();
517        for &active_state in self.get_active_chain().iter().rev() {
518            let mut best_target: Option<u32> = None;
519            let mut best_prio: i32 = i32::MIN;
520            for trans in transitions {
521                if trans.get_from_state() != active_state || trans.try_get_event_id() != event_id {
522                    continue;
523                }
524                if best_target.is_some() && trans.get_priority() <= best_prio {
525                    continue;
526                }
527                let guard_ok: bool = match trans.try_get_guard_id() {
528                    Some(g_id) => eval_guard(g_id),
529                    None => true,
530                };
531                if guard_ok {
532                    best_prio = trans.get_priority();
533                    best_target = Some(trans.get_to_state());
534                }
535            }
536            if best_target.is_some() {
537                return best_target;
538            }
539        }
540        None
541    }
542
543    /// Transitions from the active hierarchy to `target_state` using LCA bottom-up exits and top-down enters.
544    ///
545    /// # Arguments
546    ///
547    /// - `u32` - Destination state identifier.
548    /// - `&mut H` - Lifecycle event callback.
549    fn apply_transition<H>(&mut self, target_state: u32, on_event: &mut H)
550    where
551        H: FnMut(HfsmLifecycleEvent),
552    {
553        let mut target_chain: Vec<u32> = take(self.get_mut_target_chain_scratch());
554        Self::resolve_chain(self.get_states(), target_state, &mut target_chain);
555        let active: &mut Vec<u32> = self.get_mut_active_chain();
556        let mut lca_len: usize = 0;
557        let min_len: usize = active.len().min(target_chain.len());
558        while lca_len < min_len && active[lca_len] == target_chain[lca_len] {
559            lca_len += 1;
560        }
561        if lca_len == active.len() && lca_len == target_chain.len() && lca_len > 0 {
562            lca_len -= 1;
563        }
564        for idx in (lca_len..active.len()).rev() {
565            on_event(HfsmLifecycleEvent::Exit(active[idx]));
566        }
567        active.truncate(lca_len);
568        for &state_id in &target_chain[lca_len..] {
569            active.push(state_id);
570            on_event(HfsmLifecycleEvent::Enter(state_id));
571        }
572        self.set_target_chain_scratch(target_chain);
573    }
574
575    /// Dispatches `event_id` from leaf to root (parent fallback) and executes the winning guarded transition.
576    ///
577    /// # Arguments
578    ///
579    /// - `u32` - Event identifier.
580    /// - `G` - Guard evaluator callback.
581    /// - `H` - Lifecycle event callback.
582    ///
583    /// # Returns
584    ///
585    /// - `bool` - `true` if a matching transition fired.
586    pub fn trigger_event<G, H>(&mut self, event_id: u32, mut eval_guard: G, mut on_event: H) -> bool
587    where
588        G: FnMut(u32) -> bool,
589        H: FnMut(HfsmLifecycleEvent),
590    {
591        if let Some(target_state) = self.pick_transition(Some(event_id), &mut eval_guard) {
592            self.apply_transition(target_state, &mut on_event);
593            true
594        } else {
595            false
596        }
597    }
598
599    /// Checks automatic guarded transitions and emits top-down `Update` events for every active state.
600    ///
601    /// # Arguments
602    ///
603    /// - `G` - Guard evaluator callback.
604    /// - `H` - Lifecycle event callback.
605    pub fn update<G, H>(&mut self, mut eval_guard: G, mut on_event: H)
606    where
607        G: FnMut(u32) -> bool,
608        H: FnMut(HfsmLifecycleEvent),
609    {
610        if let Some(target_state) = self.pick_transition(None, &mut eval_guard) {
611            self.apply_transition(target_state, &mut on_event);
612        }
613        let active_len: usize = self.get_active_chain().len();
614        for idx in 0..active_len {
615            let state_id: u32 = self.get_active_chain()[idx];
616            on_event(HfsmLifecycleEvent::Update(state_id));
617        }
618    }
619}
620
621/// Multi-consideration scoring and hysteresis action selection for `UtilityAiBrain`.
622impl UtilityAiBrain {
623    /// Creates a new `UtilityAiBrain` with configurable inertia bonus and minimum dwell duration.
624    ///
625    /// # Arguments
626    ///
627    /// - `f32` - Additive inertia bonus applied to the active action.
628    /// - `f32` - Minimum dwell seconds before switching away from a viable active action.
629    ///
630    /// # Returns
631    ///
632    /// - `Self` - Empty utility AI brain.
633    #[must_use]
634    pub fn new(inertia_bonus: f32, min_dwell_time: f32) -> Self {
635        let safe_inertia: f32 = if inertia_bonus.is_finite() && inertia_bonus >= 0.0 {
636            inertia_bonus
637        } else {
638            DEFAULT_UTILITY_INERTIA
639        };
640        let safe_dwell: f32 = if min_dwell_time.is_finite() && min_dwell_time >= 0.0 {
641            min_dwell_time
642        } else {
643            0.0
644        };
645        Self {
646            actions: Vec::new(),
647            inertia_bonus: safe_inertia,
648            min_dwell_time: safe_dwell,
649            current_action: 0,
650            has_active: false,
651            dwell_elapsed: 0.0,
652            last_scores: Vec::new(),
653        }
654    }
655
656    /// Registers a candidate `UtilityActionDef`.
657    ///
658    /// # Arguments
659    ///
660    /// - `UtilityActionDef` - Action definition with base weight and response-curve considerations.
661    pub fn add_action(&mut self, action: UtilityActionDef) {
662        self.get_mut_actions().push(action);
663    }
664
665    /// Returns the currently selected action identifier, if any.
666    ///
667    /// # Returns
668    ///
669    /// - `Option<u32>` - Active action identifier.
670    #[must_use]
671    pub fn active_action(&self) -> Option<u32> {
672        if self.get_has_active() {
673            Some(self.get_current_action())
674        } else {
675            None
676        }
677    }
678
679    /// Scores every registered action and selects the highest-utility action with hysteresis protection.
680    ///
681    /// # Arguments
682    ///
683    /// - `f32` - Elapsed time step in seconds.
684    /// - `F` - Input sampler returning the raw scalar value for each `input_id`.
685    ///
686    /// # Returns
687    ///
688    /// - `Option<u32>` - Winning action identifier.
689    pub fn evaluate<F>(&mut self, dt: f32, mut sample_input: F) -> Option<u32>
690    where
691        F: FnMut(u32) -> f32,
692    {
693        if self.get_actions().is_empty() {
694            return None;
695        }
696        let safe_dt: f32 = if dt.is_finite() && dt > 0.0 { dt } else { 0.0 };
697        let inertia: f32 = self.get_inertia_bonus();
698        let min_dwell: f32 = self.get_min_dwell_time();
699        let has_active: bool = self.get_has_active();
700        let current_action: u32 = self.get_current_action();
701        let next_dwell: f32 = if has_active {
702            self.get_dwell_elapsed() + safe_dt
703        } else {
704            0.0
705        };
706        let mut scores: Vec<(u32, f32)> = take(self.get_mut_last_scores());
707        scores.clear();
708        let mut best_action: u32 = 0;
709        let mut best_score: f32 = f32::NEG_INFINITY;
710        let mut current_raw_score: f32 = 0.0;
711        for action in self.get_actions() {
712            let cons: &[UtilityConsideration] = action.get_considerations();
713            let raw_score: f32 = if cons.is_empty() {
714                action.get_base_weight().max(0.0)
715            } else {
716                let mut product: f32 = 1.0;
717                for item in cons {
718                    let raw_in: f32 = sample_input(item.get_input_id());
719                    let span: f32 = item.get_max_input() - item.get_min_input();
720                    let norm_x: f32 = if span.abs() > 1e-6 {
721                        ((raw_in - item.get_min_input()) / span).clamp(0.0, 1.0)
722                    } else {
723                        0.0
724                    };
725                    let curved: f32 = eval_utility_curve(item.get_curve(), norm_x);
726                    let w: f32 = if item.get_weight().is_finite() && item.get_weight() > 0.0 {
727                        item.get_weight()
728                    } else {
729                        1.0
730                    };
731                    product *= curved.powf(w);
732                }
733                let n: f32 = cons.len() as f32;
734                let mod_factor: f32 = 1.0 - (1.0 / n);
735                let makeup: f32 = (1.0 - product) * mod_factor;
736                let compensated: f32 = product + makeup * product;
737                compensated * action.get_base_weight().max(0.0)
738            };
739            let action_id: u32 = action.get_action_id();
740            if has_active && action_id == current_action {
741                current_raw_score = raw_score;
742            }
743            let effective_score: f32 =
744                if has_active && action_id == current_action && raw_score > 0.0 {
745                    raw_score + inertia
746                } else {
747                    raw_score
748                };
749            scores.push((action_id, effective_score));
750            if effective_score > best_score {
751                best_score = effective_score;
752                best_action = action_id;
753            }
754        }
755        let chosen: u32 = if has_active
756            && best_action != current_action
757            && current_raw_score > 0.0
758            && next_dwell < min_dwell
759        {
760            current_action
761        } else {
762            best_action
763        };
764        if !has_active || chosen != current_action {
765            self.set_current_action(chosen);
766            self.set_has_active(true);
767            self.set_dwell_elapsed(0.0);
768        } else {
769            self.set_dwell_elapsed(next_dwell);
770        }
771        self.set_last_scores(scores);
772        Some(chosen)
773    }
774}
775
776/// Default balanced weights and neighborhood radii for `BoidsConfig`.
777impl Default for BoidsConfig {
778    /// Returns balanced 3D Reynolds flocking weights and perception radii.
779    ///
780    /// # Returns
781    ///
782    /// - `Self` - Default boids configuration.
783    fn default() -> Self {
784        Self {
785            perception_radius: DEFAULT_BOIDS_PERCEPTION,
786            separation_radius: DEFAULT_BOIDS_SEPARATION,
787            separation_weight: 2.2,
788            alignment_weight: 1.0,
789            cohesion_weight: 0.9,
790            obstacle_weight: 4.0,
791            wander_weight: 0.3,
792            goal_weight: 1.0,
793        }
794    }
795}
796
797/// Constructors for `BoidsAgent3D`.
798impl BoidsAgent3D {
799    /// Creates a 3D boid agent with explicit position, velocity, speed, and force limits.
800    ///
801    /// # Arguments
802    ///
803    /// - `Vec3` - Initial world position.
804    /// - `Vec3` - Initial velocity vector.
805    /// - `f32` - Maximum speed.
806    /// - `f32` - Maximum steering acceleration.
807    ///
808    /// # Returns
809    ///
810    /// - `Self` - Initialized boid agent.
811    #[must_use]
812    pub fn new(position: Vec3, velocity: Vec3, max_speed: f32, max_force: f32) -> Self {
813        let safe_speed: f32 = if max_speed.is_finite() && max_speed > 0.0 {
814            max_speed
815        } else {
816            DEFAULT_BOIDS_MAX_SPEED
817        };
818        let safe_force: f32 = if max_force.is_finite() && max_force > 0.0 {
819            max_force
820        } else {
821            DEFAULT_BOIDS_MAX_FORCE
822        };
823        Self {
824            position,
825            velocity: ai_vec3_clamp_len(velocity, safe_speed),
826            wander_angle: 0.0,
827            max_speed: safe_speed,
828            max_force: safe_force,
829        }
830    }
831}
832
833/// Composable Reynolds steering behaviors and SpatialHashGrid3D-accelerated flocking for `BoidsFlockSolver`.
834impl BoidsFlockSolver {
835    /// Creates a new `BoidsFlockSolver` seeded deterministically for wander behaviors.
836    ///
837    /// # Arguments
838    ///
839    /// - `BoidsConfig` - Neighborhood radii and steering force weights.
840    /// - `u64` - Deterministic PRNG seed.
841    ///
842    /// # Returns
843    ///
844    /// - `Self` - Ready flock solver with pre-allocated `SpatialHashGrid3D`.
845    #[must_use]
846    pub fn new(config: BoidsConfig, seed: u64) -> Self {
847        let cell_size: f32 = config.get_perception_radius().max(0.5);
848        Self {
849            config,
850            agents: Vec::new(),
851            obstacles: Vec::new(),
852            goal_target: Vec3::zero(),
853            has_goal: false,
854            rng: DeterministicRng::new(seed),
855            scratch: BoidsScratch {
856                spatial_grid: SpatialHashGrid3D::new(cell_size),
857                neighbor_ids: Vec::with_capacity(64),
858                accelerations: Vec::with_capacity(64),
859                next_angles: Vec::with_capacity(64),
860            },
861        }
862    }
863
864    /// Adds a boid agent to the flock and returns its index.
865    ///
866    /// # Arguments
867    ///
868    /// - `BoidsAgent3D` - Agent state to add.
869    ///
870    /// # Returns
871    ///
872    /// - `usize` - Index of the registered agent.
873    pub fn add_agent(&mut self, agent: BoidsAgent3D) -> usize {
874        let idx: usize = self.get_agents().len();
875        self.get_mut_agents().push(agent);
876        idx
877    }
878
879    /// Registers a spherical obstacle avoided by all boids in the flock.
880    ///
881    /// # Arguments
882    ///
883    /// - `BoidsObstacle3D` - Spherical obstacle descriptor.
884    pub fn add_obstacle(&mut self, obstacle: BoidsObstacle3D) {
885        self.get_mut_obstacles().push(obstacle);
886    }
887
888    /// Sets or clears the optional shared target point that attracts the flock.
889    ///
890    /// # Arguments
891    ///
892    /// - `Option<Vec3>` - Optional 3D target coordinates.
893    pub fn set_goal(&mut self, goal: Option<Vec3>) {
894        if let Some(target) = goal {
895            self.set_goal_target(target);
896            self.set_has_goal(true);
897        } else {
898            self.set_has_goal(false);
899        }
900    }
901
902    /// Computes Reynolds `Seek` steering force toward `target`.
903    ///
904    /// # Arguments
905    ///
906    /// - `Vec3` - Agent position.
907    /// - `Vec3` - Agent current velocity.
908    /// - `Vec3` - Target position.
909    /// - `f32` - Maximum speed.
910    /// - `f32` - Maximum steering force.
911    ///
912    /// # Returns
913    ///
914    /// - `Vec3` - Clamped steering force vector.
915    #[must_use]
916    pub fn steer_seek(
917        position: Vec3,
918        velocity: Vec3,
919        target: Vec3,
920        max_speed: f32,
921        max_force: f32,
922    ) -> Vec3 {
923        let offset: Vec3 = target.sub(position);
924        if offset.length_sq() <= 1e-10 {
925            return Vec3::zero();
926        }
927        let desired: Vec3 = offset.normalize().scale(max_speed);
928        ai_vec3_clamp_len(desired.sub(velocity), max_force)
929    }
930
931    /// Computes Reynolds `Flee` steering force directly away from `threat`.
932    ///
933    /// # Arguments
934    ///
935    /// - `Vec3` - Agent position.
936    /// - `Vec3` - Agent current velocity.
937    /// - `Vec3` - Threat position.
938    /// - `f32` - Maximum speed.
939    /// - `f32` - Maximum steering force.
940    ///
941    /// # Returns
942    ///
943    /// - `Vec3` - Clamped repulsion force vector.
944    #[must_use]
945    pub fn steer_flee(
946        position: Vec3,
947        velocity: Vec3,
948        threat: Vec3,
949        max_speed: f32,
950        max_force: f32,
951    ) -> Vec3 {
952        let offset: Vec3 = position.sub(threat);
953        if offset.length_sq() <= 1e-10 {
954            return Vec3::zero();
955        }
956        let desired: Vec3 = offset.normalize().scale(max_speed);
957        ai_vec3_clamp_len(desired.sub(velocity), max_force)
958    }
959
960    /// Computes Reynolds `Arrive` steering force decelerating smoothly inside `slowing_radius`.
961    ///
962    /// # Arguments
963    ///
964    /// - `Vec3` - Agent position.
965    /// - `Vec3` - Agent current velocity.
966    /// - `Vec3` - Destination target position.
967    /// - `f32` - Deceleration radius around `target`.
968    /// - `f32` - Maximum speed.
969    /// - `f32` - Maximum steering force.
970    ///
971    /// # Returns
972    ///
973    /// - `Vec3` - Clamped arrival steering force.
974    #[must_use]
975    pub fn steer_arrive(
976        position: Vec3,
977        velocity: Vec3,
978        target: Vec3,
979        slowing_radius: f32,
980        max_speed: f32,
981        max_force: f32,
982    ) -> Vec3 {
983        let offset: Vec3 = target.sub(position);
984        let dist: f32 = offset.length();
985        if dist <= 1e-5 {
986            return ai_vec3_clamp_len(velocity.scale(-1.0), max_force);
987        }
988        let ramped_speed: f32 = if slowing_radius > 1e-5 && dist < slowing_radius {
989            max_speed * (dist / slowing_radius)
990        } else {
991            max_speed
992        };
993        let desired: Vec3 = offset.scale(ramped_speed / dist);
994        ai_vec3_clamp_len(desired.sub(velocity), max_force)
995    }
996
997    /// Computes predictive Reynolds `Pursue` steering force anticipating a moving quarry.
998    ///
999    /// # Arguments
1000    ///
1001    /// - `Vec3` - Pursuer position.
1002    /// - `Vec3` - Pursuer velocity.
1003    /// - `Vec3` - Quarry position.
1004    /// - `Vec3` - Quarry velocity.
1005    /// - `f32` - Maximum speed.
1006    /// - `f32` - Maximum steering force.
1007    ///
1008    /// # Returns
1009    ///
1010    /// - `Vec3` - Clamped pursuit steering force.
1011    #[must_use]
1012    pub fn steer_pursue(
1013        position: Vec3,
1014        velocity: Vec3,
1015        target_pos: Vec3,
1016        target_vel: Vec3,
1017        max_speed: f32,
1018        max_force: f32,
1019    ) -> Vec3 {
1020        let dist: f32 = target_pos.sub(position).length();
1021        let lookahead: f32 = (dist / max_speed.max(1e-3)).clamp(0.0, 2.0);
1022        let future_target: Vec3 = target_pos.add(target_vel.scale(lookahead));
1023        Self::steer_seek(position, velocity, future_target, max_speed, max_force)
1024    }
1025
1026    /// Computes predictive Reynolds `Evade` steering force escaping a moving pursuer.
1027    ///
1028    /// # Arguments
1029    ///
1030    /// - `Vec3` - Evader position.
1031    /// - `Vec3` - Evader velocity.
1032    /// - `Vec3` - Threat position.
1033    /// - `Vec3` - Threat velocity.
1034    /// - `f32` - Maximum speed.
1035    /// - `f32` - Maximum steering force.
1036    ///
1037    /// # Returns
1038    ///
1039    /// - `Vec3` - Clamped evasion steering force.
1040    #[must_use]
1041    pub fn steer_evade(
1042        position: Vec3,
1043        velocity: Vec3,
1044        threat_pos: Vec3,
1045        threat_vel: Vec3,
1046        max_speed: f32,
1047        max_force: f32,
1048    ) -> Vec3 {
1049        let dist: f32 = threat_pos.sub(position).length();
1050        let lookahead: f32 = (dist / max_speed.max(1e-3)).clamp(0.0, 2.0);
1051        let future_threat: Vec3 = threat_pos.add(threat_vel.scale(lookahead));
1052        Self::steer_flee(position, velocity, future_threat, max_speed, max_force)
1053    }
1054
1055    /// Computes continuous Reynolds `Wander` steering force and updated wander angle.
1056    ///
1057    /// # Arguments
1058    ///
1059    /// - `Vec3` - Current velocity vector.
1060    /// - `f32` - Current wander phase angle in radians.
1061    /// - `BoidsWanderParams` - Wander circle distance, radius, and angular jitter parameters.
1062    /// - `&mut DeterministicRng` - Deterministic PRNG.
1063    /// - `f32` - Maximum speed.
1064    /// - `f32` - Maximum steering force.
1065    ///
1066    /// # Returns
1067    ///
1068    /// - `(Vec3, f32)` - `(steering_force, updated_wander_angle)`.
1069    pub fn steer_wander(
1070        velocity: Vec3,
1071        wander_angle: f32,
1072        params: BoidsWanderParams,
1073        rng: &mut DeterministicRng,
1074        max_speed: f32,
1075        max_force: f32,
1076    ) -> (Vec3, f32) {
1077        let forward: Vec3 = if velocity.length_sq() > 1e-6 {
1078            velocity.normalize()
1079        } else {
1080            Vec3::new(1.0, 0.0, 0.0)
1081        };
1082        let up_ref: Vec3 = if forward.get_y().abs() < 0.9 {
1083            Vec3::new(0.0, 1.0, 0.0)
1084        } else {
1085            Vec3::new(1.0, 0.0, 0.0)
1086        };
1087        let right: Vec3 = forward.cross(up_ref).normalize();
1088        let ortho_up: Vec3 = right.cross(forward).normalize();
1089        let jitter: f32 = params.get_jitter();
1090        let next_angle: f32 = wander_angle + rng.next_range_f32(-jitter, jitter);
1091        let offset: Vec3 = forward
1092            .scale(params.get_circle_dist())
1093            .add(right.scale(params.get_circle_radius() * next_angle.cos()))
1094            .add(ortho_up.scale(params.get_circle_radius() * next_angle.sin()));
1095        let desired: Vec3 = offset.normalize().scale(max_speed);
1096        let force: Vec3 = ai_vec3_clamp_len(desired.sub(velocity), max_force);
1097        (force, next_angle)
1098    }
1099
1100    /// Advances the entire flock by `dt` using `SpatialHashGrid3D` neighbor queries with zero steady-state allocations.
1101    ///
1102    /// # Arguments
1103    ///
1104    /// - `f32` - Simulation time step in seconds.
1105    pub fn step(&mut self, dt: f32) {
1106        if !dt.is_finite() || dt <= 1e-6 {
1107            return;
1108        }
1109        let count: usize = self.get_agents().len();
1110        if count == 0 {
1111            return;
1112        }
1113        let cfg: BoidsConfig = self.get_config();
1114        let perc_r: f32 = cfg.get_perception_radius().max(1e-3);
1115        let sep_r: f32 = cfg.get_separation_radius().max(1e-3);
1116        let sep_r_sq: f32 = sep_r * sep_r;
1117        let has_goal: bool = self.get_has_goal();
1118        let goal_target: Vec3 = self.get_goal_target();
1119        let mut rng: DeterministicRng = self.get_rng();
1120        let mut scratch: BoidsScratch = take(self.get_mut_scratch());
1121        scratch.spatial_grid.clear();
1122        for (idx, agent) in self.get_agents().iter().enumerate() {
1123            scratch
1124                .spatial_grid
1125                .insert_point(idx as u64, agent.get_position());
1126        }
1127        scratch.accelerations.clear();
1128        scratch.accelerations.resize(count, Vec3::zero());
1129        scratch.next_angles.clear();
1130        scratch.next_angles.resize(count, 0.0);
1131        let agents: &[BoidsAgent3D] = self.get_agents();
1132        let obstacles: &[BoidsObstacle3D] = self.get_obstacles();
1133        for idx in 0..count {
1134            let agent: BoidsAgent3D = agents[idx];
1135            let pos: Vec3 = agent.get_position();
1136            let vel: Vec3 = agent.get_velocity();
1137            let max_s: f32 = agent.get_max_speed();
1138            let max_f: f32 = agent.get_max_force();
1139            scratch
1140                .spatial_grid
1141                .query_sphere_into(pos, perc_r, &mut scratch.neighbor_ids);
1142            let mut sep_sum: Vec3 = Vec3::zero();
1143            let mut sep_cnt: usize = 0;
1144            let mut ali_sum: Vec3 = Vec3::zero();
1145            let mut coh_sum: Vec3 = Vec3::zero();
1146            let mut perc_cnt: usize = 0;
1147            for &nid in &scratch.neighbor_ids {
1148                let other_idx: usize = nid as usize;
1149                if other_idx == idx || other_idx >= count {
1150                    continue;
1151                }
1152                let other: BoidsAgent3D = agents[other_idx];
1153                let diff: Vec3 = pos.sub(other.get_position());
1154                let d_sq: f32 = diff.length_sq();
1155                perc_cnt += 1;
1156                ali_sum = ali_sum.add(other.get_velocity());
1157                coh_sum = coh_sum.add(other.get_position());
1158                if d_sq < sep_r_sq && d_sq > 1e-10 {
1159                    sep_sum = sep_sum.add(diff.scale(1.0 / d_sq));
1160                    sep_cnt += 1;
1161                } else if d_sq <= 1e-10 {
1162                    let jitter_dir: Vec3 = Vec3::new(
1163                        ((idx as f32) * 1.234_567).cos(),
1164                        ((idx as f32) * 2.345_678).sin(),
1165                        0.5,
1166                    );
1167                    sep_sum = sep_sum.add(jitter_dir);
1168                    sep_cnt += 1;
1169                }
1170            }
1171            let mut total_force: Vec3 = Vec3::zero();
1172            if sep_cnt > 0 {
1173                let sep_steer: Vec3 =
1174                    ai_vec3_clamp_len(sep_sum.normalize().scale(max_s).sub(vel), max_f);
1175                total_force = total_force.add(sep_steer.scale(cfg.get_separation_weight()));
1176            }
1177            if perc_cnt > 0 {
1178                let inv_cnt: f32 = 1.0 / (perc_cnt as f32);
1179                let ali_steer: Vec3 = ai_vec3_clamp_len(
1180                    ali_sum.scale(inv_cnt).normalize().scale(max_s).sub(vel),
1181                    max_f,
1182                );
1183                let center_mass: Vec3 = coh_sum.scale(inv_cnt);
1184                let coh_steer: Vec3 = Self::steer_seek(pos, vel, center_mass, max_s, max_f);
1185                total_force = total_force.add(ali_steer.scale(cfg.get_alignment_weight()));
1186                total_force = total_force.add(coh_steer.scale(cfg.get_cohesion_weight()));
1187            }
1188            if cfg.get_obstacle_weight() > 0.0 {
1189                let mut obs_force: Vec3 = Vec3::zero();
1190                for obs in obstacles {
1191                    let avoid_r: f32 = obs.get_radius() + sep_r;
1192                    let away: Vec3 = pos.sub(obs.get_center());
1193                    let dist: f32 = away.length();
1194                    if dist < avoid_r {
1195                        let push_dir: Vec3 = if dist > 1e-5 {
1196                            away.scale(1.0 / dist)
1197                        } else {
1198                            Vec3::new(0.0, 1.0, 0.0)
1199                        };
1200                        let strength: f32 = (avoid_r - dist) / avoid_r.max(1e-4);
1201                        obs_force = obs_force.add(push_dir.scale(max_f * strength));
1202                    }
1203                }
1204                total_force = total_force.add(obs_force.scale(cfg.get_obstacle_weight()));
1205            }
1206            let (wander_force, next_ang): (Vec3, f32) = if cfg.get_wander_weight() > 0.0 {
1207                Self::steer_wander(
1208                    vel,
1209                    agent.get_wander_angle(),
1210                    BoidsWanderParams::new(2.0, 1.0, 0.35),
1211                    &mut rng,
1212                    max_s,
1213                    max_f,
1214                )
1215            } else {
1216                (Vec3::zero(), agent.get_wander_angle())
1217            };
1218            total_force = total_force.add(wander_force.scale(cfg.get_wander_weight()));
1219            scratch.next_angles[idx] = next_ang;
1220            if has_goal && cfg.get_goal_weight() > 0.0 {
1221                let goal_steer: Vec3 =
1222                    Self::steer_arrive(pos, vel, goal_target, perc_r, max_s, max_f);
1223                total_force = total_force.add(goal_steer.scale(cfg.get_goal_weight()));
1224            }
1225            scratch.accelerations[idx] = ai_vec3_clamp_len(total_force, max_f * 2.0);
1226        }
1227        for (idx, agent) in self.get_mut_agents().iter_mut().enumerate() {
1228            let max_s: f32 = agent.get_max_speed();
1229            let next_vel: Vec3 = ai_vec3_clamp_len(
1230                agent
1231                    .get_velocity()
1232                    .add(scratch.accelerations[idx].scale(dt)),
1233                max_s,
1234            );
1235            let next_pos: Vec3 = agent.get_position().add(next_vel.scale(dt));
1236            agent.set_velocity(next_vel);
1237            agent.set_position(next_pos);
1238            agent.set_wander_angle(scratch.next_angles[idx]);
1239        }
1240        self.set_rng(rng);
1241        self.set_scratch(scratch);
1242    }
1243}
1244
1245/// Default scratch construction for `BoidsScratch`.
1246impl Default for BoidsScratch {
1247    /// Returns a default `BoidsScratch` with cell size `1.0`.
1248    ///
1249    /// # Returns
1250    ///
1251    /// - `Self` - Empty boids scratch state.
1252    fn default() -> Self {
1253        Self {
1254            spatial_grid: SpatialHashGrid3D::new(1.0),
1255            neighbor_ids: Vec::new(),
1256            accelerations: Vec::new(),
1257            next_angles: Vec::new(),
1258        }
1259    }
1260}