euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
use super::*;

/// Typed blackboard storage and retrieval methods for `Blackboard`.
impl Blackboard {
    /// Creates a new empty `Blackboard`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty typed blackboard.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts or replaces a boolean entry under `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    /// - `bool` - Boolean value.
    pub fn set_bool(&mut self, key: &str, value: bool) {
        let _: Option<BtValue> = self
            .get_mut_entries()
            .insert(key.to_owned(), BtValue::Bool(value));
    }

    /// Reads a boolean entry by `key`, returning `None` if absent or mismatched in type.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    ///
    /// # Returns
    ///
    /// - `Option<bool>` - Stored boolean if present.
    #[must_use]
    pub fn get_bool(&self, key: &str) -> Option<bool> {
        match self.get_entries().get(key) {
            Some(BtValue::Bool(val)) => Some(*val),
            _ => None,
        }
    }

    /// Inserts or replaces a signed 64-bit integer entry under `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    /// - `i64` - Integer value.
    pub fn set_int(&mut self, key: &str, value: i64) {
        let _: Option<BtValue> = self
            .get_mut_entries()
            .insert(key.to_owned(), BtValue::Int(value));
    }

    /// Reads a signed integer entry by `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    ///
    /// # Returns
    ///
    /// - `Option<i64>` - Stored integer if present.
    #[must_use]
    pub fn get_int(&self, key: &str) -> Option<i64> {
        match self.get_entries().get(key) {
            Some(BtValue::Int(val)) => Some(*val),
            _ => None,
        }
    }

    /// Inserts or replaces an `f32` entry under `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    /// - `f32` - Floating-point value.
    pub fn set_float(&mut self, key: &str, value: f32) {
        let _: Option<BtValue> = self
            .get_mut_entries()
            .insert(key.to_owned(), BtValue::Float(value));
    }

    /// Reads an `f32` entry by `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    ///
    /// # Returns
    ///
    /// - `Option<f32>` - Stored scalar if present.
    #[must_use]
    pub fn get_float(&self, key: &str) -> Option<f32> {
        match self.get_entries().get(key) {
            Some(BtValue::Float(val)) => Some(*val),
            _ => None,
        }
    }

    /// Inserts or replaces a `Vec2` entry under `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    /// - `Vec2` - 2D vector value.
    pub fn set_vec2(&mut self, key: &str, value: Vec2) {
        let _: Option<BtValue> = self
            .get_mut_entries()
            .insert(key.to_owned(), BtValue::Vec2(value));
    }

    /// Reads a `Vec2` entry by `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    ///
    /// # Returns
    ///
    /// - `Option<Vec2>` - Stored 2D vector if present.
    #[must_use]
    pub fn get_vec2(&self, key: &str) -> Option<Vec2> {
        match self.get_entries().get(key) {
            Some(BtValue::Vec2(val)) => Some(*val),
            _ => None,
        }
    }

    /// Inserts or replaces a `Vec3` entry under `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    /// - `Vec3` - 3D vector value.
    pub fn set_vec3(&mut self, key: &str, value: Vec3) {
        let _: Option<BtValue> = self
            .get_mut_entries()
            .insert(key.to_owned(), BtValue::Vec3(value));
    }

    /// Reads a `Vec3` entry by `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    ///
    /// # Returns
    ///
    /// - `Option<Vec3>` - Stored 3D vector if present.
    #[must_use]
    pub fn get_vec3(&self, key: &str) -> Option<Vec3> {
        match self.get_entries().get(key) {
            Some(BtValue::Vec3(val)) => Some(*val),
            _ => None,
        }
    }

    /// Inserts or replaces a text entry under `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    /// - `&str` - Text string value.
    pub fn set_text(&mut self, key: &str, value: &str) {
        let _: Option<BtValue> = self
            .get_mut_entries()
            .insert(key.to_owned(), BtValue::Text(value.to_owned()));
    }

    /// Reads a text entry by `key`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Blackboard key name.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Stored string slice if present.
    #[must_use]
    pub fn get_text(&self, key: &str) -> Option<&str> {
        match self.get_entries().get(key) {
            Some(BtValue::Text(val)) => Some(val.as_str()),
            _ => None,
        }
    }
}

/// Tree construction, reset, and tick execution for `BehaviorTree`.
impl BehaviorTree {
    /// Creates an empty `BehaviorTree`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty arena-backed behavior tree.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a node to the arena and returns its stable node handle.
    ///
    /// # Arguments
    ///
    /// - `BtNodeKind` - Node descriptor.
    ///
    /// # Returns
    ///
    /// - `usize` - Handle of the added node.
    pub fn add_node(&mut self, kind: BtNodeKind) -> usize {
        let idx: usize = self.get_nodes().len();
        self.get_mut_nodes().push(kind);
        self.get_mut_states().push(BtNodeState::default());
        idx
    }

    /// Resets running child offsets, repeat counters, and active cooldowns across all nodes.
    pub fn reset(&mut self) {
        for state in self.get_mut_states() {
            *state = BtNodeState::default();
        }
    }

