Skip to main content

ghast_pathfinder/
plan.rs

1//! The planner: A* over feet blocks with physics-measured move costs.
2
3use std::cmp::Ordering;
4use std::collections::{BinaryHeap, HashMap, HashSet};
5
6use crate::Version;
7use crate::class::{Class, flag};
8use crate::control::ControllerConfig;
9use crate::cost::Costs;
10use crate::door;
11use crate::goal::{Goal, Heuristic};
12use crate::jump;
13use crate::moves::{
14    HEIGHT, JUMP_APEX, JUMP_MARGIN, MAX_JUMP_UP, MoveKind, NodeKind, STEP, Spot, ceiling, clear,
15    climb_wall, spot,
16};
17use crate::sim::{SimOutcome, SimReport, simulate};
18use crate::world::{BlockSource, BuildKeyHasher, Grid, Sections};
19
20/// Digging through blocks (off by default): cost per block in ticks
21/// `base + ticks_per_hardness * hardness`, blocks harder than `max_hardness` are never dug.
22#[derive(Clone, Copy, Debug, PartialEq)]
23pub struct DigCost {
24    /// Fixed ticks per block (aiming, the server's confirmation).
25    pub base: f64,
26    /// Ticks per unit of vanilla hardness (hand on dirt ≈ 30, a good pickaxe on stone ≈ 4).
27    pub ticks_per_hardness: f64,
28    /// Hardest block that may be dug.
29    pub max_hardness: f64,
30}
31
32impl Default for DigCost {
33    fn default() -> Self {
34        DigCost {
35            base: 6.0,
36            ticks_per_hardness: 30.0,
37            max_hardness: 2.0,
38        }
39    }
40}
41
42/// Planner options. Build with [`Config::default`] and the `with_*` methods.
43#[derive(Clone, Debug, PartialEq)]
44#[non_exhaustive]
45pub struct Config {
46    /// Sprint on straight runs (costs assume sprinting; needs food > 6). Default on.
47    pub sprint: bool,
48    /// Jump over gaps: up to 3 blocks on the level, onto a block one higher or up to two
49    /// lower, each only where the vanilla-exact physics lands the jump (some need sprinting).
50    /// Default on.
51    pub parkour: bool,
52    /// Highest drop onto a floor, in blocks (3 = no fall damage). Default 3.
53    pub max_fall: f64,
54    /// Highest drop into water at least 2 blocks deep. Default 16.
55    pub max_water_fall: f64,
56    /// Swim. Default on.
57    pub swim: bool,
58    /// Climb ladders and vines. Default on.
59    pub climb: bool,
60    /// Dig through blocks in the way (default off): tunnels, jump-ups into dug space,
61    /// straight down ([`MoveKind::DigDown`]) and staircases down (a [`MoveKind::Descend`]
62    /// with digs). The follower digs with the held item.
63    pub dig: Option<DigCost>,
64    /// Place blocks, at this cost in ticks per block (default off): fill a one-deep hole,
65    /// bridge over a gap (sneaking to the edge, placing against the side of the floor block),
66    /// tower straight up (jump, place under the feet). The follower places the held item: the
67    /// caller keeps blocks in hand.
68    pub place: Option<f64>,
69    /// Node budget per plan; when exhausted the best partial path is returned. Default
70    /// 250 000: enough to search all the terrain a client loads at view distance 10 on a
71    /// flat world (a maze whose way is far longer than the straight line needs that); at
72    /// most some 30–40 MB while it runs and half a second of one desktop core.
73    pub max_nodes: usize,
74    /// Heuristic weight (1 = optimal; larger plans faster, slightly longer paths).
75    pub heuristic_weight: f64,
76    /// What the player's body can do (26.1 attributes; vanilla by default).
77    pub(crate) limits: Limits,
78}
79
80/// Plan-time movement limits of the player.
81#[derive(Clone, Copy, Debug, PartialEq)]
82pub(crate) struct Limits {
83    /// Highest step walked up.
84    pub(crate) step: f64,
85    /// Highest block jumped onto.
86    pub(crate) jump_up: f64,
87    /// The measured gap-jump table applies (vanilla jump, gravity, speed and size).
88    pub(crate) parkour: bool,
89}
90
91impl Default for Limits {
92    fn default() -> Self {
93        Limits {
94            step: STEP,
95            jump_up: MAX_JUMP_UP,
96            parkour: true,
97        }
98    }
99}
100
101impl Limits {
102    /// The limits of a 26.1 player from its attributes and effects: step height, the apex of a
103    /// standing jump (jump strength, jump boost, gravity); the gap-jump table only with vanilla
104    /// jump, gravity, movement speed and scale.
105    #[cfg(ghast_modern)]
106    pub(crate) fn of(p: &ghast_physics::modern::PlayerState) -> Limits {
107        let a = &p.attributes;
108        let boost = p
109            .effects
110            .jump_boost
111            .map_or(0.0, |amp| 0.1 * f64::from(amp + 1));
112        let power = a.jump_strength.value() + boost;
113        let gravity = a.gravity.value();
114        let (mut y, mut v, mut apex) = (0.0f64, power, 0.0f64);
115        for _ in 0..200 {
116            y += v;
117            apex = apex.max(y);
118            v = (v - gravity) * 0.98;
119            if v <= 0.0 {
120                break;
121            }
122        }
123        let eq = |x: f64, d: f64| (x - d).abs() < 1e-9;
124        let vanilla = eq(a.jump_strength.value(), f64::from(0.42f32))
125            && boost == 0.0
126            && eq(gravity, 0.08)
127            && eq(a.movement_speed.base(), f64::from(0.1f32))
128            && eq(a.scale.value(), 1.0)
129            && !p.effects.slow_falling
130            && p.effects.levitation.is_none();
131        Limits {
132            step: f64::from(p.step_height()).min(STEP),
133            // Room for the arc: what the vanilla jump keeps above the 1-block step (~0.25).
134            jump_up: MAX_JUMP_UP.min(apex - 0.2),
135            parkour: vanilla,
136        }
137    }
138}
139
140impl Default for Config {
141    fn default() -> Self {
142        Config {
143            sprint: true,
144            parkour: true,
145            max_fall: 3.0,
146            max_water_fall: 16.0,
147            swim: true,
148            climb: true,
149            dig: None,
150            place: None,
151            max_nodes: 250_000,
152            heuristic_weight: 1.0,
153            limits: Limits::default(),
154        }
155    }
156}
157
158impl Config {
159    /// Sprinting on or off.
160    #[must_use]
161    pub fn with_sprint(mut self, on: bool) -> Self {
162        self.sprint = on;
163        self
164    }
165    /// Gap jumps on or off.
166    #[must_use]
167    pub fn with_parkour(mut self, on: bool) -> Self {
168        self.parkour = on;
169        self
170    }
171    /// Highest drop onto a floor.
172    #[must_use]
173    pub fn with_max_fall(mut self, blocks: f64) -> Self {
174        self.max_fall = blocks;
175        self
176    }
177    /// Swimming on or off.
178    #[must_use]
179    pub fn with_swim(mut self, on: bool) -> Self {
180        self.swim = on;
181        self
182    }
183    /// Climbing on or off.
184    #[must_use]
185    pub fn with_climb(mut self, on: bool) -> Self {
186        self.climb = on;
187        self
188    }
189    /// Digging (None = off).
190    #[must_use]
191    pub fn with_dig(mut self, dig: Option<DigCost>) -> Self {
192        self.dig = dig;
193        self
194    }
195    /// Placing blocks: filling holes, bridging, towering up (cost in ticks per block; None =
196    /// off).
197    #[must_use]
198    pub fn with_place(mut self, cost: Option<f64>) -> Self {
199        self.place = cost;
200        self
201    }
202    /// Node budget.
203    #[must_use]
204    pub fn with_max_nodes(mut self, n: usize) -> Self {
205        self.max_nodes = n;
206        self
207    }
208    /// Heuristic weight (>= 1).
209    #[must_use]
210    pub fn with_heuristic_weight(mut self, w: f64) -> Self {
211        self.heuristic_weight = w.max(1.0);
212        self
213    }
214}
215
216/// A block to place before (or during) a step: the new block at `pos`, clicked on the face of
217/// `against` toward `pos` (`against` is a neighbour of `pos`: the block below it when filling
218/// a hole or towering up, the floor block beside it when bridging).
219#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
220pub struct Place {
221    /// Where the new block goes.
222    pub pos: [i32; 3],
223    /// The block whose face is clicked.
224    pub against: [i32; 3],
225}
226
227impl Place {
228    /// The clicked face of [`Place::against`] as a unit offset (`pos - against`): `[0, 1, 0]`
229    /// is the top face.
230    #[must_use]
231    pub fn face(&self) -> [i32; 3] {
232        [
233            self.pos[0] - self.against[0],
234            self.pos[1] - self.against[1],
235            self.pos[2] - self.against[2],
236        ]
237    }
238}
239
240/// One step of a path: the feet block to reach and how.
241#[derive(Clone, Debug, PartialEq)]
242pub struct Step {
243    /// Feet block.
244    pub pos: [i32; 3],
245    /// Feet height when standing there (swim / climb steps: the block's y).
246    pub feet_y: f64,
247    /// The move that reaches this step from the previous one.
248    pub kind: MoveKind,
249    /// How the player is held up here.
250    pub node: NodeKind,
251    /// Blocks to break before the move (in order).
252    pub dig: Vec<[i32; 3]>,
253    /// Block to place before the move.
254    pub place: Option<Place>,
255}
256
257impl Step {
258    /// Centre of the step at feet height.
259    #[must_use]
260    pub fn target(&self) -> [f64; 3] {
261        [
262            f64::from(self.pos[0]) + 0.5,
263            self.feet_y,
264            f64::from(self.pos[2]) + 0.5,
265        ]
266    }
267}
268
269/// A planned path.
270#[derive(Clone, Debug, PartialEq)]
271pub struct Path {
272    /// `steps[0]` is the start; the last step reaches the goal (or the best node found).
273    pub steps: Vec<Step>,
274    /// Estimated cost in ticks.
275    pub cost: f64,
276    /// The goal was not reached (node budget, unknown terrain, or unreachable): the path ends
277    /// at the node closest to the goal (or, when the node budget ran out with no node closer
278    /// than the start, at the most promising node not expanded yet). Replan from there.
279    pub partial: bool,
280    /// Nodes expanded.
281    pub expanded: usize,
282    /// The version the path was planned for.
283    pub version: Version,
284}
285
286/// Why planning failed.
287#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
288#[non_exhaustive]
289pub enum PlanError {
290    /// The start block is not loaded.
291    StartUnknown,
292    /// The player cannot stand in the start block (inside a block, in lava, ...).
293    StartBlocked,
294    /// No node closer to the goal is reachable.
295    NoPath,
296}
297
298impl std::fmt::Display for PlanError {
299    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300        f.write_str(match self {
301            PlanError::StartUnknown => "start block not loaded",
302            PlanError::StartBlocked => "cannot stand at the start",
303            PlanError::NoPath => "no path",
304        })
305    }
306}
307
308impl std::error::Error for PlanError {}
309
310/// The path planner. Cheap to clone; holds only its configuration.
311#[derive(Clone, Debug, Default, PartialEq)]
312pub struct Pathfinder {
313    cfg: Config,
314}
315
316#[derive(Clone, Copy)]
317pub(crate) struct Edge {
318    pub(crate) to: [i32; 3],
319    pub(crate) spot: Spot,
320    pub(crate) kind: MoveKind,
321    pub(crate) cost: f64,
322    pub(crate) dig: [Option<[i32; 3]>; 3],
323    pub(crate) place: Option<Place>,
324}
325
326/// A search node (kept small: a large search holds a few hundred thousand of them).
327#[derive(Clone)]
328struct Rec {
329    pos: [i32; 3],
330    spot: Spot,
331    g: f64,
332    h: f64,
333    parent: u32,
334    /// Index into [`SearchState::work`] of the digs / place of the move here, or `NO_WORK`.
335    work: u32,
336    kind: MoveKind,
337    closed: bool,
338}
339
340/// [`Rec::work`] of a move without digs or places.
341const NO_WORK: u32 = u32::MAX;
342
343/// Digs and place of a move.
344type Work = ([Option<[i32; 3]>; 3], Option<Place>);
345
346#[derive(Clone, PartialEq)]
347struct Open {
348    f: f64,
349    h: f64,
350    idx: u32,
351}
352
353impl Eq for Open {}
354
355impl PartialOrd for Open {
356    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
357        Some(self.cmp(other))
358    }
359}
360
361impl Ord for Open {
362    fn cmp(&self, other: &Self) -> Ordering {
363        // Min-heap on f, then on h (deeper nodes first).
364        other
365            .f
366            .total_cmp(&self.f)
367            .then_with(|| other.h.total_cmp(&self.h))
368    }
369}
370
371/// A node key: 26 bits of x and z, 12 of y (the low 8 in bits 0-7, the high 4 in bits
372/// 60-63, so heights 0..256 keep their old keys; 26.1 builds from -2048 to 2047).
373#[inline]
374pub(crate) fn pack(p: [i32; 3]) -> u64 {
375    (p[0] as u32 as u64 & 0x3ff_ffff) << 34
376        | (p[2] as u32 as u64 & 0x3ff_ffff) << 8
377        | (p[1] as u8 as u64)
378        | ((p[1] >> 8) as u32 as u64 & 0xf) << 60
379}
380
381impl Pathfinder {
382    /// A planner with this configuration.
383    #[must_use]
384    pub fn new(cfg: Config) -> Self {
385        Pathfinder { cfg }
386    }
387
388    /// The configuration.
389    #[must_use]
390    pub fn config(&self) -> &Config {
391        &self.cfg
392    }
393
394    /// The start block of a player at feet position `pos` (the block under the feet when it
395    /// stands on a partial block, else the block containing the feet).
396    #[must_use]
397    pub fn start_block(pos: [f64; 3]) -> [i32; 3] {
398        [
399            pos[0].floor() as i32,
400            (pos[1] + 1e-4).floor() as i32,
401            pos[2].floor() as i32,
402        ]
403    }
404
405    /// Plans a path from the feet block `from` to `goal`.
406    ///
407    /// # Errors
408    /// [`PlanError`] when the start is unknown or blocked, or no node closer to the goal can
409    /// be reached.
410    pub fn plan<S: BlockSource + ?Sized>(
411        &self,
412        version: Version,
413        world: &S,
414        from: [i32; 3],
415        goal: &Goal,
416    ) -> Result<Path, PlanError> {
417        self.plan_avoiding(version, world, from, goal, &HashSet::new())
418    }
419
420    /// Like [`Pathfinder::plan`], never using the moves in `banned` (`(from, to)` feet blocks).
421    ///
422    /// # Errors
423    /// See [`Pathfinder::plan`].
424    pub fn plan_avoiding<S: BlockSource + ?Sized>(
425        &self,
426        version: Version,
427        world: &S,
428        from: [i32; 3],
429        goal: &Goal,
430        banned: &HashSet<([i32; 3], [i32; 3])>,
431    ) -> Result<Path, PlanError> {
432        let mut search = self.search(version, from, goal.clone(), banned.clone());
433        match search.step(world, Budget::UNLIMITED) {
434            Some(r) => r,
435            None => unreachable!("an unlimited slice finishes the search"),
436        }
437    }
438
439    /// The same search as [`Pathfinder::plan_avoiding`], run in slices: each
440    /// [`Search::step`] expands at most a [`Budget`] of nodes (and stops at its time limit),
441    /// so a long plan never blocks one tick. The result is identical to the one-shot plan on
442    /// the same world: the slices only pause the same A*. The world is read during the steps
443    /// (a slice may see blocks that changed since the previous one).
444    ///
445    /// ```
446    /// use std::collections::HashSet;
447    /// use ghast_pathfinder::{Budget, Config, Goal, Pathfinder, Version};
448    ///
449    /// let mut world = ghast_physics::v1_8::memory_world();
450    /// world.load_chunks(-2, -2, 2, 2);
451    /// world.fill_raw([-30, 63, -30], [30, 63, 30], 1 << 4);
452    /// world.fill_raw([5, 64, -20], [5, 66, 20], 1 << 4); // a wall to go around
453    /// let pf = Pathfinder::new(Config::default());
454    /// let mut search = pf.search(Version::V1_8, [0, 64, 0], Goal::Block([10, 64, 0]), HashSet::new());
455    /// let path = loop {
456    ///     // e.g. once per tick:
457    ///     if let Some(r) = search.step(&world, Budget::nodes(200)) {
458    ///         break r.unwrap();
459    ///     }
460    /// };
461    /// assert_eq!(path, pf.plan(Version::V1_8, &world, [0, 64, 0], &Goal::Block([10, 64, 0])).unwrap());
462    /// ```
463    #[must_use]
464    pub fn search(
465        &self,
466        version: Version,
467        from: [i32; 3],
468        goal: Goal,
469        banned: HashSet<([i32; 3], [i32; 3])>,
470    ) -> Search {
471        Search {
472            cfg: self.cfg.clone(),
473            heur: self.heuristic(Costs::of(version)),
474            version,
475            from,
476            goal,
477            banned,
478            state: None,
479            result: None,
480            exhausted: false,
481        }
482    }
483
484    /// Plans, then runs the path through the vanilla-exact physics ([`crate::simulate`]) with
485    /// a [`crate::Controller`]; a move the simulation fails is avoided and the path replanned,
486    /// up to `attempts` plans. Returns the last path and its simulation: check
487    /// [`SimReport::outcome`] (anything but [`crate::SimOutcome::Arrived`] means even the
488    /// last plan failed in the simulation, at [`SimReport::reached`]).
489    ///
490    /// ```
491    /// use ghast_pathfinder::{Config, Goal, Pathfinder, SimOutcome, Version};
492    ///
493    /// let mut world = ghast_physics::v1_8::memory_world();
494    /// world.load_chunks(-1, -1, 1, 1);
495    /// world.fill_raw([-10, 63, -10], [10, 63, 10], 1 << 4);
496    /// let pf = Pathfinder::new(Config::default());
497    /// let (path, sim) = pf.plan_verified(Version::V1_8, &world, [0, 64, 0], &Goal::Block([6, 64, 3]), 3).unwrap();
498    /// assert_eq!(sim.outcome, SimOutcome::Arrived);
499    /// assert!(!path.partial);
500    /// ```
501    ///
502    /// # Errors
503    /// See [`Pathfinder::plan`].
504    pub fn plan_verified<S: BlockSource + ?Sized>(
505        &self,
506        version: Version,
507        world: &S,
508        from: [i32; 3],
509        goal: &Goal,
510        attempts: usize,
511    ) -> Result<(Path, SimReport), PlanError> {
512        let ctrl = ControllerConfig::default().with_sprint(self.cfg.sprint);
513        self.plan_verified_avoiding(
514            version,
515            world,
516            from,
517            goal,
518            &mut HashSet::new(),
519            attempts,
520            &ctrl,
521        )
522    }
523
524    /// [`Pathfinder::plan_verified`] with moves to avoid (failed moves are added to `banned`)
525    /// and the controller options the simulation uses.
526    ///
527    /// # Errors
528    /// See [`Pathfinder::plan`].
529    #[allow(clippy::too_many_arguments)]
530    pub fn plan_verified_avoiding<S: BlockSource + ?Sized>(
531        &self,
532        version: Version,
533        world: &S,
534        from: [i32; 3],
535        goal: &Goal,
536        banned: &mut HashSet<([i32; 3], [i32; 3])>,
537        attempts: usize,
538        controller: &ControllerConfig,
539    ) -> Result<(Path, SimReport), PlanError> {
540        let mut last = None;
541        for _ in 0..attempts.max(1) {
542            let path = self.plan_avoiding(version, world, from, goal, banned)?;
543            let sim = simulate(&path, world, controller);
544            if sim.outcome == SimOutcome::Arrived {
545                return Ok((path, sim));
546            }
547            let k = (sim.reached + 1).min(path.steps.len() - 1);
548            if k == 0 || !banned.insert((path.steps[k - 1].pos, path.steps[k].pos)) {
549                return Ok((path, sim));
550            }
551            last = Some((path, sim));
552        }
553        Ok(last.expect("at least one attempt"))
554    }
555
556    fn heuristic(&self, c: &Costs) -> Heuristic {
557        let per_block = 1.0
558            / if self.cfg.sprint {
559                c.sprint_speed
560            } else {
561                c.walk_speed
562            };
563        let per_up = (c.jump_up)
564            .min(1.0 / c.climb_up_speed)
565            .min(1.0 / c.swim_up_speed)
566            .max(1.0);
567        let fall = c.fall_ticks(24.0) / 24.0;
568        let per_down = fall
569            .min(1.0 / c.climb_down_speed)
570            .min(1.0 / c.swim_down_speed);
571        Heuristic {
572            per_block,
573            per_up,
574            per_down,
575        }
576    }
577}
578
579/// How much work one [`Search::step`] may do.
580#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
581#[non_exhaustive]
582pub struct Budget {
583    /// Most nodes to expand (at least 1).
584    pub nodes: usize,
585    /// Wall-clock limit, checked every 64 nodes (`None`: no limit).
586    pub time: Option<std::time::Duration>,
587}
588
589impl Budget {
590    /// No limit: the step finishes the search.
591    pub const UNLIMITED: Budget = Budget {
592        nodes: usize::MAX,
593        time: None,
594    };
595
596    /// At most `n` nodes.
597    #[must_use]
598    pub const fn nodes(n: usize) -> Budget {
599        Budget {
600            nodes: n,
601            time: None,
602        }
603    }
604
605    /// And at most `d` of wall-clock time.
606    #[must_use]
607    pub const fn with_time(mut self, d: std::time::Duration) -> Budget {
608        self.time = Some(d);
609        self
610    }
611}
612
613/// The open A* state of a [`Search`].
614#[derive(Clone)]
615struct SearchState {
616    cache: Sections,
617    recs: Vec<Rec>,
618    work: Vec<Work>,
619    index: HashMap<u64, u32, BuildKeyHasher>,
620    open: BinaryHeap<Open>,
621    best: u32,
622    expanded: usize,
623    edges: Vec<Edge>,
624    /// Nodes reached by a placing building move so far ([`BUILDING_NODES`]).
625    building: usize,
626}
627
628/// Most nodes one search reaches by placing moves (towering, bridging): far more than any real
629/// path places, small next to the node budget. Digging moves are only held to progress: a deep
630/// descent through solid ground has to try many columns (the dig costs dwarf the heuristic).
631const BUILDING_NODES: usize = 4096;
632
633/// How much further from the goal (in [`Goal::blocks_left`] terms) a building move may lead:
634/// a sideways bridge step adds at most `sqrt(2) - 1`, a step straight away a whole block.
635const BUILD_SLACK: f64 = 0.5;
636
637/// A move that builds its own way (see [`BUILDING_NODES`]). Tunnels, jump-ups into dug space
638/// and filled holes are not counted: they stay next to the terrain.
639fn is_building(e: &Edge) -> bool {
640    match e.kind {
641        MoveKind::Pillar | MoveKind::DigDown => true,
642        MoveKind::Descend => e.dig[0].is_some(),
643        _ => e.place.is_some_and(|p| p.face()[1] == 0),
644    }
645}
646
647/// A resumable path search ([`Pathfinder::search`]). Owns its state (`Send`, no borrows),
648/// so it can live in a behaviour between ticks.
649#[derive(Clone)]
650pub struct Search {
651    cfg: Config,
652    heur: Heuristic,
653    version: Version,
654    from: [i32; 3],
655    goal: Goal,
656    banned: HashSet<([i32; 3], [i32; 3])>,
657    state: Option<SearchState>,
658    result: Option<Result<Path, PlanError>>,
659    /// The open set ran out (every reachable node was expanded).
660    exhausted: bool,
661}
662
663impl std::fmt::Debug for Search {
664    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
665        f.debug_struct("Search")
666            .field("from", &self.from)
667            .field("goal", &self.goal)
668            .field("expanded", &self.expanded())
669            .field("done", &self.result.is_some())
670            .finish_non_exhaustive()
671    }
672}
673
674impl Search {
675    /// 26.1: plans with the moves the live player's attributes and effects allow (step height,
676    /// jump strength, jump boost, gravity; gap jumps only with vanilla jump, gravity, movement
677    /// speed and scale) instead of the vanilla ones. Call before the first [`Search::step`].
678    #[cfg(ghast_modern)]
679    #[must_use]
680    pub fn with_modern_player(mut self, player: &ghast_physics::modern::PlayerState) -> Search {
681        self.cfg.limits = Limits::of(player);
682        self
683    }
684
685    /// Nodes expanded so far.
686    #[must_use]
687    pub fn expanded(&self) -> usize {
688        self.state.as_ref().map_or(0, |s| s.expanded)
689    }
690
691    /// The start feet block.
692    #[must_use]
693    pub fn from(&self) -> [i32; 3] {
694        self.from
695    }
696
697    /// The goal.
698    #[must_use]
699    pub fn goal(&self) -> &Goal {
700        &self.goal
701    }
702
703    /// Whether the search has finished (the next [`Search::step`] returns the result).
704    #[must_use]
705    pub fn is_done(&self) -> bool {
706        self.result.is_some()
707    }
708
709    /// Whether the search ended because every node reachable from the start through known
710    /// (loaded) terrain was expanded, not because of the node budget
711    /// ([`Config::max_nodes`]). A partial result of an exhausted search is final for the
712    /// world as it is: no path to the goal exists through the loaded terrain, and the path
713    /// ends at the reachable node closest to the goal.
714    #[must_use]
715    pub fn exhausted(&self) -> bool {
716        self.exhausted
717    }
718
719    /// Runs the search for at most `budget` in `world`; the result once it is done (`None`:
720    /// call again). After the result, further steps return it again.
721    ///
722    /// # Errors
723    /// The result is the one of [`Pathfinder::plan`].
724    pub fn step<S: BlockSource + ?Sized>(
725        &mut self,
726        world: &S,
727        budget: Budget,
728    ) -> Option<Result<Path, PlanError>> {
729        if let Some(r) = &self.result {
730            return Some(r.clone());
731        }
732        let started = budget.time.map(|_| std::time::Instant::now());
733        let cache = self.state.as_mut().map(|s| std::mem::take(&mut s.cache));
734        let mut g = match cache {
735            Some(c) => Grid::with_cache(world, self.version, c),
736            None => Grid::new(world, self.version),
737        };
738        if self.state.is_none() {
739            let start = match start_spot(&mut g, self.from) {
740                Ok(s) => s,
741                Err(e) => {
742                    self.result = Some(Err(e));
743                    return self.result.clone();
744                }
745            };
746            let h0 = self.goal.estimate(self.from, &self.heur);
747            let mut st = SearchState {
748                cache: Sections::default(),
749                recs: Vec::with_capacity(4096),
750                work: Vec::new(),
751                index: HashMap::with_capacity_and_hasher(4096, BuildKeyHasher),
752                open: BinaryHeap::with_capacity(4096),
753                best: 0,
754                expanded: 0,
755                edges: Vec::with_capacity(32),
756                building: 0,
757            };
758            st.recs.push(Rec {
759                pos: self.from,
760                spot: start,
761                g: 0.0,
762                h: h0,
763                parent: u32::MAX,
764                work: NO_WORK,
765                kind: MoveKind::Start,
766                closed: false,
767            });
768            st.index.insert(pack(self.from), 0);
769            st.open.push(Open {
770                f: h0 * self.cfg.heuristic_weight,
771                h: h0,
772                idx: 0,
773            });
774            self.state = Some(st);
775        }
776        let costs = Costs::of(self.version);
777        let w = self.cfg.heuristic_weight;
778        let st = self.state.as_mut().expect("initialised above");
779        let limit = budget.nodes.max(1);
780        let mut n = 0usize;
781        // `Some(found)` once the search ends.
782        let mut end: Option<Option<u32>> = None;
783        loop {
784            if n >= limit {
785                break;
786            }
787            if n % 64 == 63
788                && let (Some(t0), Some(max)) = (started, budget.time)
789                && t0.elapsed() >= max
790            {
791                break;
792            }
793            let Some(Open { idx, .. }) = st.open.pop() else {
794                self.exhausted = true;
795                end = Some(None);
796                break;
797            };
798            let r = &mut st.recs[idx as usize];
799            if r.closed {
800                continue;
801            }
802            r.closed = true;
803            let (pos, sp, gcost) = (r.pos, r.spot, r.g);
804            if self.goal.is_reached(pos) {
805                end = Some(Some(idx));
806                break;
807            }
808            st.expanded += 1;
809            n += 1;
810            if st.expanded > self.cfg.max_nodes {
811                end = Some(None);
812                break;
813            }
814            st.edges.clear();
815            successors(
816                &mut g,
817                &self.cfg,
818                self.version,
819                costs,
820                pos,
821                &sp,
822                &mut st.edges,
823            );
824            for e in &st.edges {
825                if !self.banned.is_empty() && self.banned.contains(&(pos, e.to)) {
826                    continue;
827                }
828                let ng = gcost + e.cost;
829                let key = pack(e.to);
830                // Building moves (towering, bridging, digging down) never away from the goal,
831                // and a bounded number of placing ones per search: they open the whole sky /
832                // void / ground to the search, which would otherwise expand all of it before
833                // giving up on an unreachable goal. "Away" is more than [`BUILD_SLACK`] blocks
834                // further: a bridge one cell sideways round an obstacle, or a staircase step
835                // that trades one block across for one down, still counts as on the way.
836                let building = is_building(e);
837                if building
838                    && self.goal.blocks_left(e.to) > self.goal.blocks_left(pos) + BUILD_SLACK
839                {
840                    continue;
841                }
842                let work = |w: &mut Vec<Work>| {
843                    if e.dig[0].is_none() && e.place.is_none() {
844                        NO_WORK
845                    } else {
846                        w.push((e.dig, e.place));
847                        (w.len() - 1) as u32
848                    }
849                };
850                match st.index.get(&key) {
851                    Some(&i) => {
852                        let rr = &mut st.recs[i as usize];
853                        if rr.closed || ng >= rr.g - 1e-9 {
854                            continue;
855                        }
856                        rr.g = ng;
857                        rr.parent = idx;
858                        rr.spot = e.spot;
859                        rr.kind = e.kind;
860                        let h = rr.h;
861                        let wk = work(&mut st.work);
862                        st.recs[i as usize].work = wk;
863                        st.open.push(Open {
864                            f: ng + h * w,
865                            h,
866                            idx: i,
867                        });
868                    }
869                    None => {
870                        if building && e.place.is_some() {
871                            if st.building >= BUILDING_NODES {
872                                continue;
873                            }
874                            st.building += 1;
875                        }
876                        let h = self.goal.estimate(e.to, &self.heur);
877                        let i = st.recs.len() as u32;
878                        let wk = work(&mut st.work);
879                        st.recs.push(Rec {
880                            pos: e.to,
881                            spot: e.spot,
882                            g: ng,
883                            h,
884                            parent: idx,
885                            work: wk,
886                            kind: e.kind,
887                            closed: false,
888                        });
889                        st.index.insert(key, i);
890                        let b = &st.recs[st.best as usize];
891                        if h < b.h || (h == b.h && ng < b.g) {
892                            st.best = i;
893                        }
894                        st.open.push(Open {
895                            f: ng + h * w,
896                            h,
897                            idx: i,
898                        });
899                    }
900                }
901            }
902        }
903        st.cache = g.into_cache();
904        let found = end?;
905        let r = st.finish(found, self.exhausted, self.version);
906        // The search state is not needed any more.
907        let expanded = st.expanded;
908        self.state = Some(SearchState {
909            cache: Sections::default(),
910            recs: Vec::new(),
911            work: Vec::new(),
912            index: HashMap::default(),
913            open: BinaryHeap::new(),
914            best: 0,
915            expanded,
916            edges: Vec::new(),
917            building: 0,
918        });
919        self.result = Some(r);
920        self.result.clone()
921    }
922}
923
924impl SearchState {
925    fn finish(
926        &self,
927        found: Option<u32>,
928        exhausted: bool,
929        version: Version,
930    ) -> Result<Path, PlanError> {
931        let (end, partial) = match found {
932            Some(i) => (i, false),
933            None if self.best != 0 => (self.best, true),
934            // Out of nodes with nothing closer than the start (a dead end of a maze): the
935            // most promising node not expanded yet, where the search would have gone on.
936            None if !exhausted => match self
937                .open
938                .iter()
939                .filter(|o| !self.recs[o.idx as usize].closed)
940                .min_by(|a, b| a.f.total_cmp(&b.f).then(a.h.total_cmp(&b.h)))
941            {
942                Some(o) => (o.idx, true),
943                None => return Err(PlanError::NoPath),
944            },
945            None => return Err(PlanError::NoPath),
946        };
947        let mut steps = Vec::new();
948        let mut i = end;
949        while i != u32::MAX {
950            let r = &self.recs[i as usize];
951            let (dig, place) = match self.work.get(r.work as usize) {
952                Some((d, p)) => (d.iter().flatten().copied().collect(), *p),
953                None => (Vec::new(), None),
954            };
955            steps.push(Step {
956                pos: r.pos,
957                feet_y: r.spot.floor,
958                kind: r.kind,
959                node: r.spot.kind,
960                dig,
961                place,
962            });
963            i = r.parent;
964        }
965        steps.reverse();
966        Ok(Path {
967            cost: self.recs[end as usize].g,
968            steps,
969            partial,
970            expanded: self.expanded,
971            version,
972        })
973    }
974}
975
976fn start_spot<S: BlockSource + ?Sized>(
977    g: &mut Grid<'_, S>,
978    p: [i32; 3],
979) -> Result<Spot, PlanError> {
980    if g.unknown(p[0], p[1], p[2]) || g.unknown(p[0], p[1] - 1, p[2]) {
981        return Err(PlanError::StartUnknown);
982    }
983    if let Some(s) = spot(g, p[0], p[1], p[2]) {
984        return Ok(s);
985    }
986    // Mid-air or in a place the model does not stand in: start as if standing at the block's
987    // bottom if the body fits there at all.
988    let base = f64::from(p[1]);
989    if clear(g, p[0], p[2], base, base + HEIGHT) {
990        return Ok(Spot {
991            kind: NodeKind::Ground,
992            floor: base,
993            floor_flags: 0,
994            water: false,
995            submerged: false,
996            climb: false,
997        });
998    }
999    Err(PlanError::StartBlocked)
1000}
1001
1002const CARDINALS: [(i32, i32); 4] = [(0, 1), (1, 0), (0, -1), (-1, 0)];
1003const DIAGONALS: [(i32, i32); 4] = [(1, 1), (1, -1), (-1, 1), (-1, -1)];
1004
1005/// Extra ticks for the floor a step ends on.
1006fn floor_penalty(s: &Spot, per_block: f64) -> f64 {
1007    let mut p = 0.0;
1008    if s.floor_flags & flag::SLOW != 0 {
1009        p += per_block * 1.5;
1010    }
1011    if s.floor_flags & flag::SLIPPERY != 0 {
1012        p += 2.0;
1013    }
1014    if s.floor_flags & flag::BOUNCY != 0 {
1015        p += 12.0;
1016    }
1017    if s.submerged {
1018        p += 4.0;
1019    }
1020    p
1021}
1022
1023fn dig_cost<S: BlockSource + ?Sized>(g: &mut Grid<'_, S>, d: &DigCost, p: [i32; 3]) -> Option<f64> {
1024    let c = g.class(p[0], p[1], p[2]);
1025    if !c.has(flag::SOLID) {
1026        return Some(0.0);
1027    }
1028    if !c.has(flag::DIGGABLE) || f64::from(c.hardness) > d.max_hardness {
1029        return None;
1030    }
1031    // Never open a liquid or bring down a falling block.
1032    if g.class(p[0], p[1] + 1, p[2])
1033        .has(flag::FALLING | flag::WATER | flag::LAVA)
1034    {
1035        return None;
1036    }
1037    for (dx, dz) in CARDINALS {
1038        if g.class(p[0] + dx, p[1], p[2] + dz)
1039            .has(flag::WATER | flag::LAVA)
1040        {
1041            return None;
1042        }
1043    }
1044    Some(d.base + d.ticks_per_hardness * f64::from(c.hardness))
1045}
1046
1047fn push(out: &mut Vec<Edge>, to: [i32; 3], spot: Spot, kind: MoveKind, cost: f64) {
1048    out.push(Edge {
1049        to,
1050        spot,
1051        kind,
1052        cost,
1053        dig: [None; 3],
1054        place: None,
1055    });
1056}
1057
1058/// All moves out of `p` (standing as `s`).
1059pub(crate) fn successors<S: BlockSource + ?Sized>(
1060    g: &mut Grid<'_, S>,
1061    cfg: &Config,
1062    version: Version,
1063    c: &Costs,
1064    p: [i32; 3],
1065    s: &Spot,
1066    out: &mut Vec<Edge>,
1067) {
1068    moves_from(g, cfg, version, c, p, s, out);
1069    if g.saw_doors() {
1070        through_doors(g, p, s, out);
1071    }
1072}
1073
1074/// [`successors`] before the door checks.
1075fn moves_from<S: BlockSource + ?Sized>(
1076    g: &mut Grid<'_, S>,
1077    cfg: &Config,
1078    version: Version,
1079    c: &Costs,
1080    p: [i32; 3],
1081    s: &Spot,
1082    out: &mut Vec<Edge>,
1083) {
1084    let per_block = 1.0
1085        / if cfg.sprint {
1086            c.sprint_speed
1087        } else {
1088            c.walk_speed
1089        };
1090    let swim_block = 1.0 / c.swim_speed;
1091    let [x, y, z] = p;
1092    let f0 = s.floor;
1093
1094    // Vertical moves.
1095    match s.kind {
1096        NodeKind::Swim if cfg.swim => {
1097            if let Some(t) = spot(g, x, y + 1, z) {
1098                push(
1099                    out,
1100                    [x, y + 1, z],
1101                    t,
1102                    MoveKind::Swim,
1103                    1.0 / c.swim_up_speed + floor_penalty(&t, per_block),
1104                );
1105            }
1106            if let Some(t) = spot(g, x, y - 1, z) {
1107                push(
1108                    out,
1109                    [x, y - 1, z],
1110                    t,
1111                    MoveKind::Swim,
1112                    1.0 / c.swim_down_speed,
1113                );
1114            }
1115        }
1116        NodeKind::Ground if cfg.swim && s.water => {
1117            // Rise out of shallow water to swim at the surface.
1118            if let Some(t) = spot(g, x, y + 1, z)
1119                && t.kind == NodeKind::Swim
1120            {
1121                push(out, [x, y + 1, z], t, MoveKind::Swim, 1.0 / c.swim_up_speed);
1122            }
1123        }
1124        _ => {}
1125    }
1126    if cfg.climb && s.climb {
1127        if let Some(t) = spot(g, x, y + 1, z)
1128            && t.climb
1129            && (climb_wall(g, x, y, z).is_some() || climbs_without_wall(version))
1130        {
1131            push(
1132                out,
1133                [x, y + 1, z],
1134                t,
1135                MoveKind::ClimbUp,
1136                1.0 / c.climb_up_speed,
1137            );
1138        }
1139        if s.kind == NodeKind::Climb
1140            && let Some(t) = spot(g, x, y - 1, z)
1141            && (t.climb || t.kind == NodeKind::Ground)
1142        {
1143            push(
1144                out,
1145                [x, y - 1, z],
1146                t,
1147                MoveKind::ClimbDown,
1148                1.0 / c.climb_down_speed,
1149            );
1150        }
1151    }
1152
1153    // Dig out the floor and fall onto the next one below.
1154    if s.kind == NodeKind::Ground
1155        && !s.water
1156        && let Some(d) = &cfg.dig
1157    {
1158        dig_down(g, cfg, d, c, p, f0, out);
1159    }
1160    // Tower up: jump, place a block under the feet.
1161    if s.kind == NodeKind::Ground
1162        && !s.water
1163        && let Some(pc) = cfg.place
1164    {
1165        pillar(g, pc, c, p, s, out);
1166    }
1167
1168    let swimming = s.kind == NodeKind::Swim;
1169    let climbing = s.kind == NodeKind::Climb;
1170    if (swimming && !cfg.swim) || (climbing && !cfg.climb) {
1171        return;
1172    }
1173
1174    // Cardinal moves.
1175    for (dx, dz) in CARDINALS {
1176        let (bx, bz) = (x + dx, z + dz);
1177        let mut found = false;
1178        // One block up: step-up, jump-up, swim out, climb off.
1179        if let Some(t) = spot(g, bx, y + 1, bz)
1180            && t.kind == NodeKind::Ground
1181        {
1182            let dh = t.floor - f0;
1183            if climbing {
1184                if dh <= 1.5 + 1e-6 && clear(g, x, z, f0 + HEIGHT, t.floor + HEIGHT) {
1185                    push(
1186                        out,
1187                        [bx, y + 1, bz],
1188                        t,
1189                        MoveKind::ClimbExit,
1190                        1.0 / c.climb_up_speed + per_block + floor_penalty(&t, per_block),
1191                    );
1192                    found = true;
1193                }
1194            } else if swimming || s.water {
1195                if dh <= 1.2 && clear(g, x, z, f0 + HEIGHT, t.floor + HEIGHT + 0.4) {
1196                    push(
1197                        out,
1198                        [bx, y + 1, bz],
1199                        t,
1200                        MoveKind::Swim,
1201                        swim_block + c.jump_up + floor_penalty(&t, per_block),
1202                    );
1203                    found = true;
1204                }
1205            } else if dh <= cfg.limits.step + 1e-6 {
1206                if clear(g, x, z, f0 + HEIGHT, t.floor + HEIGHT) {
1207                    push(
1208                        out,
1209                        [bx, y + 1, bz],
1210                        t,
1211                        MoveKind::Walk,
1212                        per_block + 0.5 + floor_penalty(&t, per_block),
1213                    );
1214                    found = true;
1215                }
1216            } else if dh <= cfg.limits.jump_up && jump_room(g, x, z, bx, bz, f0, &t) {
1217                push(
1218                    out,
1219                    [bx, y + 1, bz],
1220                    t,
1221                    MoveKind::Ascend,
1222                    c.jump_up + floor_penalty(&t, per_block),
1223                );
1224                found = true;
1225            }
1226        }
1227        // Dig through to reach the step above (jump-up into a tunnel).
1228        if !found
1229            && !swimming
1230            && !climbing
1231            && let Some(d) = &cfg.dig
1232            && (f0 - f64::from(y)).abs() < 1e-6
1233        {
1234            found |= dig_up(g, d, c, p, (dx, dz), out);
1235        }
1236        if found {
1237            continue;
1238        }
1239        // Same level and drops.
1240        let lowest = y - (cfg.max_fall.max(cfg.max_water_fall).ceil() as i32) - 1;
1241        let mut yt = y;
1242        while yt >= lowest.max(g.y_range().0 + 1) {
1243            if let Some(t) = spot(g, bx, yt, bz) {
1244                let dh = t.floor - f0;
1245                let top = t.floor.max(f0) + HEIGHT;
1246                if dh > cfg.limits.step + 1e-6 {
1247                    // A higher floor in the same block (soul sand, a slab on a step).
1248                    if !swimming
1249                        && !climbing
1250                        && dh <= cfg.limits.jump_up
1251                        && jump_room(g, x, z, bx, bz, f0, &t)
1252                    {
1253                        push(
1254                            out,
1255                            [bx, yt, bz],
1256                            t,
1257                            MoveKind::Ascend,
1258                            c.jump_up + floor_penalty(&t, per_block),
1259                        );
1260                    } else if (swimming || s.water) && dh <= 1.2 {
1261                        push(out, [bx, yt, bz], t, MoveKind::Swim, swim_block + c.jump_up);
1262                    }
1263                } else if dh >= -STEP - 1e-6 {
1264                    let kind = if swimming || t.kind == NodeKind::Swim || (s.water && t.water) {
1265                        MoveKind::Swim
1266                    } else {
1267                        MoveKind::Walk
1268                    };
1269                    let ok = match t.kind {
1270                        NodeKind::Swim => cfg.swim,
1271                        NodeKind::Climb => cfg.climb,
1272                        NodeKind::Ground => true,
1273                    };
1274                    if ok
1275                        && clear(g, x, z, f0 + HEIGHT, top)
1276                        && clear(g, bx, bz, t.floor + HEIGHT, top)
1277                    {
1278                        let cost = if kind == MoveKind::Swim {
1279                            swim_block
1280                        } else {
1281                            per_block
1282                        };
1283                        push(
1284                            out,
1285                            [bx, yt, bz],
1286                            t,
1287                            kind,
1288                            cost + floor_penalty(&t, per_block),
1289                        );
1290                    }
1291                } else if t.kind == NodeKind::Climb && cfg.climb && -dh <= 1.5 + 1e-6 {
1292                    // Onto a ladder from above: fall into it and hold on.
1293                    if clear(g, bx, bz, t.floor + HEIGHT, f0 + HEIGHT) {
1294                        push(
1295                            out,
1296                            [bx, yt, bz],
1297                            t,
1298                            MoveKind::ClimbDown,
1299                            per_block + (-dh) / c.climb_down_speed,
1300                        );
1301                    }
1302                } else if !climbing {
1303                    let drop = -dh;
1304                    let deep = t.kind == NodeKind::Swim && g.class(bx, yt - 1, bz).has(flag::WATER);
1305                    let into_water = t.kind == NodeKind::Swim || t.water;
1306                    let limit = if deep {
1307                        cfg.max_water_fall
1308                    } else {
1309                        cfg.max_fall
1310                    };
1311                    let landing_ok = t.floor_flags & (flag::FRAGILE | flag::BOUNCY) == 0;
1312                    if drop <= limit + 1e-6
1313                        && landing_ok
1314                        && (cfg.swim || !into_water)
1315                        && t.kind != NodeKind::Climb
1316                        && clear(g, bx, bz, t.floor + HEIGHT, f0 + HEIGHT)
1317                    {
1318                        push(
1319                            out,
1320                            [bx, yt, bz],
1321                            t,
1322                            MoveKind::Descend,
1323                            per_block + c.fall_ticks(drop) + 2.0 + floor_penalty(&t, per_block),
1324                        );
1325                    }
1326                }
1327                found = true;
1328                break;
1329            }
1330            // Keep falling only through cells the body passes.
1331            if !clear(g, bx, bz, f64::from(yt), f64::from(yt) + 1.0) {
1332                break;
1333            }
1334            yt -= 1;
1335        }
1336        if !found
1337            && !swimming
1338            && !climbing
1339            && let Some(d) = &cfg.dig
1340        {
1341            dig_through(g, d, per_block, p, f0, (dx, dz), out);
1342            dig_stair(g, d, c, per_block, p, f0, (dx, dz), out);
1343        }
1344        if !found && !swimming && !climbing && g.saw_doors() {
1345            open_block(g, version, per_block, p, f0, (dx, dz), out);
1346        }
1347        // Filling a one-deep hole competes with dropping into it.
1348        if !swimming
1349            && !climbing
1350            && let Some(pc) = cfg.place
1351            && spot(g, bx, y, bz).is_none()
1352            && !fill_hole(g, pc, per_block, p, f0, (dx, dz), out)
1353        {
1354            bridge(g, pc, per_block, p, s, (dx, dz), out);
1355        }
1356        if cfg.parkour
1357            && cfg.limits.parkour
1358            && !swimming
1359            && !climbing
1360            && s.kind == NodeKind::Ground
1361            && !s.water
1362        {
1363            parkour(g, cfg, version, p, s, (dx, dz), out);
1364        }
1365    }
1366
1367    // Diagonals (flat-ish only).
1368    if climbing {
1369        return;
1370    }
1371    for (dx, dz) in DIAGONALS {
1372        let (bx, bz) = (x + dx, z + dz);
1373        for yt in [y + 1, y, y - 1] {
1374            let Some(t) = spot(g, bx, yt, bz) else {
1375                continue;
1376            };
1377            let dh = t.floor - f0;
1378            if dh > cfg.limits.step + 1e-6 || dh < -STEP - 1e-6 {
1379                if yt == y {
1380                    break;
1381                }
1382                continue;
1383            }
1384            if (t.kind == NodeKind::Swim) != swimming {
1385                break;
1386            }
1387            let lo = t.floor.max(f0);
1388            let hi = lo + HEIGHT;
1389            // The box crosses both side columns: each needs a floor near the path's (a hole
1390            // beside the corner catches a box that strays from the diagonal).
1391            let floored = |g: &mut Grid<'_, S>, sx: i32, sz: i32| {
1392                [y, yt].iter().any(|&yy| {
1393                    spot(g, sx, yy, sz).is_some_and(|sp| {
1394                        sp.kind == NodeKind::Ground && sp.floor >= t.floor.min(f0) - STEP - 1e-6
1395                    })
1396                })
1397            };
1398            if !swimming && (!floored(g, x + dx, z) || !floored(g, x, z + dz)) {
1399                break;
1400            }
1401            if clear(g, x + dx, z, lo, hi)
1402                && clear(g, x, z + dz, lo, hi)
1403                && clear(g, x, z, f0 + HEIGHT, hi)
1404                && clear(g, bx, bz, t.floor + HEIGHT, hi)
1405            {
1406                let base = if swimming || (s.water && t.water) {
1407                    swim_block
1408                } else {
1409                    per_block
1410                };
1411                let kind = if swimming || (s.water && t.water) {
1412                    MoveKind::Swim
1413                } else {
1414                    MoveKind::Diagonal
1415                };
1416                push(
1417                    out,
1418                    [bx, yt, bz],
1419                    t,
1420                    kind,
1421                    base * std::f64::consts::SQRT_2
1422                        + floor_penalty(&t, per_block)
1423                        + if dh > 1e-6 { 0.5 } else { 0.0 },
1424                );
1425            }
1426            break;
1427        }
1428    }
1429}
1430
1431/// Room for a standing jump from `f0` in column (x, z) onto `t` in column (bx, bz).
1432fn jump_room<S: BlockSource + ?Sized>(
1433    g: &mut Grid<'_, S>,
1434    x: i32,
1435    z: i32,
1436    bx: i32,
1437    bz: i32,
1438    f0: f64,
1439    t: &Spot,
1440) -> bool {
1441    let top = f0 + HEIGHT + JUMP_APEX;
1442    let ca = ceiling(g, x, z, f0 + HEIGHT, top);
1443    let cb = ceiling(g, bx, bz, t.floor + HEIGHT, top);
1444    let apex = ca.min(cb) - HEIGHT - f0;
1445    apex >= (t.floor - f0) + JUMP_MARGIN
1446}
1447
1448/// Gap jumps from `p` in direction `d`: over 1 to 4 columns onto a block up to one higher or
1449/// two lower, each only in a mode validated in the physics (see [`crate::jump`]) and only
1450/// where every cell the body sweeps in that mode is free.
1451fn parkour<S: BlockSource + ?Sized>(
1452    g: &mut Grid<'_, S>,
1453    cfg: &Config,
1454    version: Version,
1455    p: [i32; 3],
1456    s: &Spot,
1457    (dx, dz): (i32, i32),
1458    out: &mut Vec<Edge>,
1459) {
1460    let [x, y, z] = p;
1461    // Exact full-block floors with ordinary friction at the take-off.
1462    if (s.floor - f64::from(y)).abs() > 1e-6 || !jump::plain_floor(g.class(x, y - 1, z)) {
1463        return;
1464    }
1465    // Something to walk onto (or step up onto) next to the take-off: no gap.
1466    let walkable = |g: &mut Grid<'_, S>, cx: i32, cz: i32| {
1467        [y + 1, y].iter().any(|&yy| {
1468            spot(g, cx, yy, cz).is_some_and(|t| (t.floor - s.floor).abs() <= STEP + 1e-6)
1469        })
1470    };
1471    if walkable(g, x + dx, z + dz) {
1472        return;
1473    }
1474    let jumps = jump::Jumps::of(version);
1475    for gap in 1..=jumps.widest() {
1476        // A floor at the take-off level ends the run of gaps: walk there, jump from there.
1477        if gap > 1 && walkable(g, x + dx * i32::from(gap), z + dz * i32::from(gap)) {
1478            return;
1479        }
1480        let a = i32::from(gap) + 1;
1481        let (tx, tz) = (x + dx * a, z + dz * a);
1482        for dy in jump::DYS {
1483            let ty = y + i32::from(dy);
1484            let Some(t) = spot(g, tx, ty, tz) else {
1485                continue;
1486            };
1487            if t.kind != NodeKind::Ground
1488                || t.water
1489                || (t.floor - f64::from(ty)).abs() > 1e-6
1490                || !jump::plain_floor(g.class(tx, ty - 1, tz))
1491            {
1492                continue;
1493            }
1494            let Some(spec) = jump::select(&jumps, p, (dx, dz), gap, dy, cfg.sprint, |q| {
1495                g.class(q[0], q[1], q[2])
1496            }) else {
1497                continue;
1498            };
1499            if f64::from(spec.fall) > cfg.max_fall + 1e-6 {
1500                continue;
1501            }
1502            push(
1503                out,
1504                [tx, ty, tz],
1505                t,
1506                MoveKind::Parkour { gap },
1507                f64::from(spec.cost),
1508            );
1509        }
1510    }
1511}
1512
1513/// Extra ticks of a door move: the click, the server's answer.
1514const DOOR_TICKS: f64 = 8.0;
1515
1516/// The door slabs ([`flag::PANEL`]) in column (x, z) between heights `lo` and `hi`
1517/// (absolute): `(y, class)`, at most four.
1518fn panels_in<S: BlockSource + ?Sized>(
1519    g: &mut Grid<'_, S>,
1520    x: i32,
1521    z: i32,
1522    lo: f64,
1523    hi: f64,
1524) -> ([(i32, Class); 4], usize) {
1525    let mut out = [(0, Class::UNKNOWN); 4];
1526    let mut n = 0;
1527    for y in lo.floor() as i32..=(hi - 1e-6).floor() as i32 {
1528        let c = g.class(x, y, z);
1529        if c.has(flag::PANEL) && n < 4 {
1530            out[n] = (y, c);
1531            n += 1;
1532        }
1533    }
1534    (out, n)
1535}
1536
1537/// Door slabs: keeps a move only when it crosses none of them, turns a walk through one
1538/// closed (or swung-into-the-way) wooden door into a [`MoveKind::Door`] move, and drops every
1539/// other move touching a door cell that is not a straight cardinal one.
1540fn through_doors<S: BlockSource + ?Sized>(
1541    g: &mut Grid<'_, S>,
1542    p: [i32; 3],
1543    s: &Spot,
1544    out: &mut Vec<Edge>,
1545) {
1546    let [x, _, z] = p;
1547    let mut i = 0;
1548    while i < out.len() {
1549        let e = out[i];
1550        let (dx, dz) = (e.to[0] - x, e.to[2] - z);
1551        if dx == 0 && dz == 0 {
1552            // Straight up or down at the centre: a side slab is never in the way.
1553            i += 1;
1554            continue;
1555        }
1556        let lo = s.floor.min(e.spot.floor);
1557        let hi = s.floor.max(e.spot.floor) + HEIGHT;
1558        let (from, nf) = panels_in(g, x, z, lo, hi);
1559        let (to, nt) = panels_in(g, e.to[0], e.to[2], lo, hi);
1560        if nf == 0 && nt == 0 {
1561            i += 1;
1562            continue;
1563        }
1564        let keep = if dx.abs() + dz.abs() != 1 || matches!(e.kind, MoveKind::Parkour { .. }) {
1565            false
1566        } else {
1567            let (out_wall, in_wall) = (door::wall_of(dx, dz), door::wall_of(-dx, -dz));
1568            let mut blocker: Option<([i32; 3], bool)> = None;
1569            let mut many = false;
1570            for (col, list, n, wall) in [
1571                ([x, z], &from, nf, out_wall),
1572                ([e.to[0], e.to[2]], &to, nt, in_wall),
1573            ] {
1574                for &(y, c) in &list[..n] {
1575                    if c.wall != wall {
1576                        continue;
1577                    }
1578                    let at = [col[0], y, col[1]];
1579                    // Doors and gates only: a trapdoor's slab across the way lies flat once
1580                    // clicked, which this move does not model.
1581                    let open = c.has(flag::OPENABLE) && !c.has(flag::HATCH);
1582                    match blocker {
1583                        None => blocker = Some((at, open)),
1584                        Some((b, o)) => {
1585                            // Both halves of one door: click the lower one.
1586                            if b[0] == at[0] && b[2] == at[2] {
1587                                blocker = Some((if at[1] < b[1] { at } else { b }, o && open));
1588                            } else {
1589                                many = true;
1590                            }
1591                        }
1592                    }
1593                }
1594            }
1595            match blocker {
1596                None => true,
1597                Some((at, true))
1598                    if !many
1599                        && e.kind == MoveKind::Walk
1600                        && e.dig[0].is_none()
1601                        && e.place.is_none() =>
1602                {
1603                    out[i].kind = MoveKind::Door { block: at };
1604                    out[i].cost += DOOR_TICKS;
1605                    true
1606                }
1607                Some(_) => false,
1608            }
1609        };
1610        if keep {
1611            i += 1;
1612        } else {
1613            out.remove(i);
1614        }
1615    }
1616}
1617
1618/// Through a closed fence gate or a trapdoor in the neighbour (bx, y, bz) at feet or head
1619/// height: click it, walk in, where its clicked state lets the body through (a trapdoor swings
1620/// to a side; across the way it would still block).
1621fn open_block<S: BlockSource + ?Sized>(
1622    g: &mut Grid<'_, S>,
1623    version: Version,
1624    per_block: f64,
1625    p: [i32; 3],
1626    f0: f64,
1627    (dx, dz): (i32, i32),
1628    out: &mut Vec<Edge>,
1629) {
1630    let [x, y, z] = p;
1631    if (f0 - f64::from(y)).abs() > 1e-6 {
1632        return;
1633    }
1634    let (bx, bz) = (x + dx, z + dz);
1635    let entry = door::wall_of(-dx, -dz);
1636    // The body's part of each cell, and whether a class lets it pass.
1637    let passes = |c: &Class, hi: f32| {
1638        !c.blocks_standing(0.0, hi) && !(c.has(flag::PANEL) && c.wall == entry)
1639    };
1640    let mut blocker = None;
1641    for (yy, hi) in [(y, 1.0f32), (y + 1, (HEIGHT - 1.0) as f32)] {
1642        let c = g.class(bx, yy, bz);
1643        if c.has(flag::AVOID | flag::LAVA) {
1644            return;
1645        }
1646        if passes(&c, hi) {
1647            continue;
1648        }
1649        if !c.has(flag::OPENABLE) || blocker.is_some() {
1650            return;
1651        }
1652        blocker = Some((yy, hi));
1653    }
1654    let Some((yy, hi)) = blocker else {
1655        return;
1656    };
1657    let fl = g.class(bx, y - 1, bz);
1658    if !fl.has(flag::SUPPORT)
1659        || fl.has(flag::IRREGULAR | flag::AVOID_FLOOR)
1660        || fl.top < 1.0 - 1e-6
1661        || fl.top_any > 1.0 + 1e-6
1662    {
1663        return;
1664    }
1665    match door::toggled_class(version, g.source(), [bx, yy, bz]) {
1666        Some(after) if passes(&after, hi) => {}
1667        _ => return,
1668    }
1669    out.push(Edge {
1670        to: [bx, y, bz],
1671        spot: Spot {
1672            kind: NodeKind::Ground,
1673            floor: f0,
1674            floor_flags: fl.flags,
1675            water: false,
1676            submerged: false,
1677            climb: false,
1678        },
1679        kind: MoveKind::Door {
1680            block: [bx, yy, bz],
1681        },
1682        cost: per_block + DOOR_TICKS,
1683        dig: [None; 3],
1684        place: None,
1685    });
1686}
1687
1688/// Tunnel: walk into the neighbour at the same level after digging its body blocks.
1689fn dig_through<S: BlockSource + ?Sized>(
1690    g: &mut Grid<'_, S>,
1691    d: &DigCost,
1692    per_block: f64,
1693    p: [i32; 3],
1694    f0: f64,
1695    (dx, dz): (i32, i32),
1696    out: &mut Vec<Edge>,
1697) -> bool {
1698    let [x, y, z] = p;
1699    if (f0 - f64::from(y)).abs() > 1e-6 {
1700        return false;
1701    }
1702    let (bx, bz) = (x + dx, z + dz);
1703    let fl = g.class(bx, y - 1, bz);
1704    if !(fl.has(flag::SUPPORT) && fl.top >= 1.0 - 1e-6 && fl.top_any <= 1.0 + 1e-6)
1705        || fl.has(flag::AVOID_FLOOR | flag::IRREGULAR)
1706    {
1707        return false;
1708    }
1709    let mut cost = per_block;
1710    let mut dig = [None; 3];
1711    let mut n = 0;
1712    for yy in [y + 1, y] {
1713        let c = g.class(bx, yy, bz);
1714        if g.unknown(bx, yy, bz) || c.has(flag::AVOID | flag::LAVA | flag::WATER) {
1715            return false;
1716        }
1717        if c.has(flag::SOLID) {
1718            match dig_cost(g, d, [bx, yy, bz]) {
1719                Some(k) => {
1720                    cost += k;
1721                    dig[n] = Some([bx, yy, bz]);
1722                    n += 1;
1723                }
1724                None => return false,
1725            }
1726        }
1727    }
1728    if n == 0 {
1729        return false;
1730    }
1731    let spot = Spot {
1732        kind: NodeKind::Ground,
1733        floor: f0,
1734        floor_flags: fl.flags,
1735        water: false,
1736        submerged: false,
1737        climb: false,
1738    };
1739    out.push(Edge {
1740        to: [bx, y, bz],
1741        spot,
1742        kind: MoveKind::Walk,
1743        cost,
1744        dig,
1745        place: None,
1746    });
1747    true
1748}
1749
1750/// Dig out the full block under the feet at `p` and fall straight down onto the next full
1751/// floor, at most [`Config::max_fall`] below. Never into a liquid, onto a hazard or a fragile /
1752/// bouncy floor, or through unknown blocks; the dig itself follows [`dig_cost`] (no liquid next
1753/// to the block, nothing falling onto the player).
1754fn dig_down<S: BlockSource + ?Sized>(
1755    g: &mut Grid<'_, S>,
1756    cfg: &Config,
1757    d: &DigCost,
1758    c: &Costs,
1759    p: [i32; 3],
1760    f0: f64,
1761    out: &mut Vec<Edge>,
1762) {
1763    let [x, y, z] = p;
1764    if (f0 - f64::from(y)).abs() > 1e-6 {
1765        return;
1766    }
1767    let below = [x, y - 1, z];
1768    let fl = g.class(x, y - 1, z);
1769    if !fl.has(flag::SUPPORT) || fl.has(flag::IRREGULAR) || fl.top < 1.0 - 1e-6 {
1770        return;
1771    }
1772    let Some(k) = dig_cost(g, d, below) else {
1773        return;
1774    };
1775    // Fall through the dug cell (feet there first) until a full floor carries the player.
1776    let lowest = (y - cfg.max_fall.floor() as i32).max(g.y_range().0 + 1);
1777    let mut yt = y - 1;
1778    while yt >= lowest {
1779        if yt < y - 1 {
1780            // The cell the feet fall into (the dug cell itself needs no check).
1781            let c0 = g.class(x, yt, z);
1782            if c0.has(flag::SOLID | flag::WATER | flag::LAVA | flag::AVOID | flag::CLIMB) {
1783                return;
1784            }
1785        }
1786        let cb = g.class(x, yt - 1, z);
1787        if cb.has(flag::WATER | flag::LAVA | flag::AVOID | flag::CLIMB) {
1788            return;
1789        }
1790        if cb.has(flag::SOLID) {
1791            if !cb.has(flag::SUPPORT)
1792                || cb.has(flag::IRREGULAR | flag::AVOID_FLOOR | flag::FRAGILE | flag::BOUNCY)
1793                || cb.top < 1.0 - 1e-6
1794                || cb.top_any > 1.0 + 1e-6
1795            {
1796                return;
1797            }
1798            let drop = f64::from(y - yt);
1799            out.push(Edge {
1800                to: [x, yt, z],
1801                spot: Spot {
1802                    kind: NodeKind::Ground,
1803                    floor: f64::from(yt),
1804                    floor_flags: cb.flags,
1805                    water: false,
1806                    submerged: false,
1807                    climb: false,
1808                },
1809                kind: MoveKind::DigDown,
1810                // Centring over the block, the dig, the fall and landing.
1811                cost: k + c.fall_ticks(drop) + 4.0,
1812                dig: [Some(below), None, None],
1813                place: None,
1814            });
1815            return;
1816        }
1817        yt -= 1;
1818    }
1819}
1820
1821/// Staircase down: dig what is in the way in the neighbour column (the cell the head passes,
1822/// then the body's two cells one lower) and step down one block onto its floor. No fall
1823/// damage at any depth; every dig follows [`dig_cost`]. A [`MoveKind::Descend`] with digs.
1824#[allow(clippy::too_many_arguments)]
1825fn dig_stair<S: BlockSource + ?Sized>(
1826    g: &mut Grid<'_, S>,
1827    d: &DigCost,
1828    c: &Costs,
1829    per_block: f64,
1830    p: [i32; 3],
1831    f0: f64,
1832    (dx, dz): (i32, i32),
1833    out: &mut Vec<Edge>,
1834) -> bool {
1835    let [x, y, z] = p;
1836    if (f0 - f64::from(y)).abs() > 1e-6 || y - 1 <= g.y_range().0 {
1837        return false;
1838    }
1839    let (bx, bz) = (x + dx, z + dz);
1840    let fl = g.class(bx, y - 2, bz);
1841    if !fl.has(flag::SUPPORT)
1842        || fl.has(flag::IRREGULAR | flag::AVOID_FLOOR | flag::FRAGILE | flag::BOUNCY | flag::WATER)
1843        || fl.top < 1.0 - 1e-6
1844        || fl.top_any > 1.0 + 1e-6
1845    {
1846        return false;
1847    }
1848    let mut cost = per_block + c.fall_ticks(1.0) + 2.0;
1849    let mut dig = [None; 3];
1850    let mut n = 0;
1851    for yy in [y + 1, y, y - 1] {
1852        let q = [bx, yy, bz];
1853        let cl = g.class(q[0], q[1], q[2]);
1854        if g.unknown(q[0], q[1], q[2]) || cl.has(flag::AVOID | flag::LAVA | flag::WATER) {
1855            return false;
1856        }
1857        if cl.has(flag::SOLID) {
1858            match dig_cost(g, d, q) {
1859                Some(k) => {
1860                    cost += k;
1861                    dig[n] = Some(q);
1862                    n += 1;
1863                }
1864                None => return false,
1865            }
1866        }
1867    }
1868    if n == 0 {
1869        return false;
1870    }
1871    out.push(Edge {
1872        to: [bx, y - 1, bz],
1873        spot: Spot {
1874            kind: NodeKind::Ground,
1875            floor: f0 - 1.0,
1876            floor_flags: fl.flags,
1877            water: false,
1878            submerged: false,
1879            climb: false,
1880        },
1881        kind: MoveKind::Descend,
1882        cost,
1883        dig,
1884        place: None,
1885    });
1886    true
1887}
1888
1889/// Jump up into the neighbour one block higher after digging what is in the way.
1890fn dig_up<S: BlockSource + ?Sized>(
1891    g: &mut Grid<'_, S>,
1892    d: &DigCost,
1893    c: &Costs,
1894    p: [i32; 3],
1895    (dx, dz): (i32, i32),
1896    out: &mut Vec<Edge>,
1897) -> bool {
1898    let [x, y, z] = p;
1899    let (bx, bz) = (x + dx, z + dz);
1900    let fl = g.class(bx, y, bz);
1901    if !(fl.has(flag::SUPPORT) && fl.top >= 1.0 - 1e-6 && fl.top_any <= 1.0 + 1e-6)
1902        || fl.has(flag::AVOID_FLOOR | flag::IRREGULAR)
1903    {
1904        return false;
1905    }
1906    // Needs: (x, y+2) above the origin (the jump), (bx, y+1), (bx, y+2) for the body.
1907    let cells = [[x, y + 2, z], [bx, y + 2, bz], [bx, y + 1, bz]];
1908    let mut cost = c.jump_up;
1909    let mut dig = [None; 3];
1910    let mut n = 0;
1911    for q in cells {
1912        let cl = g.class(q[0], q[1], q[2]);
1913        if g.unknown(q[0], q[1], q[2]) || cl.has(flag::AVOID | flag::LAVA | flag::WATER) {
1914            return false;
1915        }
1916        if cl.has(flag::SOLID) {
1917            match dig_cost(g, d, q) {
1918                Some(k) => {
1919                    cost += k;
1920                    dig[n] = Some(q);
1921                    n += 1;
1922                }
1923                None => return false,
1924            }
1925        }
1926    }
1927    if n == 0 {
1928        return false;
1929    }
1930    // Headroom above the dug space for the jump arc (y + 3 at the origin and target).
1931    let f0 = f64::from(y);
1932    let t_floor = f0 + 1.0;
1933    let arc = (f0 + HEIGHT + JUMP_APEX - (f0 + 3.0)) as f32;
1934    if g.class(x, y + 3, z).blocks_between(0.0, arc)
1935        || g.class(bx, y + 3, bz).blocks_between(0.0, arc)
1936    {
1937        return false;
1938    }
1939    let spot = Spot {
1940        kind: NodeKind::Ground,
1941        floor: t_floor,
1942        floor_flags: fl.flags,
1943        water: false,
1944        submerged: false,
1945        climb: false,
1946    };
1947    out.push(Edge {
1948        to: [bx, y + 1, bz],
1949        spot,
1950        kind: MoveKind::Ascend,
1951        cost,
1952        dig,
1953        place: None,
1954    });
1955    true
1956}
1957
1958/// Walk over a one-deep hole after placing a block into it.
1959fn fill_hole<S: BlockSource + ?Sized>(
1960    g: &mut Grid<'_, S>,
1961    cost: f64,
1962    per_block: f64,
1963    p: [i32; 3],
1964    f0: f64,
1965    (dx, dz): (i32, i32),
1966    out: &mut Vec<Edge>,
1967) -> bool {
1968    let [x, y, z] = p;
1969    if (f0 - f64::from(y)).abs() > 1e-6 {
1970        return false;
1971    }
1972    let (bx, bz) = (x + dx, z + dz);
1973    let hole = g.class(bx, y - 1, bz);
1974    let under = g.class(bx, y - 2, bz);
1975    if !hole.has(flag::REPLACEABLE)
1976        || g.unknown(bx, y - 1, bz)
1977        || !(under.has(flag::SUPPORT) && under.top >= 1.0 - 1e-6 && under.top_any <= 1.0 + 1e-6)
1978        || under.has(flag::IRREGULAR | flag::AVOID_FLOOR)
1979    {
1980        return false;
1981    }
1982    if !clear(g, bx, bz, f0, f0 + HEIGHT) {
1983        return false;
1984    }
1985    let spot = Spot {
1986        kind: NodeKind::Ground,
1987        floor: f0,
1988        floor_flags: flag::PLACED,
1989        water: false,
1990        submerged: false,
1991        climb: false,
1992    };
1993    out.push(Edge {
1994        to: [bx, y, bz],
1995        spot,
1996        kind: MoveKind::Walk,
1997        cost: per_block + cost,
1998        dig: [None; 3],
1999        place: Some(Place {
2000            pos: [bx, y - 1, bz],
2001            against: [bx, y - 2, bz],
2002        }),
2003    });
2004    true
2005}
2006
2007/// Extra ticks of a bridging step: turning round, sneaking back to the edge, turning again.
2008const BRIDGE_TICKS: f64 = 16.0;
2009
2010/// Whether the floor of a step at `p` standing as `s` is a full cube whose faces can be
2011/// clicked (or one the path places itself).
2012fn full_floor<S: BlockSource + ?Sized>(g: &mut Grid<'_, S>, p: [i32; 3], s: &Spot) -> bool {
2013    if (s.floor - f64::from(p[1])).abs() > 1e-6 {
2014        return false;
2015    }
2016    if s.floor_flags & flag::PLACED != 0 {
2017        return true;
2018    }
2019    let fl = g.class(p[0], p[1] - 1, p[2]);
2020    fl.has(flag::SUPPORT)
2021        && !fl.has(flag::IRREGULAR | flag::THIN)
2022        && fl.bottom <= 1e-6
2023        && fl.top >= 1.0 - 1e-6
2024        && fl.top_any <= 1.0 + 1e-6
2025}
2026
2027/// Bridge: walk over a gap to the neighbour at the same level after placing its floor block
2028/// against the side of this step's floor block (sneaking at the edge).
2029fn bridge<S: BlockSource + ?Sized>(
2030    g: &mut Grid<'_, S>,
2031    cost: f64,
2032    per_block: f64,
2033    p: [i32; 3],
2034    s: &Spot,
2035    (dx, dz): (i32, i32),
2036    out: &mut Vec<Edge>,
2037) -> bool {
2038    let [x, y, z] = p;
2039    if s.water || !full_floor(g, p, s) {
2040        return false;
2041    }
2042    let (bx, bz) = (x + dx, z + dz);
2043    if !g.class(bx, y - 1, bz).has(flag::REPLACEABLE) || g.unknown(bx, y - 1, bz) {
2044        return false;
2045    }
2046    if !clear(g, bx, bz, s.floor, s.floor + HEIGHT) {
2047        return false;
2048    }
2049    out.push(Edge {
2050        to: [bx, y, bz],
2051        spot: Spot {
2052            kind: NodeKind::Ground,
2053            floor: s.floor,
2054            floor_flags: flag::PLACED,
2055            water: false,
2056            submerged: false,
2057            climb: false,
2058        },
2059        kind: MoveKind::Walk,
2060        cost: per_block + cost + BRIDGE_TICKS,
2061        dig: [None; 3],
2062        place: Some(Place {
2063            pos: [bx, y - 1, bz],
2064            against: [x, y - 1, z],
2065        }),
2066    });
2067    true
2068}
2069
2070/// Tower up: jump and place a block into the feet cell, landing on it one block higher.
2071fn pillar<S: BlockSource + ?Sized>(
2072    g: &mut Grid<'_, S>,
2073    cost: f64,
2074    c: &Costs,
2075    p: [i32; 3],
2076    s: &Spot,
2077    out: &mut Vec<Edge>,
2078) {
2079    let [x, y, z] = p;
2080    if y + 1 >= g.y_range().1 - 1 || !full_floor(g, p, s) {
2081        return;
2082    }
2083    if !g.class(x, y, z).has(flag::REPLACEABLE) {
2084        return;
2085    }
2086    // Room for the body one higher and for the jump's arc above it.
2087    if !clear(g, x, z, s.floor + HEIGHT, s.floor + HEIGHT + JUMP_APEX) {
2088        return;
2089    }
2090    out.push(Edge {
2091        to: [x, y + 1, z],
2092        spot: Spot {
2093            kind: NodeKind::Ground,
2094            floor: s.floor + 1.0,
2095            floor_flags: flag::PLACED,
2096            water: false,
2097            submerged: false,
2098            climb: false,
2099        },
2100        kind: MoveKind::Pillar,
2101        cost: c.jump_up + cost + 4.0,
2102        dig: [None; 3],
2103        place: Some(Place {
2104            pos: [x, y, z],
2105            against: [x, y - 1, z],
2106        }),
2107    });
2108}
2109
2110/// 1.16.5 and 26.1 climb a ladder or vine without a block behind it; the older versions need
2111/// one.
2112fn climbs_without_wall(version: Version) -> bool {
2113    match version {
2114        #[cfg(feature = "v1_16_5")]
2115        Version::V1_16_5 => true,
2116        #[cfg(feature = "v26_1")]
2117        Version::V26_1 => true,
2118        #[cfg(feature = "v26_2")]
2119        Version::V26_2 => true,
2120        #[cfg(feature = "v26_3")]
2121        Version::V26_3 => true,
2122        #[allow(unreachable_patterns)]
2123        _ => false,
2124    }
2125}
2126
2127#[cfg(test)]
2128mod pack_tests {
2129    use super::pack;
2130
2131    #[test]
2132    fn node_keys_are_unique_over_any_build_height() {
2133        let mut seen = std::collections::HashSet::new();
2134        for y in -2048..2048 {
2135            assert!(seen.insert(pack([-3, y, 5])), "y {y}");
2136        }
2137        // The old keys (0..256) are unchanged.
2138        assert_eq!(pack([1, 200, 2]), 1 << 34 | 2 << 8 | 200);
2139    }
2140}