Skip to main content

ghast_ext/
nav.rs

1//! Walking: a straight-line walker (open ground, no planning) and following an entity.
2
3use ghast_client::{Controls, TickContext, Vec3};
4
5use crate::{Bot, Error};
6
7/// Releases the movement keys when a walker ends early.
8struct ReleaseKeys(Option<Bot>);
9
10impl Drop for ReleaseKeys {
11    fn drop(&mut self) {
12        if let Some(bot) = self.0.take() {
13            bot.act(|ctx| ctx.set_controls(Controls::NONE));
14        }
15    }
16}
17
18/// Ticks without progress before [`Error::Stuck`].
19const STUCK_TICKS: u32 = 60;
20
21/// State of the straight walker between ticks.
22#[derive(Debug, Clone, Copy, Default)]
23struct Walk {
24    last: Option<Vec3>,
25    still: u32,
26}
27
28/// One walker tick toward `goal`: aims the yaw (keeps the pitch), presses forward, sprints
29/// when far, jumps when pressing forward made no progress on the ground. `true` once
30/// within `range` (horizontal) of the goal (keys released).
31fn walk_step(
32    ctx: &mut TickContext<'_>,
33    w: &mut Walk,
34    goal: Vec3,
35    range: f64,
36    sprint: bool,
37) -> bool {
38    let p = *ctx.pose();
39    let (dx, dz) = (goal.x - p.pos.x, goal.z - p.pos.z);
40    let d = (dx * dx + dz * dz).sqrt();
41    if d <= range {
42        ctx.set_controls(Controls::NONE);
43        return true;
44    }
45    let yaw = (-dx).atan2(dz).to_degrees() as f32;
46    ctx.set_aim(yaw, p.pitch);
47    let moved = w.last.map_or(1.0, |l| {
48        ((p.pos.x - l.x).powi(2) + (p.pos.z - l.z).powi(2)).sqrt()
49    });
50    w.still = if moved < 0.01 { w.still + 1 } else { 0 };
51    w.last = Some(p.pos);
52    let jump = p.on_ground && w.still >= 2;
53    ctx.set_controls(Controls {
54        forward: true,
55        sprint: sprint && d > 3.0,
56        jump,
57        ..Controls::NONE
58    });
59    false
60}
61
62impl Bot {
63    /// Walks in a straight line until within `range` blocks (horizontally) of `goal`:
64    /// turns toward it (whole mouse counts), holds forward (sprinting while more than 3
65    /// blocks away), and jumps when blocked. No path planning: for open ground. Fails with
66    /// [`Error::Stuck`] after 3 s without progress, or when teleported / dead.
67    ///
68    /// ```no_run
69    /// use ghast_client::Vec3;
70    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
71    /// bot.walk_straight_to(Vec3::new(10.5, 64.0, 3.5), 0.5).await?;
72    /// # Ok(()) }
73    /// ```
74    pub async fn walk_straight_to(&self, goal: Vec3, range: f64) -> Result<(), Error> {
75        let mark = self.mark();
76        let mut keys = ReleaseKeys(Some(self.clone()));
77        let mut w = Walk::default();
78        loop {
79            let (done, ww) = self
80                .with(move |ctx| {
81                    let mut w = w;
82                    let done = walk_step(ctx, &mut w, goal, range, true);
83                    (done, w)
84                })
85                .await?;
86            w = ww;
87            if done {
88                keys.0 = None;
89                return Ok(());
90            }
91            if w.still > STUCK_TICKS {
92                return Err(Error::Stuck);
93            }
94            self.next_tick().await;
95            self.check(mark)?;
96        }
97    }
98
99    /// Follows entity `id`, staying within `range` blocks of it, with the straight walker
100    /// (see [`Bot::walk_straight_to`]): for open ground. To follow through mazes, over gaps
101    /// and around walls use `Bot::follow_path` (feature `pathfinder`). Runs until the entity is gone
102    /// ([`Error::NoSuchEntity`]), the walker is stuck, or the task is cancelled (e.g. with
103    /// [`Bot::timeout`] or [`crate::JoinHandle::abort`]). Needs
104    /// [`ghast_client::Interests::ENTITIES`].
105    ///
106    /// ```no_run
107    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
108    /// if let Some(p) = bot.player("Steve").await? {
109    ///     let _ = bot.timeout(20 * 60, bot.follow(p.id, 2.0)).await; // one minute
110    /// }
111    /// # Ok(()) }
112    /// ```
113    pub async fn follow(&self, id: i32, range: f64) -> Result<(), Error> {
114        let mark = self.mark();
115        let _keys = ReleaseKeys(Some(self.clone()));
116        let mut w = Walk::default();
117        loop {
118            let r = self
119                .with(move |ctx| -> Result<Walk, Error> {
120                    let e = crate::find::entity_info(ctx, id).ok_or(Error::NoSuchEntity(id))?;
121                    let mut w = w;
122                    if walk_step(ctx, &mut w, e.pos, range, true) {
123                        // Arrived: keep watching (look at it).
124                        let (yaw, pitch) = crate::yaw_pitch(
125                            ctx.eyes(ctx.pose()),
126                            Vec3::new(e.pos.x, e.pos.y + 1.6, e.pos.z),
127                        );
128                        ctx.set_aim(yaw, pitch);
129                        w = Walk::default();
130                    }
131                    Ok(w)
132                })
133                .await??;
134            w = r;
135            if w.still > STUCK_TICKS {
136                return Err(Error::Stuck);
137            }
138            self.next_tick().await;
139            self.check(mark)?;
140        }
141    }
142
143    /// Sets the movement keys (kept until changed) in this tick.
144    ///
145    /// ```no_run
146    /// use ghast_client::Controls;
147    /// # async fn f(bot: ghast_ext::Bot) {
148    /// bot.set_controls(Controls { forward: true, jump: true, ..Controls::NONE });
149    /// bot.wait_ticks(10).await;
150    /// bot.set_controls(Controls::NONE);
151    /// # }
152    /// ```
153    pub fn set_controls(&self, controls: Controls) {
154        self.act(move |ctx| ctx.set_controls(controls));
155    }
156}