    /// Advances cooldown timers by `dt` and executes the tree from `root` with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `f32` - Delta time in seconds (clamped to `>= 0.0`).
    /// - `&mut Blackboard` - Shared typed blackboard.
    /// - `C` - Condition evaluator callback.
    /// - `A` - Action executor callback.
    ///
    /// # Returns
    ///
    /// - `BtStatus` - Root evaluation status for this tick.
    pub fn tick<C, A>(
        &mut self,
        dt: f32,
        blackboard: &mut Blackboard,
        mut eval_condition: C,
        mut run_action: A,
    ) -> BtStatus
    where
        C: FnMut(u32, &mut Blackboard) -> bool,
        A: FnMut(u32, f32, &mut Blackboard) -> BtStatus,
    {
        if self.get_nodes().is_empty() {
            return BtStatus::Failure;
        }
        let safe_dt: f32 = if dt.is_finite() && dt > 0.0 { dt } else { 0.0 };
        let root_idx: usize = self.get_root();
        let mut states: Vec<BtNodeState> = take(self.get_mut_states());
        if states.len() != self.get_nodes().len() {
            states.resize(self.get_nodes().len(), BtNodeState::default());
        }
        for state in &mut states {
            if state.cooldown_remaining > 0.0 {
                state.cooldown_remaining = (state.cooldown_remaining - safe_dt).max(0.0);
            }
        }
        let status: BtStatus = bt_tick_node(
            self.get_nodes(),
            &mut states,
            root_idx,
            safe_dt,
            blackboard,
            &mut eval_condition,
            &mut run_action,
        );
        self.set_states(states);
        status
    }
}

/// Safe option accessors for `HfsmStateDef`.
impl HfsmStateDef {
    /// Constructs a new `HfsmStateDef`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Unique state identifier.
    /// - `Option<u32>` - Optional parent state identifier.
    /// - `Option<u32>` - Optional default child state identifier.
    ///
    /// # Returns
    ///
    /// - `Self` - State definition.
    #[must_use]
    pub const fn new(id: u32, parent: Option<u32>, initial_child: Option<u32>) -> Self {
        Self {
            id,
            parent,
            initial_child,
        }
    }

    /// Returns the optional parent state identifier.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Parent state ID if nested.
    #[must_use]
    pub fn try_get_parent(&self) -> Option<u32> {
        self.parent
    }

    /// Returns the optional initial child state identifier.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Initial sub-state ID if composite.
    #[must_use]
    pub fn try_get_initial_child(&self) -> Option<u32> {
        self.initial_child
    }
}

/// Safe option accessors for `HfsmTransition`.
impl HfsmTransition {
    /// Constructs a new `HfsmTransition`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Source state identifier.
    /// - `u32` - Destination state identifier.
    /// - `Option<u32>` - Optional triggering event identifier (`None` for automatic transitions).
    /// - `Option<u32>` - Optional guard predicate identifier.
    /// - `i32` - Transition priority (higher evaluated first).
    ///
    /// # Returns
    ///
    /// - `Self` - Transition rule.
    #[must_use]
    pub const fn new(
        from_state: u32,
        to_state: u32,
        event_id: Option<u32>,
        guard_id: Option<u32>,
        priority: i32,
    ) -> Self {
        Self {
            from_state,
            to_state,
            event_id,
            guard_id,
            priority,
        }
    }

    /// Returns the optional triggering event identifier.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Event ID, or `None` for automatic polled transitions.
    #[must_use]
    pub fn try_get_event_id(&self) -> Option<u32> {
        self.event_id
    }

    /// Returns the optional guard predicate identifier.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Guard ID if guarded.
    #[must_use]
    pub fn try_get_guard_id(&self) -> Option<u32> {
        self.guard_id
    }
}

/// Nested state lifecycle, LCA transitions, and parent fallback for `HierarchicalFsm`.
impl HierarchicalFsm {
    /// Creates an empty `HierarchicalFsm`.
    ///
    /// # Returns
    ///
    /// - `Self` - Unstarted hierarchical state machine.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a state definition with optional parent and initial child.
    ///
    /// # Arguments
    ///
    /// - `u32` - Unique state identifier.
    /// - `Option<u32>` - Optional parent state identifier.
    /// - `Option<u32>` - Optional default child state identifier.
    pub fn add_state(&mut self, id: u32, parent: Option<u32>, initial_child: Option<u32>) {
        self.get_mut_states()
            .push(HfsmStateDef::new(id, parent, initial_child));
    }

    /// Registers a guarded transition rule.
    ///
    /// # Arguments
    ///
    /// - `HfsmTransition` - Transition definition.
    pub fn add_transition(&mut self, transition: HfsmTransition) {
        self.get_mut_transitions().push(transition);
    }

