crcbl-nav 0.20.0

Crucible navigation: deterministic ground and span grid routing and bounded reach
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! A height-aware route grid: each column's walkable floors kept as spans, so
//! routes climb stairs, cross sloped ground and pass under floors above.
//!
//! A [`SpanGrid`] is a [`SpanGridConfig`] — where the region sits, how big a
//! cell is and how many there are — a [`NavAgent`], the body routes are for,
//! and the floors a caller's probe found in each column. It answers the same
//! two questions [`GroundGrid`](crate::grid::GroundGrid) does, in the same
//! shapes, but a position's Y now picks which floor of its column it stands on:
//!
//! * [`SpanGrid::plan`]: the floor positions of a shortest walk to another
//!   position, or why there is none.
//! * [`SpanGrid::reachable_within`]: every floor within a step budget, with how
//!   many steps each one took.
//!
//! And, as there, [`SpanGrid::nearest_walkable`] for a position that stands on
//! no kept floor: the floor to plan from instead. Its sibling
//! [`SpanGrid::plan_toward`] is for a goal no walk reaches — off the region,
//! in a wall or across one — and walks as far toward it as the grid goes.
//!
//! # The rung toward the navmesh
//!
//! This is the voxel stage of `docs/plan/24-navigation.md` in miniature: a probe
//! of the collision world supplies each column's floors, the agent's limits are
//! data, and clearance is eroded by the agent's radius when the grid is built
//! rather than when it is asked. It came from EW, built along those lines and
//! proven by its AI in play before it moved here. It covers one rectangular
//! region; tiles are not done.
//!
//! # The probe is the caller's
//!
//! [`SpanGrid::build`] takes the probe as a closure, so this crate stays free
//! of physics: which hits count as a floor and how headroom is judged are a
//! scene's policy (declined as an engine probe on 2026-09-27, `docs/backlog.md`,
//! _EW's engine port requests_). A probe casting rays at cell centres should
//! know one trap: a ray exactly on the edge two boxes share can report the
//! side face rather than the top, losing the floor, so geometry authored on
//! the same lattice as the cell centres wants the rays nudged off it.
//!
//! # How a floor is kept, and how floors link
//!
//! A probed floor is kept when its normal is no steeper than
//! [`NavAgent::min_floor_normal_y`], the probe found headroom above it, and
//! every column whose cell comes within [`NavAgent::radius_m`] of its cell's
//! centre holds a probed floor within [`NavAgent::max_climb_m`] of it. That
//! last rule is the erosion: it keeps routes through cell centres a body's
//! radius from walls and drops alike.
//!
//! A floor links to **every** floor within a climb in each of its eight
//! neighbouring columns, not only the nearest in height — linking just the
//! nearest drops stair routes where a landing and a step share a column. A
//! diagonal link also needs both columns it cuts past to hold such a floor.
//!
//! # Determinism, and how ties are broken
//!
//! Routes are A\* over link lengths with the straight-line distance as the
//! estimate. The open set is ordered by estimate and then by span index, which
//! runs row by row along +X from the origin and lowest floor first within a
//! column, and the search state is indexed by span, never iterated in an order
//! of its own; so the same grid asked the same question returns the same route
//! on every machine.
//! [`reachable_within`](SpanGrid::reachable_within) is breadth-first over the
//! links in the order +Z, +X, -Z, -X, then the diagonals.
//!
//! # Cost
//!
//! [`SpanGrid::build`] probes each column once and checks each floor against
//! the columns within the agent's radius, which [`MAX_EROSION_REACH_CELLS`]
//! bounds. [`SpanGrid::plan`] does work in proportion to the spans it
//! touches: its search state is a slot per span held by the calling thread
//! between plans, stamped with the plan that wrote it, so a plan begins by
//! bumping a generation rather than clearing the slots. Two setups clear: the
//! first plan on a thread, or on a grid with more spans than any before it on
//! that thread, grows the slots to the grid; and once the generation wraps
//! round its `u32`, every slot is cleared once. The slots are kept until the
//! thread ends, so memory follows the largest grid each thread has planned
//! on. The other queries keep state only for the spans they touch.

use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::{BTreeMap, BinaryHeap, VecDeque};

use glam::{DVec2, DVec3};

use crate::grid::{GroundRoute, GroundRouteError};

