ghast_ext/ride.rs
1//! Riding: boarding a mount or vehicle, getting off, the jump bar and the stick boost.
2//!
3//! Every helper here works the way a player does it, on every version, through the
4//! client's own simulation (which moves the mount exactly as vanilla does):
5//!
6//! - **boarding** ([`Bot::mount`]) is a right click with the crosshair on the entity; the
7//! server seats the player (`set_passengers`, 1.8: `attach_entity`) or refuses silently
8//! (no saddle, not tamed, the seats taken: [`Error::NotSeated`]);
9//! - **steering** is the normal movement keys and the look ([`Bot::set_controls`],
10//! [`Bot::look`]): a horse, camel, happy ghast or nautilus follows the rider's yaw and the
11//! keys, a pig or strider walks where the rider looks while a carrot / warped fungus on a
12//! stick is in a hand, a boat paddles with the keys, a minecart is moved by the server;
13//! - **getting off** ([`Bot::dismount`]) is the sneak key: on 1.8.9, 1.12.2 and 26.x the
14//! sneak reaches the server in the steer / input packet and the server takes the player
15//! off; on 1.16.5 the client also gets off by itself one tick after the sneak;
16//! - **the jump bar** ([`Bot::ride_jump`], [`Bot::dash`]) is the jump key held and released
17//! (horse family jump, camel and nautilus dash): the strength follows from the ticks held;
18//! - **the stick boost** ([`Bot::boost`]) is a right click with the stick (an item use).
19//!
20//! Every helper needs [`ghast_client::Interests::ENTITIES`] for the entity's box and type.
21
22use ghast_client::hands::PressOutcome;
23use ghast_client::{Buttons, Controls, TickContext, Vec3};
24
25use crate::look::step_toward;
26use crate::{Bot, Error};
27
28/// The entity interaction reach outside creative mode (blocks from the eyes to the box).
29const REACH: f64 = 3.0;
30
31/// Right clicks [`Bot::mount`] tries before it gives up.
32const MOUNT_TRIES: u32 = 3;
33
34/// Ticks [`Bot::mount`] waits for the server to seat the player after a click.
35const SEAT_TICKS: u32 = 20;
36
37/// Ticks [`Bot::dismount`] holds sneak before it gives up.
38const DISMOUNT_TICKS: u32 = 60;
39
40/// What the bot rides ([`Bot::vehicle`]).
41#[derive(Debug, Clone, Copy, PartialEq)]
42#[non_exhaustive]
43pub struct Ride {
44 /// The vehicle's entity id.
45 pub entity_id: i32,
46 /// Its type's registry / minecraft-data name, as [`crate::EntityInfo::name`] has it
47 /// (`"horse"`, `"pig"`, `"camel"`, `"oak_boat"`; 1.8.9 `"EntityHorse"`, `"Pig"`,
48 /// `"Boat"`, `"MinecartRideable"`), `""` when the entity is not tracked.
49 pub name: &'static str,
50 /// Position (the client's own for a vehicle it moves, else where the client has it).
51 pub pos: Vec3,
52 /// Yaw.
53 pub yaw: f32,
54 /// Pitch.
55 pub pitch: f32,
56 /// On the ground.
57 pub on_ground: bool,
58 /// The client moves it from the bot's keys (a saddled horse, a camel, a pig or strider
59 /// with its stick in a hand on 1.12.2+, a harnessed happy ghast, a saddled tame
60 /// nautilus, a boat) rather than the server (1.8.9 living mounts, a minecart, a llama, a
61 /// pig without the stick).
62 pub controlled: bool,
63 /// The bot's seat: its index in the vehicle's passenger list (0 steers), `None` when the
64 /// list is not known.
65 pub seat: Option<usize>,
66}
67
68/// Whether entities of this type can carry a player (any version's name; plugins can seat
69/// players on anything, which [`Bot::mount`] does not try).
70#[must_use]
71pub(crate) fn rideable(name: &str) -> bool {
72 let n = name.to_ascii_lowercase();
73 matches!(
74 n.as_str(),
75 "horse"
76 | "entityhorse"
77 | "donkey"
78 | "mule"
79 | "skeleton_horse"
80 | "zombie_horse"
81 | "llama"
82 | "trader_llama"
83 | "pig"
84 | "strider"
85 | "camel"
86 | "camel_husk"
87 | "happy_ghast"
88 | "nautilus"
89 | "zombie_nautilus"
90 | "boat"
91 | "chest_boat"
92 | "minecart"
93 | "minecartrideable"
94 ) || n.ends_with("_boat")
95 || n.ends_with("_raft")
96}
97
98/// The bot's ride in this tick.
99fn ride(ctx: &TickContext<'_>) -> Option<Ride> {
100 let v = ctx.vehicle()?;
101 let (name, seat) = match ctx.entities() {
102 Some(es) => {
103 let name = crate::find::entity_info(ctx, v.entity_id).map_or("", |e| e.name);
104 let me = es.self_id().unwrap_or_else(|| ctx.entity_id());
105 let seat = es
106 .get(v.entity_id)
107 .and_then(|e| e.passengers().iter().position(|&p| p == me));
108 (name, seat)
109 }
110 None => ("", None),
111 };
112 Some(Ride {
113 entity_id: v.entity_id,
114 name,
115 pos: v.pos,
116 yaw: v.yaw,
117 pitch: v.pitch,
118 on_ground: v.on_ground,
119 controlled: v.controlled,
120 seat,
121 })
122}
123
124/// The point of `b` nearest the eyes, pulled up to 0.4 inside per axis (a look at it lands
125/// inside the box even after rounding to whole mouse counts; a box thinner than 0.8: its
126/// middle), and the distance from the eyes to the box.
127fn aim_point(b: [f64; 6], eyes: Vec3) -> (Vec3, f64) {
128 let near = |lo: f64, hi: f64, v: f64| {
129 let m = ((hi - lo) / 2.0).min(0.4);
130 v.clamp(lo + m, hi - m)
131 };
132 let p = Vec3::new(
133 near(b[0], b[3], eyes.x),
134 near(b[1], b[4], eyes.y),
135 near(b[2], b[5], eyes.z),
136 );
137 let d = Vec3::new(
138 eyes.x.clamp(b[0], b[3]) - eyes.x,
139 eyes.y.clamp(b[1], b[4]) - eyes.y,
140 eyes.z.clamp(b[2], b[5]) - eyes.z,
141 );
142 (p, (d.x * d.x + d.y * d.y + d.z * d.z).sqrt())
143}
144
145/// One aiming tick of a right click on an entity ([`Bot::mount`], [`Bot::interact`]):
146/// `Ok(true)` once this tick's right press acts on the entity (the press is made), `Ok(false)`
147/// while turning.
148pub(crate) fn mount_step(ctx: &mut TickContext<'_>, id: i32) -> Result<bool, Error> {
149 let es = ctx.entities().ok_or(Error::NoSuchEntity(id))?;
150 let e = es
151 .get(id)
152 .filter(|e| e.is_alive())
153 .ok_or(Error::NoSuchEntity(id))?;
154 let b = e.bounding_box().ok_or(Error::NoSuchEntity(id))?;
155 let eyes = ctx.eyes(ctx.pose());
156 let (p, dist) = aim_point(b, eyes);
157 if dist > REACH {
158 return Err(Error::EntityOutOfReach(id));
159 }
160 let (yaw, pitch) = crate::yaw_pitch(eyes, p);
161 let cur = ctx.pose().yaw;
162 // A mount that moves (a nautilus bobbing, a horse wandering) keeps the look turning:
163 // press as soon as both this tick's pick and the server's view are on it.
164 step_toward(
165 ctx,
166 cur + ghast_client::rotation::wrap_degrees(yaw - cur),
167 pitch,
168 );
169 let on = matches!(ctx.press_preview(ghast_client::hands::Button::Right),
170 PressOutcome::Entity(h) if h.id == id);
171 if on && ctx.target_entity().is_some_and(|t| t.id == id) {
172 ctx.set_buttons(Buttons {
173 left: false,
174 right: true,
175 });
176 return Ok(true);
177 }
178 Ok(false)
179}
180
181/// Releases the movement keys when a helper ends early.
182struct ReleaseKeys(Option<Bot>);
183
184impl ReleaseKeys {
185 fn disarm(mut self) {
186 self.0 = None;
187 }
188}
189
190impl Drop for ReleaseKeys {
191 fn drop(&mut self) {
192 if let Some(bot) = self.0.take() {
193 bot.act(|ctx| {
194 ctx.set_controls(Controls::NONE);
195 ctx.set_buttons(Buttons::default());
196 });
197 }
198 }
199}
200
201/// The jump key ticks (press included) that charge the bar to `strength`, and the bar they
202/// give: vanilla's bar is 0.1 per held tick after the press, full (1.0) on the 10th, then
203/// falls again (`0.8 + 0.2 / (ticks - 9)`).
204fn jump_ticks(strength: f32) -> (u32, f32) {
205 let c = (strength.clamp(0.0, 1.0) * 10.0).round().clamp(1.0, 10.0) as u32;
206 let bar = if c < 10 { c as f32 * 0.1 } else { 1.0 };
207 (c + 1, bar)
208}
209
210impl Bot {
211 /// What the bot rides now (`None` on foot): the vehicle's id, type name, position,
212 /// whether the client moves it and the bot's seat.
213 ///
214 /// ```no_run
215 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
216 /// if let Some(r) = bot.vehicle().await? {
217 /// println!("on a {} (seat {:?}), steering: {}", r.name, r.seat, r.controlled);
218 /// }
219 /// # Ok(()) }
220 /// ```
221 pub async fn vehicle(&self) -> Result<Option<Ride>, Error> {
222 self.with(|ctx| ride(ctx)).await
223 }
224
225 /// Boards entity `id` the way a player does: releases the movement keys (a sneaking
226 /// right click opens a horse's inventory instead), turns until the crosshair is on the
227 /// entity (the server's view too), right-clicks it and waits until the server seats the
228 /// player. Right-clicking with an item in the hand can use it on the mount instead
229 /// (food feeds a horse, a saddle saddles it): board with an empty hand. On 26.x the client
230 /// does not model yet which entity clicks a mob handles, so it also sends the held item's
231 /// use after the click (and the off hand's click): with a carrot / fungus on a stick that
232 /// use reaches the server after the seat and boosts the mount at once; take the stick
233 /// after boarding.
234 ///
235 /// Fails with [`Error::NoSuchEntity`] (not tracked: needs
236 /// [`ghast_client::Interests::ENTITIES`]), [`Error::NotRideable`] (a type that carries
237 /// no player), [`Error::EntityOutOfReach`] (more than 3 blocks from the eyes) or
238 /// [`Error::NotSeated`] (the server did not seat the player after three clicks: no
239 /// saddle on a pig / strider / nautilus, no harness on a happy ghast, an untamed
240 /// donkey on 26.x, the seats taken, or a protected region). An untamed horse seats the
241 /// player and throws them off again a little later (taming), which this does not wait
242 /// for.
243 ///
244 /// ```no_run
245 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
246 /// if let Some(h) = bot.nearest_entity(|e| e.name == "horse", 3.0).await? {
247 /// let ride = bot.mount(h.id).await?;
248 /// assert_eq!(ride.entity_id, h.id);
249 /// }
250 /// # Ok(()) }
251 /// ```
252 pub async fn mount(&self, id: i32) -> Result<Ride, Error> {
253 let mark = self.mark();
254 let first = self
255 .with(move |ctx| -> Result<Option<Ride>, Error> {
256 if let Some(r) = ride(ctx).filter(|r| r.entity_id == id) {
257 return Ok(Some(r));
258 }
259 let info = crate::find::entity_info(ctx, id).ok_or(Error::NoSuchEntity(id))?;
260 if !info.alive {
261 return Err(Error::NoSuchEntity(id));
262 }
263 if !info.name.is_empty() && !rideable(info.name) {
264 return Err(Error::NotRideable(id));
265 }
266 ctx.set_controls(Controls::NONE);
267 Ok(None)
268 })
269 .await??;
270 if let Some(r) = first {
271 return Ok(r);
272 }
273 let keys = ReleaseKeys(Some(self.clone()));
274 for _ in 0..MOUNT_TRIES {
275 let mut pressed = false;
276 for _ in 0..60 {
277 pressed = self.with(move |ctx| mount_step(ctx, id)).await??;
278 self.next_tick().await;
279 self.check(mark)?;
280 if pressed {
281 break;
282 }
283 }
284 if !pressed {
285 return Err(Error::EntityOutOfReach(id));
286 }
287 self.act(|ctx| ctx.set_buttons(Buttons::default()));
288 for _ in 0..SEAT_TICKS {
289 if let Some(r) = self
290 .with(move |ctx| ride(ctx).filter(|r| r.entity_id == id))
291 .await?
292 {
293 keys.disarm();
294 return Ok(r);
295 }
296 self.next_tick().await;
297 self.check(mark)?;
298 }
299 }
300 Err(Error::NotSeated(id))
301 }
302
303 /// Gets off: holds sneak until the client no longer rides, then releases every key (on
304 /// 1.8.9, 1.12.2 and 26.x the server takes the player off when the sneak reaches it, on
305 /// 1.16.5 the client also gets off one tick after the sneak). The server's placement of
306 /// the player next to the vehicle (a teleport on most versions) does not interrupt it.
307 /// Returns at once when not riding. Fails with [`Error::Timeout`] when the server keeps
308 /// the player seated for 3 s (a plugin).
309 ///
310 /// ```no_run
311 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
312 /// bot.dismount().await?;
313 /// # Ok(()) }
314 /// ```
315 pub async fn dismount(&self) -> Result<(), Error> {
316 let mark = self.mark();
317 let riding = self
318 .with(|ctx| {
319 let on = ctx.is_riding();
320 if on {
321 ctx.set_buttons(Buttons::default());
322 ctx.set_controls(Controls {
323 sneak: true,
324 ..Controls::NONE
325 });
326 }
327 on
328 })
329 .await?;
330 if !riding {
331 return Ok(());
332 }
333 let _keys = ReleaseKeys(Some(self.clone()));
334 for _ in 0..DISMOUNT_TICKS {
335 self.next_tick().await;
336 self.check_alive(mark)?;
337 if !self.with(|ctx| ctx.is_riding()).await? {
338 return Ok(());
339 }
340 }
341 Err(Error::Timeout)
342 }
343
344 /// Charges the jump bar to `strength` (0 to 1, in steps of 0.1) and releases it: a horse
345 /// family mount jumps (higher with more strength), a camel or nautilus dashes. The bar
346 /// is the jump key: pressed, held one tick per 0.1 (full after 10 ticks, it falls again
347 /// when held longer), released; the client sends the riding jump with the bar on the
348 /// release. The other movement keys are kept (hold forward for a jump forward). Returns
349 /// the bar released (vanilla's float, e.g. `0.3` for `0.25`).
350 ///
351 /// The jump only happens where vanilla's does: on a saddled horse family mount or a
352 /// camel / nautilus the player controls, on the ground (a nautilus in water too), and
353 /// not while its cooldown runs (horse 10 ticks, camel 55, nautilus 40 after the last
354 /// jump: the bar does not charge then). Fails with [`Error::NotRiding`] on foot.
355 ///
356 /// ```no_run
357 /// use ghast_client::Controls;
358 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
359 /// bot.set_controls(Controls { forward: true, ..Controls::NONE });
360 /// bot.ride_jump(0.7).await?;
361 /// # Ok(()) }
362 /// ```
363 pub async fn ride_jump(&self, strength: f32) -> Result<f32, Error> {
364 let mark = self.mark();
365 let (ticks, bar) = jump_ticks(strength);
366 let set_jump = |jump: bool| {
367 move |ctx: &mut TickContext<'_>| -> Result<(), Error> {
368 if !ctx.is_riding() {
369 return Err(Error::NotRiding);
370 }
371 let mut c = ctx.controls();
372 c.jump = jump;
373 ctx.set_controls(c);
374 Ok(())
375 }
376 };
377 // A fresh press: the key up for one tick first.
378 self.with(set_jump(false)).await??;
379 self.next_tick().await;
380 self.check(mark)?;
381 for _ in 0..ticks {
382 self.with(set_jump(true)).await??;
383 self.next_tick().await;
384 self.check(mark)?;
385 }
386 self.with(set_jump(false)).await??;
387 self.next_tick().await;
388 Ok(bar)
389 }
390
391 /// A full jump bar ([`Bot::ride_jump`] with 1.0): a camel's or nautilus's dash, a
392 /// horse's highest jump.
393 ///
394 /// ```no_run
395 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
396 /// bot.dash().await?;
397 /// bot.wait_ticks(55).await; // a camel's dash cooldown
398 /// # Ok(()) }
399 /// ```
400 pub async fn dash(&self) -> Result<f32, Error> {
401 self.ride_jump(1.0).await
402 }
403
404 /// Uses the carrot on a stick (pig) or warped fungus on a stick (strider, 1.16.5+) in a
405 /// hand while riding: one right click, the item use that boosts the mount (the server
406 /// starts the boost; 1.12.2+ clients then speed the pig up themselves, on 1.8.9 the
407 /// server moves the pig). Keep the crosshair off the mount and other entities / blocks
408 /// in reach (look ahead or up): a click on them would not use the item. Fails with
409 /// [`Error::NotRiding`], [`Error::NoSuchItem`] (no stick in a hand) or
410 /// [`Error::CannotUse`] (the click would act on an entity or a block).
411 ///
412 /// ```no_run
413 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
414 /// bot.equip("carrot_on_a_stick").await?;
415 /// bot.boost().await?;
416 /// # Ok(()) }
417 /// ```
418 pub async fn boost(&self) -> Result<(), Error> {
419 let mark = self.mark();
420 self.with(|ctx| -> Result<(), Error> {
421 if !ctx.is_riding() {
422 return Err(Error::NotRiding);
423 }
424 let v = ctx.version();
425 let stick = |s: Option<&ghast_client::inventory::Stack>| {
426 s.is_some_and(|s| {
427 matches!(
428 crate::item_name(v, s.id()),
429 "carrot_on_a_stick" | "warped_fungus_on_a_stick"
430 )
431 })
432 };
433 if !stick(ctx.inventory().held()) && !stick(ctx.inventory().offhand()) {
434 return Err(Error::NoSuchItem("carrot_on_a_stick".into()));
435 }
436 let press = ctx.press_preview(ghast_client::hands::Button::Right);
437 if press != PressOutcome::Item {
438 log::debug!("boost: a right press would act on {press:?}");
439 return Err(Error::CannotUse);
440 }
441 ctx.set_buttons(Buttons {
442 left: false,
443 right: true,
444 });
445 Ok(())
446 })
447 .await??;
448 self.next_tick().await;
449 self.act(|ctx| ctx.set_buttons(Buttons::default()));
450 self.check(mark)
451 }
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457
458 #[test]
459 fn jump_bar_ticks() {
460 assert_eq!(jump_ticks(0.0), (2, 0.1));
461 assert_eq!(jump_ticks(0.25), (4, 0.3));
462 assert_eq!(jump_ticks(0.7), (8, 7.0 * 0.1));
463 assert_eq!(jump_ticks(1.0), (11, 1.0));
464 assert_eq!(jump_ticks(5.0), (11, 1.0));
465 // The value the riding jump action carries.
466 assert_eq!((jump_ticks(0.7).1 * 100.0) as i32, 70);
467 }
468
469 #[test]
470 fn rideable_names() {
471 for n in [
472 "horse",
473 "EntityHorse",
474 "Pig",
475 "Boat",
476 "oak_boat",
477 "bamboo_raft",
478 "oak_chest_boat",
479 "MinecartRideable",
480 "minecart",
481 "camel",
482 "happy_ghast",
483 "nautilus",
484 "strider",
485 ] {
486 assert!(rideable(n), "{n}");
487 }
488 for n in ["zombie", "chest_minecart", "player", "cow"] {
489 assert!(!rideable(n), "{n}");
490 }
491 }
492
493 #[test]
494 fn aim_point_inside() {
495 let b = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
496 let (p, d) = aim_point(b, Vec3::new(3.0, 0.5, 0.5));
497 assert_eq!((p.x, p.y, p.z), (0.6, 0.5, 0.5));
498 assert!((d - 2.0).abs() < 1e-12);
499 }
500}