ghast 0.5.6

Headless Minecraft Java Edition client / bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3) with vanilla-exact behaviour: facade crate re-exporting the ghast-* crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Riding with the `ghast-ext` helpers: finds the nearest entity of a type, boards it
//! (`Bot::mount`), rides a course, gets off (`Bot::dismount`) and prints what happened.
//! Every version, every mount the client simulates: horse family, pig and strider (with the
//! stick: `--stick`, `--boost`), camel (`--sprint`, a dash with `--jump 1`), happy ghast
//! (`--course fly`), nautilus (`--course swim`, `--jump 1` dashes), boats (steered with the
//! keys), minecarts (`--course idle`). `lab/mounts.sh` sets up the scenes.
//!
//! Courses, from where the bot boards (`--leg` blocks per side, default 8):
//! - `square`: north, west, south, east back to the start, steering with the look (a boat
//!   also with the left / right keys); `--jump S` charges the jump bar to S (0.1 .. 1) and
//!   releases it once on the second side;
//! - `line`: one side north (over whatever the scene put there), the jump in its middle;
//! - `fly`: up 6 blocks on the first side, the square at that height, then down to the start;
//! - `swim`: the square at the boarding height, pitch 0;
//! - `idle`: holds forward for `--leg` × 10 ticks (a minecart moves by itself).
//!
//! `--boat-look` steers a boat with the look only (1.8.9: the strafe keys turn the boat's course
//! by 90° from the look). `--settle T` waits T ticks after the join before looking for the mount (a scene that
//! teleports the bot next to it after the join: a teleport takes a rider off).
//!
//! The run ends with a `RESULT` line: the course's sides done, server teleports of the player
//! while riding (setbacks), the teleport that places the player after getting off, and Grim
//! alerts that reached the chat (ops see them). Exit code 1 when boarding or a side failed.
//!
//! ```text
//! cargo run -p ghast --release --features ext --example ride -- --mount horse --jump 0.7 \
//!     --host 127.0.0.1 --port 25626 --username GhastBot11 --version 26.1 --minutes 2
//! ```

mod support;

use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use ghast::ext::{Bot, Error, Event, Ext, Ride, WhenDone};
use ghast::{Controls, Interests, Vec3};

/// The ride's options (the rest are the examples' common ones).
#[derive(Debug, Clone)]
struct RideOpts {
    mount: String,
    course: String,
    leg: f64,
    jump: f32,
    sprint: bool,
    boost: bool,
    stick: Option<String>,
    settle: u64,
    stick_first: bool,
    boat_look: bool,
}

impl RideOpts {
    /// Takes the ride's own options out of `args`, returning the rest.
    fn take(args: Vec<String>) -> (RideOpts, Vec<String>) {
        let mut o = RideOpts {
            mount: "horse".into(),
            course: "square".into(),
            leg: 8.0,
            jump: 0.0,
            sprint: false,
            boost: false,
            stick: None,
            settle: 0,
            stick_first: false,
            boat_look: false,
        };
        let mut rest = Vec::new();
        let mut it = args.into_iter();
        while let Some(a) = it.next() {
            let mut val = || {
                it.next().unwrap_or_else(|| {
                    eprintln!("{a} needs a value");
                    std::process::exit(2)
                })
            };
            match a.as_str() {
                "--mount" => o.mount = val(),
                "--course" => o.course = val(),
                "--leg" => o.leg = val().parse().expect("--leg: a number"),
                "--jump" => o.jump = val().parse().expect("--jump: a number"),
                "--sprint" => o.sprint = true,
                "--boost" => o.boost = true,
                "--stick" => o.stick = Some(val()),
                "--stick-first" => o.stick_first = true,
                "--boat-look" => o.boat_look = true,
                "--settle" => o.settle = val().parse().expect("--settle: ticks"),
                _ => rest.push(a),
            }
        }
        (o, rest)
    }
}

/// Phases for the teleport watcher.
const BOARDING: u32 = 0;
const RIDING: u32 = 1;
const OFF: u32 = 2;

#[derive(Default)]
struct Counts {
    phase: AtomicU32,
    setbacks: AtomicU32,
    off_teleports: AtomicU32,
    alerts: AtomicU32,
}

/// A boat turns with the left / right keys (1.9+) or follows the rider's look (1.8.9).
fn is_boat(name: &str) -> bool {
    let n = name.to_ascii_lowercase();
    n == "boat" || n.ends_with("_boat") || n.ends_with("_raft")
}