/// The most columns a [`SpanGrid`] may cover.
///
/// The build calls the probe once per column and keeps an index entry per
/// column, so this bounds both. Past it a config is refused with
/// [`SpanGridError::TooManyColumns`] rather than clamped, because a clamped
/// grid would describe a different region. It is far above
/// [`MAX_GRID_CELL_COUNT`](crate::grid::MAX_GRID_CELL_COUNT) because a span
/// grid's queries do not allocate per column on every call the way a ground
/// grid's do. What [`SpanGrid::plan`] keeps instead is per span: a stamp, a
/// cost and a link for every span of the largest grid planned on a thread,
/// held by that thread between plans. That grows with the grid's own floors,
/// a few times what the grid keeps per floor, so the grid's size bounds it.
pub const MAX_SPAN_COLUMN_COUNT: usize = 1 << 22;

/// The farthest the erosion looks, in cells, from a floor's column.
///
/// Every kept floor is checked against every column within the agent's
/// radius, so the build's work grows with the square of the radius over the
/// cell size. A radius that reaches past this is refused with
/// [`SpanGridError::RadiusTooWide`]: a cell that small against the body is
/// finer than routing it needs.
pub const MAX_EROSION_REACH_CELLS: usize = 64;

/// How many points [`SpanGrid::plan_toward`] tries along the way from the
/// goal, clamped into the region, back to the start, the clamped goal first.
///
/// Each is a [`SpanGrid::nearest_walkable`] and a [`SpanGrid::plan`] at most,
/// so this bounds the walk's cost; and the farthest point it can stop at, if
/// the clamped goal's floor is unreachable, is one of these steps back. EW's
/// value.
pub const PLAN_TOWARD_STEPS: u32 = 8;

/// The body a grid is built for.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NavAgent {
    /// How far routes keep from walls and drops, in metres.
    pub radius_m: f64,
    /// The headroom a floor needs above it, in metres.
    pub height_m: f64,
    /// The tallest rise or drop between neighbouring floors walked without a
    /// jump, in metres.
    pub max_climb_m: f64,
    /// The steepest floor still walked, as its normal's Y: the cosine of the
    /// slope, not the angle.
    pub min_floor_normal_y: f64,
}

#[cfg(feature = "phys")]
impl NavAgent {
    /// The body a character controller moves under: its capsule's radius,
    /// its full height, its step offset as the climb, and its ground slope
    /// limit.
    #[must_use]
    pub fn from_character(config: &crcbl_phys::character::CharacterConfig) -> Self {
        Self {
            radius_m: config.radius,
            height_m: 2.0 * (config.half_height + config.radius),
            max_climb_m: config.step_offset,
            min_floor_normal_y: config.min_ground_normal_y,
        }
    }
}

/// The region a span grid covers.
///
/// Cell `(x, z)` covers `[origin.x + x·cell_size_m, origin.x + (x+1)·cell_size_m)`
/// along X and the same from `origin.y` along Z, for `x < width` and
/// `z < height`. The fields are public and nothing is checked here;
/// [`SpanGrid::build`] is where they are validated.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpanGridConfig {
    /// The region's minimum corner: its X, and its Z as the vector's `y`.
    pub origin: DVec2,
    /// The side of one square cell, in metres.
    pub cell_size_m: f64,
    /// Cells along +X.
    pub width: usize,
    /// Cells along +Z.
    pub height: usize,
}

impl SpanGridConfig {
    /// The X and Z of cell (`column`, `row`)'s centre, which is where
    /// [`SpanGrid::build`] probes it.
    #[must_use]
    pub fn cell_center(&self, column: usize, row: usize) -> DVec2 {
        self.origin + (DVec2::new(column as f64, row as f64) + 0.5) * self.cell_size_m
    }

    /// The number of columns, or which rule the config breaks.
    fn column_count(self) -> Result<usize, SpanGridError> {
        if !self.origin.is_finite() {
            return Err(SpanGridError::InvalidOrigin);
        }
        if !self.cell_size_m.is_finite() || self.cell_size_m <= 0.0 {
            return Err(SpanGridError::InvalidCellSize);
        }
        if self.width == 0 || self.height == 0 {
            return Err(SpanGridError::InvalidDimensions);
        }
        self.width
            .checked_mul(self.height)
            .filter(|&count| count <= MAX_SPAN_COLUMN_COUNT)
            .ok_or(SpanGridError::TooManyColumns)
    }
}