    /// Finds a state definition by `state_id`.
    ///
    /// # Arguments
    ///
    /// - `&[HfsmStateDef]` - Registered state definitions.
    /// - `u32` - State identifier to locate.
    ///
    /// # Returns
    ///
    /// - `Option<HfsmStateDef>` - Matching definition if registered.
    fn find_state_def(states: &[HfsmStateDef], state_id: u32) -> Option<HfsmStateDef> {
        states
            .iter()
            .copied()
            .find(|def: &HfsmStateDef| def.get_id() == state_id)
    }

    /// Resolves the full top-down chain `[root, ..., target, ..., leaf]` into `out_chain`.
    ///
    /// # Arguments
    ///
    /// - `&[HfsmStateDef]` - Registered state definitions.
    /// - `u32` - Target state identifier.
    /// - `&mut Vec<u32>` - Output chain buffer populated from root to leaf.
    fn resolve_chain(states: &[HfsmStateDef], target: u32, out_chain: &mut Vec<u32>) {
        out_chain.clear();
        let mut cursor: Option<u32> = Some(target);
        let mut guard_steps: usize = 0;
        while let Some(id) = cursor {
            if guard_steps > states.len() {
                break;
            }
            guard_steps += 1;
            out_chain.push(id);
            cursor =
                Self::find_state_def(states, id).and_then(|def: HfsmStateDef| def.try_get_parent());
        }
        out_chain.reverse();
        let mut child_cursor: Option<u32> = Self::find_state_def(states, target)
            .and_then(|def: HfsmStateDef| def.try_get_initial_child());
        let mut child_steps: usize = 0;
        while let Some(child_id) = child_cursor {
            if child_steps > states.len() || out_chain.contains(&child_id) {
                break;
            }
            child_steps += 1;
            out_chain.push(child_id);
            child_cursor = Self::find_state_def(states, child_id)
                .and_then(|def: HfsmStateDef| def.try_get_initial_child());
        }
    }

    /// Enters `initial_state` (descending any `initial_child` chain) and emits top-down `Enter` events.
    ///
    /// # Arguments
    ///
    /// - `u32` - Initial state identifier.
    /// - `H` - Lifecycle event callback.
    pub fn start<H>(&mut self, initial_state: u32, mut on_event: H)
    where
        H: FnMut(HfsmLifecycleEvent),
    {
        let mut target_chain: Vec<u32> = take(self.get_mut_target_chain_scratch());
        Self::resolve_chain(self.get_states(), initial_state, &mut target_chain);
        for &state_id in &target_chain {
            on_event(HfsmLifecycleEvent::Enter(state_id));
        }
        let active: &mut Vec<u32> = self.get_mut_active_chain();
        active.clear();
        active.extend_from_slice(&target_chain);
        self.set_target_chain_scratch(target_chain);
    }

    /// Returns the currently active leaf state identifier, if started.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Active leaf state identifier.
    #[must_use]
    pub fn current_state(&self) -> Option<u32> {
        self.get_active_chain().last().copied()
    }

    /// Returns `true` if `state_id` is currently active as either leaf or enclosing parent state.
    ///
    /// # Arguments
    ///
    /// - `u32` - State identifier to query.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `state_id` is in the active hierarchy.
    #[must_use]
    pub fn is_in_state(&self, state_id: u32) -> bool {
        self.get_active_chain().contains(&state_id)
    }

    /// Finds the highest-priority valid transition matching `event_id` walking leaf-to-root for parent fallback.
    ///
    /// # Arguments
    ///
    /// - `Option<u32>` - Triggering event (`None` for automatic update transitions).
    /// - `&mut G` - Guard evaluator callback.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Destination state identifier if a transition fires.
    fn pick_transition<G>(&self, event_id: Option<u32>, eval_guard: &mut G) -> Option<u32>
    where
        G: FnMut(u32) -> bool,
    {
        let transitions: &[HfsmTransition] = self.get_transitions();
        for &active_state in self.get_active_chain().iter().rev() {
            let mut best_target: Option<u32> = None;
            let mut best_prio: i32 = i32::MIN;
            for trans in transitions {
                if trans.get_from_state() != active_state || trans.try_get_event_id() != event_id {
                    continue;
                }
                if best_target.is_some() && trans.get_priority() <= best_prio {
                    continue;
                }
                let guard_ok: bool = match trans.try_get_guard_id() {
                    Some(g_id) => eval_guard(g_id),
                    None => true,
                };
                if guard_ok {
                    best_prio = trans.get_priority();
                    best_target = Some(trans.get_to_state());
                }
            }
            if best_target.is_some() {
                return best_target;
            }
        }
        None
    }

