ghast-client 0.4.8

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1 and 26.2)
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Engine replays of the legacy right-click-on-block vectors (`tests/golden/<v>/place.jsonl.gz`,
//! oracle `PlaceDump`): the real client's use key on a block (crosshair, `onRightClick`, the
//! item's placement on the client world, the swing, the fallback item use). Here the same world,
//! pose, held stack and game mode go into the engine, the right mouse button is pressed for one
//! tick, and the engine's packets (block placement, swing, encoded by the version's wire layer)
//! must equal the real client's, byte for byte. Every block ghast predicts must be the one the
//! client set; a block the client set that ghast does not predict is counted as unpredicted (the
//! server's block update decides it) — never a different state. The held stack's count after the
//! click must be the client's.

use super::super::tests::opts;
use super::super::*;
use crate::common::JoinGame;
use crate::version::ClientVersion;
use ghast_protocol::frame::{FrameDecoder, FrameEncoder};
use serde_json::Value;
use std::io::BufRead;

fn f64v(v: &Value) -> f64 {
    f64::from_bits(u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap())
}

fn f32v(v: &Value) -> f32 {
    f32::from_bits(u32::from_str_radix(v[1].as_str().unwrap(), 16).unwrap())
}

fn unhex(s: &str) -> Vec<u8> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
        .collect()
}

fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

fn stack_1_8(h: &Value) -> Option<ghast_inventory::Stack> {
    use ghast_protocol::codec::decode_exact;
    let b = bytes::Bytes::from(unhex(h.as_str().unwrap()));
    ghast_inventory::from_legacy_slot(
        decode_exact::<ghast_protocol::types::slot::legacy::Slot>(&b).unwrap(),
    )
}

fn mode_of(s: &str) -> GameMode {
    match s {
        "survival" => GameMode::Survival,
        "creative" => GameMode::Creative,
        "adventure" => GameMode::Adventure,
        _ => GameMode::Spectator,
    }
}

/// What a replay counted.
#[derive(Default, Debug)]
pub(super) struct Summary {
    pub cases: usize,
    pub placed: usize,
    pub predicted: usize,
    pub unpredicted: usize,
    /// 1.12: clicks whose packets differ after a boat's or a bucket's use in the air.
    pub air_use: usize,
    /// Clicks the rules leave undecided whose packets differ.
    pub undecided: usize,
    /// Cases whose crosshair target differs from the client's.
    pub crosshair: usize,
    pub packets: usize,
    pub diffs: Vec<String>,
}