/// One floor a probe found in a column.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ProbedFloor {
    /// The floor's height.
    pub y: f64,
    /// The floor's normal's Y, for the slope limit.
    pub normal_y: f64,
    /// Whether the agent's height fits above the floor. How that is judged is
    /// the probe's policy; EW's checks straight above the floor at the cell's
    /// centre, and across the whole cell from a climb above the floor, so a
    /// wall thinner than a cell still blocks the cells it crosses while a
    /// step's edge does not.
    pub headroom_clear: bool,
}

/// Why [`SpanGrid::build`] refused a config, an agent or a probe's answer.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum SpanGridError {
    /// A component of the origin is NaN or infinite.
    #[error("the grid origin is not a finite position")]
    InvalidOrigin,
    /// The cell size is NaN, infinite, zero or negative.
    #[error("the cell size is not a finite positive length")]
    InvalidCellSize,
    /// The width or the height is zero.
    #[error("the grid has a zero width or height")]
    InvalidDimensions,
    /// `width × height` overflows `usize` or exceeds [`MAX_SPAN_COLUMN_COUNT`].
    #[error("the grid has more columns than MAX_SPAN_COLUMN_COUNT allows")]
    TooManyColumns,
    /// A limit of the agent is NaN or infinite, its radius or climb negative,
    /// its height not positive, or its floor normal outside `-1..=1`.
    #[error("the agent's limits are not finite lengths and a normal's Y")]
    InvalidAgent,
    /// The agent's radius reaches more than [`MAX_EROSION_REACH_CELLS`] cells.
    #[error("the agent's radius spans more cells than MAX_EROSION_REACH_CELLS")]
    RadiusTooWide,
    /// The probe reported a floor whose height or normal is NaN or infinite.
    #[error("the probe reported a floor that is not finite")]
    InvalidFloor,
}

/// What [`SpanGrid::plan_toward`] planned, and how far toward its goal it
/// gets.
#[derive(Clone, Debug, PartialEq)]
pub struct TowardRoute {
    /// The walk, in [`SpanGrid::plan`]'s shape: every span after the start's,
    /// ending on [`end`](Self::end). Empty when the walk gets no farther than
    /// the start's own floor.
    pub route: GroundRoute,
    /// The feet position on the floor the walk ends on.
    pub end: DVec3,
    /// Whether that floor is the one under the goal, which `plan` reached; if
    /// not, the walk stops short of the goal at `end`.
    pub reaches_goal: bool,
}

/// Every walkable floor in a region, a few per column.
#[derive(Clone, Debug, PartialEq)]
pub struct SpanGrid {
    config: SpanGridConfig,
    agent: NavAgent,
    /// Where each column's floors start in `floors`, with one past the end.
    column_start: Vec<usize>,
    /// Each column's kept floor heights, lowest first.
    floors: Vec<f64>,
}

/// A span: its index in [`SpanGrid::floors`].
type SpanId = usize;

