Skip to main content

ghast_pathfinder/
control.rs

1//! Path following: per-tick aim and keys for a planned [`Path`].
2//!
3//! The controller is pure (no I/O, no clock): it reads an [`Observation`] of the player and
4//! the world, and answers with an aim target and keys. Where a decision depends on the
5//! physics (when to jump off an edge, when to let go of the keys to land on a block, whether
6//! a step would leave the floor) it runs `ghast-physics` a few ticks ahead from the
7//! observation, so a simulated run ([`crate::simulate`]) and a live run make the same
8//! decisions.
9//!
10//! Each tick is two calls, because the client turns toward the aim in whole mouse counts and
11//! the keys must be chosen for the look the movement step will really use:
12//!
13//! 1. [`Controller::aim`]: advances along the path and returns the look to aim at;
14//! 2. the caller sets that aim and asks for the look this tick's movement will use
15//!    (`TickContext::planned_look` in ghast-client);
16//! 3. [`Controller::keys`]: the keys (and a dig / place job) for that look.
17
18use ghast_physics::Keys;
19
20use crate::Version;
21use crate::class::{Class, Table, flag, table};
22use crate::door;
23use crate::jump::{self, Jumps, Mode};
24use crate::moves::{MoveKind, NodeKind};
25#[cfg(feature = "v1_12_2")]
26use crate::physics::P12;
27#[cfg(feature = "v1_16_5")]
28use crate::physics::P16;
29#[cfg(feature = "v1_8")]
30use crate::physics::P18;
31#[cfg(feature = "v26_1")]
32use crate::physics::P26;
33#[cfg(feature = "v26_2")]
34use crate::physics::P262;
35#[cfg(feature = "v26_3")]
36use crate::physics::P263;
37use crate::physics::{Live, Observation, Physics, SourceView};
38use crate::plan::{Path, Pathfinder, Place, Step};
39use crate::world::BlockSource;
40
41/// Eye height of a standing player.
42const EYES: f64 = 1.62;
43
44/// Options of the [`Controller`]. Build with [`ControllerConfig::default`] and the `with_*`
45/// methods.
46#[derive(Clone, Debug, PartialEq)]
47#[non_exhaustive]
48pub struct ControllerConfig {
49    /// Sprint on straight runs (needs food > 6). Default on.
50    pub sprint: bool,
51    /// The last step counts as reached within this horizontal distance of its centre.
52    /// Default 0.35.
53    pub arrive_radius: f64,
54    /// Ticks without getting closer to the next step before [`Progress::Stuck`]. Default 60.
55    pub stuck_ticks: u32,
56    /// Ticks away from the path before [`Progress::OffPath`]. Default 10.
57    pub off_path_ticks: u32,
58    /// Ticks a dig or place job may take before [`Progress::Stuck`]. Default 400.
59    pub work_ticks: u32,
60}
61
62impl Default for ControllerConfig {
63    fn default() -> Self {
64        ControllerConfig {
65            sprint: true,
66            arrive_radius: 0.35,
67            stuck_ticks: 60,
68            off_path_ticks: 10,
69            work_ticks: 400,
70        }
71    }
72}
73
74impl ControllerConfig {
75    /// Sprinting on or off.
76    #[must_use]
77    pub fn with_sprint(mut self, on: bool) -> Self {
78        self.sprint = on;
79        self
80    }
81
82    /// Arrival radius around the last step's centre.
83    #[must_use]
84    pub fn with_arrive_radius(mut self, blocks: f64) -> Self {
85        self.arrive_radius = blocks.max(0.05);
86        self
87    }
88
89    /// Ticks without progress before giving up.
90    #[must_use]
91    pub fn with_stuck_ticks(mut self, ticks: u32) -> Self {
92        self.stuck_ticks = ticks;
93        self
94    }
95
96    /// Ticks off the path before giving up.
97    #[must_use]
98    pub fn with_off_path_ticks(mut self, ticks: u32) -> Self {
99        self.off_path_ticks = ticks;
100        self
101    }
102
103    /// Time limit of one dig / place job.
104    #[must_use]
105    pub fn with_work_ticks(mut self, ticks: u32) -> Self {
106        self.work_ticks = ticks;
107        self
108    }
109}
110
111/// What the controller wants this tick.
112#[derive(Clone, Copy, Debug, PartialEq)]
113#[non_exhaustive]
114pub struct Command {
115    /// Movement keys.
116    pub keys: Keys,
117    /// Aim target yaw (degrees), as returned by [`Controller::aim`].
118    pub yaw: f32,
119    /// Aim target pitch (degrees).
120    pub pitch: f32,
121    /// Break this block (hold the left button while the crosshair is on it). The player
122    /// stands still meanwhile.
123    pub dig: Option<[i32; 3]>,
124    /// Place the held block: right-click the face [`Place::face`] of [`Place::against`]
125    /// (only sent when the crosshair, from the pose the server has, is on that face).
126    pub place: Option<Place>,
127    /// Right-click this block (open a door or fence gate) when the crosshair is on it.
128    pub interact: Option<[i32; 3]>,
129}
130
131impl Command {
132    fn idle(yaw: f32, pitch: f32) -> Self {
133        Command {
134            keys: Keys::NONE,
135            yaw,
136            pitch,
137            dig: None,
138            place: None,
139            interact: None,
140        }
141    }
142}
143
144/// Where the controller is.
145#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
146#[non_exhaustive]
147pub enum Progress {
148    /// Moving toward the next step.
149    Moving,
150    /// Digging or placing before the next move.
151    Working,
152    /// The last step is reached (keys released).
153    Arrived,
154    /// No progress toward the next step for [`ControllerConfig::stuck_ticks`] (or a job ran
155    /// out of time).
156    Stuck,
157    /// The player left the path (fell, was pushed) for [`ControllerConfig::off_path_ticks`].
158    OffPath,
159}
160
161/// A dig / place / door job before a move.
162#[derive(Clone, Copy, Debug, PartialEq)]
163enum Job {
164    Dig([i32; 3]),
165    Place(Place),
166    Open([i32; 3]),
167}
168
169/// A gap jump in progress (see [`crate::jump`]).
170#[derive(Clone, Copy, Debug, PartialEq)]
171enum Leap {
172    /// Lining up and coming to rest on the take-off block; ticks since the last key.
173    Settle(Mode, u32),
174    /// Running with the yaw fixed, replaying the checked run: ground ticks before the jump
175    /// tick and air ticks with the keys held after it, ground ticks done so far.
176    Run(Mode, f32, (u32, u32), u32),
177    /// The jump was pressed: in the air; (air ticks with the keys held, air ticks so far),
178    /// or `None` (the run went differently than checked) to steer the landing instead.
179    Air(Mode, f32, Option<(u32, u32)>),
180}
181
182/// Result of running the physics ahead with fixed keys.
183#[derive(Clone, Copy, Debug)]
184struct Roll {
185    pos: [f64; 3],
186    on_ground: bool,
187    /// A horizontal collision happened.
188    collided: bool,
189}
190
191/// Follows a [`Path`] tick by tick.
192///
193/// Pure (no I/O, no clock): it reads an [`Observation`] of the player and the world, and
194/// answers with an aim target and keys. Where a decision depends on the physics (when to
195/// jump off an edge, when to let go of the keys to land on a block, whether a step would
196/// leave the floor) it runs `ghast-physics` a few ticks ahead from the observation, so a
197/// simulated run ([`crate::simulate`]) and a live run make the same decisions.
198///
199/// Each tick is two calls, because the client turns toward the aim in whole mouse counts
200/// and the keys must be chosen for the look the movement step will really use:
201///
202/// 1. [`Controller::aim`]: advances along the path and returns the look to aim at;
203/// 2. the caller sets that aim and asks for the look this tick's movement will use
204///    (`TickContext::planned_look` in ghast-client);
205/// 3. [`Controller::keys`]: the keys (and a dig / place job) for that look.
206///
207/// It never gives up silently: [`Controller::progress`] turns [`Progress::Stuck`] or
208/// [`Progress::OffPath`] and [`Controller::current_move`] names the move, to plan around.
209///
210/// ```
211/// use ghast_pathfinder::{Config, Controller, ControllerConfig, Goal, Pathfinder, Progress, Version};
212///
213/// let mut world = ghast_physics::v1_8::memory_world();
214/// world.load_chunks(-1, -1, 1, 1);
215/// world.fill_raw([-10, 63, -10], [10, 63, 10], 1 << 4);
216/// let path = Pathfinder::new(Config::default())
217///     .plan(Version::V1_8, &world, [0, 64, 0], &Goal::Block([5, 64, 0]))
218///     .unwrap();
219/// let mut c = Controller::new(path, ControllerConfig::default());
220/// // Each tick, with `obs` the player's observation:
221/// # let obs = ghast_pathfinder::Observation { pos: [0.5, 64.0, 0.5], vel: [0.0; 3],
222/// #     on_ground: true, yaw: 0.0, pitch: 0.0, sprinting: false, food: 20 };
223/// let (yaw, pitch) = c.aim(&obs, &world);
224/// // ... the client turns toward (yaw, pitch); `look` is what this tick's movement uses.
225/// let look = (yaw, pitch);
226/// let cmd = c.keys(&obs, look, &world);
227/// assert_eq!(c.progress(), Progress::Moving);
228/// assert!(cmd.keys.forward || cmd.keys == ghast_physics::Keys::NONE);
229/// ```
230#[derive(Clone, Debug)]
231pub struct Controller {
232    path: Path,
233    cfg: ControllerConfig,
234    /// Index of the last step reached.
235    reached: usize,
236    progress: Progress,
237    /// Best distance to the next step so far, and ticks since it improved.
238    best: f64,
239    idle: u32,
240    off: u32,
241    work: u32,
242    /// This tick's aim target and the distance to the point it looks at.
243    want: (f32, f32),
244    aim_dist: f64,
245    /// The gap jump of the current move.
246    leap: Option<Leap>,
247    /// The move's keys would have left the floor: back to the centre of the last step first.
248    recover: bool,
249    /// This tick walks toward the last step's centre to line up for the move.
250    aligning: bool,
251    /// The live player beyond the observation (26.1 attributes, effects, level).
252    live: Live,
253}
254
255impl Controller {
256    /// A controller at the start of `path`.
257    #[must_use]
258    pub fn new(path: Path, cfg: ControllerConfig) -> Self {
259        let progress = if path.steps.len() <= 1 {
260            Progress::Arrived
261        } else {
262            Progress::Moving
263        };
264        Controller {
265            path,
266            cfg,
267            reached: 0,
268            progress,
269            best: f64::INFINITY,
270            idle: 0,
271            off: 0,
272            work: 0,
273            want: (0.0, 0.0),
274            aim_dist: 0.0,
275            leap: None,
276            recover: false,
277            aligning: false,
278            live: Live::default(),
279        }
280    }
281
282    /// 26.1: the live client player (`ghast_client::TickContext::modern_player`), whose
283    /// attributes (movement speed, step height, jump strength, scale, ...), effects, abilities,
284    /// input timers and build height the one-tick look-ahead and the pre-jump check simulate
285    /// with. Set it every tick before [`Controller::aim`] (the `Follower` does). Without it the
286    /// look-ahead uses vanilla defaults rebuilt from the [`Observation`].
287    #[cfg(ghast_modern)]
288    pub fn set_modern_player(&mut self, player: &ghast_physics::modern::PlayerState) {
289        self.live.set_modern(player);
290    }
291
292    /// The live player for the simulation that drives this controller.
293    pub(crate) fn live_mut(&mut self) -> &mut Live {
294        &mut self.live
295    }
296
297    /// The path being followed.
298    #[must_use]
299    pub fn path(&self) -> &Path {
300        &self.path
301    }
302
303    /// Index (into [`Path::steps`]) of the last step reached.
304    #[must_use]
305    pub fn reached(&self) -> usize {
306        self.reached
307    }
308
309    /// The current state.
310    #[must_use]
311    pub fn progress(&self) -> Progress {
312        self.progress
313    }
314
315    /// The configuration.
316    #[must_use]
317    pub fn config(&self) -> &ControllerConfig {
318        &self.cfg
319    }
320
321    /// The point the controller walks to now: the centre of the next step's feet block at its
322    /// feet height (`None` once the last step is reached).
323    #[must_use]
324    pub fn waypoint(&self) -> Option<[f64; 3]> {
325        self.path.steps.get(self.reached + 1).map(Step::target)
326    }
327
328    /// Whether this tick's move needs the controller's own look: a dig / place / door job, a
329    /// gap jump, a ladder, a pillar or a dig down (the movement-only mode of the follower aims
330    /// for these).
331    #[must_use]
332    pub(crate) fn needs_look(&self) -> bool {
333        self.progress == Progress::Working
334            || self.leap.is_some()
335            || self.path.steps.get(self.reached + 1).is_some_and(|s| {
336                matches!(
337                    s.kind,
338                    MoveKind::Parkour { .. }
339                        | MoveKind::ClimbUp
340                        | MoveKind::ClimbDown
341                        | MoveKind::ClimbExit
342                        | MoveKind::Pillar
343                        | MoveKind::DigDown
344                        | MoveKind::Door { .. }
345                )
346            })
347    }
348
349    /// Movement only: `planned` (this tick's keys for the controller's own look) pressed for
350    /// the look `look` instead: of the eight key directions, the one whose next ticks end
351    /// closest to the next step, without leaving the floor where the path does not go (jump
352    /// and sneak kept; the sprint key only with forward).
353    pub(crate) fn steer_keys<S: BlockSource + ?Sized>(
354        &self,
355        obs: &Observation,
356        planned: Keys,
357        look: (f32, f32),
358        world: &S,
359    ) -> Keys {
360        match self.path.version {
361            #[cfg(feature = "v1_8")]
362            Version::V1_8 => self.steer_as::<P18, S>(obs, planned, look, world),
363            #[cfg(feature = "v1_12_2")]
364            Version::V1_12 => self.steer_as::<P12, S>(obs, planned, look, world),
365            #[cfg(feature = "v1_16_5")]
366            Version::V1_16_5 => self.steer_as::<P16, S>(obs, planned, look, world),
367            #[cfg(feature = "v26_1")]
368            Version::V26_1 => self.steer_as::<P26, S>(obs, planned, look, world),
369            #[cfg(feature = "v26_2")]
370            Version::V26_2 => self.steer_as::<P262, S>(obs, planned, look, world),
371            #[cfg(feature = "v26_3")]
372            Version::V26_3 => self.steer_as::<P263, S>(obs, planned, look, world),
373        }
374    }
375
376    fn steer_as<P: Physics, S: BlockSource + ?Sized>(
377        &self,
378        obs: &Observation,
379        planned: Keys,
380        look: (f32, f32),
381        world: &S,
382    ) -> Keys {
383        if !(planned.forward || planned.back || planned.left || planned.right) {
384            return planned;
385        }
386        let view = SourceView::<P, S>::new(world);
387        let Some(goal) = self.waypoint() else {
388            return planned;
389        };
390        let mut best = (f64::INFINITY, planned);
391        for (f, s) in [
392            (1, 0),
393            (1, 1),
394            (0, 1),
395            (-1, 1),
396            (-1, 0),
397            (-1, -1),
398            (0, -1),
399            (1, -1),
400        ] {
401            let k = Keys {
402                forward: f > 0,
403                back: f < 0,
404                left: s > 0,
405                right: s < 0,
406                sprint: planned.sprint && f > 0,
407                ..planned
408            };
409            let (end, floor) = self.ahead::<P, S>(&view, obs, k, look);
410            let d = hdist(end, goal) + (end[1] - goal[1]).abs() + if floor { 0.0 } else { 100.0 };
411            if d < best.0 {
412                best = (d, k);
413            }
414        }
415        best.1
416    }
417
418    /// Where `keys` held for [`STEER_TICKS`] ticks at `look` take the player, and whether it
419    /// stayed on a floor or over the path.
420    fn ahead<P: Physics, S: BlockSource + ?Sized>(
421        &self,
422        view: &SourceView<'_, P, S>,
423        obs: &Observation,
424        keys: Keys,
425        look: (f32, f32),
426    ) -> ([f64; 3], bool) {
427        let mut s = P::from_observation(obs, &self.live);
428        let mut floor = true;
429        for _ in 0..STEER_TICKS {
430            P::tick(&mut s, keys, look.0, look.1, view);
431            let o = P::observe(&s);
432            floor &= o.on_ground || self.allowed_column(o.pos);
433        }
434        (P::observe(&s).pos, floor)
435    }
436
437    /// The move (`from`, `to` feet blocks) the controller is on: after [`Progress::Stuck`] /
438    /// [`Progress::OffPath`] the move that failed, for [`Pathfinder::plan_avoiding`].
439    #[must_use]
440    pub fn current_move(&self) -> Option<([i32; 3], [i32; 3])> {
441        let s = &self.path.steps;
442        (self.reached + 1 < s.len()).then(|| (s[self.reached].pos, s[self.reached + 1].pos))
443    }
444
445    fn class<S: BlockSource + ?Sized>(&self, w: &S, p: [i32; 3]) -> Class {
446        let t: &Table = table(self.path.version);
447        match w.raw_block(p[0], p[1], p[2]) {
448            Some(raw) => t.classes[t.index(raw) as usize],
449            None => Class::UNKNOWN,
450        }
451    }
452
453    /// The pending dig / place job of the next step.
454    fn job<S: BlockSource + ?Sized>(&self, w: &S) -> Option<Job> {
455        let t = self.path.steps.get(self.reached + 1)?;
456        for &d in &t.dig {
457            if self.class(w, d).has(flag::SOLID) {
458                return Some(Job::Dig(d));
459            }
460        }
461        if let Some(p) = t.place
462            && !self.class(w, p.pos).has(flag::SUPPORT)
463        {
464            return Some(Job::Place(p));
465        }
466        if let MoveKind::Door { block } = t.kind
467            && self.door_in_way(w, self.reached + 1, block)
468        {
469            return Some(Job::Open(block));
470        }
471        None
472    }
473
474    /// Whether the door or gate at `b` (as the world has it now) blocks the move to step `k`.
475    fn door_in_way<S: BlockSource + ?Sized>(&self, w: &S, k: usize, b: [i32; 3]) -> bool {
476        let (f, t) = (&self.path.steps[k - 1], &self.path.steps[k]);
477        let c = door::class_at(self.path.version, w, b);
478        if !c.has(flag::SOLID) {
479            return false;
480        }
481        if !c.has(flag::PANEL) {
482            // A closed fence gate or trapdoor.
483            return c.has(flag::OPENABLE);
484        }
485        let (dx, dz) = (t.pos[0] - f.pos[0], t.pos[2] - f.pos[2]);
486        if b[0] == f.pos[0] && b[2] == f.pos[2] {
487            c.wall == door::wall_of(dx, dz)
488        } else {
489            c.wall == door::wall_of(-dx, -dz)
490        }
491    }
492
493    /// Advances along the path from `obs` and returns the look (yaw, pitch) to aim at this
494    /// tick. Call once per tick, before [`Controller::keys`].
495    pub fn aim<S: BlockSource + ?Sized>(&mut self, obs: &Observation, world: &S) -> (f32, f32) {
496        self.update(obs, world);
497        if matches!(
498            self.progress,
499            Progress::Arrived | Progress::Stuck | Progress::OffPath
500        ) {
501            self.want = (obs.yaw, obs.pitch);
502            return self.want;
503        }
504        if let Some(job) = self.job(world) {
505            if self.progress != Progress::Working
506                && self.path.steps[self.reached + 1].kind == MoveKind::DigDown
507                && !self.over_centre(obs)
508            {
509                // Digging the floor away only drops a player whose box is inside the block's
510                // column: get there first (looking down at the block meanwhile).
511                self.progress = Progress::Moving;
512                let eyes = [obs.pos[0], obs.pos[1] + EYES, obs.pos[2]];
513                let d = self.path.steps[self.reached + 1].dig[0];
514                self.want = look_at(eyes, centre(d));
515                return self.want;
516            }
517            if self.progress != Progress::Working {
518                self.work = 0;
519            }
520            self.progress = Progress::Working;
521            let p = match job {
522                Job::Dig(d) => centre(d),
523                Job::Place(_) if self.path.steps[self.reached + 1].kind == MoveKind::Pillar => {
524                    // Straight down at the floor.
525                    self.want = (obs.yaw, 90.0);
526                    return self.want;
527                }
528                Job::Place(pl) if pl.face()[1] == 0 => {
529                    // Facing back over the edge, down at the side face of the floor block.
530                    let [fx, _, fz] = pl.face();
531                    let c = place_point(pl);
532                    let eyes = [obs.pos[0], obs.pos[1] + EYES, obs.pos[2]];
533                    let along = (eyes[0] - c[0]) * f64::from(fx) + (eyes[2] - c[2]) * f64::from(fz);
534                    let pitch = (eyes[1] - c[1]).atan2(along.max(0.05)).to_degrees();
535                    self.want = (dir_yaw(-fx, -fz), pitch as f32);
536                    return self.want;
537                }
538                Job::Place(pl) => place_point(pl),
539                Job::Open(b) => {
540                    // The middle of the door's slab (or of the gate).
541                    let mut q = centre(b);
542                    let c = door::class_at(self.path.version, world, b);
543                    if c.has(flag::PANEL) {
544                        let (sx, sz) = wall_dir(c.wall);
545                        q[0] += f64::from(sx) * (0.5 - DOOR_HALF_THICKNESS);
546                        q[2] += f64::from(sz) * (0.5 - DOOR_HALF_THICKNESS);
547                    } else if c.has(flag::SOLID) {
548                        // A gate's bars, a closed trapdoor's flat slab: the middle of its height.
549                        q[1] = f64::from(b[1]) + f64::from(c.bottom + c.top_any) / 2.0;
550                    }
551                    q
552                }
553            };
554            let eyes = [obs.pos[0], obs.pos[1] + EYES, obs.pos[2]];
555            self.want = look_at(eyes, p);
556            return self.want;
557        }
558        if self.progress == Progress::Working {
559            // The job is done: measure progress afresh.
560            self.best = f64::INFINITY;
561            self.idle = 0;
562        }
563        self.progress = Progress::Moving;
564        let yaw = self.move_yaw(obs, world);
565        self.want = (yaw, obs.pitch.clamp(-25.0, 25.0));
566        self.want
567    }
568
569    /// The keys (and dig / place job) for this tick, given the look the movement step will
570    /// use (`look`, after the client's turn toward [`Controller::aim`]'s target).
571    pub fn keys<S: BlockSource + ?Sized>(
572        &mut self,
573        obs: &Observation,
574        look: (f32, f32),
575        world: &S,
576    ) -> Command {
577        let (yaw, pitch) = self.want;
578        match self.progress {
579            Progress::Arrived | Progress::Stuck | Progress::OffPath => {
580                return Command::idle(yaw, pitch);
581            }
582            Progress::Working => {
583                self.work += 1;
584                if self.work > self.cfg.work_ticks {
585                    self.progress = Progress::Stuck;
586                    return Command::idle(yaw, pitch);
587                }
588                let mut c = Command::idle(yaw, pitch);
589                match self.job(world) {
590                    Some(Job::Dig(d)) => c.dig = Some(d),
591                    Some(Job::Place(p)) if self.moving_place(p) => {
592                        let (keys, ready) = match self.path.version {
593                            #[cfg(feature = "v1_8")]
594                            Version::V1_8 => self.place_keys::<P18, S>(obs, look, world, p),
595                            #[cfg(feature = "v1_12_2")]
596                            Version::V1_12 => self.place_keys::<P12, S>(obs, look, world, p),
597                            #[cfg(feature = "v1_16_5")]
598                            Version::V1_16_5 => self.place_keys::<P16, S>(obs, look, world, p),
599                            #[cfg(feature = "v26_1")]
600                            Version::V26_1 => self.place_keys::<P26, S>(obs, look, world, p),
601                            #[cfg(feature = "v26_2")]
602                            Version::V26_2 => self.place_keys::<P262, S>(obs, look, world, p),
603                            #[cfg(feature = "v26_3")]
604                            Version::V26_3 => self.place_keys::<P263, S>(obs, look, world, p),
605                        };
606                        c.keys = keys;
607                        if ready {
608                            c.place = Some(p);
609                        }
610                    }
611                    Some(Job::Place(p)) => c.place = Some(p),
612                    Some(Job::Open(b)) => c.interact = Some(b),
613                    None => {}
614                }
615                return c;
616            }
617            Progress::Moving => {}
618        }
619        let keys = match self.path.version {
620            #[cfg(feature = "v1_8")]
621            Version::V1_8 => self.move_keys::<P18, S>(obs, look, world),
622            #[cfg(feature = "v1_12_2")]
623            Version::V1_12 => self.move_keys::<P12, S>(obs, look, world),
624            #[cfg(feature = "v1_16_5")]
625            Version::V1_16_5 => self.move_keys::<P16, S>(obs, look, world),
626            #[cfg(feature = "v26_1")]
627            Version::V26_1 => self.move_keys::<P26, S>(obs, look, world),
628            #[cfg(feature = "v26_2")]
629            Version::V26_2 => self.move_keys::<P262, S>(obs, look, world),
630            #[cfg(feature = "v26_3")]
631            Version::V26_3 => self.move_keys::<P263, S>(obs, look, world),
632        };
633        Command {
634            keys,
635            yaw,
636            pitch,
637            dig: None,
638            place: None,
639            interact: None,
640        }
641    }
642
643    /// `true` when the player stands at step `k` the way the planner expects.
644    fn at(&self, k: usize, obs: &Observation) -> bool {
645        let steps = &self.path.steps;
646        let s = &steps[k];
647        let fb = Pathfinder::start_block(obs.pos);
648        let in_col = fb[0] == s.pos[0] && fb[2] == s.pos[2];
649        match s.node {
650            NodeKind::Ground => {
651                if !obs.on_ground || (obs.pos[1] - s.feet_y).abs() >= 0.02 {
652                    return false;
653                }
654                if in_col {
655                    return true;
656                }
657                // Standing on this step's floor with the centre still over the previous step
658                // (at another height) or already over the next one: the box is 0.6 wide.
659                let col = |n: &Step| n.pos[0] == fb[0] && n.pos[2] == fb[2];
660                over(obs.pos, s.pos, 0.3)
661                    && (steps.get(k + 1).is_some_and(col)
662                        || (k > 0
663                            && col(&steps[k - 1])
664                            && (steps[k - 1].feet_y - s.feet_y).abs() > 0.02))
665            }
666            // In the water column: from two blocks under the cell (sinking after a fall) up
667            // to floating with the feet just under its top.
668            NodeKind::Swim => {
669                in_col
670                    && obs.pos[1] < f64::from(s.pos[1]) + 0.9
671                    && obs.pos[1] > f64::from(s.pos[1]) - 2.5
672            }
673            NodeKind::Climb => in_col && (fb[1] == s.pos[1] || (obs.pos[1] - s.feet_y).abs() < 0.5),
674        }
675    }
676
677    fn update<S: BlockSource + ?Sized>(&mut self, obs: &Observation, world: &S) {
678        if matches!(
679            self.progress,
680            Progress::Arrived | Progress::Stuck | Progress::OffPath
681        ) {
682            return;
683        }
684        let last = self.path.steps.len() - 1;
685        let hi = (self.reached + 3).min(last);
686        for k in (self.reached + 1..=hi).rev() {
687            if self.at(k, obs) && (k < last || self.arrived_at_end(obs)) {
688                // Never skip a step whose dig / place is still pending.
689                let skipped_job = (self.reached + 1..=k).any(|j| {
690                    let s = &self.path.steps[j];
691                    s.dig.iter().any(|&d| self.class(world, d).has(flag::SOLID))
692                        || s.place
693                            .is_some_and(|p| !self.class(world, p.pos).has(flag::SUPPORT))
694                        || matches!(s.kind, MoveKind::Door { block } if self.door_in_way(world, j, block))
695                });
696                if skipped_job {
697                    continue;
698                }
699                self.reached = k;
700                self.best = f64::INFINITY;
701                self.idle = 0;
702                self.off = 0;
703                self.leap = None;
704                self.recover = false;
705                break;
706            }
707        }
708        if self.reached == last {
709            self.progress = Progress::Arrived;
710            return;
711        }
712        if self.progress == Progress::Working {
713            return;
714        }
715        let t = self.path.steps[self.reached + 1].target();
716        let d = hdist(obs.pos, t) + (obs.pos[1] - t[1]).abs();
717        if d < self.best - 0.05 {
718            self.best = d;
719            self.idle = 0;
720        } else {
721            self.idle += 1;
722            if self.idle > self.cfg.stuck_ticks {
723                self.progress = Progress::Stuck;
724                return;
725            }
726        }
727        if self.off_path(obs) {
728            self.off += 1;
729            if self.off > self.cfg.off_path_ticks {
730                self.progress = Progress::OffPath;
731            }
732        } else {
733            self.off = 0;
734        }
735    }
736
737    fn arrived_at_end(&self, obs: &Observation) -> bool {
738        let s = self.path.steps.last().expect("non-empty path");
739        hdist(obs.pos, s.target()) <= self.cfg.arrive_radius
740    }
741
742    fn off_path(&self, obs: &Observation) -> bool {
743        let a = self.path.steps[self.reached].target();
744        let b = self.path.steps[self.reached + 1].target();
745        let swim = self.path.steps[self.reached].node == NodeKind::Swim
746            || self.path.steps[self.reached + 1].node == NodeKind::Swim;
747        if obs.pos[1] < a[1].min(b[1]) - if swim { 3.0 } else { 1.0 } {
748            return true;
749        }
750        segment_dist(obs.pos, a, b) > 1.0
751    }
752
753    /// The yaw to move with toward the next step.
754    fn move_yaw<S: BlockSource + ?Sized>(&mut self, obs: &Observation, world: &S) -> f32 {
755        let steps = &self.path.steps;
756        let last = steps.len() - 1;
757        let f = &steps[self.reached];
758        let t = &steps[self.reached + 1];
759        let (dx, dz) = (t.pos[0] - f.pos[0], t.pos[2] - f.pos[2]);
760        self.aim_dist = hdist(obs.pos, t.target());
761        self.aligning = false;
762        if self.recover {
763            let fc = f.target();
764            let d = hdist(obs.pos, fc);
765            if d < 0.2 || !obs.on_ground {
766                self.recover = false;
767            } else {
768                self.aim_dist = d;
769                return yaw_to(obs.pos, fc);
770            }
771        }
772        match t.kind {
773            MoveKind::ClimbUp => {
774                if let Some((wx, wz)) = self.climb_wall(world, f.pos) {
775                    return dir_yaw(wx, wz);
776                }
777            }
778            MoveKind::Descend if dx == 0 || dz == 0 => {
779                // Walk off straight: a box sticking out sideways can catch a neighbouring
780                // block (or step up onto it).
781                let fc = f.target();
782                if obs.on_ground
783                    && over(obs.pos, f.pos, 0.3)
784                    && lateral(obs.pos, fc, dx.signum(), dz.signum()) > 0.15
785                    && hdist(obs.pos, fc) > 0.05
786                {
787                    self.aligning = true;
788                    self.aim_dist = hdist(obs.pos, fc);
789                    return yaw_to(obs.pos, fc);
790                }
791            }
792            MoveKind::ClimbDown => {
793                // A fixed yaw: the keys keep the player over the ladder.
794                if dx != 0 || dz != 0 {
795                    return dir_yaw(dx.signum(), dz.signum());
796                }
797                return obs.yaw;
798            }
799            MoveKind::Parkour { .. } => {
800                // Facing along the axis; once running, the yaw stays where the run began.
801                return match self.leap {
802                    Some(Leap::Run(_, yaw, ..) | Leap::Air(_, yaw, _)) => yaw,
803                    _ => dir_yaw(dx.signum(), dz.signum()),
804                };
805            }
806            _ => {}
807        }
808        // Look ahead along a straight run of plain walks on one level.
809        let mut k = self.reached + 1;
810        if matches!(t.kind, MoveKind::Walk | MoveKind::Diagonal) && plain(t) {
811            for j in self.reached + 2..=(self.reached + 4).min(last) {
812                let s = &steps[j];
813                let p = &steps[j - 1];
814                if matches!(s.kind, MoveKind::Walk | MoveKind::Diagonal)
815                    && plain(s)
816                    && s.pos[1] == t.pos[1]
817                    && (s.pos[0] - p.pos[0], s.pos[2] - p.pos[2]) == (dx, dz)
818                {
819                    k = j;
820                } else {
821                    break;
822                }
823            }
824        }
825        let mut point = steps[k].target();
826        if k == self.reached + 1 && (dx == 0) != (dz == 0) {
827            // Along a door's slab: the middle of the free part of the cell, so the box clears
828            // the slab's end.
829            for y in [t.pos[1], t.pos[1] + 1] {
830                let c = door::class_at(self.path.version, world, [t.pos[0], y, t.pos[2]]);
831                if c.has(flag::PANEL) {
832                    let (sx, sz) = wall_dir(c.wall);
833                    if (sx, sz) != (dx, dz) && (sx, sz) != (-dx, -dz) {
834                        point[0] -= f64::from(sx) * DOOR_HALF_THICKNESS;
835                        point[2] -= f64::from(sz) * DOOR_HALF_THICKNESS;
836                        break;
837                    }
838                }
839            }
840        }
841        self.aim_dist = hdist(obs.pos, point);
842        if self.aim_dist < 0.05 {
843            return obs.yaw;
844        }
845        yaw_to(obs.pos, point)
846    }
847
848    /// The direction a climber at `p` pushes toward (the wall the ladder hangs on).
849    fn climb_wall<S: BlockSource + ?Sized>(&self, w: &S, p: [i32; 3]) -> Option<(i32, i32)> {
850        let c = self.class(w, p);
851        match c.wall {
852            1 => return Some((0, -1)),
853            2 => return Some((0, 1)),
854            3 => return Some((-1, 0)),
855            4 => return Some((1, 0)),
856            _ => {}
857        }
858        if !c.has(flag::CLIMB) {
859            return None;
860        }
861        [(0, 1), (0, -1), (1, 0), (-1, 0)]
862            .into_iter()
863            .find(|&(dx, dz)| {
864                let n = self.class(w, [p[0] + dx, p[1], p[2] + dz]);
865                n.has(flag::SUPPORT) && n.top >= 1.0 && n.bottom <= 0.0
866            })
867    }
868
869    fn move_keys<P: Physics, S: BlockSource + ?Sized>(
870        &mut self,
871        obs: &Observation,
872        look: (f32, f32),
873        world: &S,
874    ) -> Keys {
875        let view = SourceView::<P, S>::new(world);
876        let steps = &self.path.steps;
877        let last = steps.len() - 1;
878        let f = &steps[self.reached];
879        let t = &steps[self.reached + 1];
880        let err = wrap(self.want.0 - look.0).abs();
881        let fwd = Keys {
882            forward: true,
883            ..Keys::NONE
884        };
885        let (dx, dz) = (t.pos[0] - f.pos[0], t.pos[2] - f.pos[2]);
886        match t.kind {
887            MoveKind::Start | MoveKind::Walk | MoveKind::Diagonal | MoveKind::Door { .. } => {
888                let mut k = Keys {
889                    forward: err < 35.0,
890                    ..Keys::NONE
891                };
892                let in_water = f.node == NodeKind::Swim || t.node == NodeKind::Swim;
893                k.sprint = k.forward
894                    && self.cfg.sprint
895                    && obs.food > 6
896                    && err < 10.0
897                    && self.aim_dist > 2.5
898                    && !in_water;
899                if self.reached + 1 == last {
900                    let level = |p: [f64; 3]| (p[1] - t.feet_y).abs() < 0.02;
901                    if hdist(obs.pos, t.target()) < 0.15 && level(obs.pos) {
902                        return Keys::NONE;
903                    }
904                    let rest = rollout::<P, S>(&view, obs, &self.live, Keys::NONE, look, 40);
905                    let fb = Pathfinder::start_block(rest.pos);
906                    if fb[0] == t.pos[0]
907                        && fb[2] == t.pos[2]
908                        && rest.on_ground
909                        && level(rest.pos)
910                        && hdist(rest.pos, t.target()) <= self.cfg.arrive_radius * 0.8
911                    {
912                        return Keys::NONE;
913                    }
914                    k.sprint = k.sprint && hdist(obs.pos, t.target()) > 3.0;
915                }
916                if k.forward && obs.on_ground {
917                    // Never step off the floor where the path does not go: this tick's keys,
918                    // then braking, must keep the player on a floor or over the path. And
919                    // brake before a wall rather than slide along it (corners of narrow
920                    // corridors) when braking avoids it.
921                    let back = Keys {
922                        back: true,
923                        ..Keys::NONE
924                    };
925                    let cands = [k, Keys { sprint: false, ..k }, Keys::NONE, back];
926                    let checks = cands.map(|c| self.safe::<P, S>(&view, obs, c, look));
927                    let first_on_floor = checks.iter().position(|c| c.0);
928                    // Braking only helps when moving: slowly, a touch is unavoidable (a box
929                    // grazing a wall), and standing still would never get anywhere.
930                    let moving = obs.vel[0].hypot(obs.vel[2]) > 0.03;
931                    // 26.1: braking that has made no progress for a while (forward and back
932                    // taking turns at a corridor's mouth, off its axis; the exact look-ahead of
933                    // the live player sees every graze coming) gives way to the graze: sliding
934                    // along the wall lines the player up. The other versions keep 0.4.0's rule.
935                    let wedged = self.idle >= WEDGED_TICKS && exact_look_ahead(self.path.version);
936                    let pick = checks
937                        .iter()
938                        .position(|&(floor, clear)| floor && (clear || !moving || wedged))
939                        .or(first_on_floor);
940                    let Some(i) = pick else {
941                        return back;
942                    };
943                    if first_on_floor.is_some_and(|j| j >= 2)
944                        && !self.recover
945                        && hdist(obs.pos, f.target()) > 0.3
946                    {
947                        // Only braking keeps to the floor here: go back to the last step's
948                        // centre and try the move again from there.
949                        self.recover = true;
950                    }
951                    return cands[i];
952                }
953                k
954            }
955            MoveKind::Ascend => {
956                let (ux, uz) = (dx.signum(), dz.signum());
957                let boundary = boundary_dist(obs.pos, f.pos, ux, uz);
958                // Jump only when lined up: sideways drift during the jump can catch a
959                // neighbouring column's block.
960                let side_speed = if ux != 0 { obs.vel[2] } else { obs.vel[0] }.abs();
961                let lined_up = (ux != 0 && uz != 0)
962                    || (lateral(obs.pos, f.target(), ux, uz) < 0.2 && side_speed < 0.05);
963                if !obs.on_ground && obs.pos[1] >= t.feet_y {
964                    // Over the edge: land on the block, not beyond it.
965                    return self.steer::<P, S>(&view, obs, look, t, fwd);
966                }
967                Keys {
968                    forward: err < 35.0,
969                    jump: obs.on_ground
970                        && err < 20.0
971                        && boundary < 0.9
972                        && lined_up
973                        && obs.pos[1] < t.feet_y - 0.3,
974                    ..Keys::NONE
975                }
976            }
977            MoveKind::Descend => {
978                if err > 35.0 && obs.on_ground {
979                    return Keys::NONE;
980                }
981                if self.aligning {
982                    let back = Keys {
983                        back: true,
984                        ..Keys::NONE
985                    };
986                    for c in [fwd, Keys::NONE, back] {
987                        if self.safe::<P, S>(&view, obs, c, look).0 {
988                            return c;
989                        }
990                    }
991                    return back;
992                }
993                self.steer::<P, S>(&view, obs, look, t, fwd)
994            }
995            MoveKind::Parkour { gap } => self.leap_keys::<P, S>(&view, obs, look, world, gap),
996            // Landing on the block placed in the air.
997            MoveKind::Pillar => Keys::NONE,
998            MoveKind::DigDown => {
999                // Over the block's centre before the dig, then fall straight down.
1000                if obs.on_ground && (obs.pos[1] - f.feet_y).abs() < 0.02 && !self.over_centre(obs) {
1001                    self.centre_tap::<P, S>(&view, obs, look, f)
1002                } else {
1003                    Keys::NONE
1004                }
1005            }
1006            MoveKind::Swim => {
1007                let horiz = dx != 0 || dz != 0;
1008                let down = t.pos[1] < f.pos[1] && t.node == NodeKind::Swim;
1009                Keys {
1010                    forward: horiz && err < 45.0,
1011                    jump: !down,
1012                    ..Keys::NONE
1013                }
1014            }
1015            MoveKind::ClimbUp | MoveKind::ClimbExit => Keys {
1016                forward: err < 35.0,
1017                jump: true,
1018                ..Keys::NONE
1019            },
1020            MoveKind::ClimbDown => {
1021                if obs.on_ground && (dx != 0 || dz != 0) && f.node == NodeKind::Ground {
1022                    // Onto a ladder from above: inch over the edge.
1023                    let slow = obs.vel[0].hypot(obs.vel[2]) < 0.08;
1024                    return Keys {
1025                        forward: slow && err < 35.0,
1026                        ..Keys::NONE
1027                    };
1028                }
1029                // On the ladder: stay over its column while sliding down, without pushing
1030                // into the wall (that would climb).
1031                let back = Keys {
1032                    back: true,
1033                    ..Keys::NONE
1034                };
1035                let goal = t.target();
1036                let mut best = (f64::INFINITY, Keys::NONE);
1037                for c in [Keys::NONE, fwd, back] {
1038                    let r = rollout::<P, S>(&view, obs, &self.live, c, look, 1);
1039                    let score = hdist(r.pos, goal) + if r.collided { 10.0 } else { 0.0 };
1040                    if score < best.0 {
1041                        best = (score, c);
1042                    }
1043                }
1044                best.1
1045            }
1046        }
1047    }
1048
1049    /// The keys of a gap jump (see [`crate::jump`] for the policy): settle on the take-off
1050    /// block, check the jump in the physics from there, run, jump at the edge (or at once),
1051    /// steer the landing.
1052    fn leap_keys<P: Physics, S: BlockSource + ?Sized>(
1053        &mut self,
1054        view: &SourceView<'_, P, S>,
1055        obs: &Observation,
1056        look: (f32, f32),
1057        world: &S,
1058        gap: u8,
1059    ) -> Keys {
1060        let f = self.path.steps[self.reached].clone();
1061        let t = self.path.steps[self.reached + 1].clone();
1062        let dir = (
1063            (t.pos[0] - f.pos[0]).signum(),
1064            (t.pos[2] - f.pos[2]).signum(),
1065        );
1066        let leap = match self.leap {
1067            Some(l) => l,
1068            None => {
1069                let dy = (t.feet_y - f.feet_y).round() as i8;
1070                let jumps = Jumps::of(self.path.version);
1071                let spec = jump::select(&jumps, f.pos, dir, gap, dy, self.cfg.sprint, |q| {
1072                    self.class(world, q)
1073                });
1074                match spec {
1075                    Some(spec) => Leap::Settle(spec.mode, 0),
1076                    None => {
1077                        // The world changed since planning: plan again.
1078                        self.progress = Progress::Stuck;
1079                        return Keys::NONE;
1080                    }
1081                }
1082            }
1083        };
1084        self.leap = Some(leap);
1085        match leap {
1086            Leap::Settle(mode, quiet) => {
1087                if mode.sprint() && obs.food <= 6 {
1088                    self.progress = Progress::Stuck;
1089                    return Keys::NONE;
1090                }
1091                if !obs.on_ground {
1092                    return Keys::NONE;
1093                }
1094                let fc = f.target();
1095                let (along, side) = axis_offsets(obs.pos, fc, dir);
1096                let axis = dir_yaw(dir.0, dir.1);
1097                let ready = wrap(look.0 - axis).abs() <= jump::YAW_ERR - 0.01
1098                    && obs.vel[0].hypot(obs.vel[2]) < jump::REST
1099                    && along.abs() <= jump::ALONG - 0.01
1100                    && side.abs() <= jump::LATERAL - 0.01
1101                    && (obs.pos[1] - f.feet_y).abs() < 1e-6
1102                    && quiet >= 2;
1103                if ready {
1104                    // The last word: the jump from exactly here, in the physics.
1105                    let start = P::from_observation(obs, &self.live);
1106                    let Some(run) = jump::attempt::<P, S>(view, start, mode, look.0, t.pos) else {
1107                        self.progress = Progress::Stuck;
1108                        return Keys::NONE;
1109                    };
1110                    // Replay exactly the keys of the run that landed.
1111                    let plan = (run.run_ticks, run.release);
1112                    return self.leap_run(mode, look.0, plan, 0);
1113                }
1114                let k = self.inch::<P, S>(view, obs, look, &f, dir);
1115                self.leap = Some(Leap::Settle(
1116                    mode,
1117                    if k == Keys::NONE { quiet + 1 } else { 0 },
1118                ));
1119                k
1120            }
1121            Leap::Run(mode, yaw, plan, done) => {
1122                if !obs.on_ground {
1123                    // Left the floor early: steer the landing.
1124                    self.leap = Some(Leap::Air(mode, yaw, None));
1125                    return self.steer::<P, S>(view, obs, look, &t, mode.keys());
1126                }
1127                self.leap_run(mode, yaw, plan, done)
1128            }
1129            Leap::Air(mode, yaw, replay) => {
1130                if obs.on_ground {
1131                    // Landed short or elsewhere: off-path detection takes over.
1132                    return Keys::NONE;
1133                }
1134                match replay {
1135                    Some((hold, done)) => {
1136                        self.leap = Some(Leap::Air(mode, yaw, Some((hold, done + 1))));
1137                        if done < hold { mode.keys() } else { Keys::NONE }
1138                    }
1139                    None => self.steer::<P, S>(view, obs, look, &t, mode.keys()),
1140                }
1141            }
1142        }
1143    }
1144
1145    /// One ground tick of the replayed run: the run keys, plus jump on its last ground tick
1146    /// (the one the check found would leave the floor, or the first one).
1147    fn leap_run(&mut self, mode: Mode, yaw: f32, (ground, hold): (u32, u32), done: u32) -> Keys {
1148        let keys = mode.keys();
1149        if done + 1 >= ground {
1150            self.leap = Some(Leap::Air(mode, yaw, Some((hold, 0))));
1151            return Keys { jump: true, ..keys };
1152        }
1153        self.leap = Some(Leap::Run(mode, yaw, (ground, hold), done + 1));
1154        keys
1155    }
1156
1157    /// Lining up on the take-off block: the key tap (one tick, then nothing until at rest)
1158    /// whose resting point is closest to the block's centre in the jump's start envelope, never
1159    /// leaving the floor. `Keys::NONE` when no tap does better than coasting.
1160    fn inch<P: Physics, S: BlockSource + ?Sized>(
1161        &self,
1162        view: &SourceView<'_, P, S>,
1163        obs: &Observation,
1164        look: (f32, f32),
1165        f: &Step,
1166        dir: (i32, i32),
1167    ) -> Keys {
1168        let fc = f.target();
1169        let rest = |keys: Keys| -> Option<f64> {
1170            let mut s = P::from_observation(obs, &self.live);
1171            let mut o = *obs;
1172            for i in 0..20 {
1173                P::tick(
1174                    &mut s,
1175                    if i == 0 { keys } else { Keys::NONE },
1176                    look.0,
1177                    look.1,
1178                    view,
1179                );
1180                o = P::observe(&s);
1181                if !o.on_ground || (o.pos[1] - f.feet_y).abs() > 1e-6 {
1182                    return None;
1183                }
1184                if i > 0 && o.vel[0].hypot(o.vel[2]) < jump::REST {
1185                    break;
1186                }
1187            }
1188            let (a, l) = axis_offsets(o.pos, fc, dir);
1189            Some((a / jump::ALONG).powi(2) + (l / jump::LATERAL).powi(2))
1190        };
1191        let mut best = (rest(Keys::NONE).unwrap_or(f64::INFINITY), Keys::NONE);
1192        for sneak in [true, false] {
1193            for (fw, bk, lf, rt) in [
1194                (true, false, false, false),
1195                (false, true, false, false),
1196                (false, false, true, false),
1197                (false, false, false, true),
1198                (true, false, true, false),
1199                (true, false, false, true),
1200                (false, true, true, false),
1201                (false, true, false, true),
1202            ] {
1203                let k = Keys {
1204                    forward: fw,
1205                    back: bk,
1206                    left: lf,
1207                    right: rt,
1208                    sneak,
1209                    ..Keys::NONE
1210                };
1211                if let Some(sc) = rest(k)
1212                    && sc < best.0 - 1e-9
1213                {
1214                    best = (sc, k);
1215                }
1216            }
1217        }
1218        best.1
1219    }
1220
1221    /// A place that needs the player to move meanwhile: bridging (a side face) or towering.
1222    fn moving_place(&self, p: Place) -> bool {
1223        p.face()[1] == 0 || self.path.steps[self.reached + 1].kind == MoveKind::Pillar
1224    }
1225
1226    /// The keys of a moving place and whether the place can be sent this tick (from the pose
1227    /// the server has: the observation's).
1228    ///
1229    /// - Bridging: sneaking (vanilla keeps a sneaking player on the floor), back to the edge
1230    ///   until the eyes are past the plane of the clicked side face, so the face is in sight.
1231    /// - Towering: looking straight down, jump; place once the feet are above the new block
1232    ///   (vanilla refuses a block that would overlap the player).
1233    fn place_keys<P: Physics, S: BlockSource + ?Sized>(
1234        &self,
1235        obs: &Observation,
1236        look: (f32, f32),
1237        world: &S,
1238        p: Place,
1239    ) -> (Keys, bool) {
1240        let f = &self.path.steps[self.reached];
1241        let looking =
1242            wrap(obs.yaw - self.want.0).abs() < 2.0 && (obs.pitch - self.want.1).abs() < 2.0;
1243        if self.path.steps[self.reached + 1].kind == MoveKind::Pillar {
1244            if obs.on_ground && (obs.pos[1] - f.feet_y).abs() < 0.02 && !self.over_centre(obs) {
1245                // The whole box over the column first: a ceiling over a neighbouring column
1246                // must not cut the jump short.
1247                let view = SourceView::<P, S>::new(world);
1248                return (self.centre_tap::<P, S>(&view, obs, look, f), false);
1249            }
1250            if obs.on_ground {
1251                let jump = (obs.pos[1] - f.feet_y).abs() < 0.02 && obs.pitch > 85.0;
1252                return (Keys { jump, ..Keys::NONE }, false);
1253            }
1254            let above = obs.pos[1] > f64::from(p.pos[1]) + 1.0 + 1e-4;
1255            return (Keys::NONE, above && obs.pitch > 85.0);
1256        }
1257        let sneak = Keys {
1258            sneak: true,
1259            ..Keys::NONE
1260        };
1261        if !obs.on_ground {
1262            return (sneak, false);
1263        }
1264        let [fx, _, fz] = p.face();
1265        let c = place_point(p);
1266        let eyes = [obs.pos[0], obs.pos[1] + EYES, obs.pos[2]];
1267        let past = (eyes[0] - c[0]) * f64::from(fx) + (eyes[2] - c[2]) * f64::from(fz);
1268        // Where to stand: the box's back edge 0.05 over the floor block.
1269        let stand = [
1270            f64::from(p.against[0]) + 0.5 + 0.75 * f64::from(fx),
1271            f.feet_y,
1272            f64::from(p.against[2]) + 0.5 + 0.75 * f64::from(fz),
1273        ];
1274        let ready = past > 0.1 && looking;
1275        if hdist(obs.pos, stand) < 0.08 && obs.vel[0].hypot(obs.vel[2]) < 0.02 {
1276            return (sneak, ready);
1277        }
1278        let view = SourceView::<P, S>::new(world);
1279        let rest = |keys: Keys| -> Option<f64> {
1280            let mut s = P::from_observation(obs, &self.live);
1281            let mut o = *obs;
1282            for i in 0..8 {
1283                P::tick(
1284                    &mut s,
1285                    if i == 0 { keys } else { sneak },
1286                    look.0,
1287                    look.1,
1288                    &view,
1289                );
1290                o = P::observe(&s);
1291                if !o.on_ground || (o.pos[1] - f.feet_y).abs() > 1e-6 {
1292                    return None;
1293                }
1294            }
1295            Some(hdist(o.pos, stand))
1296        };
1297        let mut best = (rest(sneak).unwrap_or(f64::INFINITY), sneak);
1298        for (fw, bk, lf, rt) in [
1299            (true, false, false, false),
1300            (false, true, false, false),
1301            (false, false, true, false),
1302            (false, false, false, true),
1303            (true, false, true, false),
1304            (true, false, false, true),
1305            (false, true, true, false),
1306            (false, true, false, true),
1307        ] {
1308            let k = Keys {
1309                forward: fw,
1310                back: bk,
1311                left: lf,
1312                right: rt,
1313                sneak: true,
1314                ..Keys::NONE
1315            };
1316            if let Some(sc) = rest(k)
1317                && sc < best.0 - 1e-9
1318            {
1319                best = (sc, k);
1320            }
1321        }
1322        (best.1, ready)
1323    }
1324
1325    /// Standing still with the whole box inside the current step's column (a dig-down drops
1326    /// the player).
1327    fn over_centre(&self, obs: &Observation) -> bool {
1328        let c = self.path.steps[self.reached].target();
1329        obs.on_ground
1330            && (obs.pos[0] - c[0]).abs() < 0.15
1331            && (obs.pos[2] - c[2]).abs() < 0.15
1332            && obs.vel[0].hypot(obs.vel[2]) < 0.01
1333    }
1334
1335    /// The key tap (one tick, then nothing until at rest) whose resting point is nearest the
1336    /// centre of step `f`, never leaving its floor; `Keys::NONE` when coasting does as well.
1337    fn centre_tap<P: Physics, S: BlockSource + ?Sized>(
1338        &self,
1339        view: &SourceView<'_, P, S>,
1340        obs: &Observation,
1341        look: (f32, f32),
1342        f: &Step,
1343    ) -> Keys {
1344        let fc = f.target();
1345        let rest = |keys: Keys| -> Option<f64> {
1346            let mut s = P::from_observation(obs, &self.live);
1347            let mut o = *obs;
1348            for i in 0..20 {
1349                let k = if i == 0 { keys } else { Keys::NONE };
1350                P::tick(&mut s, k, look.0, look.1, view);
1351                o = P::observe(&s);
1352                if !o.on_ground || (o.pos[1] - f.feet_y).abs() > 1e-6 {
1353                    return None;
1354                }
1355                if i > 0 && o.vel[0].hypot(o.vel[2]) < 0.003 {
1356                    break;
1357                }
1358            }
1359            Some((o.pos[0] - fc[0]).abs().max((o.pos[2] - fc[2]).abs()))
1360        };
1361        let mut best = (rest(Keys::NONE).unwrap_or(f64::INFINITY), Keys::NONE);
1362        for sneak in [true, false] {
1363            for (fw, bk, lf, rt) in [
1364                (true, false, false, false),
1365                (false, true, false, false),
1366                (false, false, true, false),
1367                (false, false, false, true),
1368                (true, false, true, false),
1369                (true, false, false, true),
1370                (false, true, true, false),
1371                (false, true, false, true),
1372            ] {
1373                let k = Keys {
1374                    forward: fw,
1375                    back: bk,
1376                    left: lf,
1377                    right: rt,
1378                    sneak,
1379                    ..Keys::NONE
1380                };
1381                if let Some(sc) = rest(k)
1382                    && sc < best.0 - 1e-9
1383                {
1384                    best = (sc, k);
1385                }
1386            }
1387        }
1388        best.1
1389    }
1390
1391    /// Bang-bang landing control: tries "`primary` for n ticks, then nothing" (and, in the
1392    /// air, the same with the back key) in the physics and returns this tick's keys of the
1393    /// sequence that lands closest to `t`'s centre. Landing anywhere else is worse than not
1394    /// having left the floor yet, which is worse than landing on `t`.
1395    fn steer<P: Physics, S: BlockSource + ?Sized>(
1396        &self,
1397        view: &SourceView<'_, P, S>,
1398        obs: &Observation,
1399        look: (f32, f32),
1400        t: &Step,
1401        primary: Keys,
1402    ) -> Keys {
1403        let goal = t.target();
1404        let from_y = self.path.steps[self.reached].feet_y;
1405        let back = Keys {
1406            back: true,
1407            ..Keys::NONE
1408        };
1409        let mut best = (f64::INFINITY, Keys::NONE);
1410        let mut try_seq = |first: Keys, n: u32| {
1411            let mut s = P::from_observation(obs, &self.live);
1412            let mut left = !obs.on_ground;
1413            let mut o = *obs;
1414            let mut rested = false;
1415            for i in 0..48 {
1416                let k = if i < n { first } else { Keys::NONE };
1417                P::tick(&mut s, k, look.0, look.1, view);
1418                o = P::observe(&s);
1419                let swim_in = t.node == NodeKind::Swim && o.pos[1] < f64::from(t.pos[1]) + 0.9;
1420                let on_target = (o.pos[1] - t.feet_y).abs() < 0.02;
1421                if !o.on_ground && !swim_in {
1422                    left = true;
1423                } else if left && !swim_in && !on_target && (o.pos[1] - from_y).abs() < 0.02 {
1424                    // Back on the take-off floor (stepped down onto it): keep going.
1425                    left = false;
1426                } else if left || swim_in {
1427                    left = true;
1428                    break;
1429                } else if i >= n && o.vel[0].hypot(o.vel[2]) < 0.003 {
1430                    rested = true;
1431                    break;
1432                }
1433            }
1434            let fb = Pathfinder::start_block(o.pos);
1435            let d = hdist(o.pos, goal);
1436            let in_col = fb[0] == t.pos[0] && fb[2] == t.pos[2];
1437            let score = if !left || rested {
1438                100.0 + d
1439            } else if in_col && (t.node != NodeKind::Ground || (o.pos[1] - t.feet_y).abs() < 0.3) {
1440                d
1441            } else {
1442                1000.0 + d
1443            };
1444            if score < best.0 {
1445                best = (score, if n == 0 { Keys::NONE } else { first });
1446            }
1447        };
1448        for n in 0..=10 {
1449            try_seq(primary, n);
1450        }
1451        if !obs.on_ground {
1452            for n in 1..=6 {
1453                try_seq(back, n);
1454            }
1455        }
1456        best.1
1457    }
1458
1459    /// Whether a feet position is in a column of the current move (or the next one).
1460    fn allowed_column(&self, pos: [f64; 3]) -> bool {
1461        let fb = Pathfinder::start_block(pos);
1462        let steps = &self.path.steps;
1463        let f = &steps[self.reached];
1464        let t = &steps[self.reached + 1];
1465        let col = |p: [i32; 3]| p[0] == fb[0] && p[2] == fb[2];
1466        if col(f.pos) || col(t.pos) {
1467            return true;
1468        }
1469        steps.get(self.reached + 2).is_some_and(|n| col(n.pos))
1470    }
1471
1472    /// `keys` this tick, then braking until at rest (at most 12 ticks): (never leaves the
1473    /// floor outside the move's columns, never collides horizontally).
1474    fn safe<P: Physics, S: BlockSource + ?Sized>(
1475        &self,
1476        view: &SourceView<'_, P, S>,
1477        obs: &Observation,
1478        keys: Keys,
1479        look: (f32, f32),
1480    ) -> (bool, bool) {
1481        let mut s = P::from_observation(obs, &self.live);
1482        let mut clear = true;
1483        for i in 0..12 {
1484            let k = if i == 0 { keys } else { Keys::NONE };
1485            P::tick(&mut s, k, look.0, look.1, view);
1486            let o = P::observe(&s);
1487            clear &= !P::horizontal_collision(&s);
1488            if !o.on_ground && !self.allowed_column(o.pos) {
1489                return (false, clear);
1490            }
1491            if i > 0 && o.on_ground && o.vel[0].hypot(o.vel[2]) < 0.003 {
1492                break;
1493            }
1494        }
1495        (true, clear)
1496    }
1497}
1498
1499/// Ticks the movement-only steering looks ahead per key direction.
1500const STEER_TICKS: u32 = 3;
1501
1502/// Ticks without progress after which the walk accepts grazing a wall instead of braking.
1503const WEDGED_TICKS: u32 = 10;
1504
1505/// The look-ahead runs from the live player's exact state (26.1).
1506fn exact_look_ahead(version: Version) -> bool {
1507    match version {
1508        #[cfg(feature = "v26_1")]
1509        Version::V26_1 => true,
1510        #[cfg(feature = "v26_2")]
1511        Version::V26_2 => true,
1512        #[cfg(feature = "v26_3")]
1513        Version::V26_3 => true,
1514        #[allow(unreachable_patterns)]
1515        _ => false,
1516    }
1517}
1518
1519/// A step without digs or places.
1520fn plain(s: &Step) -> bool {
1521    s.dig.is_empty() && s.place.is_none() && s.node == NodeKind::Ground
1522}
1523
1524/// Runs the physics from `obs` with `keys` held for up to `max` ticks; stops on landing (after
1525/// having been in the air) or once at rest on the ground.
1526fn rollout<P: Physics, S: BlockSource + ?Sized>(
1527    view: &SourceView<'_, P, S>,
1528    obs: &Observation,
1529    live: &Live,
1530    keys: Keys,
1531    look: (f32, f32),
1532    max: u32,
1533) -> Roll {
1534    let mut s = P::from_observation(obs, live);
1535    let mut left = !obs.on_ground;
1536    let mut collided = false;
1537    let mut o = *obs;
1538    for i in 0..max {
1539        P::tick(&mut s, keys, look.0, look.1, view);
1540        o = P::observe(&s);
1541        collided |= P::horizontal_collision(&s);
1542        if !o.on_ground {
1543            left = true;
1544        } else if left || (i > 0 && o.vel[0].hypot(o.vel[2]) < 0.003) {
1545            break;
1546        }
1547    }
1548    Roll {
1549        pos: o.pos,
1550        on_ground: o.on_ground,
1551        collided,
1552    }
1553}
1554
1555/// `MathHelper.wrapDegrees` for `f32`.
1556pub(crate) fn wrap(a: f32) -> f32 {
1557    let mut v = a % 360.0;
1558    if v >= 180.0 {
1559        v -= 360.0;
1560    }
1561    if v < -180.0 {
1562        v += 360.0;
1563    }
1564    v
1565}
1566
1567/// Horizontal distance.
1568fn hdist(a: [f64; 3], b: [f64; 3]) -> f64 {
1569    (a[0] - b[0]).hypot(a[2] - b[2])
1570}
1571
1572/// Yaw (vanilla convention: +Z is 0, -X is 90) from `from` toward `to`.
1573fn yaw_to(from: [f64; 3], to: [f64; 3]) -> f32 {
1574    (-(to[0] - from[0])).atan2(to[2] - from[2]).to_degrees() as f32
1575}
1576
1577/// The yaw of a horizontal direction.
1578fn dir_yaw(dx: i32, dz: i32) -> f32 {
1579    (-f64::from(dx)).atan2(f64::from(dz)).to_degrees() as f32
1580}
1581
1582/// The middle of the face a place clicks.
1583fn place_point(p: Place) -> [f64; 3] {
1584    let [fx, fy, fz] = p.face();
1585    let c = centre(p.against);
1586    [
1587        c[0] + 0.5 * f64::from(fx),
1588        c[1] + 0.5 * f64::from(fy),
1589        c[2] + 0.5 * f64::from(fz),
1590    ]
1591}
1592
1593/// Half the thickness of a door's slab (3/16).
1594const DOOR_HALF_THICKNESS: f64 = 0.09375;
1595
1596/// The unit offset toward a side given as a wall code (`Class::wall`).
1597fn wall_dir(wall: u8) -> (i32, i32) {
1598    match wall {
1599        1 => (0, -1),
1600        2 => (0, 1),
1601        3 => (-1, 0),
1602        4 => (1, 0),
1603        _ => (0, 0),
1604    }
1605}
1606
1607/// The centre of a block.
1608fn centre(p: [i32; 3]) -> [f64; 3] {
1609    [
1610        f64::from(p[0]) + 0.5,
1611        f64::from(p[1]) + 0.5,
1612        f64::from(p[2]) + 0.5,
1613    ]
1614}
1615
1616/// Yaw / pitch that look from `eyes` at `p`.
1617fn look_at(eyes: [f64; 3], p: [f64; 3]) -> (f32, f32) {
1618    let (dx, dy, dz) = (p[0] - eyes[0], p[1] - eyes[1], p[2] - eyes[2]);
1619    let yaw = (-dx).atan2(dz).to_degrees();
1620    let pitch = -(dy.atan2(dx.hypot(dz))).to_degrees();
1621    (yaw as f32, pitch as f32)
1622}
1623
1624/// Horizontal distance of `p` from the segment `a`–`b`.
1625fn segment_dist(p: [f64; 3], a: [f64; 3], b: [f64; 3]) -> f64 {
1626    let (ax, az, bx, bz) = (a[0], a[2], b[0], b[2]);
1627    let (vx, vz) = (bx - ax, bz - az);
1628    let len2 = vx * vx + vz * vz;
1629    let t = if len2 < 1e-12 {
1630        0.0
1631    } else {
1632        (((p[0] - ax) * vx + (p[2] - az) * vz) / len2).clamp(0.0, 1.0)
1633    };
1634    (p[0] - (ax + t * vx)).hypot(p[2] - (az + t * vz))
1635}
1636
1637/// Offsets of `p` from `c` along the direction (`dx`, `dz`) and to its right.
1638fn axis_offsets(p: [f64; 3], c: [f64; 3], (dx, dz): (i32, i32)) -> (f64, f64) {
1639    let (ex, ez) = (p[0] - c[0], p[2] - c[2]);
1640    let (fx, fz) = (f64::from(dx), f64::from(dz));
1641    // Right-hand side of (dx, dz) is (-dz, dx).
1642    (ex * fx + ez * fz, -ex * fz + ez * fx)
1643}
1644
1645/// Whether a box `r` either side of `p` overlaps block column `b`.
1646fn over(p: [f64; 3], b: [i32; 3], r: f64) -> bool {
1647    let (x0, z0) = (f64::from(b[0]), f64::from(b[2]));
1648    p[0] + r > x0 && p[0] - r < x0 + 1.0 && p[2] + r > z0 && p[2] - r < z0 + 1.0
1649}
1650
1651/// Distance of `p` from the axis through `c` along (`dx`, `dz`).
1652fn lateral(p: [f64; 3], c: [f64; 3], dx: i32, dz: i32) -> f64 {
1653    if dx != 0 {
1654        (p[2] - c[2]).abs()
1655    } else if dz != 0 {
1656        (p[0] - c[0]).abs()
1657    } else {
1658        0.0
1659    }
1660}
1661
1662/// Distance of `p` from the face of block column `from` toward (`dx`, `dz`).
1663fn boundary_dist(p: [f64; 3], from: [i32; 3], dx: i32, dz: i32) -> f64 {
1664    let mut d = f64::INFINITY;
1665    if dx > 0 {
1666        d = d.min(f64::from(from[0] + 1) - p[0]);
1667    } else if dx < 0 {
1668        d = d.min(p[0] - f64::from(from[0]));
1669    }
1670    if dz > 0 {
1671        d = d.min(f64::from(from[2] + 1) - p[2]);
1672    } else if dz < 0 {
1673        d = d.min(p[2] - f64::from(from[2]));
1674    }
1675    if d.is_infinite() { 0.0 } else { d }
1676}
1677
1678#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
1679mod tests {
1680    use super::*;
1681
1682    #[test]
1683    fn angles() {
1684        assert_eq!(dir_yaw(0, 1), 0.0);
1685        assert_eq!(dir_yaw(-1, 0), 90.0);
1686        assert_eq!(dir_yaw(1, 0), -90.0);
1687        assert_eq!(dir_yaw(0, -1).abs(), 180.0);
1688        assert_eq!(wrap(370.0), 10.0);
1689        assert_eq!(wrap(-190.0), 170.0);
1690        let (y, p) = look_at([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]);
1691        assert_eq!(y, 0.0);
1692        assert!((p - 45.0).abs() < 1e-4);
1693    }
1694
1695    #[test]
1696    fn geometry() {
1697        let a = [0.5, 64.0, 0.5];
1698        let b = [4.5, 64.0, 0.5];
1699        assert!((segment_dist([2.0, 64.0, 1.5], a, b) - 1.0).abs() < 1e-9);
1700        assert!((segment_dist([6.5, 64.0, 0.5], a, b) - 2.0).abs() < 1e-9);
1701        assert!((boundary_dist([0.5, 64.0, 0.5], [0, 64, 0], 1, 0) - 0.5).abs() < 1e-9);
1702        assert!((boundary_dist([0.2, 64.0, 0.5], [0, 64, 0], -1, 0) - 0.2).abs() < 1e-9);
1703        assert!((lateral([0.7, 64.0, 3.0], a, 0, 1) - 0.2).abs() < 1e-9);
1704    }
1705}