Skip to main content

ghast_pathfinder/
sim.rs

1//! Running a path offline: the [`Controller`] drives the vanilla-exact `ghast-physics` player
2//! through the path, turning in whole mouse counts like ghast-client does.
3
4use crate::Version;
5use crate::class::{flag, table};
6use crate::control::{Controller, ControllerConfig, Progress};
7use crate::door;
8use crate::moves::MoveKind;
9#[cfg(feature = "v1_12_2")]
10use crate::physics::P12;
11#[cfg(feature = "v1_16_5")]
12use crate::physics::P16;
13#[cfg(feature = "v1_8")]
14use crate::physics::P18;
15#[cfg(feature = "v26_1")]
16use crate::physics::P26;
17#[cfg(feature = "v26_2")]
18use crate::physics::P262;
19#[cfg(feature = "v26_3")]
20use crate::physics::P263;
21use crate::physics::{Live, Observation, Physics, SourceView};
22use crate::plan::Path;
23use crate::world::BlockSource;
24
25/// How a simulated run ended.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub enum SimOutcome {
29    /// The last step was reached.
30    Arrived,
31    /// The controller made no progress ([`Progress::Stuck`]).
32    Stuck,
33    /// The player left the path ([`Progress::OffPath`]).
34    OffPath,
35    /// The body touched lava or a block the planner avoids (fire, cobweb, ...).
36    Hazard,
37    /// Out of ticks.
38    Timeout,
39}
40
41/// The result of [`simulate`].
42#[derive(Clone, Debug, PartialEq)]
43#[non_exhaustive]
44pub struct SimReport {
45    /// How it ended.
46    pub outcome: SimOutcome,
47    /// Ticks run.
48    pub ticks: u32,
49    /// Index of the last step reached.
50    pub reached: usize,
51    /// Feet position at the end.
52    pub end: [f64; 3],
53    /// Ticks with a horizontal collision during moves that should not touch anything
54    /// (walks, diagonals, drops, gap jumps). Jumps up, climbs and swims onto land are
55    /// expected to touch the block they go onto and are not counted.
56    pub collisions: u32,
57    /// The first tick of such a collision.
58    pub first_collision: Option<u32>,
59    /// Largest fall distance at a landing (vanilla fall damage starts above 3).
60    pub max_fall: f32,
61    /// Feet position after every tick.
62    pub trace: Vec<[f64; 3]>,
63}
64
65/// The client's rotation (ghast-client `rotation::Rotation` at sensitivity 0.5): whole mouse
66/// counts, at most 14° yaw / 10.5° pitch per tick with a carried budget.
67#[derive(Clone, Copy, Debug, Default)]
68pub(crate) struct Turner {
69    yaw_budget: f64,
70    pitch_budget: f64,
71}
72
73impl Turner {
74    const MAX_YAW: f64 = 14.0;
75    const MAX_PITCH: f64 = 10.5;
76    /// `mouse_multiplier(0.5)`: `(0.5 * 0.6 + 0.2)^3 * 8` in `f32`.
77    const MULTIPLIER: f32 = 1.0;
78
79    fn counts(budget: &mut f64, delta: f32, per_tick_deg: f64) -> i64 {
80        let step = f64::from(Self::MULTIPLIER) * 0.15;
81        let per_tick = per_tick_deg / step;
82        *budget = (*budget + per_tick).min(per_tick + 1.0);
83        let wanted = (f64::from(delta) / step + 0.5).floor() as i64;
84        let lim = budget.trunc() as i64;
85        let count = wanted.clamp(-lim, lim);
86        *budget -= count.unsigned_abs() as f64;
87        if count == wanted {
88            *budget = 0.0;
89        }
90        count
91    }
92
93    /// One tick from (`yaw`, `pitch`) toward the target (pitch target clamped to ±89.5).
94    pub(crate) fn step(&mut self, yaw: f32, pitch: f32, target: (f32, f32)) -> (f32, f32) {
95        let m = Self::MULTIPLIER;
96        let ty = target.0;
97        let tp = target.1.clamp(-89.5, 89.5);
98        let dx = Self::counts(
99            &mut self.yaw_budget,
100            crate::control::wrap(ty - yaw),
101            Self::MAX_YAW,
102        );
103        let dy = Self::counts(&mut self.pitch_budget, tp - pitch, Self::MAX_PITCH);
104        let fx = dx as f32 * m;
105        let fy = -(dy as f32) * m;
106        let new_yaw = (f64::from(yaw) + f64::from(fx) * 0.15) as f32;
107        let new_pitch = ((f64::from(pitch) - f64::from(fy) * 0.15) as f32).clamp(-90.0, 90.0);
108        (new_yaw, new_pitch)
109    }
110}
111
112/// Runs `path` in `world` with a [`Controller`]: the player starts standing at the first
113/// step's centre, facing the second, and the physics is `ghast-physics` (bit-exact vanilla)
114/// for the path's version. Digs complete after `5 + 30 × hardness` ticks (a bare hand's
115/// order of magnitude) and places after 4 ticks (a stone block appears); the world itself is
116/// not changed.
117///
118/// ```
119/// use ghast_pathfinder::{Config, ControllerConfig, Goal, Pathfinder, SimOutcome, Version, simulate};
120///
121/// let mut world = ghast_physics::v1_8::memory_world();
122/// world.load_chunks(-2, -2, 2, 2);
123/// world.fill_raw([-20, 63, -20], [20, 63, 20], 1 << 4);
124/// world.fill_raw([4, 64, -3], [4, 64, 3], 1 << 4); // a step
125/// let path = Pathfinder::new(Config::default())
126///     .plan(Version::V1_8, &world, [0, 64, 0], &Goal::Block([9, 65, 0]))
127///     .unwrap();
128/// let report = simulate(&path, &world, &ControllerConfig::default());
129/// assert_eq!(report.outcome, SimOutcome::Arrived);
130/// ```
131#[must_use]
132pub fn simulate<S: BlockSource + ?Sized>(
133    path: &Path,
134    world: &S,
135    cfg: &ControllerConfig,
136) -> SimReport {
137    let mut sim = Simulation::new(path, cfg);
138    while sim.step(world, u32::MAX, None).is_none() {}
139    sim.into_report()
140}
141
142/// Whether a client at `obs` can place `p`: the clicked face faces the eyes and is within
143/// 4.5 blocks of them, and the new block does not overlap the player.
144fn place_ok(obs: &Observation, p: crate::plan::Place) -> bool {
145    let [fx, fy, fz] = p.face();
146    let eyes = [obs.pos[0], obs.pos[1] + 1.62, obs.pos[2]];
147    let c = [
148        f64::from(p.against[0]) + 0.5 + 0.5 * f64::from(fx),
149        f64::from(p.against[1]) + 0.5 + 0.5 * f64::from(fy),
150        f64::from(p.against[2]) + 0.5 + 0.5 * f64::from(fz),
151    ];
152    let d = [eyes[0] - c[0], eyes[1] - c[1], eyes[2] - c[2]];
153    let facing = d[0] * f64::from(fx) + d[1] * f64::from(fy) + d[2] * f64::from(fz) > 0.0;
154    let reach = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() <= 4.5;
155    let (x, y, z) = (
156        f64::from(p.pos[0]),
157        f64::from(p.pos[1]),
158        f64::from(p.pos[2]),
159    );
160    let o = obs.pos;
161    let overlap = o[0] + 0.3 > x
162        && o[0] - 0.3 < x + 1.0
163        && o[1] + 1.8 > y
164        && o[1] < y + 1.0
165        && o[2] + 0.3 > z
166        && o[2] - 0.3 < z + 1.0;
167    facing && reach && !overlap
168}
169
170/// The raw stone state of a version (what a simulated place puts down).
171pub(crate) fn stone_raw(version: Version) -> u32 {
172    match version {
173        #[cfg(feature = "v1_8")]
174        Version::V1_8 => 1 << 4,
175        #[cfg(feature = "v1_12_2")]
176        Version::V1_12 => 1 << 4,
177        #[cfg(feature = "v1_16_5")]
178        Version::V1_16_5 => u32::from(ghast_data::v1_16_5::Block::STONE.default_state().id()),
179        #[cfg(feature = "v26_1")]
180        Version::V26_1 => u32::from(ghast_data::v26_1::Block::STONE.default_state().id()),
181        #[cfg(feature = "v26_2")]
182        Version::V26_2 => u32::from(ghast_data::v26_2::Block::STONE.default_state().id()),
183        #[cfg(feature = "v26_3")]
184        Version::V26_3 => u32::from(ghast_data::v26_3::Block::STONE.default_state().id()),
185    }
186}
187
188/// The simulated player of either version.
189#[derive(Clone, Debug)]
190enum Body {
191    #[cfg(feature = "v1_8")]
192    V18(<P18 as Physics>::State),
193    #[cfg(feature = "v1_12_2")]
194    V12(<P12 as Physics>::State),
195    #[cfg(feature = "v1_16_5")]
196    V16(<P16 as Physics>::State),
197    #[cfg(feature = "v26_1")]
198    V26(Box<<P26 as Physics>::State>),
199    #[cfg(feature = "v26_2")]
200    V262(Box<<P262 as Physics>::State>),
201    #[cfg(feature = "v26_3")]
202    V263(Box<<P263 as Physics>::State>),
203}
204
205/// A resumable [`simulate`]: [`Simulation::step`] runs a slice of ticks, so a follower can
206/// verify a long path across several game ticks. Owns its state (no borrows).
207///
208/// ```
209/// use ghast_pathfinder::{Config, ControllerConfig, Goal, Pathfinder, SimOutcome, Simulation, Version};
210///
211/// let mut world = ghast_physics::v1_8::memory_world();
212/// world.load_chunks(-1, -1, 1, 1);
213/// world.fill_raw([-10, 63, -10], [10, 63, 10], 1 << 4);
214/// let path = Pathfinder::new(Config::default())
215///     .plan(Version::V1_8, &world, [0, 64, 0], &Goal::Block([8, 64, 3]))
216///     .unwrap();
217/// let mut sim = Simulation::new(&path, &ControllerConfig::default());
218/// let outcome = loop {
219///     if let Some(r) = sim.step(&world, 20, None) {
220///         break r.outcome;
221///     }
222/// };
223/// assert_eq!(outcome, SimOutcome::Arrived);
224/// ```
225#[derive(Clone, Debug)]
226pub struct Simulation {
227    body: Body,
228    run: Run,
229}
230
231/// Everything of a simulation but the player.
232#[derive(Clone, Debug)]
233struct Run {
234    version: Version,
235    turner: Turner,
236    ctrl: Controller,
237    overrides: Vec<([i32; 3], u32)>,
238    job: Option<([i32; 3], u32)>,
239    tick: u32,
240    max_ticks: u32,
241    report: SimReport,
242    done: bool,
243}
244
245impl Simulation {
246    /// A simulation of `path` from its first step (standing at the centre, facing the
247    /// second), not started yet.
248    #[must_use]
249    pub fn new(path: &Path, cfg: &ControllerConfig) -> Simulation {
250        Self::with_live(path, cfg, &Live::default())
251    }
252
253    /// 26.1: like [`Simulation::new`], with the live client player's attributes (movement
254    /// speed, step height, jump strength, scale, ...), effects, abilities and build height
255    /// (`ghast_client::TickContext::modern_player`) instead of vanilla defaults. The `Follower`
256    /// verifies its plans this way. On other versions the player is ignored.
257    #[cfg(ghast_modern)]
258    #[must_use]
259    pub fn with_modern_player(
260        path: &Path,
261        cfg: &ControllerConfig,
262        player: &ghast_physics::modern::PlayerState,
263    ) -> Simulation {
264        let mut live = Live::default();
265        live.set_modern(player);
266        Self::with_live(path, cfg, &live)
267    }
268
269    pub(crate) fn with_live(path: &Path, cfg: &ControllerConfig, live: &Live) -> Simulation {
270        let _ = live;
271        let start = path.steps[0].target();
272        let yaw0 = path.steps.get(1).map_or(0.0, |s| {
273            let t = s.target();
274            (-(t[0] - start[0])).atan2(t[2] - start[2]).to_degrees() as f32
275        });
276        let body = match path.version {
277            #[cfg(feature = "v1_8")]
278            Version::V1_8 => Body::V18(P18::new_state(start, yaw0, 0.0)),
279            #[cfg(feature = "v1_12_2")]
280            Version::V1_12 => Body::V12(P12::new_state(start, yaw0, 0.0)),
281            #[cfg(feature = "v1_16_5")]
282            Version::V1_16_5 => Body::V16(P16::new_state(start, yaw0, 0.0)),
283            #[cfg(feature = "v26_1")]
284            Version::V26_1 => Body::V26(Box::new(P26::new_state_live(start, yaw0, 0.0, live))),
285            #[cfg(feature = "v26_2")]
286            Version::V26_2 => Body::V262(Box::new(P262::new_state_live(start, yaw0, 0.0, live))),
287            #[cfg(feature = "v26_3")]
288            Version::V26_3 => Body::V263(Box::new(P263::new_state_live(start, yaw0, 0.0, live))),
289        };
290        let max_ticks = (path.cost * 4.0) as u32 + 20 * path.steps.len() as u32 + 200;
291        Simulation {
292            body,
293            run: Run {
294                version: path.version,
295                turner: Turner::default(),
296                ctrl: Controller::new(path.clone(), cfg.clone()),
297                overrides: Vec::new(),
298                job: None,
299                tick: 0,
300                max_ticks,
301                report: SimReport {
302                    outcome: SimOutcome::Timeout,
303                    ticks: 0,
304                    reached: 0,
305                    end: start,
306                    collisions: 0,
307                    first_collision: None,
308                    max_fall: 0.0,
309                    trace: Vec::with_capacity(max_ticks.min(4096) as usize),
310                },
311                done: false,
312            },
313        }
314    }
315
316    /// The path being simulated.
317    #[must_use]
318    pub fn path(&self) -> &Path {
319        self.run.ctrl.path()
320    }
321
322    /// Runs at most `ticks` simulated ticks (and stops after `time`, checked every 16
323    /// ticks); the report once the run has ended (`None`: call again).
324    pub fn step<S: BlockSource + ?Sized>(
325        &mut self,
326        world: &S,
327        ticks: u32,
328        time: Option<std::time::Duration>,
329    ) -> Option<&SimReport> {
330        if !self.run.done {
331            let done = match self.body {
332                #[cfg(feature = "v1_8")]
333                Body::V18(ref mut s) => self.run.advance::<P18, S>(s, world, ticks, time),
334                #[cfg(feature = "v1_12_2")]
335                Body::V12(ref mut s) => self.run.advance::<P12, S>(s, world, ticks, time),
336                #[cfg(feature = "v1_16_5")]
337                Body::V16(ref mut s) => self.run.advance::<P16, S>(s, world, ticks, time),
338                #[cfg(feature = "v26_1")]
339                Body::V26(ref mut s) => self.run.advance::<P26, S>(s, world, ticks, time),
340                #[cfg(feature = "v26_2")]
341                Body::V262(ref mut s) => self.run.advance::<P262, S>(s, world, ticks, time),
342                #[cfg(feature = "v26_3")]
343                Body::V263(ref mut s) => self.run.advance::<P263, S>(s, world, ticks, time),
344            };
345            self.run.done = done;
346        }
347        self.run.done.then_some(&self.run.report)
348    }
349
350    /// The report so far (final once [`Simulation::step`] returned it).
351    #[must_use]
352    pub fn report(&self) -> &SimReport {
353        &self.run.report
354    }
355
356    /// The report.
357    #[must_use]
358    pub fn into_report(self) -> SimReport {
359        self.run.report
360    }
361}
362
363impl Run {
364    /// Runs up to `ticks` ticks; `true` once the run ended.
365    fn advance<P: Physics, S: BlockSource + ?Sized>(
366        &mut self,
367        state: &mut P::State,
368        world: &S,
369        ticks: u32,
370        time: Option<std::time::Duration>,
371    ) -> bool {
372        let tbl = table(self.version);
373        let started = time.map(|_| std::time::Instant::now());
374        let mut view =
375            SourceView::<P, S>::with_overrides(world, std::mem::take(&mut self.overrides));
376        let class = |v: &SourceView<'_, P, S>, x: i32, y: i32, z: i32| {
377            v.raw(x, y, z).map_or(crate::class::Class::UNKNOWN, |r| {
378                tbl.classes[tbl.index(r) as usize]
379            })
380        };
381        let report = &mut self.report;
382        let ctrl = &mut self.ctrl;
383        let mut done = false;
384        let mut n = 0u32;
385        while !done {
386            if self.tick >= self.max_ticks {
387                done = true;
388                break;
389            }
390            if n >= ticks
391                || (n % 16 == 15
392                    && started
393                        .zip(time)
394                        .is_some_and(|(t0, max)| t0.elapsed() >= max))
395            {
396                break;
397            }
398            n += 1;
399            let tick = self.tick;
400            self.tick += 1;
401            let mut obs: Observation = P::observe(state);
402            obs.food = 20;
403            P::feed(ctrl.live_mut(), state);
404            let want = ctrl.aim(&obs, &view);
405            let look = self.turner.step(obs.yaw, obs.pitch, want);
406            let cmd = ctrl.keys(&obs, look, &view);
407            report.reached = ctrl.reached();
408            match ctrl.progress() {
409                Progress::Arrived => {
410                    report.outcome = SimOutcome::Arrived;
411                    done = true;
412                    break;
413                }
414                Progress::Stuck => {
415                    report.outcome = SimOutcome::Stuck;
416                    done = true;
417                    break;
418                }
419                Progress::OffPath => {
420                    report.outcome = SimOutcome::OffPath;
421                    done = true;
422                    break;
423                }
424                Progress::Moving | Progress::Working => {}
425            }
426            // Jobs: a dig or place takes a while, then the block changes.
427            // A place counts only where a client could make it: the face in sight and reach,
428            // the new block clear of the player.
429            let place = cmd.place.filter(|p| place_ok(&obs, *p));
430            let target = cmd.dig.or(place.map(|p| p.pos)).or(cmd.interact);
431            match (target, self.job) {
432                (Some(p), Some((q, k))) if p == q => {
433                    let need = match (cmd.dig, cmd.interact) {
434                        (Some(d), _) => {
435                            5 + (f64::from(class(&view, d[0], d[1], d[2]).hardness.max(0.0)) * 30.0)
436                                as u32
437                        }
438                        (None, Some(_)) => 2,
439                        // A place in the air (towering) is answered as fast as the server can.
440                        (None, None) if !obs.on_ground => 2,
441                        (None, None) => 4,
442                    };
443                    if k + 1 >= need {
444                        if cmd.interact.is_some() && cmd.dig.is_none() && place.is_none() {
445                            for (q, raw) in door::toggle(self.version, &view, p).unwrap_or_default()
446                            {
447                                view.set(q, raw);
448                            }
449                        } else {
450                            let raw = if cmd.dig.is_some() {
451                                0
452                            } else {
453                                stone_raw(self.version)
454                            };
455                            view.set(p, raw);
456                        }
457                        self.job = None;
458                    } else {
459                        self.job = Some((q, k + 1));
460                    }
461                }
462                (Some(p), _) => self.job = Some((p, 0)),
463                (None, _) => self.job = None,
464            }
465            let keys = cmd.keys;
466            let kind = ctrl
467                .path()
468                .steps
469                .get(ctrl.reached() + 1)
470                .map_or(MoveKind::Start, |s| s.kind);
471            let fall_before = P::fall_distance(state);
472            P::tick(state, keys, look.0, look.1, &view);
473            let o = P::observe(state);
474            report.ticks = tick + 1;
475            report.end = o.pos;
476            report.trace.push(o.pos);
477            if o.on_ground {
478                report.max_fall = report.max_fall.max(fall_before);
479            }
480            if P::horizontal_collision(state)
481                && matches!(
482                    kind,
483                    MoveKind::Walk
484                        | MoveKind::Diagonal
485                        | MoveKind::Descend
486                        | MoveKind::Parkour { .. }
487                )
488            {
489                report.collisions += 1;
490                report.first_collision.get_or_insert(tick);
491            }
492            // Hazards in the body's column.
493            let (x, z) = (o.pos[0].floor() as i32, o.pos[2].floor() as i32);
494            let y0 = o.pos[1].floor() as i32;
495            let y1 = (o.pos[1] + 1.79).floor() as i32;
496            if (y0..=y1).any(|y| class(&view, x, y, z).has(flag::LAVA | flag::AVOID)) {
497                report.outcome = SimOutcome::Hazard;
498                done = true;
499            }
500        }
501        self.overrides = view.overrides;
502        done
503    }
504}
505
506#[cfg(all(
507    test,
508    feature = "client",
509    feature = "v1_8",
510    feature = "v1_12_2",
511    feature = "v1_16_5"
512))]
513mod tests {
514    use super::Turner;
515
516    /// The simulator turns exactly like ghast-client.
517    #[test]
518    fn turner_matches_the_client_rotation() {
519        let mut r = ghast_client::rotation::Rotation::new(0.5);
520        let mut t = Turner::default();
521        let (mut yaw, mut pitch) = (12.5_f32, 3.0_f32);
522        let targets = [
523            (100.0, 40.0),
524            (-170.0, -80.0),
525            (365.0, 0.0),
526            (12.3, 1.1),
527            (-45.0, 89.9),
528        ];
529        let (mut y2, mut p2) = (yaw, pitch);
530        for (i, &(ty, tp)) in targets.iter().cycle().take(200).enumerate() {
531            if i % 7 == 0 {
532                r.set_target(ty, tp);
533            }
534            let target = r.target();
535            let a = r.step(yaw, pitch);
536            let b = t.step(y2, p2, target);
537            assert_eq!(a, b, "tick {i}");
538            (yaw, pitch) = a;
539            (y2, p2) = b;
540        }
541    }
542}