    /// Transitions from the active hierarchy to `target_state` using LCA bottom-up exits and top-down enters.
    ///
    /// # Arguments
    ///
    /// - `u32` - Destination state identifier.
    /// - `&mut H` - Lifecycle event callback.
    fn apply_transition<H>(&mut self, target_state: u32, on_event: &mut H)
    where
        H: FnMut(HfsmLifecycleEvent),
    {
        let mut target_chain: Vec<u32> = take(self.get_mut_target_chain_scratch());
        Self::resolve_chain(self.get_states(), target_state, &mut target_chain);
        let active: &mut Vec<u32> = self.get_mut_active_chain();
        let mut lca_len: usize = 0;
        let min_len: usize = active.len().min(target_chain.len());
        while lca_len < min_len && active[lca_len] == target_chain[lca_len] {
            lca_len += 1;
        }
        if lca_len == active.len() && lca_len == target_chain.len() && lca_len > 0 {
            lca_len -= 1;
        }
        for idx in (lca_len..active.len()).rev() {
            on_event(HfsmLifecycleEvent::Exit(active[idx]));
        }
        active.truncate(lca_len);
        for &state_id in &target_chain[lca_len..] {
            active.push(state_id);
            on_event(HfsmLifecycleEvent::Enter(state_id));
        }
        self.set_target_chain_scratch(target_chain);
    }

    /// Dispatches `event_id` from leaf to root (parent fallback) and executes the winning guarded transition.
    ///
    /// # Arguments
    ///
    /// - `u32` - Event identifier.
    /// - `G` - Guard evaluator callback.
    /// - `H` - Lifecycle event callback.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if a matching transition fired.
    pub fn trigger_event<G, H>(&mut self, event_id: u32, mut eval_guard: G, mut on_event: H) -> bool
    where
        G: FnMut(u32) -> bool,
        H: FnMut(HfsmLifecycleEvent),
    {
        if let Some(target_state) = self.pick_transition(Some(event_id), &mut eval_guard) {
            self.apply_transition(target_state, &mut on_event);
            true
        } else {
            false
        }
    }

    /// Checks automatic guarded transitions and emits top-down `Update` events for every active state.
    ///
    /// # Arguments
    ///
    /// - `G` - Guard evaluator callback.
    /// - `H` - Lifecycle event callback.
    pub fn update<G, H>(&mut self, mut eval_guard: G, mut on_event: H)
    where
        G: FnMut(u32) -> bool,
        H: FnMut(HfsmLifecycleEvent),
    {
        if let Some(target_state) = self.pick_transition(None, &mut eval_guard) {
            self.apply_transition(target_state, &mut on_event);
        }
        let active_len: usize = self.get_active_chain().len();
        for idx in 0..active_len {
            let state_id: u32 = self.get_active_chain()[idx];
            on_event(HfsmLifecycleEvent::Update(state_id));
        }
    }
}

/// Multi-consideration scoring and hysteresis action selection for `UtilityAiBrain`.
impl UtilityAiBrain {
    /// Creates a new `UtilityAiBrain` with configurable inertia bonus and minimum dwell duration.
    ///
    /// # Arguments
    ///
    /// - `f32` - Additive inertia bonus applied to the active action.
    /// - `f32` - Minimum dwell seconds before switching away from a viable active action.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty utility AI brain.
    #[must_use]
    pub fn new(inertia_bonus: f32, min_dwell_time: f32) -> Self {
        let safe_inertia: f32 = if inertia_bonus.is_finite() && inertia_bonus >= 0.0 {
            inertia_bonus
        } else {
            DEFAULT_UTILITY_INERTIA
        };
        let safe_dwell: f32 = if min_dwell_time.is_finite() && min_dwell_time >= 0.0 {
            min_dwell_time
        } else {
            0.0
        };
        Self {
            actions: Vec::new(),
            inertia_bonus: safe_inertia,
            min_dwell_time: safe_dwell,
            current_action: 0,
            has_active: false,
            dwell_elapsed: 0.0,
            last_scores: Vec::new(),
        }
    }

    /// Registers a candidate `UtilityActionDef`.
    ///
    /// # Arguments
    ///
    /// - `UtilityActionDef` - Action definition with base weight and response-curve considerations.
    pub fn add_action(&mut self, action: UtilityActionDef) {
        self.get_mut_actions().push(action);
    }

    /// Returns the currently selected action identifier, if any.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Active action identifier.
    #[must_use]
    pub fn active_action(&self) -> Option<u32> {
        if self.get_has_active() {
            Some(self.get_current_action())
        } else {
            None
        }
    }

