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, Heading, OrientedGraph, 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; read them with
40    /// [`parse_map`](crate::parse_map).
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 Grid {
115    /// The heading towards larger `x`.
116    pub const EAST: Heading = 0;
117    /// The heading towards smaller `y`, the row above.
118    pub const NORTH: Heading = 1;
119    /// The heading towards smaller `x`.
120    pub const WEST: Heading = 2;
121    /// The heading towards larger `y`, the row below.
122    pub const SOUTH: Heading = 3;
123}
124
125/// A grid as an [`OrientedGraph`]: four headings ([`Grid::EAST`], [`Grid::NORTH`],
126/// [`Grid::WEST`], [`Grid::SOUTH`], counter-clockwise), and a turn is a quarter turn either
127/// way, counter-clockwise first.
128///
129/// # Examples
130///
131/// ```
132/// use mapf_search::{Grid, OrientedGraph};
133///
134/// let grid = Grid::parse(&["..", "@."]);
135/// assert_eq!(grid.forward(grid.vertex(0, 0), Grid::EAST), Some(grid.vertex(1, 0)));
136/// assert_eq!(grid.forward(grid.vertex(0, 0), Grid::SOUTH), None);
137///
138/// let mut turns = Vec::new();
139/// grid.turns(Grid::EAST, |heading| turns.push(heading));
140/// assert_eq!(turns, [Grid::NORTH, Grid::SOUTH]);
141/// ```
142impl OrientedGraph for Grid {
143    fn heading_count(&self) -> usize {
144        4
145    }
146
147    fn forward(&self, vertex: Vertex, heading: Heading) -> Option<Vertex> {
148        if self.is_blocked(vertex) {
149            return None;
150        }
151
152        let (x, y) = self.cell(vertex);
153        let (nx, ny) = match heading {
154            Self::EAST => (x + 1, y),
155            Self::NORTH => (x, y.checked_sub(1)?),
156            Self::WEST => (x.checked_sub(1)?, y),
157            Self::SOUTH => (x, y + 1),
158            _ => return None,
159        };
160        if nx >= self.width || ny >= self.height {
161            return None;
162        }
163
164        let next = self.vertex(nx, ny);
165
166        (!self.is_blocked(next)).then_some(next)
167    }
168
169    fn turns(&self, heading: Heading, mut emit: impl FnMut(Heading)) {
170        emit((heading + 1) % 4);
171        emit((heading + 3) % 4);
172    }
173}
174
175impl Graph for Grid {
176    fn vertex_count(&self) -> usize {
177        self.blocked.len()
178    }
179
180    fn neighbors(&self, vertex: Vertex, mut emit: impl FnMut(Vertex)) {
181        if self.is_blocked(vertex) {
182            return;
183        }
184
185        let (x, y) = self.cell(vertex);
186        let candidates = [
187            x.checked_sub(1).map(|left| (left, y)),
188            (x + 1 < self.width).then_some((x + 1, y)),
189            y.checked_sub(1).map(|up| (x, up)),
190            (y + 1 < self.height).then_some((x, y + 1)),
191        ];
192
193        for (nx, ny) in candidates.into_iter().flatten() {
194            let next = self.vertex(nx, ny);
195            if !self.is_blocked(next) {
196                emit(next);
197            }
198        }
199    }
200}