/// Horizontal distance.
fn flat(a: Vec3, b: Vec3) -> f64 {
    ((a.x - b.x).powi(2) + (a.z - b.z).powi(2)).sqrt()
}

/// Rides to `goal` (horizontally within 1.2 blocks; with `vertical`, the look also aims at
/// its height): `Ok(true)` on arrival, `Ok(false)` after 300 ticks.
async fn ride_to(
    bot: &Bot,
    o: &RideOpts,
    boat: bool,
    goal: Vec3,
    vertical: bool,
) -> Result<bool, Error> {
    let sprint = o.sprint;
    let keys_turn = !o.boat_look;
    for _ in 0..300 {
        let arrived = bot
            .with(move |ctx| {
                let p = ctx.pose().pos;
                if flat(p, goal) < 1.2 && (!vertical || (p.y - goal.y).abs() < 1.5) {
                    return true;
                }
                let (dx, dz) = (goal.x - p.x, goal.z - p.z);
                let want = (-dx).atan2(dz).to_degrees() as f32;
                let mut keys = Controls {
                    forward: true,
                    sprint,
                    jump: ctx.controls().jump,
                    ..Controls::NONE
                };
                if boat {
                    // 1.9+: paddle, turning with the keys toward the goal; 1.8.9: the boat
                    // goes where the rider looks while forward is held. Both: look at the goal,
                    // turn with the keys, hold forward.
                    let yaw = ctx.vehicle().map_or(ctx.pose().yaw, |v| v.yaw);
                    let d = ghast::rotation::wrap_degrees(want - yaw);
                    keys.left = keys_turn && d < -6.0;
                    keys.right = keys_turn && d > 6.0;
                    let cur = ctx.pose().yaw;
                    ctx.set_aim(cur + ghast::rotation::wrap_degrees(want - cur), 0.0);
                } else {
                    let cur = ctx.pose().yaw;
                    let pitch = if vertical {
                        let h = (dx * dx + dz * dz).sqrt().max(0.5);
                        (-(goal.y - p.y).atan2(h).to_degrees() as f32).clamp(-45.0, 45.0)
                    } else {
                        0.0
                    };
                    ctx.set_aim(cur + ghast::rotation::wrap_degrees(want - cur), pitch);
                }
                ctx.set_controls(keys);
                false
            })
            .await?;
        if arrived {
            return Ok(true);
        }
        bot.next_tick().await;
    }
    Ok(false)
}

/// The course from `start` (the boarding position): `(sides done, sides)`.
async fn course(bot: &Bot, o: &RideOpts, ride: &Ride, start: Vec3) -> Result<(u32, u32), Error> {
    let boat = is_boat(ride.name);
    let l = o.leg;
    let (x, y, z) = (start.x, start.y, start.z);
    if o.course == "idle" {
        bot.set_controls(Controls {
            forward: true,
            ..Controls::NONE
        });
        bot.wait_ticks((l * 10.0) as u64).await;
        bot.set_controls(Controls::NONE);
        return Ok((1, 1));
    }
    let square = |h: f64| {
        vec![
            Vec3::new(x, y + h, z - l),
            Vec3::new(x - l, y + h, z - l),
            Vec3::new(x - l, y + h, z),
            Vec3::new(x, y + h, z),
        ]
    };
    let (points, vertical) = match o.course.as_str() {
        "line" => (vec![Vec3::new(x, y, z - l)], false),
        "fly" => {
            let mut p = square(6.0);
            p.push(Vec3::new(x, y, z));
            (p, true)
        }
        // "square", "swim"
        _ => (square(0.0), false),
    };
    let n = points.len() as u32;
    let mut done = 0;
    for (k, goal) in points.into_iter().enumerate() {
        if o.boost {
            // Look ahead (not at the mount or the ground in reach) for the item use.
            bot.look(bot.pose().yaw, 0.0).await?;
            match bot.boost().await {
                Ok(()) => log::info!("side {k}: boost"),
                Err(e) => log::warn!("side {k}: boost: {e}"),
            }
        }
        let jump_side = if o.course == "line" { 0 } else { 1 };
        if o.jump > 0.0 && k == jump_side {
            // Halfway along the side, then the jump bar with forward held.
            let from = bot.pose().pos;
            let mid = Vec3::new((from.x + goal.x) / 2.0, goal.y, (from.z + goal.z) / 2.0);
            ride_to(bot, o, boat, mid, vertical).await?;
            let bar = bot.ride_jump(o.jump).await?;
            log::info!(
                "side {k}: jump bar released at {bar} ({:?})",
                bot.pose().pos
            );
        }
        let ok = ride_to(bot, o, boat, goal, vertical).await?;
        let p = bot.pose().pos;
        if ok {
            done += 1;
            log::info!("side {k}: at {:.2} {:.2} {:.2}", p.x, p.y, p.z);
        } else {
            log::warn!(
                "side {k}: did not arrive (at {:.2} {:.2} {:.2})",
                p.x,
                p.y,
                p.z
            );
        }
    }
    bot.set_controls(Controls::NONE);
    Ok((done, n))
}