    /// Scores every registered action and selects the highest-utility action with hysteresis protection.
    ///
    /// # Arguments
    ///
    /// - `f32` - Elapsed time step in seconds.
    /// - `F` - Input sampler returning the raw scalar value for each `input_id`.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Winning action identifier.
    pub fn evaluate<F>(&mut self, dt: f32, mut sample_input: F) -> Option<u32>
    where
        F: FnMut(u32) -> f32,
    {
        if self.get_actions().is_empty() {
            return None;
        }
        let safe_dt: f32 = if dt.is_finite() && dt > 0.0 { dt } else { 0.0 };
        let inertia: f32 = self.get_inertia_bonus();
        let min_dwell: f32 = self.get_min_dwell_time();
        let has_active: bool = self.get_has_active();
        let current_action: u32 = self.get_current_action();
        let next_dwell: f32 = if has_active {
            self.get_dwell_elapsed() + safe_dt
        } else {
            0.0
        };
        let mut scores: Vec<(u32, f32)> = take(self.get_mut_last_scores());
        scores.clear();
        let mut best_action: u32 = 0;
        let mut best_score: f32 = f32::NEG_INFINITY;
        let mut current_raw_score: f32 = 0.0;
        for action in self.get_actions() {
            let cons: &[UtilityConsideration] = action.get_considerations();
            let raw_score: f32 = if cons.is_empty() {
                action.get_base_weight().max(0.0)
            } else {
                let mut product: f32 = 1.0;
                for item in cons {
                    let raw_in: f32 = sample_input(item.get_input_id());
                    let span: f32 = item.get_max_input() - item.get_min_input();
                    let norm_x: f32 = if span.abs() > 1e-6 {
                        ((raw_in - item.get_min_input()) / span).clamp(0.0, 1.0)
                    } else {
                        0.0
                    };
                    let curved: f32 = eval_utility_curve(item.get_curve(), norm_x);
                    let w: f32 = if item.get_weight().is_finite() && item.get_weight() > 0.0 {
                        item.get_weight()
                    } else {
                        1.0
                    };
                    product *= curved.powf(w);
                }
                let n: f32 = cons.len() as f32;
                let mod_factor: f32 = 1.0 - (1.0 / n);
                let makeup: f32 = (1.0 - product) * mod_factor;
                let compensated: f32 = product + makeup * product;
                compensated * action.get_base_weight().max(0.0)
            };
            let action_id: u32 = action.get_action_id();
            if has_active && action_id == current_action {
                current_raw_score = raw_score;
            }
            let effective_score: f32 =
                if has_active && action_id == current_action && raw_score > 0.0 {
                    raw_score + inertia
                } else {
                    raw_score
                };
            scores.push((action_id, effective_score));
            if effective_score > best_score {
                best_score = effective_score;
                best_action = action_id;
            }
        }
        let chosen: u32 = if has_active
            && best_action != current_action
            && current_raw_score > 0.0
            && next_dwell < min_dwell
        {
            current_action
        } else {
            best_action
        };
        if !has_active || chosen != current_action {
            self.set_current_action(chosen);
            self.set_has_active(true);
            self.set_dwell_elapsed(0.0);
        } else {
            self.set_dwell_elapsed(next_dwell);
        }
        self.set_last_scores(scores);
        Some(chosen)
    }
}

/// Default balanced weights and neighborhood radii for `BoidsConfig`.
impl Default for BoidsConfig {
    /// Returns balanced 3D Reynolds flocking weights and perception radii.
    ///
    /// # Returns
    ///
    /// - `Self` - Default boids configuration.
    fn default() -> Self {
        Self {
            perception_radius: DEFAULT_BOIDS_PERCEPTION,
            separation_radius: DEFAULT_BOIDS_SEPARATION,
            separation_weight: 2.2,
            alignment_weight: 1.0,
            cohesion_weight: 0.9,
            obstacle_weight: 4.0,
            wander_weight: 0.3,
            goal_weight: 1.0,
        }
    }
}

/// Constructors for `BoidsAgent3D`.
impl BoidsAgent3D {
    /// Creates a 3D boid agent with explicit position, velocity, speed, and force limits.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Initial world position.
    /// - `Vec3` - Initial velocity vector.
    /// - `f32` - Maximum speed.
    /// - `f32` - Maximum steering acceleration.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized boid agent.
    #[must_use]
    pub fn new(position: Vec3, velocity: Vec3, max_speed: f32, max_force: f32) -> Self {
        let safe_speed: f32 = if max_speed.is_finite() && max_speed > 0.0 {
            max_speed
        } else {
            DEFAULT_BOIDS_MAX_SPEED
        };
        let safe_force: f32 = if max_force.is_finite() && max_force > 0.0 {
            max_force
        } else {
            DEFAULT_BOIDS_MAX_FORCE
        };
        Self {
            position,
            velocity: ai_vec3_clamp_len(velocity, safe_speed),
            wander_angle: 0.0,
            max_speed: safe_speed,
            max_force: safe_force,
        }
    }
}

/// Composable Reynolds steering behaviors and SpatialHashGrid3D-accelerated flocking for `BoidsFlockSolver`.
impl BoidsFlockSolver {
    /// Creates a new `BoidsFlockSolver` seeded deterministically for wander behaviors.
    ///
    /// # Arguments
    ///
    /// - `BoidsConfig` - Neighborhood radii and steering force weights.
    /// - `u64` - Deterministic PRNG seed.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready flock solver with pre-allocated `SpatialHashGrid3D`.
    #[must_use]
    pub fn new(config: BoidsConfig, seed: u64) -> Self {
        let cell_size: f32 = config.get_perception_radius().max(0.5);
        Self {
            config,
            agents: Vec::new(),
            obstacles: Vec::new(),
            goal_target: Vec3::zero(),
            has_goal: false,
            rng: DeterministicRng::new(seed),
            scratch: BoidsScratch {
                spatial_grid: SpatialHashGrid3D::new(cell_size),
                neighbor_ids: Vec::with_capacity(64),
                accelerations: Vec::with_capacity(64),
                next_angles: Vec::with_capacity(64),
            },
        }
    }