impl SpanGrid {
    /// Builds the grid from `probe`, which reports the floors in the column at
    /// the X and Z it is given, a cell's centre. A floor is kept as the module
    /// docs say.
    ///
    /// # Errors
    ///
    /// The config's first broken rule, in [`SpanGridError`]'s declaration
    /// order, then [`SpanGridError::InvalidAgent`],
    /// [`SpanGridError::RadiusTooWide`], and [`SpanGridError::InvalidFloor`]
    /// for the first non-finite floor the probe reports.
    pub fn build(
        config: SpanGridConfig,
        agent: NavAgent,
        mut probe: impl FnMut(DVec2) -> Vec<ProbedFloor>,
    ) -> Result<Self, SpanGridError> {
        let column_count = config.column_count()?;
        let finite = [
            agent.radius_m,
            agent.height_m,
            agent.max_climb_m,
            agent.min_floor_normal_y,
        ]
        .iter()
        .all(|value| value.is_finite());
        if !finite
            || agent.radius_m < 0.0
            || agent.height_m <= 0.0
            || agent.max_climb_m < 0.0
            || !(-1.0..=1.0).contains(&agent.min_floor_normal_y)
        {
            return Err(SpanGridError::InvalidAgent);
        }
        // Every column whose cell comes within the radius of a cell's centre,
        // in cells: the nearest point of a cell `d` columns over is `d - ½`
        // cells from the centre.
        let reach = agent.radius_m / config.cell_size_m;
        if reach > MAX_EROSION_REACH_CELLS as f64 {
            return Err(SpanGridError::RadiusTooWide);
        }
        // Bounded by the check above; truncation is the point.
        #[allow(clippy::cast_possible_truncation)]
        let steps = (reach + 0.5).ceil() as isize;
        let offsets: Vec<(isize, isize)> = (-steps..=steps)
            .flat_map(|dz| (-steps..=steps).map(move |dx| (dx, dz)))
            .filter(|&(dx, dz)| {
                let gap = DVec2::new(dx.unsigned_abs() as f64, dz.unsigned_abs() as f64) - 0.5;
                gap.max(DVec2::ZERO).length() < reach
            })
            .collect();

        let mut probed: Vec<Vec<f64>> = Vec::with_capacity(column_count);
        for row in 0..config.height {
            for column in 0..config.width {
                let mut floors = Vec::new();
                for floor in probe(config.cell_center(column, row)) {
                    if !floor.y.is_finite() || !floor.normal_y.is_finite() {
                        return Err(SpanGridError::InvalidFloor);
                    }
                    if floor.headroom_clear && floor.normal_y >= agent.min_floor_normal_y {
                        floors.push(floor.y);
                    }
                }
                floors.sort_by(f64::total_cmp);
                probed.push(floors);
            }
        }

        let mut column_start = Vec::with_capacity(column_count + 1);
        let mut floors = Vec::new();
        for row in 0..config.height {
            for column in 0..config.width {
                column_start.push(floors.len());
                for &y in &probed[row * config.width + column] {
                    let clear = offsets.iter().all(|&(dx, dz)| {
                        let (Some(x), Some(z)) = (
                            column.checked_add_signed(dx).filter(|&x| x < config.width),
                            row.checked_add_signed(dz).filter(|&z| z < config.height),
                        ) else {
                            // Past the region's edge is not known to be
                            // walkable, so it erodes like a drop.
                            return false;
                        };
                        probed[z * config.width + x]
                            .iter()
                            .any(|&other| (other - y).abs() <= agent.max_climb_m)
                    });
                    if clear {
                        floors.push(y);
                    }
                }
            }
        }
        column_start.push(floors.len());
        Ok(Self {
            config,
            agent,
            column_start,
            floors,
        })
    }

    /// The region the grid covers.
    #[must_use]
    pub fn config(&self) -> SpanGridConfig {
        self.config
    }

    /// The body the grid was built for.
    #[must_use]
    pub fn agent(&self) -> NavAgent {
        self.agent
    }

    /// The side of one cell, in metres — what one straight step of
    /// [`reachable_within`](Self::reachable_within) is worth.
    #[must_use]
    pub fn cell_size_m(&self) -> f64 {
        self.config.cell_size_m
    }

    /// How many walkable floors the grid holds.
    #[must_use]
    pub fn span_count(&self) -> usize {
        self.floors.len()
    }

    /// The kept floors of the column holding `position`'s X and Z, lowest
    /// first; empty outside the region or for a position that is not finite.
    #[must_use]
    pub fn floors_at(&self, position: DVec3) -> &[f64] {
        self.column_at(position)
            .map_or(&[], |column| &self.floors[self.spans_of(column)])
    }

    /// A shortest walk from the floor under `start_world_position` to the
    /// floor under `goal_world_position`, as the feet position at each span's
    /// cell centre after the start's, ending with the goal's — the shape
    /// [`GroundGrid::plan`](crate::grid::GroundGrid::plan) returns. A start and
    /// goal on the same span give an empty route.
    ///
    /// The floor under a position is the highest in its column at or below
    /// it by up to a climb, or above it by up to a climb.
    ///
    /// # Errors
    ///
    /// [`GroundRouteError::InvalidWorldPosition`] or
    /// [`GroundRouteError::OutsideGrid`] for the start, then for the goal;
    /// [`GroundRouteError::NoRoute`] if either stands on no kept floor or no
    /// walk joins them.
    pub fn plan(
        &self,
        start_world_position: DVec3,
        goal_world_position: DVec3,
    ) -> Result<GroundRoute, GroundRouteError> {
        let from = self.span_at(start_world_position)?;
        let to = self.span_at(goal_world_position)?;
        let (Some(from), Some(to)) = (from, to) else {
            return Err(GroundRouteError::NoRoute);
        };
        self.route(from, to, |_, _, _| {})
            .ok_or(GroundRouteError::NoRoute)
    }