/// Equips the stick (the scene gives it after the join: retried for a few seconds).
async fn take_stick(bot: &Bot, stick: &str) -> Result<(), Error> {
    let mut held = bot.equip(stick).await;
    for _ in 0..10 {
        if held.is_ok() {
            break;
        }
        bot.wait_ticks(10).await;
        held = bot.equip(stick).await;
    }
    held?;
    bot.wait_ticks(5).await;
    Ok(())
}

async fn run(bot: Bot, o: RideOpts, counts: Arc<Counts>) -> Result<(), Error> {
    // Grim alerts in the chat and server teleports, by phase.
    {
        let b = bot.clone();
        let c = counts.clone();
        let _watch = bot.spawn(async move {
            let mut ev = b.events();
            while let Some(e) = ev.recv().await {
                match e {
                    Event::Chat(m) => {
                        let t = m.plain();
                        if t.contains("Grim") || t.contains("failed") {
                            c.alerts.fetch_add(1, Ordering::Relaxed);
                            log::warn!("ALERT chat: {t}");
                        }
                    }
                    Event::Teleport(t) => {
                        let p = t.after.pos;
                        match c.phase.load(Ordering::Relaxed) {
                            RIDING => {
                                c.setbacks.fetch_add(1, Ordering::Relaxed);
                                log::warn!(
                                    "ALERT setback while riding to {:.3} {:.3} {:.3}",
                                    p.x,
                                    p.y,
                                    p.z
                                );
                            }
                            OFF => {
                                c.off_teleports.fetch_add(1, Ordering::Relaxed);
                                log::info!(
                                    "placed after getting off: {:.3} {:.3} {:.3}",
                                    p.x,
                                    p.y,
                                    p.z
                                );
                            }
                            _ => log::info!(
                                "teleport before boarding: {:.3} {:.3} {:.3}",
                                p.x,
                                p.y,
                                p.z
                            ),
                        }
                    }
                    _ => {}
                }
            }
        });
    }
    let want = o.mount.to_ascii_lowercase();
    let matches = move |name: &str| {
        let n = name.to_ascii_lowercase();
        n == want
            || (want == "boat" && is_boat(&n))
            || (want == "horse" && n == "entityhorse")
            || (want == "minecart" && n == "minecartrideable")
    };
    // The scene puts the bot next to the mount after it joined (`--settle`: ticks to wait for
    // that), then look for one nearby.
    bot.wait_ticks(o.settle).await;
    let mut target = None;
    for _ in 0..60 {
        let m = matches.clone();
        if let Some(e) = bot
            .nearest_entity(move |e| e.alive && m(e.name), 8.0)
            .await?
        {
            target = Some(e);
            break;
        }
        bot.wait_ticks(10).await;
    }
    let Some(target) = target else {
        let seen: Vec<String> = bot
            .find_entities(|_| true, 16.0)
            .await?
            .into_iter()
            .map(|e| {
                format!(
                    "{} {:?} at {:.1} {:.1} {:.1}",
                    e.id, e.name, e.pos.x, e.pos.y, e.pos.z
                )
            })
            .collect();
        log::error!("FAIL no {} within 8 blocks (tracked: {seen:?})", o.mount);
        return Err(Error::Timeout);
    };
    bot.wait_ticks(20).await;
    // Board with an empty hand (slot 9; the scene's items land in slot 1): 26.x does not
    // model yet which entity clicks a mob handles, so an item in the hand would be used
    // right after the click (a carrot on a stick: a boost the server starts at once).
    // `--stick-first` boards with the stick in the hand (the 26.x lab finding).
    if o.stick_first
        && let Some(stick) = &o.stick
    {
        take_stick(&bot, stick).await?;
    } else {
        bot.select_slot(8);
        bot.wait_ticks(2).await;
    }
    // Board; a mount that wandered off (or a big one whose middle is far): walk closer first.
    let mut boarded = Err(Error::EntityOutOfReach(target.id));
    for _ in 0..4 {
        boarded = bot.mount(target.id).await;
        let Err(Error::EntityOutOfReach(_)) = boarded else {
            break;
        };
        let Some(e) = bot.entity(target.id).await? else {
            break;
        };
        log::info!(
            "{} out of reach at {:.2} {:.2} {:.2}: walking closer",
            target.name,
            e.pos.x,
            e.pos.y,
            e.pos.z
        );
        let _ = bot.timeout(100, bot.walk_straight_to(e.pos, 1.0)).await;
        bot.set_controls(Controls::NONE);
    }
    let ride = match boarded {
        Ok(r) => r,
        Err(e) => {
            log::error!("FAIL boarding {} {}: {e}", target.name, target.id);
            return Err(e);
        }
    };
    counts.phase.store(RIDING, Ordering::Relaxed);
    log::info!("boarded {ride:?}");
    if let Some(stick) = &o.stick
        && !o.stick_first
    {
        take_stick(&bot, stick).await?;
    }
    // A scene may still change the world around the mount (lab/mounts.sh opens a cage).
    bot.wait_ticks(30).await;
    let start = bot.pose().pos;
    let t0 = bot.tick();
    let r = course(&bot, &o, &ride, start).await;
    let ticks = bot.tick() - t0;
    let (done, sides) = match r {
        Ok(d) => d,
        Err(e) => {
            log::error!("FAIL course: {e}");
            (0, 1)
        }
    };
    bot.wait_ticks(10).await;
    let still_on = bot
        .vehicle()
        .await?
        .is_some_and(|v| v.entity_id == ride.entity_id);
    counts.phase.store(OFF, Ordering::Relaxed);
    let off = bot.dismount().await;
    let p = bot.pose().pos;
    match &off {
        Ok(()) => log::info!("got off at {:.3} {:.3} {:.3}", p.x, p.y, p.z),
        Err(e) => log::error!("FAIL getting off: {e}"),
    }
    bot.wait_ticks(40).await;
    let setbacks = counts.setbacks.load(Ordering::Relaxed);
    let alerts = counts.alerts.load(Ordering::Relaxed);
    let pass = still_on && off.is_ok() && done == sides && setbacks == 0 && alerts == 0;
    println!(
        "RESULT {} {}: {} sides of {sides} in {ticks} ticks, {setbacks} setbacks, {} placement \
         teleports after getting off, {alerts} chat alerts{} {}",
        ride.name,
        o.course,
        done,
        counts.off_teleports.load(Ordering::Relaxed),
        if still_on {
            ""
        } else {
            ", thrown off during the course"
        },
        if pass { "PASS" } else { "FAIL" }
    );
    if pass { Ok(()) } else { Err(Error::Stuck) }
}