/// One replay per version: the sim, its data and protocol modules, the test chunks, the wire
/// layer and the packet names the oracle writes.
macro_rules! replay {
    ($name:ident, $sim:ty, $data:ident, $proto:ident, $version:expr, $chunks:ident, $wire:ty, $offhand:expr, $named:expr, $sneak:expr, $stone:expr, $state:expr, $raw:expr, $stack:expr, $air:expr) => {
pub(super) fn $name(path: &std::path::Path) -> Summary {
    use ghast_protocol::$proto::play::serverbound::id;
    let f = std::fs::File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
    let mut sum = Summary::default();
    let only: Option<u64> = std::env::var("GHAST_PLACE_CASE")
        .ok()
        .map(|c| c.parse().unwrap());
    for line in std::io::BufReader::new(flate2::read::GzDecoder::new(f)).lines() {
        let c: Value = serde_json::from_str(&line.unwrap()).unwrap();
        if c.get("type").is_some() {
            continue;
        }
        let k = c["case"].as_u64().unwrap();
        if only.is_some_and(|o| o != k) {
            continue;
        }
        sum.cases += 1;
        let mode = mode_of(c["mode"].as_str().unwrap());
        let mut e = Engine::new(opts($version), <$sim>::new());
        e.handle(Inbound::JoinGame(JoinGame {
            entity_id: 1,
            game_mode: mode,
            dimension: "0".into(),
            hardcore: false,
            dimension_nbt: None,
            respawn_screen: true,
        }));
        for x in -1..=0 {
            for z in -1..=0 {
                e.sim
                    .world_packet(&crate::sim::test_chunks::$chunks(x, z))
                    .unwrap();
            }
        }
        // the oracle world: a stone floor at y 63 for x -4..=4, z -3..=7 only
        for x in -16..16 {
            for z in -16..16 {
                let floor = (-4..=4).contains(&x) && (-3..=7).contains(&z);
                e.sim.test_set_block(
                    x,
                    63,
                    z,
                    ($state)(if floor { $stone } else { 0 }),
                );
            }
        }
        // the area: the case's blocks, air elsewhere
        let mut before = std::collections::HashMap::new();
        for b in c["blocks"].as_array().unwrap() {
            let v: Vec<i32> = (0..4).map(|i| b[i].as_i64().unwrap() as i32).collect();
            before.insert((v[0], v[1], v[2]), v[3] as u16);
        }
        for x in -4..=4 {
            for y in 63..=69 {
                for z in -2..=6 {
                    let raw = before.get(&(x, y, z)).copied().unwrap_or(0);
                    e.sim
                        .test_set_block(x, y, z, ($state)(raw));
                }
            }
        }
        let pos = &c["pos"];
        let (yaw, pitch) = (f32v(&c["yaw"]), f32v(&c["pitch"]));
        e.handle(Inbound::Teleport(crate::common::Teleport {
            x: f64v(&pos[0]),
            y: f64v(&pos[1]),
            z: f64v(&pos[2]),
            yaw,
            pitch,
            teleport_id: None,
            ..Default::default()
        }));
        let sel = c["selected"].as_u64().unwrap() as u8;
        e.core.test_set_slot(sel);
        let held = ($stack)(&c["held"]);
        e.inventory_mut()
            .on_set_slot(0, 36 + i16::from(sel), held.clone());
        if $offhand {
            e.inventory_mut().on_set_slot(0, 45, ($stack)(&c["offhand"]));
        }
        e.inventory_mut().set_creative(mode == GameMode::Creative);
        let sneak = c["sneaking"].as_bool().unwrap();
        // the sneaking pose before anything reads the player (the rules' box, the eyes)
        e.core.pose.sneaking = sneak;
        ($sneak)(&mut e, sneak, mode);
        // the client's target (the crosshair is oracle-proven separately, `picks.jsonl.gz`: a
        // different target is counted, not compared further)
        let t = &c["target"];
        let want_target = (t["type"] == "BLOCK").then(|| {
            let p = &t["pos"];
            (
                ghast_protocol::BlockPos::new(
                    p[0].as_i64().unwrap() as i32,
                    p[1].as_i64().unwrap() as i32,
                    p[2].as_i64().unwrap() as i32,
                ),
                crate::common::Face::from_id(t["face"].as_i64().unwrap() as i8).unwrap(),
            )
        });
        // what the rules decide before the packet (an undecided click's packets are the engine's
        // guess: counted, not compared)
        // (1.12: the off hand's turn too, after a main hand whose click did not succeed)
        let off = if $offhand {
            ($stack)(&c["offhand"])
        } else {
            None
        };
        let decided = want_target.is_none_or(|(p, f)| {
            let hit: [f64; 3] = std::array::from_fn(|i| f64v(&t["hit"][i]));
            let base = [p.x, p.y, p.z];
            let rules = |h: Option<&ghast_inventory::Stack>| {
                e.sim.place_rules(&crate::sim::predict::PlaceQuery {
                    pos: p,
                    face: f,
                    cursor: std::array::from_fn(|i| (hit[i] - f64::from(base[i])) as f32),
                    held: h,
                    sneaking: sneak,
                    any_item: held.is_some() || off.is_some(),
                    game_mode: mode,
                    yaw,
                })
            };
            let r = rules(held.as_ref());
            let known = |r: crate::sim::predict::PlaceRules| {
                r.block_packet.is_some() && r.used.is_some()
            };
            known(r) && (!$offhand || r.used == Some(true) || known(rules(off.as_ref())))
        });
        let t0 = Instant::now();
        // the oracle clicks without a tick: the pose as set (sneaking: the crouched eyes)
        e.core.ready = true;

        let mut target = None;
        // the right button for one tick
        e.core.forced_look = Some((yaw, pitch));
        e.note_inbound(t0);
        e.tick(
            &mut super::super::tests::Script(|ctx: &mut TickContext<'_>| {
                ctx.set_controls(Controls {
                    sneak,
                    ..Controls::default()
                });
                ctx.set_buttons(Buttons {
                    left: false,
                    right: true,
                });
                target = match ctx.press_preview(hands::Button::Right) {
                    hands::PressOutcome::Block(t) => Some((
                        t.pos,
                        t.face,
                        [
                            (t.hit.x - f64::from(t.pos.x)) as f32,
                            (t.hit.y - f64::from(t.pos.y)) as f32,
                            (t.hit.z - f64::from(t.pos.z)) as f32,
                        ],
                    )),
                    _ => None,
                };
            }),
            t0,
        );
        let out = std::mem::take(e.outbound());
        // the same block and face, and the same hit point
        let want_hit = want_target.map(|(p, f)| {
            let hit: [f64; 3] = std::array::from_fn(|i| f64v(&t["hit"][i]));
            let base = [p.x, p.y, p.z];
            (
                p,
                f,
                std::array::from_fn::<f32, 3, _>(|i| (hit[i] - f64::from(base[i])) as f32),
            )
        });
        if target != want_hit {
            sum.crosshair += 1;
            if std::env::var_os("GHAST_PLACE_CROSSHAIR").is_some() {
                let clicked = before
                    .get(&want_target.map_or((0, 0, 0), |(p, _)| (p.x, p.y, p.z)))
                    .copied()
                    .unwrap_or(0);
                eprintln!(
                    "crosshair case {k} sneak {sneak} mode {:?} clicked {} ghast {target:?} client {want_hit:?}",
                    mode,
                    clicked >> 4
                );
            }
            continue;
        }
        let mut enc = FrameEncoder::new();
        for o in &out {
            <$wire as ClientVersion>::write_play(&mut enc, o, &mut Default::default()).unwrap();
        }
        let bytes = enc.take();
        let mut dec = FrameDecoder::new();
        dec.push(&bytes);
        let mut got = Vec::new();
        while let Some(p) = dec.next_packet().unwrap() {
            if p.id == id::BLOCK_PLACE {
                got.push(format!("p{}", hex(&p.body)));
            } else if let Some(n) = ($named)(p.id) {
                got.push(n.replace("{}", &hex(&p.body)));
            }
        }
        let want: Vec<String> = c["packets"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p.as_str().unwrap().to_owned())
            .collect();
        sum.packets += want.len();
        let at = format!(
            "case {k} ({} held {:?})",
            c["mode"],
            held.as_ref().map(|s| (s.id(), s.damage()))
        );
        // 1.12: the main hand's use in the air of a boat or a bucket (a ray with fluids, the
        // boat's room, the bucket's fill or pour) is not modelled
        let air_use = $offhand
            && held
                .as_ref()
                .is_some_and(|h| u16::try_from(h.id()).is_ok_and($air));
        // no block clicked (the crosshair missed): the item's use in the air alone, which the
        // click rules do not cover (counted with the air uses)
        // (also the off hand's use in the air, the click's last step)
        let off_air = off
            .as_ref()
            .is_some_and(|h| u16::try_from(h.id()).is_ok_and($air));
        let air_use = air_use || off_air || want_target.is_none();
        if got != want && air_use {
            sum.air_use += 1;
        } else if got != want && !decided {
            sum.undecided += 1;
            if std::env::var_os("GHAST_PLACE_UNDECIDED").is_some() {
                let clicked = want_target
                    .and_then(|(p, _)| before.get(&(p.x, p.y, p.z)).copied())
                    .unwrap_or(0);
                eprintln!(
                    "undecided case {k} held {:?} clicked {} ghast {got:?} client {want:?}",
                    held.as_ref().map(|s| s.id()),
                    clicked >> 4
                );
            }
        } else if got != want {
            sum.diffs
                .push(format!("{at}: packets ghast {got:?}, client {want:?}"));
        }
        // the blocks
        let mut after = before.clone();
        for ch in c["changed"].as_array().unwrap() {
            let v: Vec<i32> = (0..5).map(|i| ch[i].as_i64().unwrap() as i32).collect();
            after.insert((v[0], v[1], v[2]), v[4] as u16);
        }
        let world = e.sim.test_world();
        let changed = !c["changed"].as_array().unwrap().is_empty();
        sum.placed += usize::from(changed);
        let mut ghast_changed = false;
        let mut wrong = false;
        for x in -4..=4 {
            for y in 63..=69 {
                for z in -2..=6 {
                    let g = world.block_state(x, y, z).map_or(0, $raw);
                    let b = before.get(&(x, y, z)).copied().unwrap_or(0);
                    let a = after.get(&(x, y, z)).copied().unwrap_or(0);
                    if g != b {
                        ghast_changed = true;
                        if g != a {
                            wrong = true;
                            sum.diffs.push(format!(
                                "{at}: block ({x}, {y}, {z}): ghast {g}, client {a} (before {b})"
                            ));
                        }
                    }
                }
            }
        }
        if changed && !ghast_changed {
            sum.unpredicted += 1;
        } else if changed && !wrong {
            sum.predicted += 1;
        }
        // the held stack's count
        let held_after = ($stack)(&c["slot_after"]);
        let now = e.core.inv.held().cloned();
        let count = |s: &Option<ghast_inventory::Stack>| s.as_ref().map(|s| (s.id(), s.count()));
        let count_before = count(&held);
        // (after packets the engine only guessed, its count is a guess too)
        if (decided || got == want)
            && count(&now) != count(&held_after)
            && count(&now) != count_before
        {
            sum.diffs.push(format!(
                "{at}: held ghast {:?}, client {:?}",
                count(&now),
                count(&held_after)
            ));
        }
    }
    sum
}
    };
}