    /// [`plan`](Self::plan)'s search from span `from` to span `to`, or `None`
    /// if no walk joins them, calling `popped` with each span popped short of
    /// the goal, the cost its entry was pushed at, and its cost so far. A span
    /// is expanded when its entry's cost is not above its cost so far, and
    /// passed over otherwise.
    ///
    /// The search state is the calling thread's [`Scratch`], so a plan's work
    /// is in proportion to the spans it touches, not to the grid.
    ///
    /// No closed set is kept, so a span whose cost improves after it was
    /// pushed has an earlier, costlier entry left in the open set, which is
    /// passed over. Nothing is lost by that: the latest entry holds the
    /// span's lowest cost, so its estimate is no higher than an older one's.
    /// It pops first, or at an equal estimate in a run of this span's entries
    /// that no other span's can break into, the order breaking ties by span;
    /// and an older entry popping first in that run is passed over, leaving
    /// the latest to expand the span at its current cost, at the same point
    /// in the order. Once a span is expanded at a cost, each neighbour holds
    /// a cost no higher than that cost plus the link, so expanding it again at
    /// the same cost would change nothing.
    fn route(
        &self,
        from: SpanId,
        to: SpanId,
        mut popped: impl FnMut(SpanId, f64, f64),
    ) -> Option<GroundRoute> {
        SCRATCH.with(|scratch| match scratch.try_borrow_mut() {
            Ok(mut scratch) => self.route_in(&mut scratch, from, to, &mut popped),
            // Only a `popped` that plans again gets here.
            Err(_) => self.route_in(&mut Scratch::default(), from, to, &mut popped),
        })
    }

    /// [`route`](Self::route) with its search state in `scratch`.
    fn route_in(
        &self,
        scratch: &mut Scratch,
        from: SpanId,
        to: SpanId,
        popped: &mut impl FnMut(SpanId, f64, f64),
    ) -> Option<GroundRoute> {
        let target = self.feet_of(to);
        scratch.begin(self.floors.len());
        scratch.reach(from, 0.0, from);
        let from_column = self.column_of(from);
        let mut open = BinaryHeap::from([Open {
            estimate: self.feet_at(from, from_column).distance(target),
            span: from,
            column: from_column,
            cost: 0.0,
        }]);
        while let Some(Open {
            span, column, cost, ..
        }) = open.pop()
        {
            if span == to {
                let mut waypoints = Vec::new();
                let mut at = to;
                while at != from {
                    waypoints.push(self.feet_of(at));
                    at = scratch.slots[at].before;
                }
                waypoints.reverse();
                return Some(GroundRoute { waypoints });
            }
            let so_far = scratch.slots[span].cost;
            popped(span, cost, so_far);
            // Stale: the span was pushed again since, at a lower cost.
            if cost > so_far {
                continue;
            }
            let here = self.feet_at(span, column);
            self.each_neighbour(span, column, |next, next_column| {
                let there = self.feet_at(next, next_column);
                let through = so_far + here.distance(there);
                if scratch.cost_of(next).is_none_or(|cost| through < cost) {
                    scratch.reach(next, through, span);
                    open.push(Open {
                        estimate: through + there.distance(target),
                        span: next,
                        column: next_column,
                        cost: through,
                    });
                }
            });
        }
        None
    }

    /// Every span within `max_steps` links of the floor under
    /// `start_world_position`, as its feet position and its fewest steps
    /// there, the start first and the rest in breadth-first order (the link
    /// order the module docs name), the same every time. `max_steps == 0`
    /// gives the start alone.
    ///
    /// # Errors
    ///
    /// [`GroundRouteError::InvalidWorldPosition`] or
    /// [`GroundRouteError::OutsideGrid`] for the start;
    /// [`GroundRouteError::NoRoute`] if it stands on no kept floor.
    pub fn reachable_within(
        &self,
        start_world_position: DVec3,
        max_steps: usize,
    ) -> Result<Vec<(DVec3, usize)>, GroundRouteError> {
        let from = self
            .span_at(start_world_position)?
            .ok_or(GroundRouteError::NoRoute)?;
        let mut steps = BTreeMap::from([(from, 0)]);
        let mut frontier = VecDeque::from([(from, self.column_of(from))]);
        let mut reached = Vec::new();
        while let Some((span, column)) = frontier.pop_front() {
            let here = steps[&span];
            reached.push((self.feet_at(span, column), here));
            if here == max_steps {
                continue;
            }
            self.each_neighbour(span, column, |next, next_column| {
                steps.entry(next).or_insert_with(|| {
                    frontier.push_back((next, next_column));
                    here + 1
                });
            });
        }
        Ok(reached)
    }