    /// Adds a boid agent to the flock and returns its index.
    ///
    /// # Arguments
    ///
    /// - `BoidsAgent3D` - Agent state to add.
    ///
    /// # Returns
    ///
    /// - `usize` - Index of the registered agent.
    pub fn add_agent(&mut self, agent: BoidsAgent3D) -> usize {
        let idx: usize = self.get_agents().len();
        self.get_mut_agents().push(agent);
        idx
    }

    /// Registers a spherical obstacle avoided by all boids in the flock.
    ///
    /// # Arguments
    ///
    /// - `BoidsObstacle3D` - Spherical obstacle descriptor.
    pub fn add_obstacle(&mut self, obstacle: BoidsObstacle3D) {
        self.get_mut_obstacles().push(obstacle);
    }

    /// Sets or clears the optional shared target point that attracts the flock.
    ///
    /// # Arguments
    ///
    /// - `Option<Vec3>` - Optional 3D target coordinates.
    pub fn set_goal(&mut self, goal: Option<Vec3>) {
        if let Some(target) = goal {
            self.set_goal_target(target);
            self.set_has_goal(true);
        } else {
            self.set_has_goal(false);
        }
    }

    /// Computes Reynolds `Seek` steering force toward `target`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Agent position.
    /// - `Vec3` - Agent current velocity.
    /// - `Vec3` - Target position.
    /// - `f32` - Maximum speed.
    /// - `f32` - Maximum steering force.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Clamped steering force vector.
    #[must_use]
    pub fn steer_seek(
        position: Vec3,
        velocity: Vec3,
        target: Vec3,
        max_speed: f32,
        max_force: f32,
    ) -> Vec3 {
        let offset: Vec3 = target.sub(position);
        if offset.length_sq() <= 1e-10 {
            return Vec3::zero();
        }
        let desired: Vec3 = offset.normalize().scale(max_speed);
        ai_vec3_clamp_len(desired.sub(velocity), max_force)
    }

    /// Computes Reynolds `Flee` steering force directly away from `threat`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Agent position.
    /// - `Vec3` - Agent current velocity.
    /// - `Vec3` - Threat position.
    /// - `f32` - Maximum speed.
    /// - `f32` - Maximum steering force.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Clamped repulsion force vector.
    #[must_use]
    pub fn steer_flee(
        position: Vec3,
        velocity: Vec3,
        threat: Vec3,
        max_speed: f32,
        max_force: f32,
    ) -> Vec3 {
        let offset: Vec3 = position.sub(threat);
        if offset.length_sq() <= 1e-10 {
            return Vec3::zero();
        }
        let desired: Vec3 = offset.normalize().scale(max_speed);
        ai_vec3_clamp_len(desired.sub(velocity), max_force)
    }

    /// Computes Reynolds `Arrive` steering force decelerating smoothly inside `slowing_radius`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Agent position.
    /// - `Vec3` - Agent current velocity.
    /// - `Vec3` - Destination target position.
    /// - `f32` - Deceleration radius around `target`.
    /// - `f32` - Maximum speed.
    /// - `f32` - Maximum steering force.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Clamped arrival steering force.
    #[must_use]
    pub fn steer_arrive(
        position: Vec3,
        velocity: Vec3,
        target: Vec3,
        slowing_radius: f32,
        max_speed: f32,
        max_force: f32,
    ) -> Vec3 {
        let offset: Vec3 = target.sub(position);
        let dist: f32 = offset.length();
        if dist <= 1e-5 {
            return ai_vec3_clamp_len(velocity.scale(-1.0), max_force);
        }
        let ramped_speed: f32 = if slowing_radius > 1e-5 && dist < slowing_radius {
            max_speed * (dist / slowing_radius)
        } else {
            max_speed
        };
        let desired: Vec3 = offset.scale(ramped_speed / dist);
        ai_vec3_clamp_len(desired.sub(velocity), max_force)
    }

    /// Computes predictive Reynolds `Pursue` steering force anticipating a moving quarry.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Pursuer position.
    /// - `Vec3` - Pursuer velocity.
    /// - `Vec3` - Quarry position.
    /// - `Vec3` - Quarry velocity.
    /// - `f32` - Maximum speed.
    /// - `f32` - Maximum steering force.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Clamped pursuit steering force.
    #[must_use]
    pub fn steer_pursue(
        position: Vec3,
        velocity: Vec3,
        target_pos: Vec3,
        target_vel: Vec3,
        max_speed: f32,
        max_force: f32,
    ) -> Vec3 {
        let dist: f32 = target_pos.sub(position).length();
        let lookahead: f32 = (dist / max_speed.max(1e-3)).clamp(0.0, 2.0);
        let future_target: Vec3 = target_pos.add(target_vel.scale(lookahead));
        Self::steer_seek(position, velocity, future_target, max_speed, max_force)
    }

