Skip to main content

ghast_ext/
look.rs

1//! Looking: GCD-correct turning through the client's rotation, and choosing a visible
2//! point of a block face.
3
4use ghast_client::hands::{self, BlockHit};
5use ghast_client::{BlockPos, Face, TickContext, Vec3};
6
7use crate::{Bot, Error};
8
9/// Ticks a turn may take before [`Error::Timeout`] (a 180° turn takes about 13).
10const LOOK_TICKS: u64 = 60;
11
12/// Yaw / pitch (degrees, vanilla convention) that look from `eyes` at `p`.
13///
14/// ```
15/// use ghast_client::Vec3;
16/// let (yaw, pitch) = ghast_ext::yaw_pitch(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
17/// assert_eq!((yaw, pitch), (0.0, 0.0)); // +Z is yaw 0
18/// let (yaw, _) = ghast_ext::yaw_pitch(Vec3::new(0.0, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0));
19/// assert_eq!(yaw, 90.0); // -X is yaw 90
20/// ```
21#[must_use]
22pub fn yaw_pitch(eyes: Vec3, p: Vec3) -> (f32, f32) {
23    let (dx, dy, dz) = (p.x - eyes.x, p.y - eyes.y, p.z - eyes.z);
24    let yaw = (-dx).atan2(dz).to_degrees();
25    let pitch = -(dy.atan2((dx * dx + dz * dz).sqrt())).to_degrees();
26    (yaw as f32, pitch as f32)
27}
28
29/// The unit normal of a face.
30pub(crate) fn normal(f: Face) -> (f64, f64, f64) {
31    match f {
32        Face::Down => (0.0, -1.0, 0.0),
33        Face::Up => (0.0, 1.0, 0.0),
34        Face::North => (0.0, 0.0, -1.0),
35        Face::South => (0.0, 0.0, 1.0),
36        Face::West => (-1.0, 0.0, 0.0),
37        Face::East => (1.0, 0.0, 0.0),
38    }
39}
40
41pub(crate) const FACES: [Face; 6] = [
42    Face::Up,
43    Face::North,
44    Face::South,
45    Face::West,
46    Face::East,
47    Face::Down,
48];
49
50/// The crosshair from `eyes` along (`yaw`, `pitch`), as the client computes it.
51pub(crate) fn ray(ctx: &TickContext<'_>, eyes: Vec3, yaw: f32, pitch: f32) -> Option<BlockHit> {
52    let w = ctx.world();
53    let blocks = |x: i32, y: i32, z: i32| w.block_query(x, y, z);
54    hands::pick(&blocks, eyes, hands::look_vector(yaw, pitch), hands::REACH)
55}
56
57/// A point to aim at: the point, its face and the look.
58pub(crate) type AimPoint = (Vec3, Face, f32, f32);
59
60/// Points on `pos`'s faces (only `want` when given) that the crosshair from the current
61/// eyes hits on exactly that block and face, best first: faces turned toward the eyes most,
62/// each face's centre first, then points nearer its edges. At most `max` points.
63pub(crate) fn aim_points(
64    ctx: &TickContext<'_>,
65    pos: BlockPos,
66    want: Option<Face>,
67    max: usize,
68) -> Vec<AimPoint> {
69    let mut out = Vec::new();
70    let eyes = ctx.eyes(ctx.pose());
71    let Some(b) = ctx.world().block_query(pos.x, pos.y, pos.z) else {
72        return out;
73    };
74    // The block's ray box (local), or the full cube.
75    let s = b.selection.unwrap_or([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]);
76    let (bx, by, bz) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z));
77    let mut faces: Vec<(f64, Face)> = FACES
78        .iter()
79        .filter(|f| want.is_none_or(|w| w == **f))
80        .filter_map(|&f| {
81            let n = normal(f);
82            // The face plane's coordinate along its normal.
83            let c = (
84                bx + (s[0] + s[3]) / 2.0,
85                by + (s[1] + s[4]) / 2.0,
86                bz + (s[2] + s[5]) / 2.0,
87            );
88            let plane = (
89                if n.0 > 0.0 {
90                    bx + s[3]
91                } else if n.0 < 0.0 {
92                    bx + s[0]
93                } else {
94                    c.0
95                },
96                if n.1 > 0.0 {
97                    by + s[4]
98                } else if n.1 < 0.0 {
99                    by + s[1]
100                } else {
101                    c.1
102                },
103                if n.2 > 0.0 {
104                    bz + s[5]
105                } else if n.2 < 0.0 {
106                    bz + s[2]
107                } else {
108                    c.2
109                },
110            );
111            let d = (eyes.x - plane.0) * n.0 + (eyes.y - plane.1) * n.1 + (eyes.z - plane.2) * n.2;
112            (d > 0.0).then_some((d, f))
113        })
114        .collect();
115    faces.sort_by(|a, b| b.0.total_cmp(&a.0));
116    // Points on the face: centre, then a ring toward the edges.
117    const OFFSETS: [(f64, f64); 9] = [
118        (0.5, 0.5),
119        (0.3, 0.5),
120        (0.7, 0.5),
121        (0.5, 0.3),
122        (0.5, 0.7),
123        (0.2, 0.2),
124        (0.8, 0.2),
125        (0.2, 0.8),
126        (0.8, 0.8),
127    ];
128    for (_, f) in faces {
129        let n = normal(f);
130        for (u, v) in OFFSETS {
131            let lerp = |lo: f64, hi: f64, t: f64| lo + (hi - lo) * t;
132            let p = match f {
133                Face::Up | Face::Down => Vec3::new(
134                    bx + lerp(s[0], s[3], u),
135                    by + if n.1 > 0.0 { s[4] } else { s[1] },
136                    bz + lerp(s[2], s[5], v),
137                ),
138                Face::North | Face::South => Vec3::new(
139                    bx + lerp(s[0], s[3], u),
140                    by + lerp(s[1], s[4], v),
141                    bz + if n.2 > 0.0 { s[5] } else { s[2] },
142                ),
143                Face::West | Face::East => Vec3::new(
144                    bx + if n.0 > 0.0 { s[3] } else { s[0] },
145                    by + lerp(s[1], s[4], v),
146                    bz + lerp(s[2], s[5], u),
147                ),
148            };
149            let (yaw, pitch) = yaw_pitch(eyes, p);
150            if ray(ctx, eyes, yaw, pitch).is_some_and(|h| h.pos == pos && h.face == f) {
151                out.push((p, f, yaw, pitch));
152                if out.len() >= max {
153                    return out;
154                }
155            }
156        }
157    }
158    out
159}
160
161/// One tick of a turn toward (`yaw`, `pitch`): sets the aim and says whether the look has
162/// arrived (the rotation will not move any more and the server has this look).
163pub(crate) fn step_toward(ctx: &mut TickContext<'_>, yaw: f32, pitch: f32) -> bool {
164    ctx.set_aim(yaw, pitch);
165    let p = *ctx.pose();
166    let s = *ctx.sent();
167    ctx.planned_look() == (p.yaw, p.pitch) && s.yaw == p.yaw && s.pitch == p.pitch
168}
169
170impl Bot {
171    /// Turns to look at `point` in whole mouse counts (sensitivity GCD, at most 14° yaw /
172    /// 10.5° pitch per tick, like a player's mouse) and returns once the server has the final
173    /// look. The eyes are re-read every tick, so it also works while moving.
174    ///
175    /// ```no_run
176    /// use ghast_client::Vec3;
177    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
178    /// bot.look_at(Vec3::new(10.5, 65.0, -3.5)).await?;
179    /// # Ok(()) }
180    /// ```
181    pub async fn look_at(&self, point: Vec3) -> Result<(), Error> {
182        let mark = self.mark();
183        for _ in 0..LOOK_TICKS {
184            let done = self
185                .with(move |ctx| {
186                    let (yaw, pitch) = yaw_pitch(ctx.eyes(ctx.pose()), point);
187                    step_toward(ctx, yaw, pitch)
188                })
189                .await?;
190            if done {
191                return Ok(());
192            }
193            self.next_tick().await;
194            self.check(mark)?;
195        }
196        Err(Error::Timeout)
197    }
198
199    /// Turns to an absolute yaw / pitch (degrees; pitch clamped to ±89.5 like the client)
200    /// and returns once the server has the final look.
201    ///
202    /// ```no_run
203    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
204    /// bot.look(90.0, 0.0).await?; // face -X
205    /// # Ok(()) }
206    /// ```
207    pub async fn look(&self, yaw: f32, pitch: f32) -> Result<(), Error> {
208        let mark = self.mark();
209        for _ in 0..LOOK_TICKS {
210            if self.with(move |ctx| step_toward(ctx, yaw, pitch)).await? {
211                return Ok(());
212            }
213            self.next_tick().await;
214            self.check(mark)?;
215        }
216        Err(Error::Timeout)
217    }
218
219    /// Turns until the crosshair (as the server judges it, from the sent pose) is on `pos`
220    /// (on `face`, if given) and returns the hit. Fails with [`Error::OutOfReach`] when no
221    /// visible point of the block is within reach (4.5).
222    ///
223    /// ```no_run
224    /// use ghast_client::BlockPos;
225    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
226    /// let hit = bot.look_at_block(BlockPos::new(2, 63, 0), None).await?;
227    /// println!("on face {:?} at {:?}", hit.face, hit.hit);
228    /// # Ok(()) }
229    /// ```
230    pub async fn look_at_block(
231        &self,
232        pos: BlockPos,
233        face: Option<Face>,
234    ) -> Result<BlockHit, Error> {
235        let mark = self.mark();
236        let points = self
237            .with(move |ctx| {
238                if ctx.world().raw_block(pos.x, pos.y, pos.z).is_none() {
239                    return Err(Error::NotLoaded(pos));
240                }
241                Ok(aim_points(ctx, pos, face, 6))
242            })
243            .await??;
244        // Try the points in turn: the look lands on a multiple of the mouse step, which can
245        // miss a thin face's centre.
246        for (_, _, yaw, pitch) in points {
247            for _ in 0..LOOK_TICKS {
248                let r = self
249                    .with(move |ctx| {
250                        let arrived = step_toward(ctx, yaw, pitch);
251                        let on = ctx
252                            .target()
253                            .filter(|t| t.pos == pos && face.is_none_or(|f| f == t.face));
254                        (arrived, on)
255                    })
256                    .await?;
257                match r {
258                    (true, Some(hit)) => return Ok(hit),
259                    (true, None) => break,
260                    (false, _) => {}
261                }
262                self.next_tick().await;
263                self.check(mark)?;
264            }
265        }
266        Err(Error::OutOfReach(pos))
267    }
268
269    /// Where a throw or a bow shot from the current pose would fly: the expected path (no random
270    /// spread) and its first block hit within `max_ticks` ticks, from the version's
271    /// oracle-proven launch and projectile physics (all six versions; see
272    /// [`ghast_client::TickContext::predict_throw`]). `None` when the version has no such item
273    /// or the bow was not drawn long enough. Entities in the way are not seen.
274    ///
275    /// ```no_run
276    /// use ghast_client::throw::Throw;
277    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
278    /// bot.look(30.0, -20.0).await?;
279    /// if let Some(p) = bot.predict_throw(Throw::Bow { ticks_held: 20 }, 100).await?
280    ///     && let Some(hit) = p.hit
281    /// {
282    ///     println!("the arrow sticks in {:?} after {} ticks", hit.block, hit.tick);
283    /// }
284    /// # Ok(()) }
285    /// ```
286    pub async fn predict_throw(
287        &self,
288        throw: ghast_client::throw::Throw,
289        max_ticks: u32,
290    ) -> Result<Option<ghast_client::throw::ThrowPrediction>, Error> {
291        self.with(move |ctx| ctx.predict_throw(throw, max_ticks))
292            .await
293    }
294}