    /// The feet position on the kept floor nearest `world_position`, among the
    /// columns within `max_rings` rings of the one holding it, or `None` if
    /// none of them keeps a floor.
    ///
    /// For a start that stands on no kept floor — an agent pushed into a door
    /// leaf, or against a wall by a squadmate — where [`plan`](Self::plan) and
    /// [`reachable_within`](Self::reachable_within) answer
    /// [`GroundRouteError::NoRoute`]: plan from this position instead, and
    /// walk to it first.
    ///
    /// A position on a kept floor answers that floor, as `plan` would read it.
    /// Otherwise the nearest is by straight-line distance from
    /// `world_position` to each floor's feet position, so a floor on another
    /// storey is as far as its height makes it; ties go to the lower span
    /// index (the order the module docs name), so the answer is the same every
    /// time. Ring `r` is the columns `r` steps away with a diagonal step
    /// counted as one, so `max_rings == 0` searches the position's own column
    /// alone. The search visits every floor of the square the rings cover that
    /// lies in the region.
    ///
    /// # Errors
    ///
    /// [`GroundRouteError::InvalidWorldPosition`] or
    /// [`GroundRouteError::OutsideGrid`] for the position.
    pub fn nearest_walkable(
        &self,
        world_position: DVec3,
        max_rings: usize,
    ) -> Result<Option<DVec3>, GroundRouteError> {
        let column = self.column_of_position(world_position)?;
        if let Some(span) = self.floor_in(column, world_position.y) {
            return Ok(Some(self.feet_of(span)));
        }
        let (width, height) = (self.config.width, self.config.height);
        let (x, z) = (column % width, column / width);
        let mut nearest: Option<(f64, SpanId)> = None;
        for row in z.saturating_sub(max_rings)..=z.saturating_add(max_rings).min(height - 1) {
            for column in x.saturating_sub(max_rings)..=x.saturating_add(max_rings).min(width - 1) {
                for span in self.spans_of(row * width + column) {
                    let distance = self.feet_of(span).distance(world_position);
                    // Strictly nearer, so a tie keeps the lower span.
                    if nearest.is_none_or(|(best, _)| distance < best) {
                        nearest = Some((distance, span));
                    }
                }
            }
        }
        Ok(nearest.map(|(_, span)| self.feet_of(span)))
    }

