Skip to main content

mapf_search/graph/
grid.rs

1//! A 4-connected grid with blocked cells ([`Grid`]).
2
3use alloc::vec;
4use alloc::vec::Vec;
5
6use super::{Graph, Vertex};
7
8/// A rectangular 4-connected grid. Cells are vertices in row-major order,
9/// `y * width + x`; blocked cells are vertices without edges.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Grid {
12    /// Number of columns. Never zero.
13    width: usize,
14    /// Number of rows. Never zero.
15    height: usize,
16    /// `blocked[y * width + x]` is `true` for obstacles. Length `width * height`.
17    blocked: Vec<bool>,
18}
19
20impl Grid {
21    /// Creates a grid of `width` by `height` free cells.
22    ///
23    /// # Panics
24    ///
25    /// Panics if `width` or `height` is zero.
26    #[must_use]
27    pub fn new(width: usize, height: usize) -> Self {
28        assert!(width > 0 && height > 0, "a grid needs at least one cell");
29
30        Self {
31            width,
32            height,
33            blocked: vec![false; width * height],
34        }
35    }
36
37    /// Parses a grid from rows of text: `.` is free, `@` is blocked.
38    ///
39    /// All rows must have the same length. Moving AI maps use more symbols; their parser
40    /// is planned separately.
41    ///
42    /// # Panics
43    ///
44    /// Panics if there are no rows, rows differ in length, or a row has another character.
45    #[must_use]
46    pub fn parse(rows: &[&str]) -> Self {
47        let width = rows.first().map_or(0, |row| row.len());
48        let mut grid = Self::new(width, rows.len());
49
50        for (y, row) in rows.iter().enumerate() {
51            assert_eq!(row.len(), width, "row {y} has a different length");
52            for (x, cell) in row.chars().enumerate() {
53                match cell {
54                    '.' => {}
55                    '@' => grid.block(x, y),
56                    other => panic!("unknown grid cell {other:?} at ({x}, {y})"),
57                }
58            }
59        }
60
61        grid
62    }
63
64    /// Marks the cell at `(x, y)` as an obstacle.
65    ///
66    /// # Panics
67    ///
68    /// Panics if `(x, y)` is outside the grid.
69    pub fn block(&mut self, x: usize, y: usize) {
70        let vertex = self.vertex(x, y);
71        self.blocked[vertex] = true;
72    }
73
74    /// The number of columns.
75    #[must_use]
76    pub fn width(&self) -> usize {
77        self.width
78    }
79
80    /// The number of rows.
81    #[must_use]
82    pub fn height(&self) -> usize {
83        self.height
84    }
85
86    /// The vertex of cell `(x, y)`.
87    ///
88    /// # Panics
89    ///
90    /// Panics if `(x, y)` is outside the grid.
91    #[must_use]
92    pub fn vertex(&self, x: usize, y: usize) -> Vertex {
93        assert!(
94            x < self.width && y < self.height,
95            "cell ({x}, {y}) is outside the grid"
96        );
97
98        y * self.width + x
99    }
100
101    /// The cell `(x, y)` of `vertex`.
102    #[must_use]
103    pub fn cell(&self, vertex: Vertex) -> (usize, usize) {
104        (vertex % self.width, vertex / self.width)
105    }
106
107    /// Returns `true` if `vertex` is an obstacle.
108    #[must_use]
109    pub fn is_blocked(&self, vertex: Vertex) -> bool {
110        self.blocked[vertex]
111    }
112}
113
114impl Graph for Grid {
115    fn vertex_count(&self) -> usize {
116        self.blocked.len()
117    }
118
119    fn neighbors(&self, vertex: Vertex, mut emit: impl FnMut(Vertex)) {
120        if self.is_blocked(vertex) {
121            return;
122        }
123
124        let (x, y) = self.cell(vertex);
125        let candidates = [
126            x.checked_sub(1).map(|left| (left, y)),
127            (x + 1 < self.width).then_some((x + 1, y)),
128            y.checked_sub(1).map(|up| (x, up)),
129            (y + 1 < self.height).then_some((x, y + 1)),
130        ];
131
132        for (nx, ny) in candidates.into_iter().flatten() {
133            let next = self.vertex(nx, ny);
134            if !self.is_blocked(next) {
135                emit(next);
136            }
137        }
138    }
139}