Skip to main content

unbanished_path/pathfind/
regions.rs

1//! Walkable regions: flood fills that number the connected walkable areas.
2
3use super::*;
4
5/// Label connected walkable cells in scan order, starting at 1 (0 = none).
6///
7/// Original: `FUN_1400a1950`.
8pub fn regions(size: usize, types: &[CellType]) -> Vec<u16> {
9    let mut region = vec![0u16; types.len()];
10    let mut id: u16 = 1;
11    for i in 0..types.len() {
12        if bit(types[i]) & WALKABLE != 0 && region[i] == 0 {
13            fill(size, types, &mut region, i, id);
14            id = id.wrapping_add(1);
15        }
16    }
17    region
18}
19
20/// `FUN_1400a1640`: FIFO scanline fill. A run is widened by one cell for the rows above and
21/// below only when that cell is strictly inside the row (`row_start < left - 1`,
22/// `right + 1 < row_end`), so runs touch diagonal neighbours except at the map edge.
23pub(super) fn fill(size: usize, types: &[CellType], region: &mut [u16], start: usize, id: u16) {
24    let n = size as i32;
25    let walk = |c: i32| bit(types[c as usize]) & WALKABLE != 0;
26    let mut queue = VecDeque::from([start as i32]);
27    while let Some(c) = queue.pop_front() {
28        let row = c / n;
29        let (row_start, row_end) = (n * row, (row + 1) * n - 1);
30        if region[c as usize] != 0 || !walk(c) {
31            continue;
32        }
33        let mut left = c;
34        while left - 1 >= row_start && walk(left - 1) {
35            left -= 1;
36        }
37        let mut right = c;
38        while right + 1 <= row_end && walk(right + 1) {
39            right += 1;
40        }
41        for k in left..=right {
42            region[k as usize] = id;
43        }
44        if row_start < left - 1 {
45            left -= 1;
46        }
47        if right + 1 < row_end {
48            right += 1;
49        }
50        for (ok, step) in [(row > 0, -n), (row < n - 1, n)] {
51            if !ok {
52                continue;
53            }
54            for u in left..=right {
55                let k = u + step;
56                if region[k as usize] == 0 && walk(k) {
57                    queue.push_back(k);
58                }
59            }
60        }
61    }
62}