Skip to main content

euv_core/game/algorithms/pathfinding/
impl.rs

1use super::*;
2
3/// Core operations for `GridPathfinder` including A*, multi-goal Dijkstra, and Jump Point Search.
4impl GridPathfinder {
5    /// Creates a uniform-cost `GridPathfinder` with every cell initialized to `1.0`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Number of grid columns.
10    /// - `usize` - Number of grid rows.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Initialized uniform-cost grid pathfinder.
15    #[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    /// Creates a `GridPathfinder` from explicit row-major cell traversal costs (`<= 0.0` blocks).
39    ///
40    /// # Arguments
41    ///
42    /// - `usize` - Number of grid columns.
43    /// - `usize` - Number of grid rows.
44    /// - `Vec<f32>` - Row-major cost array of length `width * height`.
45    ///
46    /// # Returns
47    ///
48    /// - `Self` - Configured weighted grid pathfinder.
49    #[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    /// Recomputes minimum walkable cost and uniform-cost flag after modifying cell weights.
60    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    /// Converts a grid coordinate into a flat index if in bounds.
83    ///
84    /// # Arguments
85    ///
86    /// - `GridCoord` - Cell coordinate to check.
87    ///
88    /// # Returns
89    ///
90    /// - `Option<usize>` - Row-major cell index when inside grid bounds.
91    #[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    /// Converts a flat row-major cell index back into a `GridCoord`.
101    ///
102    /// # Arguments
103    ///
104    /// - `usize` - Flat cell index.
105    ///
106    /// # Returns
107    ///
108    /// - `GridCoord` - Corresponding `(x, y)` coordinate.
109    #[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    /// Returns whether `coord` is in bounds and has a positive finite traversal cost.
116    ///
117    /// # Arguments
118    ///
119    /// - `GridCoord` - Cell coordinate to inspect.
120    ///
121    /// # Returns
122    ///
123    /// - `bool` - `true` when walkable.
124    #[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    /// Returns whether signed integer coordinate `(cx, cy)` is in bounds and walkable.
135    ///
136    /// # Arguments
137    ///
138    /// - `isize` - Signed column index.
139    /// - `isize` - Signed row index.
140    ///
141    /// # Returns
142    ///
143    /// - `bool` - `true` when `(cx, cy)` lies inside the grid and is walkable.
144    #[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    /// Sets the traversal cost of `coord` (`<= 0.0` marks the cell blocked).
159    ///
160    /// # Arguments
161    ///
162    /// - `GridCoord` - Cell coordinate to update.
163    /// - `f32` - New traversal cost (`<= 0.0` or non-finite blocks the cell).
164    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    /// Marks `coord` blocked (`blocked == true`) or walkable with cost `1.0` (`blocked == false`).
177    ///
178    /// # Arguments
179    ///
180    /// - `GridCoord` - Cell coordinate to update.
181    /// - `bool` - Whether the cell should be impassable.
182    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    /// Advances scratch search generation, resetting stamps only upon `u32::MAX` wraparound.
187    ///
188    /// # Arguments
189    ///
190    /// - `&mut GridPathScratch` - Scratch state to prepare.
191    /// - `usize` - Total grid cell count.
192    ///
193    /// # Returns
194    ///
195    /// - `u32` - Active search generation token.
196    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    /// Finds an optimal shortest path using the selected algorithm and connectivity policy.
216    ///
217    /// # Arguments
218    ///
219    /// - `GridCoord` - Start cell coordinate.
220    /// - `GridCoord` - Goal cell coordinate.
221    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
222    /// - `GridSearchAlgorithm` - Search strategy (`AStar`, `Dijkstra`, or `JumpPointSearch`).
223    ///
224    /// # Returns
225    ///
226    /// - `Option<GridPathResult>` - Optimal path and cost if reachable.
227    #[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    /// Finds an optimal shortest path using A* with admissible Manhattan or Octile heuristics.
243    ///
244    /// # Arguments
245    ///
246    /// - `GridCoord` - Start cell coordinate.
247    /// - `GridCoord` - Goal cell coordinate.
248    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
249    ///
250    /// # Returns
251    ///
252    /// - `Option<GridPathResult>` - Optimal path and total cost if reachable.
253    #[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    /// Finds an optimal shortest path using A* while writing waypoints into a caller-owned buffer.
271    ///
272    /// # Arguments
273    ///
274    /// - `GridCoord` - Start cell coordinate.
275    /// - `GridCoord` - Goal cell coordinate.
276    /// - `GridConnectivity` - 4-way or 8-way connectivity.
277    /// - `&mut Vec<GridCoord>` - Reusable output path buffer.
278    ///
279    /// # Returns
280    ///
281    /// - `Option<f32>` - Optimal total path cost when reachable.
282    #[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    /// Finds an optimal shortest path to a single goal using Dijkstra's algorithm.
296    ///
297    /// # Arguments
298    ///
299    /// - `GridCoord` - Start cell coordinate.
300    /// - `GridCoord` - Goal cell coordinate.
301    /// - `GridConnectivity` - 4-way or 8-way connectivity.
302    ///
303    /// # Returns
304    ///
305    /// - `Option<GridPathResult>` - Optimal path and total cost if reachable.
306    #[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    /// Shared zero-allocation A* / Dijkstra search writing the optimal path into `out_path`.
324    ///
325    /// # Arguments
326    ///
327    /// - `GridCoord` - Start cell coordinate.
328    /// - `GridCoord` - Goal cell coordinate.
329    /// - `GridConnectivity` - Neighbor connectivity policy.
330    /// - `bool` - `true` for A* heuristic guidance, `false` for pure Dijkstra.
331    /// - `&mut Vec<GridCoord>` - Reusable output path buffer.
332    ///
333    /// # Returns
334    ///
335    /// - `Option<(f32, usize)>` - `(total_cost, nodes_expanded)` when reachable.
336    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    /// Finds the optimal shortest path to the nearest reachable goal in `goals` using Dijkstra.
455    ///
456    /// # Arguments
457    ///
458    /// - `GridCoord` - Start cell coordinate.
459    /// - `&[GridCoord]` - Candidate target goal cells.
460    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
461    ///
462    /// # Returns
463    ///
464    /// - `Option<GridPathResult>` - Shortest path to whichever goal has minimum total cost.
465    #[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    /// Performs a single directional Jump Point Search ray scan on a uniform-cost grid.
588    ///
589    /// # Arguments
590    ///
591    /// - `isize` - Origin X coordinate.
592    /// - `isize` - Origin Y coordinate.
593    /// - `isize` - Step X direction in `{-1, 0, 1}`.
594    /// - `isize` - Step Y direction in `{-1, 0, 1}`.
595    /// - `GridCoord` - Goal cell coordinate.
596    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
597    ///
598    /// # Returns
599    ///
600    /// - `Option<usize>` - Flat index of the next jump point or goal along `(dx, dy)`.
601    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    /// Collects pruned natural and forced JPS successor directions from `current` given `parent`.
676    ///
677    /// # Arguments
678    ///
679    /// - `isize` - Current cell X coordinate.
680    /// - `isize` - Current cell Y coordinate.
681    /// - `Option<GridCoord>` - Parent jump point coordinate (`None` at start).
682    /// - `GridConnectivity` - 4-way or 8-way connectivity.
683    /// - `&mut [(isize, isize); 8]` - Fixed stack buffer receiving candidate directions.
684    ///
685    /// # Returns
686    ///
687    /// - `usize` - Number of valid directions written into the output array.
688    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    /// Finds an optimal shortest path using Jump Point Search on uniform-cost grids (falling back to A* if weighted).
808    ///
809    /// # Arguments
810    ///
811    /// - `GridCoord` - Start cell coordinate.
812    /// - `GridCoord` - Goal cell coordinate.
813    /// - `GridConnectivity` - 4-way or 8-way (no-corner-cutting) connectivity.
814    ///
815    /// # Returns
816    ///
817    /// - `Option<GridPathResult>` - Optimal expanded cell-by-cell path with exact shortest cost.
818    #[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
944/// Construction and point-containment helpers for `NavPolygon2D`.
945impl NavPolygon2D {
946    /// Constructs a convex `NavPolygon2D`, automatically normalizing vertices to CCW winding.
947    ///
948    /// # Arguments
949    ///
950    /// - `Vec<Vec2>` - Convex polygon vertices in either CW or CCW order.
951    /// - `f32` - Positive traversal cost multiplier (clamped to `>= 1e-4`).
952    ///
953    /// # Returns
954    ///
955    /// - `Self` - Normalized CCW navigation polygon.
956    #[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    /// Tests whether `point` lies inside or on the boundary of this convex CCW polygon.
990    ///
991    /// # Arguments
992    ///
993    /// - `Vec2` - Query point in 2D space.
994    ///
995    /// # Returns
996    ///
997    /// - `bool` - `true` when contained within the polygon.
998    #[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
1016/// Portal graph construction, A* corridor search, and funnel string-pulling for `NavMesh2D`.
1017impl NavMesh2D {
1018    /// Builds a `NavMesh2D` from convex polygons and automatically wires shared-edge portals.
1019    ///
1020    /// # Arguments
1021    ///
1022    /// - `Vec<NavPolygon2D>` - Convex navigation polygons.
1023    ///
1024    /// # Returns
1025    ///
1026    /// - `Self` - Connected navigation mesh ready for pathfinding.
1027    #[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    /// Locates the index of the polygon containing `point`.
1081    ///
1082    /// # Arguments
1083    ///
1084    /// - `Vec2` - Query position.
1085    ///
1086    /// # Returns
1087    ///
1088    /// - `Option<usize>` - Containing polygon index if `point` lies on the mesh.
1089    #[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    /// Finds a taut string-pulled waypoint path between `start` and `goal` via portal A* and Funnel.
1100    ///
1101    /// # Arguments
1102    ///
1103    /// - `Vec2` - Start world position on the navmesh.
1104    /// - `Vec2` - Goal world position on the navmesh.
1105    ///
1106    /// # Returns
1107    ///
1108    /// - `Option<Vec<Vec2>>` - Smooth taut waypoint sequence from `start` to `goal` if connected.
1109    #[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    /// Finds a taut string-pulled waypoint path writing directly into reusable buffer `out_path`.
1120    ///
1121    /// # Arguments
1122    ///
1123    /// - `Vec2` - Start world position on the navmesh.
1124    /// - `Vec2` - Goal world position on the navmesh.
1125    /// - `&mut Vec<Vec2>` - Reusable output waypoint buffer.
1126    ///
1127    /// # Returns
1128    ///
1129    /// - `bool` - `true` if a connected corridor exists and `out_path` was populated.
1130    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
1231/// Integration and flow-vector construction and O(1) lookup for `FlowFieldGrid`.
1232impl FlowFieldGrid {
1233    /// Creates a walkable `FlowFieldGrid` with uniform cost `1` per cell.
1234    ///
1235    /// # Arguments
1236    ///
1237    /// - `usize` - Number of columns.
1238    /// - `usize` - Number of rows.
1239    /// - `f32` - World-space cell width and height (clamped to `>= 1e-4`).
1240    /// - `Vec2` - World-space origin `(min_x, min_y)` of cell `(0, 0)`.
1241    ///
1242    /// # Returns
1243    ///
1244    /// - `Self` - Initialized flow field grid.
1245    #[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    /// Sets the traversal cost of `coord` (`0` clamped to `1`, `255` marks impassable).
1268    ///
1269    /// # Arguments
1270    ///
1271    /// - `GridCoord` - Cell coordinate to modify.
1272    /// - `u8` - Cost byte (`1..=254` walkable, `255` wall).
1273    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    /// Marks `coord` as impassable (`blocked == true`) or normal cost `1` (`blocked == false`).
1283    ///
1284    /// # Arguments
1285    ///
1286    /// - `GridCoord` - Cell coordinate to update.
1287    /// - `bool` - Whether the cell is a solid obstacle.
1288    pub fn set_blocked(&mut self, coord: GridCoord, blocked: bool) {
1289        self.set_cost(coord, if blocked { FLOW_IMPASSABLE } else { 1 });
1290    }
1291
1292    /// Computes Dijkstra integration distances and smooth downhill flow vectors toward `goals`.
1293    ///
1294    /// # Arguments
1295    ///
1296    /// - `&[GridCoord]` - One or more goal cell coordinates.
1297    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    /// Returns the unit flow direction at integer cell `coord` in O(1) time.
1411    ///
1412    /// # Arguments
1413    ///
1414    /// - `GridCoord` - Cell coordinate.
1415    ///
1416    /// # Returns
1417    ///
1418    /// - `Vec2` - Unit flow direction, or `(0, 0)` at goals, walls, or out of bounds.
1419    #[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    /// Returns the integration distance at `coord` (`u32::MAX` if unreachable or out of bounds).
1431    ///
1432    /// # Arguments
1433    ///
1434    /// - `GridCoord` - Cell coordinate.
1435    ///
1436    /// # Returns
1437    ///
1438    /// - `u32` - Integration distance to the nearest goal.
1439    #[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    /// Converts a world position to its enclosing `GridCoord` if within bounds.
1451    ///
1452    /// # Arguments
1453    ///
1454    /// - `Vec2` - World-space 2D position.
1455    ///
1456    /// # Returns
1457    ///
1458    /// - `Option<GridCoord>` - Containing cell coordinate if inside grid extents.
1459    #[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    /// Converts a `GridCoord` into the world-space center of that cell.
1477    ///
1478    /// # Arguments
1479    ///
1480    /// - `GridCoord` - Cell coordinate.
1481    ///
1482    /// # Returns
1483    ///
1484    /// - `Vec2` - World-space center of the cell.
1485    #[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    /// Samples the flow direction at continuous world position `world_pos` in O(1) time.
1496    ///
1497    /// # Arguments
1498    ///
1499    /// - `Vec2` - World-space agent position.
1500    ///
1501    /// # Returns
1502    ///
1503    /// - `Vec2` - Unit steering direction toward the nearest goal.
1504    #[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
1514/// Default configuration for `OrcaCrowdConfig`.
1515impl Default for OrcaCrowdConfig {
1516    /// Returns balanced default neighbor radius, lookahead horizon, and neighbor cap.
1517    ///
1518    /// # Returns
1519    ///
1520    /// - `Self` - Default ORCA crowd configuration.
1521    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
1530/// Constructors for `OrcaAgent2D`.
1531impl OrcaAgent2D {
1532    /// Creates an ORCA agent with explicit position, radius, and maximum speed.
1533    ///
1534    /// # Arguments
1535    ///
1536    /// - `Vec2` - Initial 2D position.
1537    /// - `f32` - Agent collision disk radius.
1538    /// - `f32` - Maximum movement speed.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `Self` - Initialized crowd agent.
1543    #[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
1567/// Multi-agent ORCA / RVO2 half-plane solver implementation for `OrcaCrowdSolver`.
1568impl OrcaCrowdSolver {
1569    /// Creates a new `OrcaCrowdSolver` with the supplied configuration defaults.
1570    ///
1571    /// # Arguments
1572    ///
1573    /// - `OrcaCrowdConfig` - Default neighbor search and horizon parameters.
1574    ///
1575    /// # Returns
1576    ///
1577    /// - `Self` - Empty ORCA crowd solver.
1578    #[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    /// Adds an agent to the crowd solver and returns its stable index.
1593    ///
1594    /// # Arguments
1595    ///
1596    /// - `OrcaAgent2D` - Agent descriptor to register.
1597    ///
1598    /// # Returns
1599    ///
1600    /// - `usize` - Index of the added agent.
1601    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    /// Updates an agent's preferred velocity (clamped to its maximum speed).
1615    ///
1616    /// # Arguments
1617    ///
1618    /// - `usize` - Target agent index.
1619    /// - `Vec2` - Desired preferred velocity vector.
1620    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    /// Solves collision-free velocities for all agents and advances their positions by `dt`.
1628    ///
1629    /// # Arguments
1630    ///
1631    /// - `f32` - Simulation time step in seconds (must be positive and finite).
1632    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}