    /// A walk from the floor under `start_world_position` toward
    /// `goal_world_position`, as far as the grid goes: to the goal where
    /// [`plan`](Self::plan) reaches it, and otherwise as near it as a floor
    /// the start reaches lies — "walk as far toward X as this grid goes", for
    /// a goal off the region, in a wall, or across one.
    ///
    /// Where `plan` finds no walk to the goal, the goal's X and Z are clamped
    /// onto the rectangle the region's outermost cell centres span, keeping
    /// its Y. From that point to the start, [`PLAN_TOWARD_STEPS`] points are
    /// tried at even steps, the clamped goal first and the start left out:
    /// each point's [`nearest_walkable`](Self::nearest_walkable) floor within
    /// `max_rings`, and the first of those floors `plan` reaches from the
    /// start is where the walk ends. So the walk ends on the floor nearest the
    /// farthest point along the way that has a reachable one — nearest
    /// `nearest_walkable`'s sense, so a floor across a thin wall can be the
    /// nearest to a point and still be passed over as unreachable, for the
    /// next point back. If none is, the walk ends where it starts, on the
    /// start's own floor, with an empty route.
    ///
    /// A start on a kept floor therefore always gets an answer, and
    /// [`TowardRoute::reaches_goal`] says whether it is the goal. The same
    /// grid asked the same question gives the same answer.
    ///
    /// # Errors
    ///
    /// [`GroundRouteError::InvalidWorldPosition`] or
    /// [`GroundRouteError::OutsideGrid`] for the start, then
    /// [`GroundRouteError::NoRoute`] if it stands on no kept floor, then
    /// [`GroundRouteError::InvalidWorldPosition`] for a goal that is not
    /// finite. A goal outside the region is not an error: it is what the
    /// clamp is for.
    pub fn plan_toward(
        &self,
        start_world_position: DVec3,
        goal_world_position: DVec3,
        max_rings: usize,
    ) -> Result<TowardRoute, GroundRouteError> {
        let from = self
            .span_at(start_world_position)?
            .ok_or(GroundRouteError::NoRoute)?;
        if !goal_world_position.is_finite() {
            return Err(GroundRouteError::InvalidWorldPosition);
        }
        if let (Ok(Some(to)), Ok(route)) = (
            self.span_at(goal_world_position),
            self.plan(start_world_position, goal_world_position),
        ) {
            return Ok(TowardRoute {
                route,
                end: self.feet_of(to),
                reaches_goal: true,
            });
        }

        let (width, height) = (self.config.width, self.config.height);
        let clamped = DVec2::new(goal_world_position.x, goal_world_position.z).clamp(
            self.config.cell_center(0, 0),
            self.config.cell_center(width - 1, height - 1),
        );
        let toward = DVec3::new(clamped.x, goal_world_position.y, clamped.y);
        let mut tried = None;
        for step in 0..PLAN_TOWARD_STEPS {
            let point = toward.lerp(
                start_world_position,
                f64::from(step) / f64::from(PLAN_TOWARD_STEPS),
            );
            // Inside the region: both ends are, and it is a rectangle.
            let Some(floor) = self.nearest_walkable(point, max_rings)? else {
                continue;
            };
            // Neighbouring points often snap to one floor; plan it once.
            if tried == Some(floor) {
                continue;
            }
            tried = Some(floor);
            if let Ok(route) = self.plan(start_world_position, floor) {
                return Ok(TowardRoute {
                    route,
                    end: floor,
                    reaches_goal: false,
                });
            }
        }
        Ok(TowardRoute {
            route: GroundRoute {
                waypoints: Vec::new(),
            },
            end: self.feet_of(from),
            reaches_goal: false,
        })
    }

    /// The column holding `position`'s X and Z, if the region does.
    fn column_at(&self, position: DVec3) -> Option<usize> {
        let local =
            (DVec2::new(position.x, position.z) - self.config.origin) / self.config.cell_size_m;
        if !local.is_finite() || local.x < 0.0 || local.y < 0.0 {
            return None;
        }
        let (column, row) = (local.x.floor(), local.y.floor());
        if column >= self.config.width as f64 || row >= self.config.height as f64 {
            return None;
        }
        // In range by the checks above; truncation is the point.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        Some(row as usize * self.config.width + column as usize)
    }

    /// The span a body with its feet at `position` stands on, or `None` for a
    /// column with no floor within a climb of it.
    fn span_at(&self, position: DVec3) -> Result<Option<SpanId>, GroundRouteError> {
        let column = self.column_of_position(position)?;
        Ok(self.floor_in(column, position.y))
    }

    /// The column holding a query's `position`, or why it names none.
    fn column_of_position(&self, position: DVec3) -> Result<usize, GroundRouteError> {
        if !position.is_finite() {
            return Err(GroundRouteError::InvalidWorldPosition);
        }
        self.column_at(position)
            .ok_or(GroundRouteError::OutsideGrid)
    }

    /// The span of `column` a body with its feet at height `y` stands on: the
    /// highest within a climb of it.
    fn floor_in(&self, column: usize, y: f64) -> Option<SpanId> {
        self.spans_of(column)
            .rev()
            .find(|&span| (y - self.floors[span]).abs() <= self.agent.max_climb_m)
    }

    /// The spans of `column`.
    fn spans_of(&self, column: usize) -> std::ops::Range<SpanId> {
        self.column_start[column]..self.column_start[column + 1]
    }

    /// The column `span` is in: the last whose range starts at or before it,
    /// which is never an empty column, since the next starts at the same
    /// index.
    fn column_of(&self, span: SpanId) -> usize {
        self.column_start.partition_point(|&start| start <= span) - 1
    }

    /// The feet position on `span`: its cell's centre at its floor's height.
    fn feet_of(&self, span: SpanId) -> DVec3 {
        self.feet_at(span, self.column_of(span))
    }

