Skip to main content

unbanished_path/
pathfind.rs

1//! Path finding over the map's cells: the walkable regions and the A* pathfinder.
2//!
3//! - [`regions`] gives every walkable cell the number of its connected region. A request between
4//!   two regions fails at once, without a search.
5//! - [`Pathfinder`] is the A* search, with a cost for each cell type ([`mode_costs`]).
6//! - [`request`] checks a request as the original does, then searches.
7//! - [`nearest_neighbour`] finds the allowed cell next to a cell that is nearest to a target.
8//!
9//! The original solves paths on a worker thread, and a walker polls for the result. The port
10//! solves a path when it is requested; the walker reads the result in a later iteration, not in
11//! the update that follows its start in the same pass, so the timing is the same.
12//!
13//! See [Citizens](https://tanepiper.github.io/unbanished/topics/citizens) for how citizens use it.
14
15mod regions;
16pub use regions::regions;
17
18// Original: regions FUN_1400a1950 / FUN_1400a1640 (map cell +0x26); the path manager at map
19// +0x68 (FUN_1400abcc0), whose worker thread runs queued commands (FUN_1400ab900: 0 walk mask,
20// 1 per-type cost, 4 search options, 5 find path); A* FUN_14001d760 / FUN_14001d9a0; request
21// validation FUN_1400a2480; per-mover cost tables FUN_1400a3a20; nearest neighbour FUN_1400a21c0.
22// See docs/CITIZEN-AI.md.
23
24use std::cmp::Reverse;
25use std::collections::{BTreeSet, VecDeque};
26
27use unbanished_terrain::CellType;
28
29/// Cell types a walker may enter (0–4, 9–11).
30pub const WALKABLE: u32 = 0xe1f;
31/// Water and blocking types (5–8): requests touching them skip the region check.
32pub const WATER: u32 = 0x1e0;
33/// Longest path a search returns.
34///
35/// Original: `FUN_14001d760`.
36pub const MAX_PATH: usize = 0x4000;
37
38/// The bit of a cell type in a type mask such as [`WALKABLE`].
39pub fn bit(t: CellType) -> u32 {
40    1u32 << (t.0 & 0x1f)
41}
42
43/// Whether a walker may enter a cell of this type (the test [`regions`] labels by).
44pub fn walkable(t: CellType) -> bool {
45    bit(t) & WALKABLE != 0
46}
47
48// +0x470
49/// Per-type cost tables a mover selects (MoveTo) and whether the search may step diagonally.
50///
51/// Original: `FUN_1400a3a20`.
52pub fn mode_costs(mode: u32) -> Option<(&'static [(u8, i32)], bool)> {
53    const CITIZEN: [(u8, i32); 11] = [
54        (0, 3),
55        (1, 3),
56        (2, 4),
57        (3, 8),
58        (4, 16),
59        (5, 16),
60        (6, 16),
61        (7, 16),
62        (8, 16),
63        (9, 3),
64        (10, 4),
65    ];
66    const MODE1: [(u8, i32); 11] = [
67        (0, 16),
68        (1, 16),
69        (2, 4),
70        (3, 4),
71        (4, 16),
72        (5, 16),
73        (6, 16),
74        (7, 4),
75        (8, 4),
76        (9, 4),
77        (10, 4),
78    ];
79    const UNIFORM: [(u8, i32); 11] = [
80        (0, 1),
81        (1, 1),
82        (2, 1),
83        (3, 1),
84        (4, 1),
85        (5, 1),
86        (6, 1),
87        (7, 1),
88        (8, 1),
89        (9, 1),
90        (10, 1),
91    ];
92    const MODE3: [(u8, i32); 11] = [
93        (0, 10),
94        (1, 10),
95        (2, 10),
96        (3, 10),
97        (4, 10),
98        (5, 10),
99        (6, 10),
100        (7, 5),
101        (8, 1),
102        (9, 5),
103        (10, 10),
104    ];
105    match mode {
106        0 => Some((&CITIZEN, true)),
107        1 => Some((&MODE1, true)),
108        2 => Some((&UNIFORM, false)),
109        3 => Some((&MODE3, true)),
110        _ => None,
111    }
112}
113
114#[derive(Clone, Copy, Default)]
115struct Node {
116    parent: i32,
117    /// `+0x0c` / `+0x10`: equal to the search id while open / closed.
118    open: i32,
119    closed: i32,
120    g: i32,
121    /// Open-set key while open: `(f, counter)`.
122    key: (i32, i32),
123}
124
125// The path manager is at map +0x68, its grid at +0x78.
126/// The pathfinder: the map's cells, the cost of each cell type, and the state of the A* search.
127///
128/// Original: `FUN_1400abcc0` (the path manager).
129pub struct Pathfinder {
130    size: i32,
131    /// Path grid bytes: cell type `& 0x7f`, `0x80` blocked (commands 2 and 3).
132    cells: Vec<u8>,
133    /// `+0x50`: cost per type (command 1).
134    costs: [i32; 32],
135    // +0xd0
136    /// Allowed types (command 0).
137    pub mask: u32,
138    /// `+0xd4..+0xd6` (command 4): diagonal steps, Manhattan heuristic, honour blocked bit.
139    diagonal: bool,
140    manhattan: bool,
141    check_blocked: bool,
142    search: i32,
143    counter: i32,
144    nodes: Vec<Node>,
145    open: BTreeSet<((i32, Reverse<i32>), i32)>,
146}
147
148impl Pathfinder {
149    /// Built from the map with diagonal steps on.
150    ///
151    /// Original: `FUN_1400a3d90`.
152    pub fn new(size: usize, types: &[CellType]) -> Pathfinder {
153        Pathfinder {
154            size: size as i32,
155            cells: types.iter().map(|t| t.0 & 0x7f).collect(),
156            costs: [1; 32],
157            mask: 0,
158            diagonal: true,
159            manhattan: false,
160            check_blocked: false,
161            search: 0,
162            counter: 0,
163            nodes: vec![Node::default(); types.len()],
164            open: BTreeSet::new(),
165        }
166    }
167
168    /// Command 2: a cell's type changed.
169    pub fn set_type(&mut self, cell: usize, t: CellType) {
170        self.cells[cell] = self.cells[cell] & 0x80 | t.0 & 0x7f;
171    }
172
173    /// Command 3.
174    pub fn set_blocked(&mut self, cell: usize, blocked: bool) {
175        self.cells[cell] = self.cells[cell] & 0x7f | if blocked { 0x80 } else { 0 };
176    }
177
178    /// Select a mover's cost table and diagonal option.
179    ///
180    /// Original: `FUN_1400a3a20`.
181    pub fn set_mode(&mut self, mode: u32) {
182        if let Some((costs, diagonal)) = mode_costs(mode) {
183            for &(t, c) in costs {
184                self.costs[t as usize] = c;
185            }
186            self.diagonal = diagonal;
187            self.manhattan = false;
188            self.check_blocked = false;
189        }
190    }
191
192    /// `FUN_1400ab390`: neighbour `dir` of `cell`, if inside, unblocked and allowed.
193    fn neighbour(&self, cell: i32, dir: usize) -> Option<i32> {
194        let n = self.size;
195        let (mut x, mut y) = (cell % n, cell / n);
196        match dir {
197            0 => x += 1,
198            1 => x -= 1,
199            2 => y += 1,
200            3 => y -= 1,
201            4 => (x, y) = (x + 1, y + 1),
202            5 => (x, y) = (x + 1, y - 1),
203            6 => (x, y) = (x - 1, y - 1),
204            _ => (x, y) = (x - 1, y + 1),
205        }
206        if x < 0 || x >= n || y < 0 || y >= n {
207            return None;
208        }
209        let k = n * y + x;
210        let byte = self.cells[k as usize];
211        if self.check_blocked && byte & 0x80 != 0 {
212            return None;
213        }
214        (self.mask >> (byte & 0x1f) & 1 != 0).then_some(k)
215    }
216
217    /// `FUN_1400ab500`.
218    fn heuristic(&self, a: i32, b: i32) -> i32 {
219        let n = self.size;
220        let dx = (a % n - b % n).abs();
221        let dy = (a / n - b / n).abs();
222        if self.diagonal {
223            (dy + dx) * 10 - 6 * dx.min(dy)
224        } else if self.manhattan {
225            (dy + dx) * 10
226        } else {
227            dy.max(dx) * 10
228        }
229    }
230
231    /// `FUN_14001dc80`: open (or reopen) `cell` with a new parent and cost.
232    fn push(&mut self, cell: i32, parent: i32, g: i32, f: i32) {
233        let node = self.nodes[cell as usize];
234        if node.open == self.search {
235            self.open.remove(&((node.key.0, Reverse(node.key.1)), cell));
236        }
237        let counter = self.counter;
238        self.counter += 1;
239        let node = &mut self.nodes[cell as usize];
240        node.closed = node.closed.wrapping_sub(1);
241        node.parent = parent;
242        node.open = self.search;
243        node.g = g;
244        node.key = (f, counter);
245        self.open.insert(((f, Reverse(counter)), cell));
246    }
247
248    /// `FUN_14001d9a0`: A* from `from` to `to`. The open set orders by `f`, then by the most
249    /// recent insertion (the AVL comparator at `FUN_14001ddb0`).
250    fn solve(&mut self, from: i32, to: i32) -> bool {
251        self.open.clear();
252        self.counter = 0;
253        let h = self.heuristic(from, to);
254        self.push(from, -1, 0, h);
255        let n = self.size;
256        while let Some(&first) = self.open.first() {
257            let cur = first.1;
258            if cur == to {
259                return true;
260            }
261            self.open.remove(&first);
262            let search = self.search;
263            let node = &mut self.nodes[cur as usize];
264            node.open = node.open.wrapping_sub(1);
265            node.closed = search;
266            let g_cur = node.g;
267            for dir in 0..if self.diagonal { 8 } else { 4 } {
268                let Some(nb) = self.neighbour(cur, dir) else {
269                    continue;
270                };
271                let straight = (cur % n - nb % n).abs() + (cur / n - nb / n).abs() == 1;
272                let cost = self.costs[(self.cells[nb as usize] & 0x7f) as usize & 31]
273                    * if straight { 10 } else { 14 };
274                let g = g_cur + cost;
275                let node = &mut self.nodes[nb as usize];
276                if node.closed == search {
277                    if node.g <= g {
278                        continue;
279                    }
280                    node.closed = node.closed.wrapping_sub(1);
281                }
282                if node.open != search || g < node.g {
283                    let f = self.heuristic(nb, to) + g;
284                    self.push(nb, cur, g, f);
285                }
286            }
287        }
288        false
289    }
290
291    /// The cells of a road from one cell to another: every cell type costs 1, there are no
292    /// diagonal steps, and blocked cells and cells outside `mask` are avoided. `blocked` marks the
293    /// cells that have an occupant.
294    ///
295    /// Original: `FUN_1400a22d0`; its search options `FUN_1400abd80(0, manhattan, 1)`.
296    pub fn find_road(
297        &mut self,
298        from: i32,
299        to: i32,
300        mask: u32,
301        manhattan: bool,
302        blocked: &[bool],
303    ) -> Option<Vec<i32>> {
304        let saved = (
305            self.costs,
306            self.diagonal,
307            self.manhattan,
308            self.check_blocked,
309            self.mask,
310        );
311        self.costs = [1; 32];
312        self.diagonal = false;
313        self.manhattan = manhattan;
314        self.check_blocked = true;
315        self.mask = mask;
316        let old: Vec<u8> = self.cells.clone();
317        for (c, &b) in self.cells.iter_mut().zip(blocked) {
318            if b {
319                *c |= 0x80;
320            }
321        }
322        let path = self.find(from, to);
323        self.cells = old;
324        (
325            self.costs,
326            self.diagonal,
327            self.manhattan,
328            self.check_blocked,
329            self.mask,
330        ) = saved;
331        path
332    }
333
334    /// Run `search` and put the costs, diagonal, heuristic, blocked check and mask back.
335    pub fn keeping_state<T>(&mut self, search: impl FnOnce(&mut Self) -> T) -> T {
336        let saved = (
337            self.costs,
338            self.diagonal,
339            self.manhattan,
340            self.check_blocked,
341            self.mask,
342        );
343        let out = search(self);
344        (
345            self.costs,
346            self.diagonal,
347            self.manhattan,
348            self.check_blocked,
349            self.mask,
350        ) = saved;
351        out
352    }
353
354    /// The cells from `from` to `to` inclusive, or `None`.
355    ///
356    /// Original: `FUN_14001d760`.
357    pub fn find(&mut self, from: i32, to: i32) -> Option<Vec<i32>> {
358        self.search = self.search.wrapping_add(1);
359        if !self.solve(from, to) {
360            return None;
361        }
362        let mut path = Vec::new();
363        let mut c = to;
364        while c != -1 {
365            path.push(c);
366            c = self.nodes[c as usize].parent;
367        }
368        path.reverse();
369        path.truncate(MAX_PATH);
370        Some(path)
371    }
372}
373
374/// Validate a request (both end types join the mask; without water types both ends must share a
375/// non-zero region), set the mask and search.
376///
377/// Original: `FUN_1400a2480`.
378pub fn request(
379    finder: &mut Pathfinder,
380    types: &[CellType],
381    region: &[u16],
382    flags: u32,
383    from: i32,
384    to: i32,
385) -> Option<Vec<i32>> {
386    let (a, b) = (bit(types[from as usize]), bit(types[to as usize]));
387    let mut flags = flags | a | b;
388    if flags & WATER == 0 {
389        let (ra, rb) = (region[from as usize], region[to as usize]);
390        if ra == 0 || rb == 0 || ra != rb {
391            return None;
392        }
393    }
394    if flags & 0x180 != 0 {
395        flags |= 0x180;
396    }
397    finder.mask = flags;
398    finder.find(from, to)
399}
400
401/// Of the 8 cells around `cell` whose type is in `mask`, the one nearest (squared cell distance) to
402/// `toward`; the first found wins ties (x outer, y inner).
403///
404/// Original: `FUN_1400a21c0`.
405pub fn nearest_neighbour(
406    size: usize,
407    types: &[CellType],
408    cell: i32,
409    toward: i32,
410    mask: u32,
411) -> Option<i32> {
412    let n = size as i32;
413    let (cx, cy) = (cell % n, cell / n);
414    let mut best: Option<(i32, i32)> = None;
415    for dx in -1..=1 {
416        for dy in -1..=1 {
417            let (x, y) = (cx + dx, cy + dy);
418            if (dx == 0 && dy == 0) || x < 0 || y < 0 || x >= n || y >= n {
419                continue;
420            }
421            let k = n * y + x;
422            if mask & bit(types[k as usize]) == 0 {
423                continue;
424            }
425            let (ex, ey) = (k / n - toward / n, k % n - toward % n);
426            let d = ex * ex + ey * ey;
427            if best.is_none_or(|(_, bd)| d < bd) {
428                best = Some((k, d));
429            }
430        }
431    }
432    best.map(|(k, _)| k)
433}
434
435#[cfg(test)]
436mod tests;