1mod mesh;
3pub use mesh::*;
4mod route;
5mod search;
6pub use route::*;
7pub use search::*;
8use std::cmp::Ordering;
9use std::collections::BinaryHeap;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub struct Cell {
13 pub x: u32,
14 pub y: u32,
15}
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum NavigationError {
18 InvalidDimensions,
19 OutOfBounds,
20 BlockedEndpoint,
21 NoPath,
22 InvalidCost,
23 Capacity,
24 InvalidInput,
25 RevisionExhausted,
26}
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum Connectivity {
29 Four,
30 Eight,
31}
32
33static NEXT_GRID_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
34pub struct Grid {
35 identity: u64,
36 width: u32,
37 height: u32,
38 revision: u64,
39 costs: Vec<u16>, }
41impl Grid {
42 pub fn new(width: u32, height: u32) -> Result<Self, NavigationError> {
43 let count = width
44 .checked_mul(height)
45 .filter(|n| *n > 0 && *n <= 4_000_000)
46 .ok_or(NavigationError::InvalidDimensions)?;
47 #[allow(deprecated)]
49 let identity = NEXT_GRID_ID
50 .fetch_update(
51 std::sync::atomic::Ordering::Relaxed,
52 std::sync::atomic::Ordering::Relaxed,
53 |v| v.checked_add(1),
54 )
55 .map_err(|_| NavigationError::RevisionExhausted)?;
56 Ok(Self {
57 identity,
58 width,
59 height,
60 revision: 0,
61 costs: vec![1; count as usize],
62 })
63 }
64 pub fn width(&self) -> u32 {
65 self.width
66 }
67 pub fn height(&self) -> u32 {
68 self.height
69 }
70 pub fn set_blocked(&mut self, cell: Cell, blocked: bool) -> Result<(), NavigationError> {
71 let index = self.index(cell)?;
72 self.change_cost(index, if blocked { 0 } else { 1 })
73 }
74 pub fn set_cost(&mut self, cell: Cell, cost: u16) -> Result<(), NavigationError> {
75 if cost == 0 {
76 return Err(NavigationError::InvalidCost);
77 }
78 let index = self.index(cell)?;
79 self.change_cost(index, cost)
80 }
81 pub fn revision(&self) -> u64 {
82 self.revision
83 }
84 fn change_cost(&mut self, index: usize, cost: u16) -> Result<(), NavigationError> {
85 if self.costs[index] != cost {
86 self.revision = self
87 .revision
88 .checked_add(1)
89 .ok_or(NavigationError::RevisionExhausted)?;
90 self.costs[index] = cost;
91 }
92 Ok(())
93 }
94 pub fn walkable(&self, cell: Cell) -> bool {
95 self.index(cell).is_ok_and(|index| self.costs[index] != 0)
96 }
97 pub fn path(
98 &self,
99 start: Cell,
100 end: Cell,
101 connectivity: Connectivity,
102 ) -> Result<Vec<Cell>, NavigationError> {
103 let start_index = self.index(start)?;
104 let end_index = self.index(end)?;
105 if !self.walkable(start) || !self.walkable(end) {
106 return Err(NavigationError::BlockedEndpoint);
107 }
108 let mut distance = vec![u64::MAX; self.costs.len()];
109 let mut parent = vec![usize::MAX; self.costs.len()];
110 let mut open = BinaryHeap::new();
111 distance[start_index] = 0;
112 open.push(Visit {
113 index: start_index,
114 cost: 0,
115 estimate: heuristic(start, end, connectivity),
116 });
117 while let Some(visit) = open.pop() {
118 if visit.cost != distance[visit.index] {
119 continue;
120 }
121 if visit.index == end_index {
122 let mut route = Vec::new();
123 let mut index = end_index;
124 loop {
125 route.push(self.cell(index));
126 if index == start_index {
127 break;
128 }
129 index = parent[index];
130 }
131 route.reverse();
132 return Ok(route);
133 }
134 let current = self.cell(visit.index);
135 for (dx, dy) in [
136 (-1_i64, 0_i64),
137 (0, -1),
138 (1, 0),
139 (0, 1),
140 (-1, -1),
141 (1, -1),
142 (1, 1),
143 (-1, 1),
144 ] {
145 let diagonal = dx != 0 && dy != 0;
146 if diagonal && connectivity == Connectivity::Four {
147 continue;
148 }
149 let (x, y) = (i64::from(current.x) + dx, i64::from(current.y) + dy);
150 if x < 0 || y < 0 || x >= i64::from(self.width) || y >= i64::from(self.height) {
151 continue;
152 }
153 let next = Cell {
154 x: x as u32,
155 y: y as u32,
156 };
157 if !self.walkable(next) {
158 continue;
159 }
160 if diagonal
161 && (!self.walkable(Cell {
162 x: next.x,
163 y: current.y,
164 }) || !self.walkable(Cell {
165 x: current.x,
166 y: next.y,
167 }))
168 {
169 continue;
170 }
171 let index = self.index(next)?;
172 let cost =
173 visit.cost + u64::from(self.costs[index]) * if diagonal { 14 } else { 10 };
174 if cost < distance[index] {
175 distance[index] = cost;
176 parent[index] = visit.index;
177 open.push(Visit {
178 index,
179 cost,
180 estimate: cost + heuristic(next, end, connectivity),
181 });
182 }
183 }
184 }
185 Err(NavigationError::NoPath)
186 }
187 fn index(&self, cell: Cell) -> Result<usize, NavigationError> {
188 if cell.x < self.width && cell.y < self.height {
189 Ok((cell.y * self.width + cell.x) as usize)
190 } else {
191 Err(NavigationError::OutOfBounds)
192 }
193 }
194 fn cell(&self, index: usize) -> Cell {
195 Cell {
196 x: index as u32 % self.width,
197 y: index as u32 / self.width,
198 }
199 }
200}
201#[derive(Clone, Copy, Eq, PartialEq)]
202struct Visit {
203 index: usize,
204 cost: u64,
205 estimate: u64,
206}
207impl Ord for Visit {
208 fn cmp(&self, other: &Self) -> Ordering {
209 other
210 .estimate
211 .cmp(&self.estimate)
212 .then_with(|| other.cost.cmp(&self.cost))
213 .then_with(|| other.index.cmp(&self.index))
214 }
215}
216impl PartialOrd for Visit {
217 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
218 Some(self.cmp(other))
219 }
220}
221fn heuristic(a: Cell, b: Cell, connectivity: Connectivity) -> u64 {
222 let dx = u64::from(a.x.abs_diff(b.x));
223 let dy = u64::from(a.y.abs_diff(b.y));
224 if connectivity == Connectivity::Four {
225 (dx + dy) * 10
226 } else {
227 dx.min(dy) * 14 + dx.abs_diff(dy) * 10
228 }
229}
230pub fn arrive(position: [f32; 2], target: [f32; 2], max_speed: f32, slow_radius: f32) -> [f32; 2] {
233 if !position.into_iter().chain(target).all(f32::is_finite)
234 || !max_speed.is_finite()
235 || !slow_radius.is_finite()
236 || max_speed <= 0.0
237 || slow_radius <= 0.0
238 {
239 return [0.0; 2];
240 }
241 let d = [target[0] - position[0], target[1] - position[1]];
242 let length = d[0].hypot(d[1]);
243 if length <= f32::EPSILON || !length.is_finite() {
244 return [0.0; 2];
245 }
246 let scale = max_speed * (length / slow_radius).min(1.0) / length;
247 [d[0] * scale, d[1] * scale]
248}
249pub fn separation(position: [f32; 2], peers: &[[f32; 2]], radius: f32, max_speed: f32) -> [f32; 2] {
251 if !radius.is_finite() || radius <= 0.0 || !max_speed.is_finite() || max_speed <= 0.0 {
252 return [0.0; 2];
253 }
254 let mut sum = [0.0; 2];
255 for peer in peers {
256 let d = [position[0] - peer[0], position[1] - peer[1]];
257 let length = d[0].hypot(d[1]);
258 if length.is_finite() && length > 0.0001 && length < radius {
259 let weight = (1.0 - length / radius) / length;
260 sum[0] += d[0] * weight;
261 sum[1] += d[1] * weight;
262 }
263 }
264 arrive([0.0; 2], sum, max_speed, 1.0)
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270 fn c(x: u32, y: u32) -> Cell {
271 Cell { x, y }
272 }
273 #[test]
274 fn detours_around_walls_and_respects_costs() {
275 let mut grid = Grid::new(5, 3).unwrap();
276 grid.set_blocked(c(2, 1), true).unwrap();
277 let path = grid.path(c(0, 1), c(4, 1), Connectivity::Four).unwrap();
278 assert_eq!(path.len(), 7);
279 assert!(path.iter().all(|cell| grid.walkable(*cell)));
280 grid.set_blocked(c(2, 1), false).unwrap();
281 grid.set_cost(c(2, 1), 50).unwrap();
282 assert!(
283 !grid
284 .path(c(0, 1), c(4, 1), Connectivity::Four)
285 .unwrap()
286 .contains(&c(2, 1))
287 );
288 }
289 #[test]
290 fn diagonal_moves_do_not_cut_blocked_corners() {
291 let mut grid = Grid::new(2, 2).unwrap();
292 grid.set_blocked(c(1, 0), true).unwrap();
293 grid.set_blocked(c(0, 1), true).unwrap();
294 assert_eq!(
295 grid.path(c(0, 0), c(1, 1), Connectivity::Eight),
296 Err(NavigationError::NoPath)
297 );
298 grid.set_blocked(c(1, 0), false).unwrap();
299 assert_eq!(
300 grid.path(c(0, 0), c(1, 1), Connectivity::Eight)
301 .unwrap()
302 .len(),
303 3
304 );
305 }
306 #[test]
307 fn boundaries_empty_routes_and_invalid_dimensions() {
308 assert!(matches!(
309 Grid::new(0, 3),
310 Err(NavigationError::InvalidDimensions)
311 ));
312 let grid = Grid::new(3, 3).unwrap();
313 assert_eq!(
314 grid.path(c(1, 1), c(1, 1), Connectivity::Four).unwrap(),
315 vec![c(1, 1)]
316 );
317 assert_eq!(
318 grid.path(c(5, 0), c(0, 0), Connectivity::Four),
319 Err(NavigationError::OutOfBounds)
320 );
321 assert_eq!(
322 grid.path(c(0, 0), c(2, 2), Connectivity::Eight)
323 .unwrap()
324 .len(),
325 3
326 );
327 }
328 #[test]
329 fn steering_stops_at_target_and_slows_on_arrival() {
330 assert_eq!(arrive([1.0, 0.0], [1.0, 0.0], 4.0, 2.0), [0.0; 2]);
331 assert_eq!(arrive([0.0; 2], [1.0, 0.0], 4.0, 2.0), [2.0, 0.0]);
332 assert_eq!(arrive([0.0; 2], [f32::NAN, 0.0], 4.0, 2.0), [0.0; 2]);
333 assert!(separation([0.0; 2], &[[1.0, 0.0]], 2.0, 4.0)[0] < 0.0);
334 }
335}