src/pathfinding.rs 19.1 K · 590 lines · raw · history

1 use std::{
2 cmp::Reverse,
3 collections::{BinaryHeap, HashSet, VecDeque},
4 };
5
6 use bevy::prelude::*;
7
8 use crate::world::{CHEAPEST_MOVE_COST, WorldMap};
9
10 const STRAIGHT: u32 = 10;
11 const DIAGONAL: u32 = 14;
12 const MIN_TERRAIN_COST: u32 = CHEAPEST_MOVE_COST;
13
14 const NEIGHBORS: [IVec2; 8] = [
15 IVec2::new(1, 0),
16 IVec2::new(-1, 0),
17 IVec2::new(0, 1),
18 IVec2::new(0, -1),
19 IVec2::new(1, 1),
20 IVec2::new(1, -1),
21 IVec2::new(-1, 1),
22 IVec2::new(-1, -1),
23 ];
24
25 pub fn find_path(map: &WorldMap, start: UVec2, goal: UVec2) -> Option<Vec<UVec2>> {
26 map.move_cost(goal.as_ivec2())?;
27 let goal = goal.as_ivec2();
28 astar(map, start, |p| p == goal, |p| octile(p, goal))
29 }
30
31 pub fn find_path_adjacent(map: &WorldMap, start: UVec2, target: UVec2) -> Option<Vec<UVec2>> {
32 let target = target.as_ivec2();
33 astar(
34 map,
35 start,
36 |p| is_adjacent(p, target),
37 |p| octile(p, target).saturating_sub(DIAGONAL * MIN_TERRAIN_COST),
38 )
39 }
40
41 pub fn is_adjacent(a: IVec2, b: IVec2) -> bool {
42 a != b && (a - b).abs().max_element() == 1
43 }
44
45 pub fn can_step(map: &WorldMap, from: IVec2, step: IVec2) -> bool {
46 let next = from + step;
47 map.move_cost(next).is_some()
48 && (step.x == 0
49 || step.y == 0
50 || (map.move_cost(from + IVec2::new(step.x, 0)).is_some()
51 && map.move_cost(from + IVec2::new(0, step.y)).is_some()))
52 }
53
54 pub fn nearest_tile(
55 map: &WorldMap,
56 start: UVec2,
57 max_tiles: usize,
58 mut is_target: impl FnMut(UVec2) -> bool,
59 ) -> Option<UVec2> {
60 let index = |p: UVec2| (p.y * map.size.x + p.x) as usize;
61 let mut seen = vec![false; (map.size.x * map.size.y) as usize];
62 let mut seen_count = 1;
63 if let Some(cell) = seen.get_mut(index(start)) {
64 *cell = true;
65 }
66 let mut queue = VecDeque::from([start]);
67 while let Some(pos) = queue.pop_front() {
68 if is_target(pos) {
69 return Some(pos);
70 }
71 if seen_count >= max_tiles {
72 continue;
73 }
74 for step in NEIGHBORS {
75 let next = pos.as_ivec2() + step;
76 if can_step(map, pos.as_ivec2(), step) && !seen[index(next.as_uvec2())] {
77 seen[index(next.as_uvec2())] = true;
78 seen_count += 1;
79 queue.push_back(next.as_uvec2());
80 }
81 }
82 }
83 None
84 }
85
86 #[derive(Default, Debug, Clone)]
87 pub struct Reach {
88 width: u32,
89 seen: Vec<bool>,
90 }
91
92 #[derive(Resource, Default, Debug, Clone)]
93 pub struct ColonyReach(pub Option<Reach>);
94
95 impl ColonyReach {
96 pub fn allows(&self, tile: UVec2) -> bool {
97 self.0.as_ref().is_none_or(|reach| reach.contains(tile))
98 }
99
100 pub fn allows_near(&self, tile: UVec2) -> bool {
101 self.0.as_ref().is_none_or(|reach| reach.near(tile))
102 }
103
104 pub fn nearest(
105 &self,
106 map: &WorldMap,
107 from: UVec2,
108 max_tiles: usize,
109 targets: &HashSet<UVec2>,
110 ) -> Option<UVec2> {
111 match &self.0 {
112 Some(reach) if reach.contains(from) => targets
113 .iter()
114 .filter(|t| reach.contains(**t))
115 .min_by_key(|t| {
116 let d = t.as_ivec2() - from.as_ivec2();
117 (d.length_squared(), t.y, t.x)
118 })
119 .copied(),
120 _ => nearest_of(map, from, max_tiles, targets),
121 }
122 }
123 }
124
125 impl Reach {
126 pub fn flood(map: &WorldMap, start: UVec2) -> Self {
127 let width = map.size.x;
128 let mut seen = vec![false; map.size.element_product() as usize];
129 let index = |p: UVec2| (p.y * width + p.x) as usize;
130 if map.move_cost(start.as_ivec2()).is_some() {
131 seen[index(start)] = true;
132 let mut queue = VecDeque::from([start]);
133 while let Some(pos) = queue.pop_front() {
134 for step in NEIGHBORS {
135 let next = pos.as_ivec2() + step;
136 if can_step(map, pos.as_ivec2(), step) && !seen[index(next.as_uvec2())] {
137 seen[index(next.as_uvec2())] = true;
138 queue.push_back(next.as_uvec2());
139 }
140 }
141 }
142 }
143 Self { width, seen }
144 }
145
146 pub fn contains(&self, p: UVec2) -> bool {
147 p.x < self.width
148 && self
149 .seen
150 .get((p.y * self.width + p.x) as usize)
151 .copied()
152 .unwrap_or(false)
153 }
154
155 pub fn near(&self, p: UVec2) -> bool {
156 (-1..=1).any(|dy| {
157 (-1..=1).any(|dx| {
158 let q = p.as_ivec2() + IVec2::new(dx, dy);
159 q.min_element() >= 0 && self.contains(q.as_uvec2())
160 })
161 })
162 }
163 }
164
165 pub fn search_reach(max_tiles: usize) -> u32 {
166 ((max_tiles as f32).sqrt() / 2.0).ceil() as u32
167 }
168
169 pub fn nearest_of(
170 map: &WorldMap,
171 start: UVec2,
172 max_tiles: usize,
173 targets: &HashSet<UVec2>,
174 ) -> Option<UVec2> {
175 let reach = search_reach(max_tiles) as i32;
176 let in_reach = |p: &&UVec2| (p.as_ivec2() - start.as_ivec2()).abs().max_element() <= reach;
177 if !targets.iter().any(|p| in_reach(&p)) {
178 return None;
179 }
180 nearest_tile(map, start, max_tiles, |p| targets.contains(&p))
181 }
182
183 fn octile(a: IVec2, b: IVec2) -> u32 {
184 let d = (a - b).abs();
185 let (min, max) = (d.x.min(d.y) as u32, d.x.max(d.y) as u32);
186 (DIAGONAL * min + STRAIGHT * (max - min)) * MIN_TERRAIN_COST
187 }
188
189 #[derive(Default)]
190 struct Scratch {
191 generation: u32,
192 stamp: Vec<u32>,
193 cost: Vec<u32>,
194 from: Vec<IVec2>,
195 open: BinaryHeap<Reverse<(u32, i32, i32)>>,
196 }
197
198 thread_local! {
199 static SCRATCH: std::cell::RefCell<Scratch> = std::cell::RefCell::new(Scratch::default());
200 }
201
202 fn astar(
203 map: &WorldMap,
204 start: UVec2,
205 is_goal: impl Fn(IVec2) -> bool,
206 heuristic: impl Fn(IVec2) -> u32,
207 ) -> Option<Vec<UVec2>> {
208 astar_limited(map, start, is_goal, heuristic, usize::MAX)
209 }
210
211 fn astar_limited(
212 map: &WorldMap,
213 start: UVec2,
214 is_goal: impl Fn(IVec2) -> bool,
215 heuristic: impl Fn(IVec2) -> u32,
216 max_expanded: usize,
217 ) -> Option<Vec<UVec2>> {
218 let start = start.as_ivec2();
219 if !map.in_bounds(start) {
220 return None;
221 }
222 if is_goal(start) {
223 return Some(vec![]);
224 }
225 SCRATCH.with_borrow_mut(|scratch| {
226 let tiles = map.size.element_product() as usize;
227 if scratch.stamp.len() != tiles {
228 *scratch = Scratch {
229 stamp: vec![0; tiles],
230 cost: vec![0; tiles],
231 from: vec![IVec2::ZERO; tiles],
232 ..default()
233 };
234 }
235 scratch.generation = scratch.generation.wrapping_add(1);
236 if scratch.generation == 0 {
237 scratch.stamp.fill(0);
238 scratch.generation = 1;
239 }
240 let Scratch {
241 generation,
242 stamp,
243 cost,
244 from,
245 open,
246 } = scratch;
247 let generation = *generation;
248 let width = map.size.x as usize;
249 let index = |p: IVec2| p.y as usize * width + p.x as usize;
250 open.clear();
251 stamp[index(start)] = generation;
252 cost[index(start)] = 0;
253 from[index(start)] = start;
254 open.push(Reverse((heuristic(start), start.x, start.y)));
255 let mut expanded = 0;
256 while let Some(Reverse((_, x, y))) = open.pop() {
257 let current = IVec2::new(x, y);
258 if is_goal(current) {
259 let mut path = vec![current.as_uvec2()];
260 let mut at = current;
261 while from[index(at)] != start {
262 at = from[index(at)];
263 path.push(at.as_uvec2());
264 }
265 path.reverse();
266 return Some(path);
267 }
268 expanded += 1;
269 if expanded > max_expanded {
270 return None;
271 }
272 let current_cost = cost[index(current)];
273 for step in NEIGHBORS {
274 let next = current + step;
275 if !can_step(map, current, step) {
276 continue;
277 }
278 let Some(terrain_cost) = map.step_cost(current, next) else {
279 continue;
280 };
281 let diagonal = step.x != 0 && step.y != 0;
282 let base = if diagonal { DIAGONAL } else { STRAIGHT };
283 let new_cost = current_cost + base * terrain_cost;
284 let i = index(next);
285 if stamp[i] != generation || new_cost < cost[i] {
286 stamp[i] = generation;
287 cost[i] = new_cost;
288 from[i] = current;
289 open.push(Reverse((new_cost + heuristic(next), next.x, next.y)));
290 }
291 }
292 }
293 None
294 })
295 }
296
297 pub const WANDER_SEARCH: usize = 800;
298
299 pub fn find_nearby_path(
300 map: &WorldMap,
301 start: UVec2,
302 goal: UVec2,
303 max_expanded: usize,
304 ) -> Option<Vec<UVec2>> {
305 map.move_cost(goal.as_ivec2())?;
306 let goal = goal.as_ivec2();
307 astar_limited(map, start, |p| p == goal, |p| octile(p, goal), max_expanded)
308 }
309
310 #[cfg(test)]
311 mod tests {
312 use super::*;
313 use crate::world::Terrain;
314
315 // Inside the colony's flooded reach, the nearest reachable target by distance stands in for
316 // a fresh flood fill per search; with 40+ colonists those floods dominated job choice.
317 #[test]
318 fn colony_reach_picks_the_nearest_reachable_target() {
319 let mut map = WorldMap::filled(UVec2::splat(30), Terrain::Grass);
320 for y in 0..30 {
321 map.set(UVec2::new(10, y), Terrain::DeepWater);
322 }
323 let reach = ColonyReach(Some(Reach::flood(&map, UVec2::new(5, 5))));
324 let across = UVec2::new(12, 5);
325 let far = UVec2::new(5, 20);
326 let targets = HashSet::from([across, far]);
327 assert_eq!(
328 reach.nearest(&map, UVec2::new(5, 5), 100, &targets),
329 Some(far)
330 );
331 let elsewhere = UVec2::new(20, 5);
332 assert_eq!(reach.nearest(&map, elsewhere, 1000, &targets), Some(across));
333 }
334
335 // Wandering picks random nearby goals; one walled off by a river or cliff made A* search the
336 // whole connected region before failing. Short trips cap the search instead.
337 #[test]
338 fn nearby_paths_give_up_early_on_unreachable_goals() {
339 let mut map = WorldMap::filled(UVec2::splat(100), Terrain::Grass);
340 for y in 0..100 {
341 map.set(UVec2::new(50, y), Terrain::DeepWater);
342 }
343 let start = UVec2::new(45, 50);
344 assert!(find_nearby_path(&map, start, UVec2::new(40, 52), 200).is_some());
345 assert_eq!(find_nearby_path(&map, start, UVec2::new(55, 50), 200), None);
346 assert_eq!(find_path(&map, start, UVec2::new(55, 50)), None);
347 }
348
349 // Target searches must use the same no-corner-cutting rule as A*. A stack on a tile touching
350 // the colony only diagonally between two rocks was "found" by the search, A* then explored
351 // the whole map before failing, and the job was picked again at once: ~10 ms, many times a
352 // second, which made Max speed crawl on a 50-day colony.
353 #[test]
354 fn searches_never_pick_targets_that_paths_cannot_reach() {
355 let mut map = WorldMap::filled(UVec2::splat(6), Terrain::Grass);
356 for y in 3..6 {
357 for x in 0..6 {
358 map.set(UVec2::new(x, y), Terrain::Stone);
359 }
360 }
361 map.set(UVec2::new(2, 3), Terrain::Grass);
362 map.set(UVec2::new(3, 4), Terrain::Gravel);
363 let pocket = UVec2::new(3, 4);
364 assert!(map.move_cost(IVec2::new(2, 3)).is_some());
365 assert_eq!(find_path(&map, UVec2::ZERO, pocket), None);
366 let targets = HashSet::from([pocket]);
367 assert_eq!(nearest_of(&map, UVec2::ZERO, 100, &targets), None);
368 }
369
370 // Idle colonists look for food and cooking input several times per game minute. A stack far
371 // beyond what the flood fill can cover made every one of those searches visit the full tile
372 // budget and fail, which dominated frame time at high speeds. The reach is a radius: the
373 // flood fills a square, so its half-width (not its width, as it once was) bounds it.
374 #[test]
375 fn target_searches_skip_targets_beyond_their_reach() {
376 let map = WorldMap::filled(UVec2::splat(300), Terrain::Grass);
377 let start = UVec2::splat(10);
378 let max_tiles = 400;
379 let near = start + UVec2::new(search_reach(max_tiles) / 4, 0);
380 let far = start + UVec2::new(search_reach(max_tiles) + 1, 0);
381 assert_eq!(
382 nearest_of(&map, start, max_tiles, &HashSet::from([far])),
383 None
384 );
385 assert_eq!(
386 nearest_of(&map, start, max_tiles, &HashSet::from([far, near])),
387 Some(near)
388 );
389 let edge = start + UVec2::new(search_reach(max_tiles) - 1, 0);
390 assert_eq!(
391 nearest_of(&map, start, max_tiles, &HashSet::from([edge])),
392 Some(edge)
393 );
394 }
395
396 fn map_from(rows: &[&str]) -> WorldMap {
397 let size = UVec2::new(rows[0].len() as u32, rows.len() as u32);
398 let mut map = WorldMap::filled(size, Terrain::Grass);
399 for (row, line) in rows.iter().enumerate() {
400 let y = size.y - 1 - row as u32;
401 for (x, c) in line.chars().enumerate() {
402 let terrain = match c {
403 '#' => Terrain::Stone,
404 '~' => Terrain::ShallowWater,
405 _ => Terrain::Grass,
406 };
407 map.set(UVec2::new(x as u32, y), terrain);
408 }
409 }
410 map
411 }
412
413 fn is_connected(start: UVec2, path: &[UVec2]) -> bool {
414 std::iter::once(start)
415 .chain(path.iter().copied())
416 .collect::<Vec<_>>()
417 .windows(2)
418 .all(|w| (w[0].as_ivec2() - w[1].as_ivec2()).abs().max_element() == 1)
419 }
420
421 #[test]
422 fn path_excludes_start_and_ends_at_goal() {
423 let map = map_from(&["....."]);
424 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
425 assert_eq!(
426 path,
427 vec![
428 UVec2::new(1, 0),
429 UVec2::new(2, 0),
430 UVec2::new(3, 0),
431 UVec2::new(4, 0)
432 ]
433 );
434 }
435
436 #[test]
437 fn path_to_self_is_empty() {
438 let map = map_from(&["..."]);
439 assert_eq!(find_path(&map, UVec2::ZERO, UVec2::ZERO), Some(vec![]));
440 }
441
442 #[test]
443 fn path_goes_around_walls() {
444 let map = map_from(&[
445 ".....", //
446 ".###.", ".#.#.", "...#.",
447 ]);
448 let start = UVec2::new(2, 1);
449 let goal = UVec2::new(4, 0);
450 let path = find_path(&map, start, goal).unwrap();
451 assert!(is_connected(start, &path));
452 assert_eq!(path.last(), Some(&goal));
453 assert!(path.iter().all(|p| map.move_cost(p.as_ivec2()).is_some()));
454 }
455
456 #[test]
457 fn unreachable_or_impassable_goal_has_no_path() {
458 let map = map_from(&[
459 "..#..", //
460 "..#..",
461 ]);
462 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)), None);
463 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(2, 0)), None);
464 }
465
466 // Colonists move in straight lines between tile centers, so a diagonal step between two
467 // blocked orthogonal neighbours would visually clip through the corners of walls.
468 #[test]
469 fn diagonal_steps_never_cut_wall_corners() {
470 let map = map_from(&[
471 "#.", //
472 ".#",
473 ]);
474 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(1, 1)), None);
475 let map = map_from(&[
476 "..", //
477 "#.",
478 ]);
479 let path = find_path(&map, UVec2::new(0, 1), UVec2::new(1, 0)).unwrap();
480 assert_eq!(path, vec![UVec2::new(1, 1), UVec2::new(1, 0)]);
481 }
482
483 #[test]
484 fn prefers_detour_over_slow_terrain() {
485 let map = map_from(&[
486 ".....", //
487 "..~..",
488 ]);
489 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
490 assert!(!path.contains(&UVec2::new(2, 0)));
491 }
492
493 #[test]
494 fn walks_around_a_hill_rather_than_over_it() {
495 let mut map = map_from(&[
496 ".....", //
497 ".....",
498 ]);
499 map.set_height(UVec2::new(2, 0), 10.0);
500 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
501 assert!(!path.contains(&UVec2::new(2, 0)));
502 }
503
504 #[test]
505 fn detours_along_paths_when_they_are_faster() {
506 let mut map = map_from(&[
507 "..........", //
508 "..........",
509 ]);
510 for x in 0..10 {
511 map.set(UVec2::new(x, 1), Terrain::Paved);
512 }
513 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(9, 0)).unwrap();
514 assert!(path.iter().filter(|p| p.y == 1).count() >= 6);
515 }
516
517 // A wall can go up on a tile a colonist is standing on (or just about to enter); routes must
518 // still start from that tile so nobody gets permanently stuck inside a wall.
519 #[test]
520 fn colonists_can_walk_out_of_a_blocked_tile() {
521 let mut map = map_from(&["....."]);
522 map.set_wall(UVec2::new(2, 0), true);
523 let path = find_path(&map, UVec2::new(2, 0), UVec2::new(4, 0)).unwrap();
524 assert_eq!(path, vec![UVec2::new(3, 0), UVec2::new(4, 0)]);
525 }
526
527 #[test]
528 fn crosses_slow_terrain_when_it_is_the_only_way() {
529 let map = map_from(&["..~.."]);
530 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
531 assert!(path.contains(&UVec2::new(2, 0)));
532 }
533
534 #[test]
535 fn path_adjacent_stops_next_to_target() {
536 let map = map_from(&["......"]);
537 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(5, 0)).unwrap();
538 assert_eq!(path.last(), Some(&UVec2::new(4, 0)));
539 }
540
541 #[test]
542 fn path_adjacent_works_for_impassable_targets() {
543 let map = map_from(&["...#"]);
544 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(3, 0)).unwrap();
545 assert_eq!(path.last(), Some(&UVec2::new(2, 0)));
546 }
547
548 #[test]
549 fn path_adjacent_from_neighbor_is_empty() {
550 let map = map_from(&["..."]);
551 let path = find_path_adjacent(&map, UVec2::new(1, 0), UVec2::new(2, 0));
552 assert_eq!(path, Some(vec![]));
553 }
554
555 #[test]
556 fn path_adjacent_to_enclosed_target_is_none() {
557 let walled = map_from(&[
558 "#####", //
559 "#...#", "#####", ".....",
560 ]);
561 assert_eq!(
562 find_path_adjacent(&walled, UVec2::new(0, 0), UVec2::new(2, 2)),
563 None
564 );
565 }
566
567 #[test]
568 fn nearest_tile_finds_closest_match_by_walking_distance() {
569 let map = map_from(&[
570 ".#...", //
571 ".#.#.", "...#.",
572 ]);
573 let found = nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 4);
574 assert_eq!(found, Some(UVec2::new(4, 2)));
575 assert_eq!(
576 nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 9),
577 None
578 );
579 }
580
581 #[test]
582 fn finds_paths_across_a_generated_world() {
583 let map = crate::worldgen::generate(crate::worldgen::WORLD_SIZE, 1);
584 let region = crate::worldgen::largest_region(&map);
585 let (start, goal) = (region[0], region[region.len() - 1]);
586 let path = find_path(&map, start, goal).unwrap();
587 assert!(is_connected(start, &path));
588 assert_eq!(path.last(), Some(&goal));
589 }
590 }