    /// Computes predictive Reynolds `Evade` steering force escaping a moving pursuer.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Evader position.
    /// - `Vec3` - Evader velocity.
    /// - `Vec3` - Threat position.
    /// - `Vec3` - Threat velocity.
    /// - `f32` - Maximum speed.
    /// - `f32` - Maximum steering force.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Clamped evasion steering force.
    #[must_use]
    pub fn steer_evade(
        position: Vec3,
        velocity: Vec3,
        threat_pos: Vec3,
        threat_vel: Vec3,
        max_speed: f32,
        max_force: f32,
    ) -> Vec3 {
        let dist: f32 = threat_pos.sub(position).length();
        let lookahead: f32 = (dist / max_speed.max(1e-3)).clamp(0.0, 2.0);
        let future_threat: Vec3 = threat_pos.add(threat_vel.scale(lookahead));
        Self::steer_flee(position, velocity, future_threat, max_speed, max_force)
    }

    /// Computes continuous Reynolds `Wander` steering force and updated wander angle.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Current velocity vector.
    /// - `f32` - Current wander phase angle in radians.
    /// - `BoidsWanderParams` - Wander circle distance, radius, and angular jitter parameters.
    /// - `&mut DeterministicRng` - Deterministic PRNG.
    /// - `f32` - Maximum speed.
    /// - `f32` - Maximum steering force.
    ///
    /// # Returns
    ///
    /// - `(Vec3, f32)` - `(steering_force, updated_wander_angle)`.
    pub fn steer_wander(
        velocity: Vec3,
        wander_angle: f32,
        params: BoidsWanderParams,
        rng: &mut DeterministicRng,
        max_speed: f32,
        max_force: f32,
    ) -> (Vec3, f32) {
        let forward: Vec3 = if velocity.length_sq() > 1e-6 {
            velocity.normalize()
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        };
        let up_ref: Vec3 = if forward.get_y().abs() < 0.9 {
            Vec3::new(0.0, 1.0, 0.0)
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        };
        let right: Vec3 = forward.cross(up_ref).normalize();
        let ortho_up: Vec3 = right.cross(forward).normalize();
        let jitter: f32 = params.get_jitter();
        let next_angle: f32 = wander_angle + rng.next_range_f32(-jitter, jitter);
        let offset: Vec3 = forward
            .scale(params.get_circle_dist())
            .add(right.scale(params.get_circle_radius() * next_angle.cos()))
            .add(ortho_up.scale(params.get_circle_radius() * next_angle.sin()));
        let desired: Vec3 = offset.normalize().scale(max_speed);
        let force: Vec3 = ai_vec3_clamp_len(desired.sub(velocity), max_force);
        (force, next_angle)
    }

