1use super::*;
2
3impl GridPathfinder {
5 #[must_use]
16 pub fn new(width: usize, height: usize) -> Self {
17 let count: usize = width.saturating_mul(height);
18 let scratch: GridPathScratch = GridPathScratch {
19 generation: 0,
20 seen_gen: vec![0; count],
21 closed_gen: vec![0; count],
22 g_scores: vec![f32::INFINITY; count],
23 came_from: vec![usize::MAX; count],
24 open_heap: Vec::with_capacity(count.min(256)),
25 goal_flags: vec![0; count],
26 goal_gen: 0,
27 };
28 Self {
29 width,
30 height,
31 min_walkable_cost: 1.0,
32 uniform_walkable: true,
33 costs: vec![1.0; count],
34 scratch,
35 }
36 }
37
38 #[must_use]
50 pub fn from_costs(width: usize, height: usize, mut costs: Vec<f32>) -> Self {
51 let count: usize = width.saturating_mul(height);
52 costs.resize(count, 0.0);
53 let mut pathfinder: Self = Self::new(width, height);
54 pathfinder.set_costs(costs);
55 pathfinder.recompute_cost_metadata();
56 pathfinder
57 }
58
59 fn recompute_cost_metadata(&mut self) {
61 let mut min_cost: f32 = f32::INFINITY;
62 let mut first_cost: f32 = 0.0;
63 let mut has_walkable: bool = false;
64 let mut is_uniform: bool = true;
65 for &cost in self.get_costs() {
66 if cost.is_finite() && cost > 0.0 {
67 if !has_walkable {
68 first_cost = cost;
69 has_walkable = true;
70 } else if (cost - first_cost).abs() > 1e-6 {
71 is_uniform = false;
72 }
73 if cost < min_cost {
74 min_cost = cost;
75 }
76 }
77 }
78 self.set_min_walkable_cost(if has_walkable { min_cost } else { 1.0 });
79 self.set_uniform_walkable(is_uniform);
80 }
81
82 #[must_use]
92 pub fn index_of(&self, coord: GridCoord) -> Option<usize> {
93 if coord.get_x() < self.get_width() && coord.get_y() < self.get_height() {
94 Some(coord.get_y() * self.get_width() + coord.get_x())
95 } else {
96 None
97 }
98 }
99
100 #[must_use]
110 pub fn coord_of(&self, index: usize) -> GridCoord {
111 let width: usize = self.get_width().max(1);
112 GridCoord::new(index % width, index / width)
113 }
114
115 #[must_use]
125 pub fn is_walkable(&self, coord: GridCoord) -> bool {
126 if let Some(idx) = self.index_of(coord) {
127 let cost: f32 = self.get_costs()[idx];
128 cost.is_finite() && cost > 0.0
129 } else {
130 false
131 }
132 }
133
134 #[must_use]
145 fn is_walkable_signed(&self, cx: isize, cy: isize) -> bool {
146 if cx < 0 || cy < 0 {
147 return false;
148 }
149 let ux: usize = cx as usize;
150 let uy: usize = cy as usize;
151 if ux >= self.get_width() || uy >= self.get_height() {
152 return false;
153 }
154 let cost: f32 = self.get_costs()[uy * self.get_width() + ux];
155 cost.is_finite() && cost > 0.0
156 }
157
158 pub fn set_cell_cost(&mut self, coord: GridCoord, cost: f32) {
165 if let Some(idx) = self.index_of(coord) {
166 let sanitized: f32 = if cost.is_finite() && cost > 0.0 {
167 cost
168 } else {
169 0.0
170 };
171 self.get_mut_costs()[idx] = sanitized;
172 self.recompute_cost_metadata();
173 }
174 }
175
176 pub fn set_blocked(&mut self, coord: GridCoord, blocked: bool) {
183 self.set_cell_cost(coord, if blocked { 0.0 } else { 1.0 });
184 }
185
186 fn begin_search_generation(scratch: &mut GridPathScratch, cell_count: usize) -> u32 {
197 if scratch.seen_gen.len() != cell_count {
198 scratch.seen_gen.resize(cell_count, 0);
199 scratch.closed_gen.resize(cell_count, 0);
200 scratch.g_scores.resize(cell_count, f32::INFINITY);
201 scratch.came_from.resize(cell_count, usize::MAX);
202 scratch.goal_flags.resize(cell_count, 0);
203 }
204 scratch.open_heap.clear();
205 if scratch.generation == u32::MAX {
206 scratch.seen_gen.fill(0);
207 scratch.closed_gen.fill(0);
208 scratch.generation = 1;
209 } else {
210 scratch.generation += 1;
211 }
212 scratch.generation
213 }
214
215 #[must_use]
228 pub fn find_path(
229 &mut self,
230 start: GridCoord,
231 goal: GridCoord,
232 connectivity: GridConnectivity,
233 algorithm: GridSearchAlgorithm,
234 ) -> Option<GridPathResult> {
235 match algorithm {
236 GridSearchAlgorithm::AStar => self.find_path_astar(start, goal, connectivity),
237 GridSearchAlgorithm::Dijkstra => self.find_path_dijkstra(start, goal, connectivity),
238 GridSearchAlgorithm::JumpPointSearch => self.find_path_jps(start, goal, connectivity),
239 }
240 }
241
242 #[must_use]
254 pub fn find_path_astar(
255 &mut self,
256 start: GridCoord,
257 goal: GridCoord,
258 connectivity: GridConnectivity,
259 ) -> Option<GridPathResult> {
260 let mut path: Vec<GridCoord> = Vec::new();
261 let (total_cost, nodes_expanded): (f32, usize) =
262 self.search_astar_into(start, goal, connectivity, true, &mut path)?;
263 Some(GridPathResult {
264 path,
265 total_cost,
266 nodes_expanded,
267 })
268 }
269
270 #[must_use]
283 pub fn find_path_astar_into(
284 &mut self,
285 start: GridCoord,
286 goal: GridCoord,
287 connectivity: GridConnectivity,
288 out_path: &mut Vec<GridCoord>,
289 ) -> Option<f32> {
290 let (total_cost, _): (f32, usize) =
291 self.search_astar_into(start, goal, connectivity, true, out_path)?;
292 Some(total_cost)
293 }
294
295 #[must_use]
307 pub fn find_path_dijkstra(
308 &mut self,
309 start: GridCoord,
310 goal: GridCoord,
311 connectivity: GridConnectivity,
312 ) -> Option<GridPathResult> {
313 let mut path: Vec<GridCoord> = Vec::new();
314 let (total_cost, nodes_expanded): (f32, usize) =
315 self.search_astar_into(start, goal, connectivity, false, &mut path)?;
316 Some(GridPathResult {
317 path,
318 total_cost,
319 nodes_expanded,
320 })
321 }
322
323 fn search_astar_into(
337 &mut self,
338 start: GridCoord,
339 goal: GridCoord,
340 connectivity: GridConnectivity,
341 use_heuristic: bool,
342 out_path: &mut Vec<GridCoord>,
343 ) -> Option<(f32, usize)> {
344 out_path.clear();
345 let start_idx: usize = self.index_of(start)?;
346 let goal_idx: usize = self.index_of(goal)?;
347 if !self.is_walkable(start) || !self.is_walkable(goal) {
348 return None;
349 }
350 if start_idx == goal_idx {
351 out_path.push(start);
352 return Some((0.0, 1));
353 }
354 let width: usize = self.get_width();
355 let height: usize = self.get_height();
356 let cell_count: usize = width * height;
357 let min_cost: f32 = self.get_min_walkable_cost();
358 let mut scratch: GridPathScratch = take(self.get_mut_scratch());
359 let gen_id: u32 = Self::begin_search_generation(&mut scratch, cell_count);
360 scratch.seen_gen[start_idx] = gen_id;
361 scratch.g_scores[start_idx] = 0.0;
362 scratch.came_from[start_idx] = usize::MAX;
363 let start_h: f32 = if use_heuristic {
364 grid_heuristic(start, goal, connectivity, min_cost)
365 } else {
366 0.0
367 };
368 min_heap_f32_push(&mut scratch.open_heap, start_h, start_idx);
369 let dirs_4: [(isize, isize, f32); 4] =
370 [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0)];
371 let dirs_8: [(isize, isize, f32); 8] = [
372 (1, 0, 1.0),
373 (-1, 0, 1.0),
374 (0, 1, 1.0),
375 (0, -1, 1.0),
376 (1, 1, SQRT_2),
377 (1, -1, SQRT_2),
378 (-1, 1, SQRT_2),
379 (-1, -1, SQRT_2),
380 ];
381 let dirs: &[(isize, isize, f32)] = match connectivity {
382 GridConnectivity::FourWay => &dirs_4,
383 GridConnectivity::EightWay => &dirs_8,
384 };
385 let mut nodes_expanded: usize = 0;
386 let mut found: bool = false;
387 while let Some((_, current_idx)) = min_heap_f32_pop(&mut scratch.open_heap) {
388 if scratch.closed_gen[current_idx] == gen_id {
389 continue;
390 }
391 scratch.closed_gen[current_idx] = gen_id;
392 nodes_expanded += 1;
393 if current_idx == goal_idx {
394 found = true;
395 break;
396 }
397 let cx: isize = (current_idx % width) as isize;
398 let cy: isize = (current_idx / width) as isize;
399 let current_g: f32 = scratch.g_scores[current_idx];
400 for &(dx, dy, dist_mult) in dirs {
401 let nx: isize = cx + dx;
402 let ny: isize = cy + dy;
403 if !self.is_walkable_signed(nx, ny) {
404 continue;
405 }
406 if dx != 0
407 && dy != 0
408 && (!self.is_walkable_signed(cx + dx, cy)
409 || !self.is_walkable_signed(cx, cy + dy))
410 {
411 continue;
412 }
413 let next_idx: usize = (ny as usize) * width + (nx as usize);
414 if scratch.closed_gen[next_idx] == gen_id {
415 continue;
416 }
417 let step_cost: f32 = self.get_costs()[next_idx] * dist_mult;
418 let tentative_g: f32 = current_g + step_cost;
419 let is_better: bool = scratch.seen_gen[next_idx] != gen_id
420 || tentative_g < scratch.g_scores[next_idx];
421 if is_better {
422 scratch.seen_gen[next_idx] = gen_id;
423 scratch.g_scores[next_idx] = tentative_g;
424 scratch.came_from[next_idx] = current_idx;
425 let next_coord: GridCoord = GridCoord::new(nx as usize, ny as usize);
426 let heuristic: f32 = if use_heuristic {
427 grid_heuristic(next_coord, goal, connectivity, min_cost)
428 } else {
429 0.0
430 };
431 min_heap_f32_push(&mut scratch.open_heap, tentative_g + heuristic, next_idx);
432 }
433 }
434 }
435 let outcome: Option<(f32, usize)> = if found {
436 let total_cost: f32 = scratch.g_scores[goal_idx];
437 let mut cursor: usize = goal_idx;
438 while cursor != usize::MAX {
439 out_path.push(self.coord_of(cursor));
440 if cursor == start_idx {
441 break;
442 }
443 cursor = scratch.came_from[cursor];
444 }
445 out_path.reverse();
446 Some((total_cost, nodes_expanded))
447 } else {
448 None
449 };
450 self.set_scratch(scratch);
451 outcome
452 }
453
454 #[must_use]
466 pub fn find_path_dijkstra_multi_goal(
467 &mut self,
468 start: GridCoord,
469 goals: &[GridCoord],
470 connectivity: GridConnectivity,
471 ) -> Option<GridPathResult> {
472 let start_idx: usize = self.index_of(start)?;
473 if !self.is_walkable(start) || goals.is_empty() {
474 return None;
475 }
476 let width: usize = self.get_width();
477 let height: usize = self.get_height();
478 let cell_count: usize = width * height;
479 let mut scratch: GridPathScratch = take(self.get_mut_scratch());
480 let gen_id: u32 = Self::begin_search_generation(&mut scratch, cell_count);
481 if scratch.goal_gen == u32::MAX {
482 scratch.goal_flags.fill(0);
483 scratch.goal_gen = 1;
484 } else {
485 scratch.goal_gen += 1;
486 }
487 let goal_stamp: u32 = scratch.goal_gen;
488 let mut valid_goals: usize = 0;
489 for &goal in goals {
490 if let Some(g_idx) = self.index_of(goal)
491 && self.is_walkable(goal)
492 {
493 scratch.goal_flags[g_idx] = goal_stamp;
494 valid_goals += 1;
495 }
496 }
497 if valid_goals == 0 {
498 self.set_scratch(scratch);
499 return None;
500 }
501 scratch.seen_gen[start_idx] = gen_id;
502 scratch.g_scores[start_idx] = 0.0;
503 scratch.came_from[start_idx] = usize::MAX;
504 min_heap_f32_push(&mut scratch.open_heap, 0.0, start_idx);
505 let dirs_4: [(isize, isize, f32); 4] =
506 [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0)];
507 let dirs_8: [(isize, isize, f32); 8] = [
508 (1, 0, 1.0),
509 (-1, 0, 1.0),
510 (0, 1, 1.0),
511 (0, -1, 1.0),
512 (1, 1, SQRT_2),
513 (1, -1, SQRT_2),
514 (-1, 1, SQRT_2),
515 (-1, -1, SQRT_2),
516 ];
517 let dirs: &[(isize, isize, f32)] = match connectivity {
518 GridConnectivity::FourWay => &dirs_4,
519 GridConnectivity::EightWay => &dirs_8,
520 };
521 let mut nodes_expanded: usize = 0;
522 let mut reached_goal: Option<usize> = None;
523 while let Some((_, current_idx)) = min_heap_f32_pop(&mut scratch.open_heap) {
524 if scratch.closed_gen[current_idx] == gen_id {
525 continue;
526 }
527 scratch.closed_gen[current_idx] = gen_id;
528 nodes_expanded += 1;
529 if scratch.goal_flags[current_idx] == goal_stamp {
530 reached_goal = Some(current_idx);
531 break;
532 }
533 let cx: isize = (current_idx % width) as isize;
534 let cy: isize = (current_idx / width) as isize;
535 let current_g: f32 = scratch.g_scores[current_idx];
536 for &(dx, dy, dist_mult) in dirs {
537 let nx: isize = cx + dx;
538 let ny: isize = cy + dy;
539 if !self.is_walkable_signed(nx, ny) {
540 continue;
541 }
542 if dx != 0
543 && dy != 0
544 && (!self.is_walkable_signed(cx + dx, cy)
545 || !self.is_walkable_signed(cx, cy + dy))
546 {
547 continue;
548 }
549 let next_idx: usize = (ny as usize) * width + (nx as usize);
550 if scratch.closed_gen[next_idx] == gen_id {
551 continue;
552 }
553 let tentative_g: f32 = current_g + self.get_costs()[next_idx] * dist_mult;
554 if scratch.seen_gen[next_idx] != gen_id || tentative_g < scratch.g_scores[next_idx]
555 {
556 scratch.seen_gen[next_idx] = gen_id;
557 scratch.g_scores[next_idx] = tentative_g;
558 scratch.came_from[next_idx] = current_idx;
559 min_heap_f32_push(&mut scratch.open_heap, tentative_g, next_idx);
560 }
561 }
562 }
563 let result: Option<GridPathResult> = if let Some(goal_idx) = reached_goal {
564 let total_cost: f32 = scratch.g_scores[goal_idx];
565 let mut path: Vec<GridCoord> = Vec::new();
566 let mut cursor: usize = goal_idx;
567 while cursor != usize::MAX {
568 path.push(self.coord_of(cursor));
569 if cursor == start_idx {
570 break;
571 }
572 cursor = scratch.came_from[cursor];
573 }
574 path.reverse();
575 Some(GridPathResult {
576 path,
577 total_cost,
578 nodes_expanded,
579 })
580 } else {
581 None
582 };
583 self.set_scratch(scratch);
584 result
585 }
586
587 fn jps_jump(
602 &self,
603 origin_x: isize,
604 origin_y: isize,
605 dx: isize,
606 dy: isize,
607 goal: GridCoord,
608 connectivity: GridConnectivity,
609 ) -> Option<usize> {
610 let goal_x: isize = goal.get_x() as isize;
611 let goal_y: isize = goal.get_y() as isize;
612 let width: usize = self.get_width();
613 let mut x: isize = origin_x;
614 let mut y: isize = origin_y;
615 loop {
616 let nx: isize = x + dx;
617 let ny: isize = y + dy;
618 if !self.is_walkable_signed(nx, ny) {
619 return None;
620 }
621 if dx != 0
622 && dy != 0
623 && (!self.is_walkable_signed(x + dx, y) || !self.is_walkable_signed(x, y + dy))
624 {
625 return None;
626 }
627 x = nx;
628 y = ny;
629 if x == goal_x && y == goal_y {
630 return Some((y as usize) * width + (x as usize));
631 }
632 match connectivity {
633 GridConnectivity::FourWay => {
634 if dx != 0 {
635 if self.jps_jump(x, y, 0, 1, goal, connectivity).is_some()
636 || self.jps_jump(x, y, 0, -1, goal, connectivity).is_some()
637 {
638 return Some((y as usize) * width + (x as usize));
639 }
640 } else if (!self.is_walkable_signed(x - 1, y - dy)
641 && self.is_walkable_signed(x - 1, y))
642 || (!self.is_walkable_signed(x + 1, y - dy)
643 && self.is_walkable_signed(x + 1, y))
644 {
645 return Some((y as usize) * width + (x as usize));
646 }
647 }
648 GridConnectivity::EightWay => {
649 if dx != 0 && dy != 0 {
650 if self.jps_jump(x, y, dx, 0, goal, connectivity).is_some()
651 || self.jps_jump(x, y, 0, dy, goal, connectivity).is_some()
652 {
653 return Some((y as usize) * width + (x as usize));
654 }
655 } else if dx != 0 {
656 if (!self.is_walkable_signed(x - dx, y + 1)
657 && self.is_walkable_signed(x, y + 1))
658 || (!self.is_walkable_signed(x - dx, y - 1)
659 && self.is_walkable_signed(x, y - 1))
660 {
661 return Some((y as usize) * width + (x as usize));
662 }
663 } else if (!self.is_walkable_signed(x + 1, y - dy)
664 && self.is_walkable_signed(x + 1, y))
665 || (!self.is_walkable_signed(x - 1, y - dy)
666 && self.is_walkable_signed(x - 1, y))
667 {
668 return Some((y as usize) * width + (x as usize));
669 }
670 }
671 }
672 }
673 }
674
675 fn jps_pruned_directions(
689 &self,
690 cx: isize,
691 cy: isize,
692 parent: Option<GridCoord>,
693 connectivity: GridConnectivity,
694 out_dirs: &mut [(isize, isize); 8],
695 ) -> usize {
696 let mut count: usize = 0;
697 let Some(prev) = parent else {
698 let initial_4: [(isize, isize); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)];
699 let initial_8: [(isize, isize); 8] = [
700 (1, 0),
701 (-1, 0),
702 (0, 1),
703 (0, -1),
704 (1, 1),
705 (1, -1),
706 (-1, 1),
707 (-1, -1),
708 ];
709 let slice: &[(isize, isize)] = match connectivity {
710 GridConnectivity::FourWay => &initial_4,
711 GridConnectivity::EightWay => &initial_8,
712 };
713 for &dir in slice {
714 out_dirs[count] = dir;
715 count += 1;
716 }
717 return count;
718 };
719 let dx: isize = (cx - prev.get_x() as isize).signum();
720 let dy: isize = (cy - prev.get_y() as isize).signum();
721 match connectivity {
722 GridConnectivity::FourWay => {
723 if dx != 0 {
724 out_dirs[count] = (dx, 0);
725 count += 1;
726 out_dirs[count] = (0, 1);
727 count += 1;
728 out_dirs[count] = (0, -1);
729 count += 1;
730 } else if dy != 0 {
731 out_dirs[count] = (0, dy);
732 count += 1;
733 if !self.is_walkable_signed(cx - 1, cy - dy)
734 && self.is_walkable_signed(cx - 1, cy)
735 {
736 out_dirs[count] = (-1, 0);
737 count += 1;
738 }
739 if !self.is_walkable_signed(cx + 1, cy - dy)
740 && self.is_walkable_signed(cx + 1, cy)
741 {
742 out_dirs[count] = (1, 0);
743 count += 1;
744 }
745 }
746 }
747 GridConnectivity::EightWay => {
748 if dx != 0 && dy != 0 {
749 out_dirs[count] = (dx, 0);
750 count += 1;
751 out_dirs[count] = (0, dy);
752 count += 1;
753 out_dirs[count] = (dx, dy);
754 count += 1;
755 } else if dx != 0 {
756 out_dirs[count] = (dx, 0);
757 count += 1;
758 if !self.is_walkable_signed(cx - dx, cy + 1)
759 && self.is_walkable_signed(cx, cy + 1)
760 {
761 out_dirs[count] = (0, 1);
762 count += 1;
763 if self.is_walkable_signed(cx + dx, cy) {
764 out_dirs[count] = (dx, 1);
765 count += 1;
766 }
767 }
768 if !self.is_walkable_signed(cx - dx, cy - 1)
769 && self.is_walkable_signed(cx, cy - 1)
770 {
771 out_dirs[count] = (0, -1);
772 count += 1;
773 if self.is_walkable_signed(cx + dx, cy) {
774 out_dirs[count] = (dx, -1);
775 count += 1;
776 }
777 }
778 } else if dy != 0 {
779 out_dirs[count] = (0, dy);
780 count += 1;
781 if !self.is_walkable_signed(cx + 1, cy - dy)
782 && self.is_walkable_signed(cx + 1, cy)
783 {
784 out_dirs[count] = (1, 0);
785 count += 1;
786 if self.is_walkable_signed(cx, cy + dy) {
787 out_dirs[count] = (1, dy);
788 count += 1;
789 }
790 }
791 if !self.is_walkable_signed(cx - 1, cy - dy)
792 && self.is_walkable_signed(cx - 1, cy)
793 {
794 out_dirs[count] = (-1, 0);
795 count += 1;
796 if self.is_walkable_signed(cx, cy + dy) {
797 out_dirs[count] = (-1, dy);
798 count += 1;
799 }
800 }
801 }
802 }
803 }
804 count
805 }
806
807 #[must_use]
819 pub fn find_path_jps(
820 &mut self,
821 start: GridCoord,
822 goal: GridCoord,
823 connectivity: GridConnectivity,
824 ) -> Option<GridPathResult> {
825 if !self.get_uniform_walkable() {
826 return self.find_path_astar(start, goal, connectivity);
827 }
828 let start_idx: usize = self.index_of(start)?;
829 let goal_idx: usize = self.index_of(goal)?;
830 if !self.is_walkable(start) || !self.is_walkable(goal) {
831 return None;
832 }
833 if start_idx == goal_idx {
834 return Some(GridPathResult {
835 path: vec![start],
836 total_cost: 0.0,
837 nodes_expanded: 1,
838 });
839 }
840 let width: usize = self.get_width();
841 let height: usize = self.get_height();
842 let cell_count: usize = width * height;
843 let unit_cost: f32 = self.get_min_walkable_cost();
844 let mut scratch: GridPathScratch = take(self.get_mut_scratch());
845 let gen_id: u32 = Self::begin_search_generation(&mut scratch, cell_count);
846 scratch.seen_gen[start_idx] = gen_id;
847 scratch.g_scores[start_idx] = 0.0;
848 scratch.came_from[start_idx] = usize::MAX;
849 min_heap_f32_push(
850 &mut scratch.open_heap,
851 grid_heuristic(start, goal, connectivity, unit_cost),
852 start_idx,
853 );
854 let mut nodes_expanded: usize = 0;
855 let mut found: bool = false;
856 let mut dir_buf: [(isize, isize); 8] = [(0, 0); 8];
857 while let Some((_, current_idx)) = min_heap_f32_pop(&mut scratch.open_heap) {
858 if scratch.closed_gen[current_idx] == gen_id {
859 continue;
860 }
861 scratch.closed_gen[current_idx] = gen_id;
862 nodes_expanded += 1;
863 if current_idx == goal_idx {
864 found = true;
865 break;
866 }
867 let current_coord: GridCoord = self.coord_of(current_idx);
868 let parent_idx: usize = scratch.came_from[current_idx];
869 let parent_coord: Option<GridCoord> = if parent_idx == usize::MAX {
870 None
871 } else {
872 Some(self.coord_of(parent_idx))
873 };
874 let cx: isize = current_coord.get_x() as isize;
875 let cy: isize = current_coord.get_y() as isize;
876 let dir_count: usize =
877 self.jps_pruned_directions(cx, cy, parent_coord, connectivity, &mut dir_buf);
878 let current_g: f32 = scratch.g_scores[current_idx];
879 for &(dx, dy) in &dir_buf[..dir_count] {
880 if let Some(jump_idx) = self.jps_jump(cx, cy, dx, dy, goal, connectivity) {
881 if scratch.closed_gen[jump_idx] == gen_id {
882 continue;
883 }
884 let jump_coord: GridCoord = self.coord_of(jump_idx);
885 let seg_cost: f32 =
886 grid_heuristic(current_coord, jump_coord, connectivity, unit_cost);
887 let tentative_g: f32 = current_g + seg_cost;
888 if scratch.seen_gen[jump_idx] != gen_id
889 || tentative_g < scratch.g_scores[jump_idx]
890 {
891 scratch.seen_gen[jump_idx] = gen_id;
892 scratch.g_scores[jump_idx] = tentative_g;
893 scratch.came_from[jump_idx] = current_idx;
894 let h_val: f32 = grid_heuristic(jump_coord, goal, connectivity, unit_cost);
895 min_heap_f32_push(&mut scratch.open_heap, tentative_g + h_val, jump_idx);
896 }
897 }
898 }
899 }
900 let result: Option<GridPathResult> = if found {
901 let total_cost: f32 = scratch.g_scores[goal_idx];
902 let mut jump_points: Vec<GridCoord> = Vec::new();
903 let mut cursor: usize = goal_idx;
904 while cursor != usize::MAX {
905 jump_points.push(self.coord_of(cursor));
906 if cursor == start_idx {
907 break;
908 }
909 cursor = scratch.came_from[cursor];
910 }
911 jump_points.reverse();
912 let mut full_path: Vec<GridCoord> = Vec::with_capacity(jump_points.len() * 2);
913 if let Some(&first) = jump_points.first() {
914 full_path.push(first);
915 for pair in jump_points.windows(2) {
916 let from_pt: GridCoord = pair[0];
917 let to_pt: GridCoord = pair[1];
918 let mut x: isize = from_pt.get_x() as isize;
919 let mut y: isize = from_pt.get_y() as isize;
920 let tx: isize = to_pt.get_x() as isize;
921 let ty: isize = to_pt.get_y() as isize;
922 let step_x: isize = (tx - x).signum();
923 let step_y: isize = (ty - y).signum();
924 while x != tx || y != ty {
925 x += step_x;
926 y += step_y;
927 full_path.push(GridCoord::new(x as usize, y as usize));
928 }
929 }
930 }
931 Some(GridPathResult {
932 path: full_path,
933 total_cost,
934 nodes_expanded,
935 })
936 } else {
937 None
938 };
939 self.set_scratch(scratch);
940 result
941 }
942}
943
944impl NavPolygon2D {
946 #[must_use]
957 pub fn new(mut vertices: Vec<Vec2>, cost_multiplier: f32) -> Self {
958 let mut signed_area_2: f32 = 0.0;
959 let len: usize = vertices.len();
960 for idx in 0..len {
961 let curr: Vec2 = vertices[idx];
962 let next: Vec2 = vertices[(idx + 1) % len];
963 signed_area_2 += pf_vec2_det(curr, next);
964 }
965 if signed_area_2 < 0.0 {
966 vertices.reverse();
967 }
968 let mut sum: Vec2 = Vec2::zero();
969 for &vertex in &vertices {
970 sum = pf_vec2_add(sum, vertex);
971 }
972 let center: Vec2 = if len > 0 {
973 pf_vec2_scale(sum, 1.0 / (len as f32))
974 } else {
975 Vec2::zero()
976 };
977 let safe_cost: f32 = if cost_multiplier.is_finite() && cost_multiplier > 1e-4 {
978 cost_multiplier
979 } else {
980 1.0
981 };
982 Self {
983 vertices,
984 cost_multiplier: safe_cost,
985 center,
986 }
987 }
988
989 #[must_use]
999 pub fn contains_point(&self, point: Vec2) -> bool {
1000 let verts: &[Vec2] = self.get_vertices();
1001 let len: usize = verts.len();
1002 if len < 3 {
1003 return false;
1004 }
1005 for idx in 0..len {
1006 let v0: Vec2 = verts[idx];
1007 let v1: Vec2 = verts[(idx + 1) % len];
1008 if pf_tri_area_2(v0, v1, point) < -NAV_EDGE_EPSILON {
1009 return false;
1010 }
1011 }
1012 true
1013 }
1014}
1015
1016impl NavMesh2D {
1018 #[must_use]
1028 pub fn from_polygons(polygons: Vec<NavPolygon2D>) -> Self {
1029 let count: usize = polygons.len();
1030 let mut adjacency: Vec<Vec<NavPortal2D>> = vec![Vec::new(); count];
1031 let eps_sq: f32 = NAV_EDGE_EPSILON * NAV_EDGE_EPSILON;
1032 for poly_a in 0..count {
1033 let verts_a: &[Vec2] = polygons[poly_a].get_vertices();
1034 let len_a: usize = verts_a.len();
1035 if len_a < 3 {
1036 continue;
1037 }
1038 for poly_b in (poly_a + 1)..count {
1039 let verts_b: &[Vec2] = polygons[poly_b].get_vertices();
1040 let len_b: usize = verts_b.len();
1041 if len_b < 3 {
1042 continue;
1043 }
1044 for ea in 0..len_a {
1045 let a0: Vec2 = verts_a[ea];
1046 let a1: Vec2 = verts_a[(ea + 1) % len_a];
1047 for eb in 0..len_b {
1048 let b0: Vec2 = verts_b[eb];
1049 let b1: Vec2 = verts_b[(eb + 1) % len_b];
1050 let match_opp: bool =
1051 pf_vec2_dist_sq(a0, b1) <= eps_sq && pf_vec2_dist_sq(a1, b0) <= eps_sq;
1052 let match_same: bool =
1053 pf_vec2_dist_sq(a0, b0) <= eps_sq && pf_vec2_dist_sq(a1, b1) <= eps_sq;
1054 if match_opp || match_same {
1055 let midpoint: Vec2 = pf_vec2_scale(pf_vec2_add(a0, a1), 0.5);
1056 adjacency[poly_a].push(NavPortal2D::new(poly_b, a1, a0, midpoint));
1057 adjacency[poly_b].push(NavPortal2D::new(poly_a, a0, a1, midpoint));
1058 }
1059 }
1060 }
1061 }
1062 }
1063 let scratch: NavMeshScratch = NavMeshScratch {
1064 generation: 0,
1065 seen_gen: vec![0; count],
1066 closed_gen: vec![0; count],
1067 g_scores: vec![f32::INFINITY; count],
1068 came_from_poly: vec![usize::MAX; count],
1069 came_from_portal: vec![usize::MAX; count],
1070 open_heap: Vec::with_capacity(count.min(128)),
1071 portal_corridor: Vec::with_capacity(32),
1072 };
1073 Self {
1074 polygons,
1075 adjacency,
1076 scratch,
1077 }
1078 }
1079
1080 #[must_use]
1090 pub fn find_polygon(&self, point: Vec2) -> Option<usize> {
1091 for (idx, poly) in self.get_polygons().iter().enumerate() {
1092 if poly.contains_point(point) {
1093 return Some(idx);
1094 }
1095 }
1096 None
1097 }
1098
1099 #[must_use]
1110 pub fn find_path(&mut self, start: Vec2, goal: Vec2) -> Option<Vec<Vec2>> {
1111 let mut out: Vec<Vec2> = Vec::new();
1112 if self.find_path_into(start, goal, &mut out) {
1113 Some(out)
1114 } else {
1115 None
1116 }
1117 }
1118
1119 pub fn find_path_into(&mut self, start: Vec2, goal: Vec2, out_path: &mut Vec<Vec2>) -> bool {
1131 out_path.clear();
1132 let Some(start_poly) = self.find_polygon(start) else {
1133 return false;
1134 };
1135 let Some(goal_poly) = self.find_polygon(goal) else {
1136 return false;
1137 };
1138 if start_poly == goal_poly {
1139 out_path.push(start);
1140 if pf_vec2_dist_sq(start, goal) > 1e-10 {
1141 out_path.push(goal);
1142 }
1143 return true;
1144 }
1145 let poly_count: usize = self.get_polygons().len();
1146 let mut scratch: NavMeshScratch = take(self.get_mut_scratch());
1147 if scratch.seen_gen.len() != poly_count {
1148 scratch.seen_gen.resize(poly_count, 0);
1149 scratch.closed_gen.resize(poly_count, 0);
1150 scratch.g_scores.resize(poly_count, f32::INFINITY);
1151 scratch.came_from_poly.resize(poly_count, usize::MAX);
1152 scratch.came_from_portal.resize(poly_count, usize::MAX);
1153 }
1154 scratch.open_heap.clear();
1155 scratch.portal_corridor.clear();
1156 if scratch.generation == u32::MAX {
1157 scratch.seen_gen.fill(0);
1158 scratch.closed_gen.fill(0);
1159 scratch.generation = 1;
1160 } else {
1161 scratch.generation += 1;
1162 }
1163 let gen_id: u32 = scratch.generation;
1164 scratch.seen_gen[start_poly] = gen_id;
1165 scratch.g_scores[start_poly] = 0.0;
1166 scratch.came_from_poly[start_poly] = usize::MAX;
1167 scratch.came_from_portal[start_poly] = usize::MAX;
1168 let start_center: Vec2 = self.get_polygons()[start_poly].get_center();
1169 min_heap_f32_push(
1170 &mut scratch.open_heap,
1171 pf_vec2_dist(start_center, goal),
1172 start_poly,
1173 );
1174 let mut found: bool = false;
1175 while let Some((_, current_poly)) = min_heap_f32_pop(&mut scratch.open_heap) {
1176 if scratch.closed_gen[current_poly] == gen_id {
1177 continue;
1178 }
1179 scratch.closed_gen[current_poly] = gen_id;
1180 if current_poly == goal_poly {
1181 found = true;
1182 break;
1183 }
1184 let current_g: f32 = scratch.g_scores[current_poly];
1185 let entry_point: Vec2 = if current_poly == start_poly {
1186 start
1187 } else {
1188 let parent_p: usize = scratch.came_from_poly[current_poly];
1189 let portal_idx: usize = scratch.came_from_portal[current_poly];
1190 self.get_adjacency()[parent_p][portal_idx].get_midpoint()
1191 };
1192 let current_cost_mult: f32 = self.get_polygons()[current_poly].get_cost_multiplier();
1193 for (portal_idx, portal) in self.get_adjacency()[current_poly].iter().enumerate() {
1194 let neighbor: usize = portal.get_target_polygon();
1195 if scratch.closed_gen[neighbor] == gen_id {
1196 continue;
1197 }
1198 let step_dist: f32 =
1199 pf_vec2_dist(entry_point, portal.get_midpoint()) * current_cost_mult;
1200 let tentative_g: f32 = current_g + step_dist;
1201 if scratch.seen_gen[neighbor] != gen_id || tentative_g < scratch.g_scores[neighbor]
1202 {
1203 scratch.seen_gen[neighbor] = gen_id;
1204 scratch.g_scores[neighbor] = tentative_g;
1205 scratch.came_from_poly[neighbor] = current_poly;
1206 scratch.came_from_portal[neighbor] = portal_idx;
1207 let heuristic: f32 = pf_vec2_dist(portal.get_midpoint(), goal);
1208 min_heap_f32_push(&mut scratch.open_heap, tentative_g + heuristic, neighbor);
1209 }
1210 }
1211 }
1212 if found {
1213 let mut cursor: usize = goal_poly;
1214 while cursor != start_poly && cursor != usize::MAX {
1215 let parent_p: usize = scratch.came_from_poly[cursor];
1216 let portal_idx: usize = scratch.came_from_portal[cursor];
1217 let portal: NavPortal2D = self.get_adjacency()[parent_p][portal_idx];
1218 scratch
1219 .portal_corridor
1220 .push((portal.get_left(), portal.get_right()));
1221 cursor = parent_p;
1222 }
1223 scratch.portal_corridor.reverse();
1224 funnel_string_pull(start, goal, &scratch.portal_corridor, out_path);
1225 }
1226 self.set_scratch(scratch);
1227 found
1228 }
1229}
1230
1231impl FlowFieldGrid {
1233 #[must_use]
1246 pub fn new(width: usize, height: usize, cell_size: f32, origin: Vec2) -> Self {
1247 let count: usize = width.saturating_mul(height);
1248 let safe_size: f32 = if cell_size.is_finite() && cell_size > 1e-4 {
1249 cell_size
1250 } else {
1251 1.0
1252 };
1253 Self {
1254 width,
1255 height,
1256 cell_size: safe_size,
1257 origin,
1258 costs: vec![1; count],
1259 integration: vec![u32::MAX; count],
1260 flow_vectors: vec![Vec2::zero(); count],
1261 scratch: FlowFieldScratch {
1262 open_heap: Vec::with_capacity(count.min(256)),
1263 },
1264 }
1265 }
1266
1267 pub fn set_cost(&mut self, coord: GridCoord, cost: u8) {
1274 let width: usize = self.get_width();
1275 let height: usize = self.get_height();
1276 if coord.get_x() < width && coord.get_y() < height {
1277 let idx: usize = coord.get_y() * width + coord.get_x();
1278 self.get_mut_costs()[idx] = if cost == 0 { 1 } else { cost };
1279 }
1280 }
1281
1282 pub fn set_blocked(&mut self, coord: GridCoord, blocked: bool) {
1289 self.set_cost(coord, if blocked { FLOW_IMPASSABLE } else { 1 });
1290 }
1291
1292 pub fn build_for_goals(&mut self, goals: &[GridCoord]) {
1298 let width: usize = self.get_width();
1299 let height: usize = self.get_height();
1300 let count: usize = width * height;
1301 if count == 0 {
1302 return;
1303 }
1304 let mut integration: Vec<u32> = take(self.get_mut_integration());
1305 integration.resize(count, u32::MAX);
1306 integration.fill(u32::MAX);
1307 let mut flow_vectors: Vec<Vec2> = take(self.get_mut_flow_vectors());
1308 flow_vectors.resize(count, Vec2::zero());
1309 flow_vectors.fill(Vec2::zero());
1310 let mut scratch: FlowFieldScratch = take(self.get_mut_scratch());
1311 scratch.open_heap.clear();
1312 let costs: &[u8] = self.get_costs();
1313 for &goal in goals {
1314 if goal.get_x() < width && goal.get_y() < height {
1315 let idx: usize = goal.get_y() * width + goal.get_x();
1316 if costs[idx] < FLOW_IMPASSABLE {
1317 integration[idx] = 0;
1318 min_heap_u32_push(&mut scratch.open_heap, 0, idx);
1319 }
1320 }
1321 }
1322 let dirs_8: [(isize, isize, u32); 8] = [
1323 (1, 0, 10),
1324 (-1, 0, 10),
1325 (0, 1, 10),
1326 (0, -1, 10),
1327 (1, 1, 14),
1328 (1, -1, 14),
1329 (-1, 1, 14),
1330 (-1, -1, 14),
1331 ];
1332 while let Some((dist, current_idx)) = min_heap_u32_pop(&mut scratch.open_heap) {
1333 if dist > integration[current_idx] {
1334 continue;
1335 }
1336 let cx: isize = (current_idx % width) as isize;
1337 let cy: isize = (current_idx / width) as isize;
1338 for &(dx, dy, base_step) in &dirs_8 {
1339 let nx: isize = cx + dx;
1340 let ny: isize = cy + dy;
1341 let in_x: bool = nx >= 0 && nx < width as isize;
1342 let in_y: bool = ny >= 0 && ny < height as isize;
1343 if !in_x || !in_y {
1344 continue;
1345 }
1346 let next_idx: usize = (ny as usize) * width + (nx as usize);
1347 let cell_cost: u8 = costs[next_idx];
1348 if cell_cost == FLOW_IMPASSABLE {
1349 continue;
1350 }
1351 if dx != 0 && dy != 0 {
1352 let adj_x: usize = (cy as usize) * width + ((cx + dx) as usize);
1353 let adj_y: usize = ((cy + dy) as usize) * width + (cx as usize);
1354 if costs[adj_x] == FLOW_IMPASSABLE || costs[adj_y] == FLOW_IMPASSABLE {
1355 continue;
1356 }
1357 }
1358 let next_dist: u32 =
1359 dist.saturating_add(base_step.saturating_mul(cell_cost as u32));
1360 if next_dist < integration[next_idx] {
1361 integration[next_idx] = next_dist;
1362 min_heap_u32_push(&mut scratch.open_heap, next_dist, next_idx);
1363 }
1364 }
1365 }
1366 for y in 0..height {
1367 for x in 0..width {
1368 let idx: usize = y * width + x;
1369 let cur_dist: u32 = integration[idx];
1370 if cur_dist == 0 || cur_dist == u32::MAX {
1371 flow_vectors[idx] = Vec2::zero();
1372 continue;
1373 }
1374 let mut best_dist: u32 = cur_dist;
1375 let mut best_dir: Vec2 = Vec2::zero();
1376 let cx: isize = x as isize;
1377 let cy: isize = y as isize;
1378 for &(dx, dy, _) in &dirs_8 {
1379 let nx: isize = cx + dx;
1380 let ny: isize = cy + dy;
1381 let in_x: bool = nx >= 0 && nx < width as isize;
1382 let in_y: bool = ny >= 0 && ny < height as isize;
1383 if !in_x || !in_y {
1384 continue;
1385 }
1386 let n_idx: usize = (ny as usize) * width + (nx as usize);
1387 if costs[n_idx] == FLOW_IMPASSABLE {
1388 continue;
1389 }
1390 if dx != 0 && dy != 0 {
1391 let adj_x: usize = (cy as usize) * width + ((cx + dx) as usize);
1392 let adj_y: usize = ((cy + dy) as usize) * width + (cx as usize);
1393 if costs[adj_x] == FLOW_IMPASSABLE || costs[adj_y] == FLOW_IMPASSABLE {
1394 continue;
1395 }
1396 }
1397 if integration[n_idx] < best_dist {
1398 best_dist = integration[n_idx];
1399 best_dir = Vec2::new(dx as f32, dy as f32);
1400 }
1401 }
1402 flow_vectors[idx] = pf_vec2_normalize_or_zero(best_dir);
1403 }
1404 }
1405 self.set_integration(integration);
1406 self.set_flow_vectors(flow_vectors);
1407 self.set_scratch(scratch);
1408 }
1409
1410 #[must_use]
1420 pub fn direction_at_cell(&self, coord: GridCoord) -> Vec2 {
1421 let width: usize = self.get_width();
1422 let height: usize = self.get_height();
1423 if coord.get_x() < width && coord.get_y() < height {
1424 self.get_flow_vectors()[coord.get_y() * width + coord.get_x()]
1425 } else {
1426 Vec2::zero()
1427 }
1428 }
1429
1430 #[must_use]
1440 pub fn integration_at(&self, coord: GridCoord) -> u32 {
1441 let width: usize = self.get_width();
1442 let height: usize = self.get_height();
1443 if coord.get_x() < width && coord.get_y() < height {
1444 self.get_integration()[coord.get_y() * width + coord.get_x()]
1445 } else {
1446 u32::MAX
1447 }
1448 }
1449
1450 #[must_use]
1460 pub fn world_to_cell(&self, world_pos: Vec2) -> Option<GridCoord> {
1461 let rel: Vec2 = pf_vec2_sub(world_pos, self.get_origin());
1462 let inv_size: f32 = 1.0 / self.get_cell_size();
1463 let gx: isize = (rel.get_x() * inv_size).floor() as isize;
1464 let gy: isize = (rel.get_y() * inv_size).floor() as isize;
1465 if gx >= 0
1466 && gy >= 0
1467 && (gx as usize) < self.get_width()
1468 && (gy as usize) < self.get_height()
1469 {
1470 Some(GridCoord::new(gx as usize, gy as usize))
1471 } else {
1472 None
1473 }
1474 }
1475
1476 #[must_use]
1486 pub fn cell_center(&self, coord: GridCoord) -> Vec2 {
1487 let size: f32 = self.get_cell_size();
1488 let origin: Vec2 = self.get_origin();
1489 Vec2::new(
1490 origin.get_x() + (coord.get_x() as f32 + 0.5) * size,
1491 origin.get_y() + (coord.get_y() as f32 + 0.5) * size,
1492 )
1493 }
1494
1495 #[must_use]
1505 pub fn sample_direction(&self, world_pos: Vec2) -> Vec2 {
1506 if let Some(cell) = self.world_to_cell(world_pos) {
1507 self.direction_at_cell(cell)
1508 } else {
1509 Vec2::zero()
1510 }
1511 }
1512}
1513
1514impl Default for OrcaCrowdConfig {
1516 fn default() -> Self {
1522 Self {
1523 default_neighbor_dist: DEFAULT_ORCA_NEIGHBOR_DIST,
1524 default_time_horizon: DEFAULT_ORCA_TIME_HORIZON,
1525 max_neighbors: 16,
1526 }
1527 }
1528}
1529
1530impl OrcaAgent2D {
1532 #[must_use]
1544 pub fn new(position: Vec2, radius: f32, max_speed: f32) -> Self {
1545 let safe_radius: f32 = if radius.is_finite() && radius > 1e-4 {
1546 radius
1547 } else {
1548 0.5
1549 };
1550 let safe_speed: f32 = if max_speed.is_finite() && max_speed > 0.0 {
1551 max_speed
1552 } else {
1553 1.0
1554 };
1555 Self {
1556 position,
1557 velocity: Vec2::zero(),
1558 preferred_velocity: Vec2::zero(),
1559 radius: safe_radius,
1560 max_speed: safe_speed,
1561 neighbor_dist: DEFAULT_ORCA_NEIGHBOR_DIST,
1562 time_horizon: DEFAULT_ORCA_TIME_HORIZON,
1563 }
1564 }
1565}
1566
1567impl OrcaCrowdSolver {
1569 #[must_use]
1579 pub fn new(config: OrcaCrowdConfig) -> Self {
1580 Self {
1581 config,
1582 agents: Vec::new(),
1583 scratch: OrcaScratch {
1584 orca_lines: Vec::with_capacity(32),
1585 proj_lines: Vec::with_capacity(32),
1586 new_velocities: Vec::with_capacity(64),
1587 neighbor_indices: Vec::with_capacity(32),
1588 },
1589 }
1590 }
1591
1592 pub fn add_agent(&mut self, mut agent: OrcaAgent2D) -> usize {
1602 let cfg: OrcaCrowdConfig = self.get_config();
1603 if agent.get_neighbor_dist() <= 0.0 || !agent.get_neighbor_dist().is_finite() {
1604 agent.set_neighbor_dist(cfg.get_default_neighbor_dist());
1605 }
1606 if agent.get_time_horizon() <= 0.0 || !agent.get_time_horizon().is_finite() {
1607 agent.set_time_horizon(cfg.get_default_time_horizon());
1608 }
1609 let idx: usize = self.get_agents().len();
1610 self.get_mut_agents().push(agent);
1611 idx
1612 }
1613
1614 pub fn set_preferred_velocity(&mut self, index: usize, preferred: Vec2) {
1621 if let Some(agent) = self.get_mut_agents().get_mut(index) {
1622 let max_speed: f32 = agent.get_max_speed();
1623 agent.set_preferred_velocity(pf_vec2_clamp_len(preferred, max_speed));
1624 }
1625 }
1626
1627 pub fn step(&mut self, dt: f32) {
1633 if !dt.is_finite() || dt <= 1e-6 {
1634 return;
1635 }
1636 let count: usize = self.get_agents().len();
1637 if count == 0 {
1638 return;
1639 }
1640 let max_neighbors: usize = self.get_config().get_max_neighbors().max(1);
1641 let inv_time_step: f32 = 1.0 / dt;
1642 let mut scratch: OrcaScratch = take(self.get_mut_scratch());
1643 scratch.new_velocities.clear();
1644 scratch.new_velocities.resize(count, Vec2::zero());
1645 let agents: &[OrcaAgent2D] = self.get_agents();
1646 for idx in 0..count {
1647 let agent_i: OrcaAgent2D = agents[idx];
1648 let pos_i: Vec2 = agent_i.get_position();
1649 let vel_i: Vec2 = agent_i.get_velocity();
1650 let pref_i: Vec2 =
1651 pf_vec2_clamp_len(agent_i.get_preferred_velocity(), agent_i.get_max_speed());
1652 let rad_i: f32 = agent_i.get_radius();
1653 let max_speed_i: f32 = agent_i.get_max_speed();
1654 let neighbor_dist_sq: f32 = agent_i.get_neighbor_dist() * agent_i.get_neighbor_dist();
1655 let inv_tau: f32 = 1.0 / agent_i.get_time_horizon().max(dt);
1656 scratch.neighbor_indices.clear();
1657 for (other_idx, other) in agents.iter().enumerate() {
1658 if other_idx == idx {
1659 continue;
1660 }
1661 let d_sq: f32 = pf_vec2_dist_sq(pos_i, other.get_position());
1662 if d_sq <= neighbor_dist_sq {
1663 scratch.neighbor_indices.push((d_sq, other_idx));
1664 }
1665 }
1666 scratch
1667 .neighbor_indices
1668 .sort_by(|lhs: &(f32, usize), rhs: &(f32, usize)| lhs.0.total_cmp(&rhs.0));
1669 let active_neighbors: usize = scratch.neighbor_indices.len().min(max_neighbors);
1670 scratch.orca_lines.clear();
1671 let mut has_head_on: bool = false;
1672 for n_slot in 0..active_neighbors {
1673 let other_idx: usize = scratch.neighbor_indices[n_slot].1;
1674 let agent_j: OrcaAgent2D = agents[other_idx];
1675 let rel_pos: Vec2 = pf_vec2_sub(agent_j.get_position(), pos_i);
1676 let rel_vel: Vec2 = pf_vec2_sub(vel_i, agent_j.get_velocity());
1677 let dist_sq: f32 = pf_vec2_len_sq(rel_pos);
1678 let comb_r: f32 = rad_i + agent_j.get_radius();
1679 let comb_r_sq: f32 = comb_r * comb_r;
1680 if pf_vec2_det(rel_pos, pref_i).abs() < 1e-3 * comb_r.max(1.0)
1681 && rel_pos.dot(pref_i) > 0.0
1682 {
1683 has_head_on = true;
1684 }
1685 let (u_vec, direction): (Vec2, Vec2) = if dist_sq > comb_r_sq {
1686 let w_vec: Vec2 = pf_vec2_sub(rel_vel, pf_vec2_scale(rel_pos, inv_tau));
1687 let w_len_sq: f32 = pf_vec2_len_sq(w_vec);
1688 let dot_product: f32 = w_vec.dot(rel_pos);
1689 if dot_product < 0.0 && dot_product * dot_product > comb_r_sq * w_len_sq {
1690 let w_len: f32 = w_len_sq.sqrt();
1691 let unit_w: Vec2 = if w_len > ORCA_EPSILON {
1692 pf_vec2_scale(w_vec, 1.0 / w_len)
1693 } else {
1694 pf_vec2_normalize_or_zero(pf_vec2_scale(rel_pos, -1.0))
1695 };
1696 let dir: Vec2 = Vec2::new(unit_w.get_y(), -unit_w.get_x());
1697 let u_out: Vec2 = pf_vec2_scale(unit_w, comb_r * inv_tau - w_len);
1698 (u_out, dir)
1699 } else {
1700 let leg: f32 = (dist_sq - comb_r_sq).max(0.0).sqrt();
1701 let side_det: f32 = pf_vec2_det(rel_pos, w_vec);
1702 let dir: Vec2 = if side_det > 0.0 {
1703 pf_vec2_scale(
1704 Vec2::new(
1705 rel_pos.get_x() * leg - rel_pos.get_y() * comb_r,
1706 rel_pos.get_x() * comb_r + rel_pos.get_y() * leg,
1707 ),
1708 1.0 / dist_sq,
1709 )
1710 } else {
1711 pf_vec2_scale(
1712 Vec2::new(
1713 rel_pos.get_x() * leg + rel_pos.get_y() * comb_r,
1714 -rel_pos.get_x() * comb_r + rel_pos.get_y() * leg,
1715 ),
1716 -1.0 / dist_sq,
1717 )
1718 };
1719 let proj: f32 = rel_vel.dot(dir);
1720 let u_out: Vec2 = pf_vec2_sub(pf_vec2_scale(dir, proj), rel_vel);
1721 (u_out, dir)
1722 }
1723 } else {
1724 let w_vec: Vec2 = pf_vec2_sub(rel_vel, pf_vec2_scale(rel_pos, inv_time_step));
1725 let w_len: f32 = pf_vec2_len(w_vec);
1726 let unit_w: Vec2 = if w_len > ORCA_EPSILON {
1727 pf_vec2_scale(w_vec, 1.0 / w_len)
1728 } else if dist_sq > 1e-10 {
1729 pf_vec2_normalize_or_zero(pf_vec2_scale(rel_pos, -1.0))
1730 } else {
1731 let angle: f32 = (idx as f32) * 2.399_963_1;
1732 Vec2::new(angle.cos(), angle.sin())
1733 };
1734 let dir: Vec2 = Vec2::new(unit_w.get_y(), -unit_w.get_x());
1735 let u_out: Vec2 = pf_vec2_scale(unit_w, comb_r * inv_time_step - w_len);
1736 (u_out, dir)
1737 };
1738 let point: Vec2 = pf_vec2_add(vel_i, pf_vec2_scale(u_vec, 0.5));
1739 scratch.orca_lines.push(OrcaLine2D::new(point, direction));
1740 }
1741 let opt_vel: Vec2 = if has_head_on {
1742 let right_dir: Vec2 =
1743 pf_vec2_normalize_or_zero(Vec2::new(pref_i.get_y(), -pref_i.get_x()));
1744 pf_vec2_clamp_len(
1745 pf_vec2_add(
1746 pref_i,
1747 pf_vec2_scale(right_dir, ORCA_PASSING_BIAS * max_speed_i * 50.0),
1748 ),
1749 max_speed_i,
1750 )
1751 } else {
1752 pref_i
1753 };
1754 let mut solved_vel: Vec2 = Vec2::zero();
1755 let fail_line: usize = orca_linear_program2(
1756 &scratch.orca_lines,
1757 max_speed_i,
1758 opt_vel,
1759 false,
1760 &mut solved_vel,
1761 );
1762 if fail_line < scratch.orca_lines.len() {
1763 orca_linear_program3(
1764 &scratch.orca_lines,
1765 fail_line,
1766 max_speed_i,
1767 &mut scratch.proj_lines,
1768 &mut solved_vel,
1769 );
1770 }
1771 scratch.new_velocities[idx] = pf_vec2_clamp_len(solved_vel, max_speed_i);
1772 }
1773 for (idx, agent) in self.get_mut_agents().iter_mut().enumerate() {
1774 let next_vel: Vec2 = scratch.new_velocities[idx];
1775 let next_pos: Vec2 = pf_vec2_add(agent.get_position(), pf_vec2_scale(next_vel, dt));
1776 agent.set_velocity(next_vel);
1777 agent.set_position(next_pos);
1778 }
1779 self.set_scratch(scratch);
1780 }
1781}