Skip to main content

heuristic_search/
grid.rs

1//! Searches specialised to 8-connected grids with uniform costs: the [`UniformGrid`]
2//! trait, the exact octile cost [`Octile`], the plain grid graph [`EightConnected`], and
3//! Jump Point Search ([`jps()`]).
4//!
5//! A cell is `(x, y)` with `x < width` and `y < height`. A move goes to one of the eight
6//! neighbours: a straight move costs `1`, a diagonal move `√2`.
7//!
8//! **Corner rule: no corner cutting.** A diagonal move from `(x, y)` to `(x + dx, y + dy)`
9//! needs the target *and both* orthogonal neighbours `(x + dx, y)` and `(x, y + dy)` to be
10//! passable, so a path never squeezes between two blocked cells that touch at a corner and
11//! never clips the corner of a single blocked cell. Every search here over cells follows
12//! this rule; `CostGrid` (feature `float`) adds per-cell costs for Field D*, which plans
13//! over cell corners instead.
14
15mod jps;
16mod sight;
17#[cfg(feature = "float")]
18mod theta;
19
20use core::cmp::Ordering;
21use core::fmt;
22use core::ops::Add;
23
24use search_core::{Cost, Heuristic};
25
26pub use jps::{jps, jps_multi};
27pub use sight::LineOfSight;
28#[cfg(feature = "float")]
29pub use theta::{
30    AnyAngleResult, lazy_theta_star, lazy_theta_star_multi, theta_star, theta_star_multi,
31};
32
33use crate::problem::Successors;
34#[cfg(feature = "float")]
35use search_core::NonNegF64;
36
37/// A cell of a grid: `(x, y)`, column first.
38pub type GridCell = (usize, usize);
39
40/// A unit step `(dx, dy)` between neighbouring cells, each component `-1`, `0` or `1`.
41pub type GridStep = (i8, i8);
42
43/// A rectangular grid of cells that are passable or blocked, for 8-connected searches with
44/// uniform costs.
45///
46/// A cell is `(x, y)` ([`GridCell`]) with `x < width` and `y < height`. A move goes to one
47/// of the eight neighbours: a straight move costs `1`, a diagonal move `√2` (see
48/// [`Octile`]).
49///
50/// **Corner rule: no corner cutting.** A diagonal move from `(x, y)` to `(x + dx, y + dy)`
51/// needs the target *and both* orthogonal neighbours `(x + dx, y)` and `(x, y + dy)` to be
52/// passable, so a path never squeezes between two blocked cells that touch at a corner and
53/// never clips the corner of a single blocked cell. Every search over grid cells in this
54/// crate follows this rule; Field D* (`FieldDStar`), which plans over cell corners, does
55/// not.
56///
57/// # Examples
58///
59/// ```
60/// use heuristic_search::UniformGrid;
61///
62/// /// A grid parsed from text rows, where `#` is blocked.
63/// struct Map(Vec<Vec<bool>>);
64///
65/// impl UniformGrid for Map {
66///     fn width(&self) -> usize {
67///         self.0[0].len()
68///     }
69///
70///     fn height(&self) -> usize {
71///         self.0.len()
72///     }
73///
74///     fn is_passable(&self, x: usize, y: usize) -> bool {
75///         self.0[y][x]
76///     }
77/// }
78///
79/// let map = Map(["..#", "..."].iter().map(|row| row.chars().map(|c| c != '#').collect()).collect());
80///
81/// assert!(map.is_passable(1, 0));
82/// assert!(!map.is_passable(2, 0));
83/// ```
84pub trait UniformGrid {
85    /// The number of columns. Cells have `x < width()`.
86    fn width(&self) -> usize;
87
88    /// The number of rows. Cells have `y < height()`.
89    fn height(&self) -> usize;
90
91    /// Returns `true` if the cell `(x, y)` can be entered. Only called with `x < width()`
92    /// and `y < height()`.
93    fn is_passable(&self, x: usize, y: usize) -> bool;
94}
95
96impl<G: UniformGrid + ?Sized> UniformGrid for &G {
97    fn width(&self) -> usize {
98        (**self).width()
99    }
100
101    fn height(&self) -> usize {
102        (**self).height()
103    }
104
105    fn is_passable(&self, x: usize, y: usize) -> bool {
106        (**self).is_passable(x, y)
107    }
108}
109
110/// A [`UniformGrid`] whose passable cells have traversal costs, for Field D*
111/// (`FieldDStar`, feature `float`).
112///
113/// A cell's cost is the cost per unit of length of a path through its interior. A path
114/// along the border between two cells pays the cheaper of the two. Blocked cells
115/// ([`UniformGrid::is_passable`] is `false`) and cells off the grid cost infinity.
116///
117/// The default cost is `1` for every passable cell, so `impl CostGrid for Map {}` makes a
118/// uniform grid; the costs then are Euclidean lengths.
119///
120/// # Examples
121///
122/// ```
123/// use heuristic_search::{CostGrid, NonNegF64, UniformGrid};
124///
125/// /// A 4 x 1 strip of mud (cost 3) at x = 2, otherwise grass (cost 1).
126/// struct Strip;
127///
128/// impl UniformGrid for Strip {
129///     fn width(&self) -> usize {
130///         4
131///     }
132///
133///     fn height(&self) -> usize {
134///         1
135///     }
136///
137///     fn is_passable(&self, _: usize, _: usize) -> bool {
138///         true
139///     }
140/// }
141///
142/// impl CostGrid for Strip {
143///     fn cell_cost(&self, x: usize, _: usize) -> NonNegF64 {
144///         NonNegF64::new(if x == 2 { 3.0 } else { 1.0 }).expect("positive")
145///     }
146/// }
147///
148/// assert_eq!(Strip.cell_cost(2, 0).get(), 3.0);
149/// ```
150#[cfg(feature = "float")]
151pub trait CostGrid: UniformGrid {
152    /// The cost per unit of length of crossing the passable cell `(x, y)`: finite and
153    /// strictly positive. Only called for passable cells on the grid.
154    fn cell_cost(&self, x: usize, y: usize) -> NonNegF64 {
155        let _ = (x, y);
156
157        NonNegF64::new(1.0).expect("one is a valid cost")
158    }
159}
160
161#[cfg(feature = "float")]
162impl<G: CostGrid + ?Sized> CostGrid for &G {
163    fn cell_cost(&self, x: usize, y: usize) -> NonNegF64 {
164        (**self).cell_cost(x, y)
165    }
166}
167
168/// Returns `true` if `cell + (dx, dy)` lies on the grid and is passable.
169pub(crate) fn passable<G: UniformGrid + ?Sized>(
170    grid: &G,
171    cell: GridCell,
172    (dx, dy): GridStep,
173) -> bool {
174    offset(grid, cell, (dx, dy)).is_some_and(|(x, y)| grid.is_passable(x, y))
175}
176
177/// `cell + (dx, dy)` if it lies on the grid.
178pub(crate) fn offset<G: UniformGrid + ?Sized>(
179    grid: &G,
180    (x, y): GridCell,
181    (dx, dy): GridStep,
182) -> Option<GridCell> {
183    let x = x.checked_add_signed(isize::from(dx))?;
184    let y = y.checked_add_signed(isize::from(dy))?;
185
186    (x < grid.width() && y < grid.height()).then_some((x, y))
187}
188
189/// Returns `true` if `cell` lies on the grid and is passable.
190pub(crate) fn is_open<G: UniformGrid + ?Sized>(grid: &G, cell: GridCell) -> bool {
191    passable(grid, cell, (0, 0))
192}
193
194/// Returns `true` if the move `step` from the passable `cell` is allowed: the target is
195/// passable, and for a diagonal step both orthogonal neighbours are too.
196pub(crate) fn can_move<G: UniformGrid + ?Sized>(
197    grid: &G,
198    cell: GridCell,
199    (dx, dy): GridStep,
200) -> bool {
201    passable(grid, cell, (dx, dy))
202        && (dx == 0 || dy == 0 || (passable(grid, cell, (dx, 0)) && passable(grid, cell, (0, dy))))
203}
204
205/// The eight unit steps, straight ones first.
206pub(crate) const STEPS: [GridStep; 8] = [
207    (1, 0),
208    (-1, 0),
209    (0, 1),
210    (0, -1),
211    (1, 1),
212    (1, -1),
213    (-1, 1),
214    (-1, -1),
215];
216
217/// An exact octile cost `straight + diagonal * √2`: a number of straight and of diagonal
218/// unit moves.
219///
220/// Integer approximations of `√2` (such as 10 and 14) make ties and comparisons wrong, so
221/// this type keeps both counts and compares the real values exactly: `a + b√2 < c + d√2`
222/// is decided by the signs of `a - c` and `d - b` and, when they differ, by comparing
223/// `(a - c)²` with `2 (d - b)²` in integers. Since `√2` is irrational, two costs are equal
224/// only if both counts are, so [`Ord`] agrees with [`Eq`].
225///
226/// [`Cost::saturating_add`] and [`Cost::saturating_times`] saturate each count at
227/// `u32::MAX`; `+` panics on overflow in debug builds like `u32`.
228///
229/// # Examples
230///
231/// ```
232/// use heuristic_search::Octile;
233///
234/// let two_straight = Octile::new(2, 0);
235/// let one_diagonal = Octile::new(0, 1);
236///
237/// assert!(one_diagonal < two_straight);
238/// assert!(Octile::new(3, 0) > Octile::new(0, 2));
239/// assert_eq!(one_diagonal + one_diagonal, Octile::new(0, 2));
240/// assert!((Octile::new(1, 1).to_f64() - (1.0 + core::f64::consts::SQRT_2)).abs() < 1e-12);
241/// ```
242#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
243pub struct Octile {
244    /// The number of straight unit moves.
245    straight: u32,
246    /// The number of diagonal unit moves.
247    diagonal: u32,
248}
249
250impl Octile {
251    /// One straight move: `1`.
252    pub const STRAIGHT: Self = Self::new(1, 0);
253
254    /// One diagonal move: `√2`.
255    pub const DIAGONAL: Self = Self::new(0, 1);
256
257    /// The cost of `straight` straight and `diagonal` diagonal moves.
258    #[must_use]
259    pub const fn new(straight: u32, diagonal: u32) -> Self {
260        Self { straight, diagonal }
261    }
262
263    /// The number of straight moves.
264    #[must_use]
265    pub const fn straight(self) -> u32 {
266        self.straight
267    }
268
269    /// The number of diagonal moves.
270    #[must_use]
271    pub const fn diagonal(self) -> u32 {
272        self.diagonal
273    }
274
275    /// The octile distance between two cells: the cost of the cheapest path on an
276    /// obstacle-free grid, `min(|dx|, |dy|)` diagonal moves and `||dx| - |dy||` straight
277    /// ones. An admissible and consistent heuristic for 8-connected grids.
278    ///
279    /// # Panics
280    ///
281    /// Panics if a count exceeds `u32::MAX`.
282    #[must_use]
283    pub fn between((x0, y0): GridCell, (x1, y1): GridCell) -> Self {
284        let (dx, dy) = (x0.abs_diff(x1), y0.abs_diff(y1));
285        let count = |n: usize| u32::try_from(n).expect("grid distances fit in u32");
286
287        Self::new(count(dx.max(dy) - dx.min(dy)), count(dx.min(dy)))
288    }
289
290    /// The cost as a float, `straight + diagonal * √2`, rounded.
291    #[must_use]
292    pub fn to_f64(self) -> f64 {
293        f64::from(self.straight) + f64::from(self.diagonal) * core::f64::consts::SQRT_2
294    }
295}
296
297impl Ord for Octile {
298    fn cmp(&self, other: &Self) -> Ordering {
299        // The sign of x + y√2 with integer x, y.
300        let x = i128::from(self.straight) - i128::from(other.straight);
301        let y = i128::from(self.diagonal) - i128::from(other.diagonal);
302        match (x.cmp(&0), y.cmp(&0)) {
303            (Ordering::Equal, sign) | (sign, Ordering::Equal) => sign,
304            (Ordering::Greater, Ordering::Greater) => Ordering::Greater,
305            (Ordering::Less, Ordering::Less) => Ordering::Less,
306            (Ordering::Greater, Ordering::Less) => (x * x).cmp(&(2 * y * y)),
307            (Ordering::Less, Ordering::Greater) => (2 * y * y).cmp(&(x * x)),
308        }
309    }
310}
311
312impl PartialOrd for Octile {
313    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
314        Some(self.cmp(other))
315    }
316}
317
318impl Add for Octile {
319    type Output = Self;
320
321    fn add(self, other: Self) -> Self {
322        Self::new(
323            self.straight + other.straight,
324            self.diagonal + other.diagonal,
325        )
326    }
327}
328
329impl Cost for Octile {
330    const ZERO: Self = Self::new(0, 0);
331
332    fn saturating_add(self, other: Self) -> Self {
333        Self::new(
334            self.straight.saturating_add(other.straight),
335            self.diagonal.saturating_add(other.diagonal),
336        )
337    }
338
339    fn saturating_times(self, factor: u32) -> Self {
340        Self::new(
341            self.straight.saturating_mul(factor),
342            self.diagonal.saturating_mul(factor),
343        )
344    }
345}
346
347impl fmt::Display for Octile {
348    /// Formats as `a + b√2`.
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        write!(f, "{} + {}√2", self.straight, self.diagonal)
351    }
352}
353
354/// The octile distance to a fixed goal cell, as a [`Heuristic`] over cells: admissible and
355/// consistent on every 8-connected grid.
356///
357/// # Examples
358///
359/// ```
360/// use heuristic_search::{Heuristic, Octile, OctileDistance};
361///
362/// let mut h = OctileDistance((4, 1));
363///
364/// assert_eq!(h.estimate(&(0, 0)), Some(Octile::new(3, 1)));
365/// ```
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
367pub struct OctileDistance(pub GridCell);
368
369impl Heuristic<GridCell, Octile> for OctileDistance {
370    fn estimate(&mut self, cell: &GridCell) -> Option<Octile> {
371        Some(Octile::between(*cell, self.0))
372    }
373}
374
375/// A [`UniformGrid`] as an 8-connected graph with [`Octile`] costs, for the general searches
376/// ([`a_star`](crate::a_star) and the others) on the same moves that [`jps()`] uses.
377///
378/// It implements [`Successors`] only. The searches that also need
379/// [`CostExt`](crate::CostExt) on the cost ([`ana_star`](crate::ana_star),
380/// [`dps`](crate::dps), [`dibbs`](crate::dibbs), [`bae_star`](crate::bae_star),
381/// [`bidirectional_dijkstra`](crate::bidirectional_dijkstra)) or
382/// [`Predecessors`](crate::Predecessors) do not run on it: `Octile` has no subtraction.
383///
384/// Edges follow the corner rule of [`UniformGrid`]; an edge's action is
385/// its [`GridStep`]. Blocked cells and cells off the grid have no successors.
386///
387/// # Examples
388///
389/// ```
390/// use heuristic_search::{EightConnected, Limits, Octile, OctileDistance, UniformGrid, a_star};
391///
392/// /// An open 5 x 3 grid.
393/// struct Open;
394///
395/// impl UniformGrid for Open {
396///     fn width(&self) -> usize {
397///         5
398///     }
399///
400///     fn height(&self) -> usize {
401///         3
402///     }
403///
404///     fn is_passable(&self, _: usize, _: usize) -> bool {
405///         true
406///     }
407/// }
408///
409/// let goal = (4, 2);
410/// let result = a_star(&EightConnected(Open), (0, 0), &|c: &(usize, usize)| *c == goal, OctileDistance(goal), Limits::NONE);
411///
412/// assert_eq!(result.solution().map(|s| s.cost), Some(Octile::new(2, 2)));
413/// ```
414#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
415pub struct EightConnected<G>(pub G);
416
417impl<G: UniformGrid> Successors for EightConnected<G> {
418    type State = GridCell;
419    type Action = GridStep;
420    type Cost = Octile;
421
422    fn successors(&self, cell: &GridCell, mut emit: impl FnMut(GridStep, GridCell, Octile)) {
423        let grid = &self.0;
424        if !is_open(grid, *cell) {
425            return;
426        }
427
428        for step in STEPS {
429            if !can_move(grid, *cell, step) {
430                continue;
431            }
432
433            let target = offset(grid, *cell, step).expect("a passable target is on the grid");
434            let cost = if step.0 == 0 || step.1 == 0 {
435                Octile::STRAIGHT
436            } else {
437                Octile::DIAGONAL
438            };
439            emit(step, target, cost);
440        }
441    }
442}
443
444/// The square root of `x`, without `std`: Newton's method from an exponent-halving guess,
445/// iterated until it stops decreasing, accurate to about one unit in the last place.
446/// `0`, `+∞` and NaN are returned unchanged; negative inputs give NaN.
447#[cfg(feature = "float")]
448pub(crate) fn sqrt(x: f64) -> f64 {
449    if x.is_nan() || x == 0.0 || x == f64::INFINITY {
450        return x;
451    }
452
453    if x < 0.0 {
454        return f64::NAN;
455    }
456
457    // Halving the biased exponent gives a guess within a factor of two for normal inputs;
458    // subnormal ones take a few more halving steps.
459    let guess = f64::from_bits((x.to_bits() >> 1) + (1023_u64 << 51));
460    // From any positive guess, one step lands at or above the root; from there the
461    // iterates fall until rounding stops them.
462    let mut root = guess.midpoint(x / guess);
463    loop {
464        let next = root.midpoint(x / root);
465        if next >= root {
466            return root;
467        }
468
469        root = next;
470    }
471}
472
473#[cfg(all(test, feature = "float"))]
474mod tests {
475    //! The `no_std` square root against exact squares and the defining relation.
476
477    use proptest::prelude::*;
478
479    use super::sqrt;
480
481    proptest! {
482        /// Squares of integers come back exactly.
483        #[test]
484        fn exact_on_squares(n in 0_u32..1_000_000) {
485            let n = f64::from(n);
486            prop_assert_eq!(sqrt(n * n).to_bits(), n.to_bits());
487        }
488
489        /// Over many magnitudes, including subnormals, the root squared is within a few
490        /// units in the last place of the input.
491        #[test]
492        fn root_squared_is_the_input(bits in 1_u64..0x7FEF_FFFF_FFFF_FFFF) {
493            let x = f64::from_bits(bits);
494            let root = sqrt(x);
495            prop_assert!(root > 0.0);
496            let relative = (root * root - x).abs() / x;
497            let tolerance = if root * root < f64::MIN_POSITIVE { 1e-3 } else { 1e-15 };
498            prop_assert!(relative <= tolerance, "sqrt({x}) = {root}");
499        }
500    }
501
502    /// Zero, infinity and NaN pass through; negative inputs give NaN.
503    #[test]
504    fn special_values() {
505        assert_eq!(sqrt(0.0).to_bits(), 0.0_f64.to_bits());
506        assert_eq!(sqrt(f64::INFINITY).to_bits(), f64::INFINITY.to_bits());
507        assert!(sqrt(f64::NAN).is_nan());
508        assert!(sqrt(-1.0).is_nan());
509    }
510}