replay!(
    replay_1_8,
    crate::sim::Sim18,
    v1_8,
    v1_8,
    GameVersion::V1_8_9,
    v1_8,
    crate::version::V1_8,
    false,
    |i| {
        use ghast_protocol::v1_8::play::serverbound::id;
        match i {
            id::ARM_ANIMATION => Some("o:HandSwingC2SPacket"),
            id::HELD_ITEM_SLOT => Some("o:UpdateSelectedSlotC2SPacket"),
            _ => None,
        }
    },
    |_: &mut Engine<crate::sim::Sim18>, _: bool, _: GameMode| {},
    1 << 4,
    ghast_data::v1_8::BlockState::from_raw_vanilla,
    ghast_data::v1_8::BlockState::raw,
    stack_1_8,
    |_: u16| false
);

replay!(
    replay_1_12,
    crate::sim::Sim12,
    v1_12,
    v1_12_2,
    GameVersion::V1_12_2,
    v1_12_2,
    crate::version::V1_12_2,
    true,
    |i| {
        use ghast_protocol::v1_12_2::play::serverbound::id;
        match i {
            id::ARM_ANIMATION => Some("o:HandSwingC2SPacket:{}"),
            id::USE_ITEM => Some("o:SwingHandC2SPacket:{}"),
            id::HELD_ITEM_SLOT => Some("o:UpdateSelectedSlotC2SPacket:{}"),
            _ => None,
        }
    },
    // the eyes read the physics player's sneak key
    |e: &mut Engine<crate::sim::Sim12>, sneak: bool, _: GameMode| {
        let mut p = *e.sim.test_player();
        p.input.sneak = sneak;
        e.sim.test_set_player(p);
    },
    1 << 4,
    ghast_data::v1_12::BlockState::from_raw_vanilla,
    ghast_data::v1_12::BlockState::raw,
    stack_1_8,
    ghast_data::v1_12::place::air_use_unknown
);

