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