1use super::*;
2
3impl Blackboard {
5 #[must_use]
11 pub fn new() -> Self {
12 Self::default()
13 }
14
15 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 #[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 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 #[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 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 #[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 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 #[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 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 #[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 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 #[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
190impl BehaviorTree {
192 #[must_use]
198 pub fn new() -> Self {
199 Self::default()
200 }
201
202 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 pub fn reset(&mut self) {
220 for state in self.get_mut_states() {
221 *state = BtNodeState::default();
222 }
223 }
224
225 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
276impl HfsmStateDef {
278 #[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 #[must_use]
304 pub fn try_get_parent(&self) -> Option<u32> {
305 self.parent
306 }
307
308 #[must_use]
314 pub fn try_get_initial_child(&self) -> Option<u32> {
315 self.initial_child
316 }
317}
318
319impl HfsmTransition {
321 #[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 #[must_use]
357 pub fn try_get_event_id(&self) -> Option<u32> {
358 self.event_id
359 }
360
361 #[must_use]
367 pub fn try_get_guard_id(&self) -> Option<u32> {
368 self.guard_id
369 }
370}
371
372impl HierarchicalFsm {
374 #[must_use]
380 pub fn new() -> Self {
381 Self::default()
382 }
383
384 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 pub fn add_transition(&mut self, transition: HfsmTransition) {
402 self.get_mut_transitions().push(transition);
403 }
404
405 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 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 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 #[must_use]
484 pub fn current_state(&self) -> Option<u32> {
485 self.get_active_chain().last().copied()
486 }
487
488 #[must_use]
498 pub fn is_in_state(&self, state_id: u32) -> bool {
499 self.get_active_chain().contains(&state_id)
500 }
501
502 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 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 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 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
621impl UtilityAiBrain {
623 #[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 pub fn add_action(&mut self, action: UtilityActionDef) {
662 self.get_mut_actions().push(action);
663 }
664
665 #[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 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
776impl Default for BoidsConfig {
778 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
797impl BoidsAgent3D {
799 #[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
833impl BoidsFlockSolver {
835 #[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 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 pub fn add_obstacle(&mut self, obstacle: BoidsObstacle3D) {
885 self.get_mut_obstacles().push(obstacle);
886 }
887
888 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 #[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 #[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 #[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 #[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 #[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 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 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
1245impl Default for BoidsScratch {
1247 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}