/// The 1.16.5 wire slot (present, item id, count, NBT).
fn stack_1_16(h: &Value) -> Option<ghast_inventory::Stack> {
    use ghast_protocol::codec::decode_exact;
    let b = bytes::Bytes::from(unhex(h.as_str().unwrap()));
    ghast_inventory::from_modern_slot(
        decode_exact::<ghast_protocol::types::slot::modern::Slot>(&b).unwrap(),
    )
}

replay!(
    replay_1_16,
    crate::sim::Sim16,
    v1_16_5,
    v1_16_5,
    GameVersion::V1_16_5,
    v1_16_5,
    crate::version::V1_16_5,
    true,
    |i| {
        use ghast_protocol::v1_16_5::play::serverbound::id;
        match i {
            id::ARM_ANIMATION => Some("o:HandSwingC2SPacket:{}"),
            id::USE_ITEM => Some("o:PlayerInteractItemC2SPacket:{}"),
            id::HELD_ITEM_SLOT => Some("o:UpdateSelectedSlotC2SPacket:{}"),
            _ => None,
        }
    },
    // the eyes and the box read the physics player's sneak key and pose
    |e: &mut Engine<crate::sim::Sim16>, sneak: bool, mode: GameMode| {
        let mut p = *e.sim.test_player();
        p.input.sneaking = sneak;
        if sneak && mode != GameMode::Spectator {
            p.pose = ghast_physics::v1_16_5::Pose::Crouching;
            p.bb.max_y = p.bb.min_y + 1.5;
        }
        e.sim.test_set_player(p);
    },
    1,
    |id: u16| ghast_data::v1_16_5::BlockState::from_id(id).unwrap(),
    ghast_data::v1_16_5::BlockState::id,
    stack_1_16,
    ghast_data::v1_16_5::place::air_use_unknown
);