    /// [`feet_of`](Self::feet_of) for a `span` whose `column` is known.
    fn feet_at(&self, span: SpanId, column: usize) -> DVec3 {
        let at = self
            .config
            .cell_center(column % self.config.width, column / self.config.width);
        DVec3::new(at.x, self.floors[span], at.y)
    }

    /// Calls `visit` with each span a body steps to from `span`, in `column`,
    /// and that span's column, in the link order the module docs name.
    fn each_neighbour(&self, span: SpanId, column: usize, mut visit: impl FnMut(SpanId, usize)) {
        let (width, height) = (self.config.width, self.config.height);
        let (x, z) = (column % width, column / width);
        let y = self.floors[span];
        let toward = |dx: isize, dz: isize| -> Option<usize> {
            let nx = x.checked_add_signed(dx).filter(|&v| v < width)?;
            let nz = z.checked_add_signed(dz).filter(|&v| v < height)?;
            Some(nz * width + nx)
        };
        // Visits the floors within a climb in the column `dx`, `dz` over, and
        // says whether there were any.
        let mut step = |dx: isize, dz: isize| -> bool {
            let Some(next_column) = toward(dx, dz) else {
                return false;
            };
            let mut any = false;
            for other in self.spans_of(next_column) {
                if (self.floors[other] - y).abs() <= self.agent.max_climb_m {
                    any = true;
                    visit(other, next_column);
                }
            }
            any
        };
        // +Z, +X, -Z, -X: what a diagonal cuts past.
        let linked = [step(0, 1), step(1, 0), step(0, -1), step(-1, 0)];
        let (plus_z, plus_x, minus_z, minus_x) = (linked[0], linked[1], linked[2], linked[3]);
        for (dx, dz, past_x, past_z) in [
            (1, 1, plus_x, plus_z),
            (1, -1, plus_x, minus_z),
            (-1, -1, minus_x, minus_z),
            (-1, 1, minus_x, plus_z),
        ] {
            if past_x && past_z {
                step(dx, dz);
            }
        }
    }
}

thread_local! {
    /// The search state of each thread's plans, kept between them.
    static SCRATCH: RefCell<Scratch> = RefCell::default();
}

/// A plan's search state: a slot per span, valid only while its stamp is the
/// current plan's generation, so a plan starts by bumping the generation
/// rather than by clearing every slot.
#[derive(Default)]
struct Scratch {
    /// The current plan's stamp; never zero once a plan has begun.
    generation: u32,
    slots: Vec<Slot>,
}

/// One span's search state.
#[derive(Clone, Copy, Default)]
struct Slot {
    /// The generation that wrote the slot; zero for never.
    stamp: u32,
    /// The span's cost so far.
    cost: f64,
    /// The span before it on its cheapest walk so far.
    before: SpanId,
}

impl Scratch {
    /// Starts a plan over `spans` spans, with none of them reached.
    fn begin(&mut self, spans: usize) {
        if self.slots.len() < spans {
            self.slots.resize(spans, Slot::default());
        }
        if self.generation == u32::MAX {
            // Every stamp could be mistaken for a generation to come.
            for slot in &mut self.slots {
                slot.stamp = 0;
            }
            self.generation = 0;
        }
        self.generation += 1;
    }

    /// `span`'s cost so far, if this plan has reached it.
    fn cost_of(&self, span: SpanId) -> Option<f64> {
        let slot = self.slots[span];
        (slot.stamp == self.generation).then_some(slot.cost)
    }

    /// Records that this plan reached `span` at `cost` from `before`.
    fn reach(&mut self, span: SpanId, cost: f64, before: SpanId) {
        self.slots[span] = Slot {
            stamp: self.generation,
            cost,
            before,
        };
    }
}

/// An open span ordered for a min-heap by estimate, ties by span, so a plan
/// is the same every time. Its column and the cost it was pushed at ride
/// along and play no part in the order.
#[derive(Clone, Copy, Debug)]
struct Open {
    estimate: f64,
    span: SpanId,
    column: usize,
    cost: f64,
}

impl PartialEq for Open {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Open {}

impl Ord for Open {
    fn cmp(&self, other: &Self) -> Ordering {
        other
            .estimate
            .total_cmp(&self.estimate)
            .then_with(|| other.span.cmp(&self.span))
    }
}

impl PartialOrd for Open {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[cfg(test)]
#[path = "spans/tests.rs"]
mod tests;

#[cfg(test)]
#[path = "spans/route_equivalence_tests.rs"]
mod route_equivalence_tests;