fn main() {
    let (ro, rest) = RideOpts::take(std::env::args().skip(1).collect());
    let opts = support::Options::parse_from(rest);
    support::init_logger(opts.verbose);
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    let counts = Arc::new(Counts::default());
    counts.phase.store(BOARDING, Ordering::Relaxed);
    let c = counts.clone();
    let mut ext = Ext::new(move |bot| run(bot, ro.clone(), c.clone()))
        .name("ride")
        .interests(Interests::CHAT | Interests::ENTITIES)
        // Setbacks are counted, not fatal.
        .interrupt_on_teleport(false)
        .when_done(WhenDone::Disconnect);
    let limit = opts.limit();
    let ok = rt.block_on(async {
        let client = match opts.client() {
            Ok(c) => c,
            Err(e) => {
                log::error!("{e}");
                std::process::exit(2);
            }
        };
        let shutdown = async {
            let stop = async {
                #[cfg(unix)]
                {
                    let mut term =
                        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                            .expect("SIGTERM handler");
                    tokio::select! {
                        _ = tokio::signal::ctrl_c() => {}
                        _ = term.recv() => {}
                    }
                }
                #[cfg(not(unix))]
                let _ = tokio::signal::ctrl_c().await;
            };
            match limit {
                Some(l) => {
                    tokio::select! {
                        () = stop => {}
                        () = tokio::time::sleep(l) => log::warn!("time limit reached"),
                    }
                }
                None => stop.await,
            }
        };
        match client.run_until(&mut ext, shutdown).await {
            Ok(e) => {
                log::info!("session ended: {e:?}; result {:?}", ext.result());
                matches!(ext.result(), Some(Ok(())))
            }
            Err(e) => {
                log::error!("session failed: {e}");
                false
            }
        }
    });
    std::process::exit(if ok { 0 } else { 1 });
}