fn golden(v: &str) -> std::path::PathBuf {
    std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/golden")
        .join(v)
        .join("place.jsonl.gz")
}

fn report(v: &str, s: &Summary) {
    eprintln!(
        "{v} place: {} cases ({} with another crosshair target), {} placements by the client: {} predicted, {} left to the server; {} packets ({} undecided clicks differ, {} after a use in the air: a miss, a boat, a bucket...), {} differences",
        s.cases,
        s.crosshair,
        s.placed,
        s.predicted,
        s.unpredicted,
        s.packets,
        s.undecided,
        s.air_use,
        s.diffs.len()
    );
    let n = std::env::var("GHAST_PLACE_SHOW")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(25);
    for d in s.diffs.iter().take(n) {
        eprintln!("  {d}");
    }
}

#[test]
fn place_golden_1_8_9() {
    let path = std::env::var_os("GHAST_PLACE_VECTORS_1_8")
        .map_or_else(|| golden("1.8.9"), std::path::PathBuf::from);
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_8(&path);
    report("1.8.9", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}

#[test]
fn place_golden_1_12_2() {
    let path = std::env::var_os("GHAST_PLACE_VECTORS_1_12")
        .map_or_else(|| golden("1.12.2"), std::path::PathBuf::from);
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_12(&path);
    report("1.12.2", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}

#[test]
fn place_golden_1_16_5() {
    let path = std::env::var_os("GHAST_PLACE_VECTORS_1_16")
        .map_or_else(|| golden("1.16.5"), std::path::PathBuf::from);
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_16(&path);
    report("1.16.5", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}