    /// Advances the entire flock by `dt` using `SpatialHashGrid3D` neighbor queries with zero steady-state allocations.
    ///
    /// # Arguments
    ///
    /// - `f32` - Simulation time step in seconds.
    pub fn step(&mut self, dt: f32) {
        if !dt.is_finite() || dt <= 1e-6 {
            return;
        }
        let count: usize = self.get_agents().len();
        if count == 0 {
            return;
        }
        let cfg: BoidsConfig = self.get_config();
        let perc_r: f32 = cfg.get_perception_radius().max(1e-3);
        let sep_r: f32 = cfg.get_separation_radius().max(1e-3);
        let sep_r_sq: f32 = sep_r * sep_r;
        let has_goal: bool = self.get_has_goal();
        let goal_target: Vec3 = self.get_goal_target();
        let mut rng: DeterministicRng = self.get_rng();
        let mut scratch: BoidsScratch = take(self.get_mut_scratch());
        scratch.spatial_grid.clear();
        for (idx, agent) in self.get_agents().iter().enumerate() {
            scratch
                .spatial_grid
                .insert_point(idx as u64, agent.get_position());
        }
        scratch.accelerations.clear();
        scratch.accelerations.resize(count, Vec3::zero());
        scratch.next_angles.clear();
        scratch.next_angles.resize(count, 0.0);
        let agents: &[BoidsAgent3D] = self.get_agents();
        let obstacles: &[BoidsObstacle3D] = self.get_obstacles();
        for idx in 0..count {
            let agent: BoidsAgent3D = agents[idx];
            let pos: Vec3 = agent.get_position();
            let vel: Vec3 = agent.get_velocity();
            let max_s: f32 = agent.get_max_speed();
            let max_f: f32 = agent.get_max_force();
            scratch
                .spatial_grid
                .query_sphere_into(pos, perc_r, &mut scratch.neighbor_ids);
            let mut sep_sum: Vec3 = Vec3::zero();
            let mut sep_cnt: usize = 0;
            let mut ali_sum: Vec3 = Vec3::zero();
            let mut coh_sum: Vec3 = Vec3::zero();
            let mut perc_cnt: usize = 0;
            for &nid in &scratch.neighbor_ids {
                let other_idx: usize = nid as usize;
                if other_idx == idx || other_idx >= count {
                    continue;
                }
                let other: BoidsAgent3D = agents[other_idx];
                let diff: Vec3 = pos.sub(other.get_position());
                let d_sq: f32 = diff.length_sq();
                perc_cnt += 1;
                ali_sum = ali_sum.add(other.get_velocity());
                coh_sum = coh_sum.add(other.get_position());
                if d_sq < sep_r_sq && d_sq > 1e-10 {
                    sep_sum = sep_sum.add(diff.scale(1.0 / d_sq));
                    sep_cnt += 1;
                } else if d_sq <= 1e-10 {
                    let jitter_dir: Vec3 = Vec3::new(
                        ((idx as f32) * 1.234_567).cos(),
                        ((idx as f32) * 2.345_678).sin(),
                        0.5,
                    );
                    sep_sum = sep_sum.add(jitter_dir);
                    sep_cnt += 1;
                }
            }
            let mut total_force: Vec3 = Vec3::zero();
            if sep_cnt > 0 {
                let sep_steer: Vec3 =
                    ai_vec3_clamp_len(sep_sum.normalize().scale(max_s).sub(vel), max_f);
                total_force = total_force.add(sep_steer.scale(cfg.get_separation_weight()));
            }
            if perc_cnt > 0 {
                let inv_cnt: f32 = 1.0 / (perc_cnt as f32);
                let ali_steer: Vec3 = ai_vec3_clamp_len(
                    ali_sum.scale(inv_cnt).normalize().scale(max_s).sub(vel),
                    max_f,
                );
                let center_mass: Vec3 = coh_sum.scale(inv_cnt);
                let coh_steer: Vec3 = Self::steer_seek(pos, vel, center_mass, max_s, max_f);
                total_force = total_force.add(ali_steer.scale(cfg.get_alignment_weight()));
                total_force = total_force.add(coh_steer.scale(cfg.get_cohesion_weight()));
            }
            if cfg.get_obstacle_weight() > 0.0 {
                let mut obs_force: Vec3 = Vec3::zero();
                for obs in obstacles {
                    let avoid_r: f32 = obs.get_radius() + sep_r;
                    let away: Vec3 = pos.sub(obs.get_center());
                    let dist: f32 = away.length();
                    if dist < avoid_r {
                        let push_dir: Vec3 = if dist > 1e-5 {
                            away.scale(1.0 / dist)
                        } else {
                            Vec3::new(0.0, 1.0, 0.0)
                        };
                        let strength: f32 = (avoid_r - dist) / avoid_r.max(1e-4);
                        obs_force = obs_force.add(push_dir.scale(max_f * strength));
                    }
                }
                total_force = total_force.add(obs_force.scale(cfg.get_obstacle_weight()));
            }
            let (wander_force, next_ang): (Vec3, f32) = if cfg.get_wander_weight() > 0.0 {
                Self::steer_wander(
                    vel,
                    agent.get_wander_angle(),
                    BoidsWanderParams::new(2.0, 1.0, 0.35),
                    &mut rng,
                    max_s,
                    max_f,
                )
            } else {
                (Vec3::zero(), agent.get_wander_angle())
            };
            total_force = total_force.add(wander_force.scale(cfg.get_wander_weight()));
            scratch.next_angles[idx] = next_ang;
            if has_goal && cfg.get_goal_weight() > 0.0 {
                let goal_steer: Vec3 =
                    Self::steer_arrive(pos, vel, goal_target, perc_r, max_s, max_f);
                total_force = total_force.add(goal_steer.scale(cfg.get_goal_weight()));
            }
            scratch.accelerations[idx] = ai_vec3_clamp_len(total_force, max_f * 2.0);
        }
        for (idx, agent) in self.get_mut_agents().iter_mut().enumerate() {
            let max_s: f32 = agent.get_max_speed();
            let next_vel: Vec3 = ai_vec3_clamp_len(
                agent
                    .get_velocity()
                    .add(scratch.accelerations[idx].scale(dt)),
                max_s,
            );
            let next_pos: Vec3 = agent.get_position().add(next_vel.scale(dt));
            agent.set_velocity(next_vel);
            agent.set_position(next_pos);
            agent.set_wander_angle(scratch.next_angles[idx]);
        }
        self.set_rng(rng);
        self.set_scratch(scratch);
    }
}

/// Default scratch construction for `BoidsScratch`.
impl Default for BoidsScratch {
    /// Returns a default `BoidsScratch` with cell size `1.0`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty boids scratch state.
    fn default() -> Self {
        Self {
            spatial_grid: SpatialHashGrid3D::new(1.0),
            neighbor_ids: Vec::new(),
            accelerations: Vec::new(),
            next_angles: Vec::new(),
        }
    }
}