ghast-client 0.5.5

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, 26.2 and 26.3)
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
//! The engine replay of the 1.12.2 entity goldens (`tests/golden/1.12.2/entities.jsonl.gz`):
//! other entities arrive as real 1.12.2 packets (spawns, teleports, relative moves, destroys,
//! tab-list entries, teams) through the sim's tracker, and every movement packet of every tick
//! must equal vanilla's.

use super::tests::opts;
use super::*;
use crate::common::{EntityAction, JoinGame};
use crate::phys_golden::v112 as golden;
use crate::sim::Sim12;
use ghast_protocol::RawPacket;
use ghast_protocol::v1_12_2::play::clientbound as cb;
use serde_json::Value;
use std::io::BufRead;

/// A packet body under construction (1.12.2 wire types).
#[derive(Default)]
struct Body(Vec<u8>);

impl Body {
    fn varint(mut self, v: i32) -> Self {
        let mut u = v as u32;
        loop {
            let b = (u & 0x7f) as u8;
            u >>= 7;
            if u == 0 {
                self.0.push(b);
                return self;
            }
            self.0.push(b | 0x80);
        }
    }
    fn uuid(mut self, most: u64, least: u64) -> Self {
        self.0.extend_from_slice(&most.to_be_bytes());
        self.0.extend_from_slice(&least.to_be_bytes());
        self
    }
    fn f64(mut self, v: f64) -> Self {
        self.0.extend_from_slice(&v.to_be_bytes());
        self
    }
    fn i8(mut self, v: i8) -> Self {
        self.0.push(v as u8);
        self
    }
    fn i16(mut self, v: i16) -> Self {
        self.0.extend_from_slice(&v.to_be_bytes());
        self
    }
    fn i32(mut self, v: i32) -> Self {
        self.0.extend_from_slice(&v.to_be_bytes());
        self
    }
    fn bool(mut self, v: bool) -> Self {
        self.0.push(u8::from(v));
        self
    }
    fn f32(mut self, v: f32) -> Self {
        self.0.extend_from_slice(&v.to_be_bytes());
        self
    }
    fn string(self, s: &str) -> Self {
        let mut b = self.varint(s.len() as i32);
        b.0.extend_from_slice(s.as_bytes());
        b
    }
    fn raw(self, id: i32) -> RawPacket {
        RawPacket {
            id,
            body: bytes::Bytes::from(self.0),
        }
    }
}

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())
}

/// The protocol angle byte of a yaw (`floor(yaw * 256 / 360)`, as the oracle sends it).
fn angle(yaw: f32) -> i8 {
    (yaw * 256.0 / 360.0).floor() as i32 as i8
}

/// The 1.12.2 packet of one oracle entity event (see `oracle/src/mc_1_12_2/.../Ent.java`).
fn packet(ev: &Value) -> RawPacket {
    let id = |k: &str| ev[k].as_i64().unwrap() as i32;
    let pos = |b: Body| {
        let p = &ev["pos"];
        b.f64(f64v(&p[0])).f64(f64v(&p[1])).f64(f64v(&p[2]))
    };
    match ev["type"].as_str().unwrap() {
        "spawn" => {
            let eid = id("id");
            let yaw = angle(f32v(&ev["yaw"]));
            let ty = ev["entity"].as_str().unwrap();
            let object = match ty {
                "boat" => Some(1),
                "item" => Some(2),
                "minecart" => Some(10),
                "armor_stand" => Some(78),
                _ => None,
            };
            if ty == "player" {
                let b = Body::default().varint(eid).uuid(0x706c_6179, eid as u64);
                pos(b)
                    .i8(yaw)
                    .i8(0)
                    .i8(-1) // no metadata
                    .raw(cb::id::NAMED_ENTITY_SPAWN)
            } else if let Some(object) = object {
                let b = Body::default()
                    .varint(eid)
                    .uuid(0x0065_6e74, eid as u64)
                    .i8(object);
                pos(b)
                    .i8(0)
                    .i8(yaw)
                    .i32(0)
                    .i16(0)
                    .i16(0)
                    .i16(0)
                    .raw(cb::id::SPAWN_ENTITY)
            } else {
                let mob = ghast_data::v1_12::entity_by_name(ty)
                    .unwrap_or_else(|| panic!("entity {ty}"))
                    .id;
                let b = Body::default()
                    .varint(eid)
                    .uuid(0x0065_6e74, eid as u64)
                    .varint(i32::from(mob));
                pos(b)
                    .i8(yaw)
                    .i8(0)
                    .i8(yaw)
                    .i16(0)
                    .i16(0)
                    .i16(0)
                    .i8(-1) // no metadata
                    .raw(cb::id::SPAWN_ENTITY_LIVING)
            }
        }
        "entity_move" => {
            let b = Body::default().varint(id("id"));
            pos(b)
                .i8(angle(f32v(&ev["yaw"])))
                .i8(0)
                .bool(ev["on_ground"].as_bool().unwrap())
                .raw(cb::id::ENTITY_TELEPORT)
        }
        "entity_rel_move" => Body::default()
            .varint(id("id"))
            .i16(id("dx") as i16)
            .i16(id("dy") as i16)
            .i16(id("dz") as i16)
            .bool(ev["on_ground"].as_bool().unwrap())
            .raw(cb::id::REL_ENTITY_MOVE),
        "remove_entity" => Body::default()
            .varint(1)
            .varint(id("id"))
            .raw(cb::id::ENTITY_DESTROY),
        "tab" => {
            let pid = id("id");
            let add = ev["add"].as_bool().unwrap();
            let b = Body::default()
                .varint(if add { 0 } else { 1 })
                .varint(1)
                .uuid(0x706c_6179, pid as u64);
            if add {
                b.string(&format!("p{pid}"))
                    .varint(0)
                    .varint(id("game_mode"))
                    .varint(0)
                    .bool(false)
                    .raw(cb::id::PLAYER_INFO)
            } else {
                b.varint(id("game_mode")).raw(cb::id::PLAYER_INFO)
            }
        }
        "team" => {
            let name = ev["name"].as_str().unwrap();
            let mode = id("mode");
            let mut b = Body::default().string(name).i8(mode as i8);
            if mode == 0 || mode == 2 {
                b = b
                    .string(name)
                    .string("")
                    .string("")
                    .i8(0)
                    .string("always")
                    .string(ev["rule"].as_str().unwrap())
                    .i8(-1);
            }
            if matches!(mode, 0 | 3 | 4) {
                let m = ev["members"].as_array().unwrap();
                b = b.varint(m.len() as i32);
                for s in m {
                    b = b.string(s.as_str().unwrap());
                }
            }
            b.raw(cb::id::TEAMS)
        }
        "ride" => {
            let ps = ev["passengers"].as_array().unwrap();
            let mut b = Body::default()
                .varint(id("vehicle"))
                .varint(ps.len() as i32);
            for v in ps {
                b = b.varint(v.as_i64().unwrap() as i32);
            }
            b.raw(cb::id::SET_PASSENGERS)
        }
        "vehicle_move" => pos(Body::default())
            .f32(f32v(&ev["yaw"]))
            .f32(f32v(&ev["pitch"]))
            .raw(cb::id::VEHICLE_MOVE),
        // Piston cases (`oracle/src/mc_1_12_2/.../Pistons.java`).
        "block_action" | "block_change" | "world_time" => piston_packet(ev),
        other => panic!("event {other}"),
    }
}

/// The 1.12.2 packet of a piston event: block action, block update, world time.
fn piston_packet(ev: &Value) -> RawPacket {
    let mut b = Vec::new();
    let n = |k: &str| ev[k].as_i64().unwrap();
    let pos = |b: &mut Vec<u8>| {
        let q = &ev["pos"];
        let c = |k: usize| q[k].as_i64().unwrap();
        let v = ((c(0) & 0x3FF_FFFF) << 38) | ((c(1) & 0xFFF) << 26) | (c(2) & 0x3FF_FFFF);
        b.extend_from_slice(&v.to_be_bytes());
    };
    let varint = |b: &mut Vec<u8>, v: i64| {
        let mut u = v as u32;
        loop {
            let x = (u & 0x7f) as u8;
            u >>= 7;
            if u == 0 {
                b.push(x);
                return;
            }
            b.push(x | 0x80);
        }
    };
    let id = match ev["type"].as_str().unwrap() {
        "block_action" => {
            pos(&mut b);
            b.push(n("action") as u8);
            b.push(n("data") as u8);
            varint(&mut b, n("block"));
            cb::id::BLOCK_ACTION
        }
        "block_change" => {
            pos(&mut b);
            varint(&mut b, n("raw"));
            cb::id::BLOCK_CHANGE
        }
        _ => {
            b.extend_from_slice(&n("time").to_be_bytes());
            b.extend_from_slice(&n("time").to_be_bytes());
            cb::id::UPDATE_TIME
        }
    };
    RawPacket {
        id,
        body: bytes::Bytes::from(b),
    }
}

/// A 1.12.2 join packet: our entity id 1, survival, the overworld.
fn login_packet() -> RawPacket {
    Body::default()
        .i32(1)
        .i8(0)
        .i32(0)
        .i8(1)
        .i8(20)
        .string("flat")
        .bool(false)
        .raw(cb::id::LOGIN)
}

/// The movement packets of a tick, as comparable values.
fn ours(o: &Outbound) -> Option<Value> {
    let bits = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()];
    Some(match *o {
        Outbound::Move(MovePacket::Position { pos, on_ground, .. }) => {
            serde_json::json!(["position", bits(pos), on_ground])
        }
        Outbound::Move(MovePacket::PositionLook {
            pos,
            yaw,
            pitch,
            on_ground,
            ..
        }) => serde_json::json!([
            "position_look",
            bits(pos),
            yaw.to_bits(),
            pitch.to_bits(),
            on_ground
        ]),
        Outbound::Move(MovePacket::Look {
            yaw,
            pitch,
            on_ground,
            ..
        }) => serde_json::json!(["look", yaw.to_bits(), pitch.to_bits(), on_ground]),
        Outbound::Move(MovePacket::Flying { on_ground, .. }) => {
            serde_json::json!(["flying", on_ground])
        }
        Outbound::VehicleMove {
            pos, yaw, pitch, ..
        } => serde_json::json!(["vehicle_move", bits(pos), yaw.to_bits(), pitch.to_bits()]),
        Outbound::SteerBoat { left, right } => serde_json::json!(["steer_boat", left, right]),
        Outbound::SteerVehicle {
            sideways,
            forward,
            jump,
            sneak,
        } => serde_json::json!([
            "steer_vehicle",
            sideways.to_bits(),
            forward.to_bits(),
            jump,
            sneak
        ]),
        Outbound::EntityAction { action, .. } => serde_json::json!([
            "entity_action",
            match action {
                EntityAction::StartSprinting => "start_sprinting",
                EntityAction::StopSprinting => "stop_sprinting",
                EntityAction::StartSneaking => "start_sneaking",
                EntityAction::StopSneaking => "stop_sneaking",
                EntityAction::StartFallFlying => "start_fall_flying",
                _ => "other",
            }
        ]),
        _ => return None,
    })
}

fn theirs(p: &Value) -> Option<Value> {
    let bits = |v: &Value| {
        [
            f64v(&v[0]).to_bits(),
            f64v(&v[1]).to_bits(),
            f64v(&v[2]).to_bits(),
        ]
    };
    let og = &p["on_ground"];
    Some(match p["name"].as_str().unwrap() {
        "position" => serde_json::json!(["position", bits(&p["pos"]), og]),
        "position_look" => serde_json::json!([
            "position_look",
            bits(&p["pos"]),
            f32v(&p["yaw"]).to_bits(),
            f32v(&p["pitch"]).to_bits(),
            og
        ]),
        "look" => serde_json::json!([
            "look",
            f32v(&p["yaw"]).to_bits(),
            f32v(&p["pitch"]).to_bits(),
            og
        ]),
        "flying" => serde_json::json!(["flying", og]),
        "entity_action" => serde_json::json!(["entity_action", p["action_name"]]),
        "vehicle_move" => serde_json::json!([
            "vehicle_move",
            bits(&p["pos"]),
            f32v(&p["yaw"]).to_bits(),
            f32v(&p["pitch"]).to_bits()
        ]),
        "steer_boat" => serde_json::json!(["steer_boat", p["left"], p["right"]]),
        "steer_vehicle" => serde_json::json!([
            "steer_vehicle",
            f32v(&p["sideways"]).to_bits(),
            f32v(&p["forward"]).to_bits(),
            p["jump"],
            p["sneak"]
        ]),
        _ => return None,
    })
}

struct Keys(Controls, bool);

impl Behavior for Keys {
    fn name(&self) -> &str {
        "entities-replay-1.12"
    }
    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        ctx.set_controls(self.0);
        ctx.set_buttons(crate::hands::Buttons {
            left: false,
            right: self.1,
        });
    }
}

/// A 1.12.2 `entity_metadata` for our entity (id 1): the shared flags byte (index 0).
fn shared_flags_packet(flags: u8) -> RawPacket {
    Body::default()
        .varint(1)
        .i8(0)
        .varint(0)
        .i8(flags as i8)
        .i8(-1)
        .raw(cb::id::ENTITY_METADATA)
}

/// A 1.12 stack of item `id` with a damage value (and the depth strider level of boots).
fn stack_1_12(id: i32, damage: i16, depth_strider: u8) -> ghast_inventory::Stack {
    let s = ghast_inventory::Stack::new(id, 1, damage);
    if depth_strider == 0 {
        return s;
    }
    // {ench: [{id: 8s, lvl: <level>s}]}
    let mut b = vec![10, 0, 0, 9, 0, 4];
    b.extend_from_slice(b"ench");
    b.push(10);
    b.extend_from_slice(&1i32.to_be_bytes());
    b.extend_from_slice(&[2, 0, 2]);
    b.extend_from_slice(b"id");
    b.extend_from_slice(&8i16.to_be_bytes());
    b.extend_from_slice(&[2, 0, 3]);
    b.extend_from_slice(b"lvl");
    b.extend_from_slice(&i16::from(depth_strider).to_be_bytes());
    b.extend_from_slice(&[0, 0]);
    s.with_nbt(Some(
        ghast_protocol::nbt::RawNbt::from_bytes(bytes::Bytes::from(b)).unwrap(),
    ))
}

/// The chest item of an elytra case (elytra 443, a chestplate 311).
fn chest_1_12(item: Option<&str>, damage: i64) -> Option<ghast_inventory::Stack> {
    let id = match item? {
        "elytra" => 443,
        "diamond_chestplate" => 311,
        other => panic!("chest item {other}"),
    };
    Some(stack_1_12(id, damage as i16, 0))
}

/// What the server sends for a rocket it spawns for us: the spawn-object packet (type 76, no
/// motion) and its entity data naming us as the shooter (index 7, a VarInt).
fn firework_packets(id: i32, pos: [f64; 3]) -> Vec<RawPacket> {
    vec![
        Body::default()
            .varint(id)
            .uuid(0x6669_7265, id as u64)
            .i8(76)
            .f64(pos[0])
            .f64(pos[1])
            .f64(pos[2])
            .i8(0)
            .i8(0)
            .i32(0)
            .i16(0)
            .i16(0)
            .i16(0)
            .raw(cb::id::SPAWN_ENTITY),
        Body::default()
            .varint(id)
            .i8(7)
            .varint(1)
            .varint(1)
            .i8(-1)
            .raw(cb::id::ENTITY_METADATA),
    ]
}

/// Replays every case of `entities.jsonl.gz` through the engine with entity tracking (`metadata`:
/// with the generic metadata store); returns (cases, ticks).
fn replay(metadata: bool) -> (usize, usize) {
    replay_file(
        &format!(
            "{}/../../tests/golden/1.12.2/entities.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        ),
        metadata,
    )
}

/// [`replay`] of one file.
fn replay_file(path: &str, metadata: bool) -> (usize, usize) {
    let f = std::fs::File::open(path).unwrap();
    // One case in memory at a time (the cached files are large).
    let mut lines = std::io::BufReader::new(flate2::read::GzDecoder::new(f))
        .lines()
        .map(|l| serde_json::from_str::<Value>(&l.unwrap()).unwrap())
        .peekable();
    let (mut cases, mut ticks_done, mut packets) = (0, 0, 0);
    let mut failed = Vec::new();
    while let Some(header) = lines.next() {
        let sc = &header;
        let name = sc["name"].as_str().unwrap().to_owned();
        let mut owned = Vec::new();
        while let Some(t) = lines.next_if(|l| l["type"] == "tick") {
            owned.push(t);
        }
        let ticks: Vec<&Value> = owned.iter().collect();
        cases += 1;
        let setup = &sc["setup"];
        let mut sim = Sim12::new();
        sim.test_set_profile_name("oracle");
        let mut e = Engine::new(opts(GameVersion::V1_12_2), sim);
        e.handle(Inbound::JoinGame(JoinGame {
            entity_id: 1,
            game_mode: match setup["game_mode"].as_str().unwrap() {
                "spectator" => GameMode::Spectator,
                "creative" => GameMode::Creative,
                "adventure" => GameMode::Adventure,
                _ => GameMode::Survival,
            },
            dimension: "0".into(),
            hardcore: false,
            dimension_nbt: None,
            respawn_screen: true,
        }));
        // What `Client` sets up for `Interests::ENTITY_TRACKING` (+ `ENTITIES`) on 1.12.2.
        e.sim.set_entities(Some(
            ghast_entity::Config::default()
                .with_metadata(metadata)
                .with_equipment(false)
                .with_effects(false)
                .with_player_list(false)
                .with_player_names(true)
                .with_events(false),
        ));
        // Riding cases: a join packet first (our entity id for set_passengers).
        let ride = setup
            .get("ext")
            .and_then(|x| x.get("ride"))
            .and_then(Value::as_bool)
            == Some(true);
        if ride {
            e.sim.world_packet(&login_packet()).unwrap();
        }
        // The oracle world: the loaded columns, air outside the fills (in order).
        for r in sc["loaded_chunks"].as_array().unwrap() {
            let r: Vec<i32> = (0..4).map(|k| r[k].as_i64().unwrap() as i32).collect();
            for x in r[0]..=r[2] {
                for z in r[1]..=r[3] {
                    e.sim
                        .world_packet(&crate::sim::test_chunks::v1_12_2(x, z))
                        .unwrap();
                }
            }
            for x in r[0] * 16..r[2] * 16 + 16 {
                for z in r[1] * 16..r[3] * 16 + 16 {
                    e.sim.predict_air(x, 63, z);
                }
            }
        }
        for fill in sc["fills"].as_array().unwrap() {
            let v: Vec<i64> = (0..8).map(|k| fill[k].as_i64().unwrap()).collect();
            let st = ghast_data::v1_12::BlockState::from_raw_vanilla(
                ((v[6] as u16) << 4) | (v[7] as u16 & 15),
            );
            for x in v[0]..=v[3] {
                for y in v[1]..=v[4] {
                    for z in v[2]..=v[5] {
                        e.sim.test_set_block(x as i32, y as i32, z as i32, st);
                    }
                }
            }
        }
        e.handle(Inbound::Teleport(crate::common::Teleport {
            x: f64v(&setup["pos"][0]),
            y: f64v(&setup["pos"][1]),
            z: f64v(&setup["pos"][2]),
            yaw: f32v(&setup["yaw"]),
            pitch: f32v(&setup["pitch"]),
            teleport_id: None,
            ..Default::default()
        }));
        let mut p = golden::player_of(sc, ticks[0]);
        // The oracle's setup put the player into its (loaded) chunk.
        p.added_to_chunk = true;
        e.sim.test_set_player(p);
        for ev in setup["entities"].as_array().into_iter().flatten() {
            e.sim.world_packet(&packet(ev)).unwrap();
        }
        // Elytra cases: the chest item and boots in the inventory window, rockets in the hand,
        // the server's flag 7 at setup.
        if let Some(x) = setup.get("ext").filter(|_| !ride) {
            e.sim.test_watch_glide();
            let damage = x.get("chest_damage").map_or(0, |v| v.as_i64().unwrap());
            e.inventory_mut().on_set_slot(
                0,
                6,
                chest_1_12(x.get("chest").and_then(Value::as_str), damage),
            );
            let ds = setup["depth_strider"].as_u64().unwrap_or(0) as u8;
            if ds > 0 {
                e.inventory_mut()
                    .on_set_slot(0, 8, Some(stack_1_12(313, 0, ds)));
            }
            if x.get("hand").and_then(Value::as_str) == Some("fireworks") {
                e.inventory_mut()
                    .on_set_slot(0, 36, Some(stack_1_12(401, 0, 0)));
            }
            if x.get("fall_flying").and_then(Value::as_bool) == Some(true) {
                let cur = e.sim.test_shared_flags_1_12();
                e.sim
                    .world_packet(&shared_flags_packet(cur | 0x80))
                    .unwrap();
            }
        }
        e.core.pose.pos = Vec3::new(p.pos[0], p.bb.min_y, p.pos[2]);
        e.core.pose.yaw = p.yaw;
        e.core.pose.pitch = p.pitch;
        e.core.ready = true;
        e.outbound().clear();
        let t0 = Instant::now();
        // The engine does not tick the player outside the loaded columns (on purpose; a
        // vanilla 1.12 client ticks it there): a case ends where the oracle's player leaves
        // them.
        let rects: Vec<[i32; 4]> = sc["loaded_chunks"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| std::array::from_fn(|k| r[k].as_i64().unwrap() as i32))
            .collect();
        let column_loaded = |s: &Value| {
            let (cx, cz) = (
                (f64v(&s["pos"][0]).floor() as i32) >> 4,
                (f64v(&s["pos"][2]).floor() as i32) >> 4,
            );
            rects
                .iter()
                .any(|r| r[0] <= cx && cx <= r[2] && r[1] <= cz && cz <= r[3])
        };
        let mut teleport_id = 0;
        for (k, rec) in ticks.iter().enumerate().skip(1) {
            if !column_loaded(&ticks[k - 1]["state"]) {
                break;
            }
            let input = &rec["input"];
            let mut replies: Vec<Outbound> = Vec::new();
            for ev in input["events"].as_array().into_iter().flatten() {
                match ev["type"].as_str().unwrap() {
                    "velocity" => {
                        let c = |k: &str| f64::from(ev[k].as_i64().unwrap() as i32) / 8000.0;
                        e.handle(Inbound::Velocity {
                            entity_id: 1,
                            motion: Vec3::new(c("x"), c("y"), c("z")),
                        });
                    }
                    "shared_flags" => {
                        let set = ev["set"].as_u64().unwrap() as u8;
                        let clear = ev["clear"].as_u64().unwrap() as u8;
                        let cur = e.sim.test_shared_flags_1_12();
                        e.sim
                            .world_packet(&shared_flags_packet((cur & !clear) | set))
                            .unwrap();
                    }
                    "equip" => {
                        let item = ev.get("item").and_then(Value::as_str);
                        let damage = ev["damage"].as_i64().unwrap();
                        e.inventory_mut()
                            .on_set_slot(0, 6, chest_1_12(item, damage));
                    }
                    "teleport" => {
                        // The server's position-look packet (1.12: with a teleport id).
                        let flags = ev.get("flags").and_then(Value::as_i64).unwrap_or(0);
                        teleport_id += 1;
                        e.handle(Inbound::Teleport(crate::common::Teleport {
                            x: f64v(&ev["pos"][0]),
                            y: f64v(&ev["pos"][1]),
                            z: f64v(&ev["pos"][2]),
                            yaw: f32v(&ev["yaw"]),
                            pitch: f32v(&ev["pitch"]),
                            flags: flags as i8,
                            relative: flags as u32,
                            teleport_id: Some(teleport_id),
                            ..Default::default()
                        }));
                    }
                    "firework" => {
                        // At our position when the server handles the use (after our last tick).
                        let s = &ticks[k - 1]["state"]["pos"];
                        let pos = [f64v(&s[0]), f64v(&s[1]), f64v(&s[2])];
                        for raw in firework_packets(ev["id"].as_i64().unwrap() as i32, pos) {
                            e.sim.world_packet(&raw).unwrap();
                        }
                    }
                    _ => {
                        e.sim.world_packet(&packet(ev)).unwrap();
                        // The client's answer to the server's vehicle move goes out at once.
                        if let Some(o) = e.sim.take_reply() {
                            replies.push(o);
                        }
                    }
                }
            }
            let keys = input["keys"].as_str().unwrap();
            let has = |k: &str| keys.split(',').any(|n| n == k);
            let mut b = Keys(
                Controls {
                    forward: has("forward"),
                    back: has("back"),
                    left: has("left"),
                    right: has("right"),
                    jump: has("jump"),
                    sneak: has("sneak"),
                    sprint: has("sprint"),
                },
                has("use"),
            );
            e.core.forced_look = Some((f32v(&input["yaw"]), f32v(&input["pitch"])));
            e.note_inbound(t0);
            e.tick(&mut b, t0);
            // A tick the engine flags (`piston_uncertain`) is outside the model: the case ends.
            if e.sim.piston_uncertain() {
                eprintln!("{name}: ends at tick {k} (flagged piston_uncertain)");
                break;
            }
            let out = std::mem::take(e.outbound());
            let got: Vec<Value> = replies.iter().chain(out.iter()).filter_map(ours).collect();
            let want: Vec<Value> = rec["packets"]
                .as_array()
                .unwrap()
                .iter()
                .filter_map(theirs)
                .collect();
            if got != want {
                failed.push(format!("{name} tick {k}: got {got:?} want {want:?}"));
                break;
            }
            // Piston cases: the client copies of the entities that push or collide, where the
            // moving blocks left them.
            if rec.get("pistons").is_some() {
                let mut bad = None;
                for x in rec["entities"].as_array().into_iter().flatten() {
                    let Some(id) = x["id"].as_i64().filter(|_| x.get("post").is_some()) else {
                        continue;
                    };
                    let Some((pos, bb)) = e.sim.test_near_box(id as i32) else {
                        continue;
                    };
                    let want_bb: Vec<u64> = (0..6).map(|k| f64v(&x["post"][k]).to_bits()).collect();
                    let want_pos: Vec<u64> = (0..3).map(|k| f64v(&x["pos"][k]).to_bits()).collect();
                    let got_bb: Vec<u64> =
                        [bb.min_x, bb.min_y, bb.min_z, bb.max_x, bb.max_y, bb.max_z]
                            .iter()
                            .map(|v| v.to_bits())
                            .collect();
                    let got_pos: Vec<u64> = pos.iter().map(|v| v.to_bits()).collect();
                    if got_bb != want_bb || got_pos != want_pos {
                        bad = Some(format!(
                            "{name} tick {k}: entity {id} {} box {bb:?} at {pos:?}, want {} at {}",
                            x["type"], x["post"], x["pos"]
                        ));
                        break;
                    }
                }
                if let Some(b) = bad {
                    failed.push(b);
                    break;
                }
            }
            packets += want.len();
            ticks_done += 1;
        }
    }
    eprintln!(
        "1.12.2 {path} through the engine (metadata {metadata}): {cases} cases, {ticks_done} ticks, {packets} packets identical"
    );
    assert!(
        failed.is_empty(),
        "{} of {cases} cases failed:\n{}",
        failed.len(),
        failed.join("\n")
    );
    (cases, ticks_done)
}

/// The 1.12.2 piston goldens through the engine with entity tracking: mobs, boats and shulkers
/// next to moving pistons (their pushes and collisions after the player's tick, the moving
/// blocks last), world-time packets mid-push.
#[test]
fn pistons_with_entities_match_the_oracle_1_12_2() {
    let (cases, ticks) = replay_file(
        &format!(
            "{}/../../tests/golden/1.12.2/pistons.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        ),
        true,
    );
    // Every tick: the pistons move the other entities' client copies too.
    assert!(cases >= 143 && ticks > 7000, "{cases} cases, {ticks} ticks");
}

/// The cached piston fuzz (`oracle/cache/1.12.2/fuzz-pistons/`, git-ignored) with entity
/// tracking: the pistons push the other entities' client copies; their boxes are compared
/// every tick.
#[test]
#[ignore = "cache run: cargo test --release -p ghast-client --lib -- --ignored pistons_with_entities_cache_1_12_2"]
fn pistons_with_entities_cache_1_12_2() {
    let dir = format!(
        "{}/../../oracle/cache/1.12.2/fuzz-pistons",
        env!("CARGO_MANIFEST_DIR")
    );
    let mut files: Vec<_> = std::fs::read_dir(&dir)
        .expect("oracle/cache/1.12.2/fuzz-pistons")
        .flatten()
        .map(|e| e.path())
        .collect();
    files.sort();
    let (mut cases, mut ticks) = (0, 0);
    for f in files {
        let (c, t) = replay_file(f.to_str().unwrap(), true);
        cases += c;
        ticks += t;
    }
    eprintln!("1.12.2 piston cache with entities through the engine: {cases} cases, {ticks} ticks");
    assert!(cases > 0);
}

/// 1.12.2 entity pushes and entity collisions through the engine: 0 differences.
#[test]
fn entities_match_the_oracle_1_12_2() {
    let (cases, ticks) = replay(true);
    assert!(cases >= 80 && ticks > 4000, "{cases} cases, {ticks} ticks");
}

/// The same with `Interests::ENTITY_TRACKING` alone (no generic metadata store).
#[test]
fn entities_match_the_oracle_1_12_2_without_metadata() {
    replay(false);
}

/// The 1.12.2 elytra goldens through the engine: the chest item in the inventory window, the
/// server's flag 7 as our entity data, rockets as the server's spawn and entity data packets;
/// every movement and `entity_action` packet (the glide request) must equal the real client's.
#[test]
fn elytra_match_the_oracle_1_12_2() {
    let (cases, ticks) = replay_file(
        &format!(
            "{}/../../tests/golden/1.12.2/elytra.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        ),
        false,
    );
    assert!(cases >= 120 && ticks > 7000, "{cases} cases, {ticks} ticks");
}

/// The cached elytra fuzz (`oracle/cache/1.12.2/fuzz-elytra/`, git-ignored) through the engine.
#[test]
#[ignore = "needs the oracle cache"]
fn elytra_cache_match_the_oracle_1_12_2() {
    let dir = format!(
        "{}/../../oracle/cache/1.12.2/fuzz-elytra",
        env!("CARGO_MANIFEST_DIR")
    );
    let Ok(rd) = std::fs::read_dir(&dir) else {
        eprintln!("skipped: {dir} not found");
        return;
    };
    let mut files: Vec<_> = rd
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
        .collect();
    files.sort();
    let (mut cases, mut ticks) = (0, 0);
    for f in &files {
        let (c, t) = replay_file(&f.to_string_lossy(), false);
        cases += c;
        ticks += t;
    }
    eprintln!("1.12.2 elytra fuzz cache through the engine: {cases} cases, {ticks} ticks");
}

/// The cached entity fuzz (`oracle/cache/1.12.2/fuzz-entities/`, git-ignored; see the oracle
/// README) through the engine. Slow: run in release with `--ignored`.
#[test]
#[ignore = "needs the oracle cache"]
fn entities_cache_match_the_oracle_1_12_2() {
    let dir = format!(
        "{}/../../oracle/cache/1.12.2/fuzz-entities",
        env!("CARGO_MANIFEST_DIR")
    );
    let mut files: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
        .collect();
    files.sort();
    let (mut cases, mut ticks) = (0, 0);
    for f in &files {
        let (c, t) = replay_file(&f.to_string_lossy(), true);
        cases += c;
        ticks += t;
    }
    eprintln!("1.12.2 entity fuzz cache through the engine: {cases} cases, {ticks} ticks");
    assert!(cases > 0);
}

/// The 1.12.2 boat goldens through the engine (entity tracking): boarding by `set_passengers`,
/// the boat the client moves, `steer_boat` / `look` / `steer_vehicle` / `vehicle_move` every
/// tick, the answer to the server's `vehicle_move`, the server's dismount.
#[test]
fn boats_match_the_oracle_1_12_2() {
    let (cases, ticks) = replay_file(
        &format!(
            "{}/../../tests/golden/1.12.2/boats.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        ),
        false,
    );
    assert!(cases >= 122 && ticks > 7000, "{cases} cases, {ticks} ticks");
}

/// The 1.12.2 boat seat goldens through the engine: a second passenger in front of or behind
/// us, the boat the server moves while another passenger sits in front (`look` /
/// `steer_vehicle` only), hand-overs of the front seat.
#[test]
fn boats_seat_match_the_oracle_1_12_2() {
    let (cases, ticks) = replay_file(
        &format!(
            "{}/../../tests/golden/1.12.2/boats_seat.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        ),
        false,
    );
    assert!(cases >= 13 && ticks > 700, "{cases} cases, {ticks} ticks");
}

/// The 1.12.2 dismount placements through the engine: off a minecart or a boat by the server,
/// the teleport above or beside it, the free ticks after.
#[test]
fn dismounts_match_the_oracle_1_12_2() {
    let (cases, ticks) = replay_file(
        &format!(
            "{}/../../tests/golden/1.12.2/dismounts.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        ),
        false,
    );
    assert!(cases >= 12 && ticks > 400, "{cases} cases, {ticks} ticks");
}

/// The cached boat seat fuzz (`oracle/cache/1.12.2/fuzz-boat-seats/`, git-ignored) through the
/// engine.
#[test]
#[ignore = "needs the oracle cache"]
fn boat_seats_cache_match_the_oracle_1_12_2() {
    let dir = format!(
        "{}/../../oracle/cache/1.12.2/fuzz-boat-seats",
        env!("CARGO_MANIFEST_DIR")
    );
    let Ok(rd) = std::fs::read_dir(&dir) else {
        eprintln!("skipped: {dir} not found");
        return;
    };
    let mut files: Vec<_> = rd
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
        .collect();
    files.sort();
    let (mut cases, mut ticks) = (0, 0);
    for f in &files {
        let (c, t) = replay_file(&f.to_string_lossy(), false);
        cases += c;
        ticks += t;
    }
    eprintln!("1.12.2 boat seat cache through the engine: {cases} cases, {ticks} ticks");
    assert!(cases > 0);
}

/// The cached boat fuzz (`oracle/cache/1.12.2/fuzz-boats/`, git-ignored) through the engine.
#[test]
#[ignore = "needs the oracle cache"]
fn boats_cache_match_the_oracle_1_12_2() {
    let dir = format!(
        "{}/../../oracle/cache/1.12.2/fuzz-boats",
        env!("CARGO_MANIFEST_DIR")
    );
    let Ok(rd) = std::fs::read_dir(&dir) else {
        eprintln!("skipped: {dir} not found");
        return;
    };
    let mut files: Vec<_> = rd
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
        .collect();
    files.sort();
    let (mut cases, mut ticks) = (0, 0);
    for f in &files {
        let (c, t) = replay_file(&f.to_string_lossy(), false);
        cases += c;
        ticks += t;
    }
    eprintln!("1.12.2 boat fuzz cache through the engine: {cases} cases, {ticks} ticks");
    assert!(cases > 0);
}

/// The 1.12.2 minecart goldens through the engine: boarding by `set_passengers`, the cart's
/// interpolation of the server's moves, `look` / `steer_vehicle` every tick, the server's dismount.
#[test]
fn minecarts_match_the_oracle_1_12_2() {
    let (cases, ticks) = replay_file(
        &format!(
            "{}/../../tests/golden/1.12.2/minecarts.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        ),
        false,
    );
    assert!(cases >= 107 && ticks > 6000, "{cases} cases, {ticks} ticks");
}

/// The cached minecart fuzz (`oracle/cache/1.12.2/fuzz-minecarts/`, git-ignored) through the
/// engine.
#[test]
#[ignore = "needs the oracle cache"]
fn minecarts_cache_match_the_oracle_1_12_2() {
    let dir = format!(
        "{}/../../oracle/cache/1.12.2/fuzz-minecarts",
        env!("CARGO_MANIFEST_DIR")
    );
    let Ok(rd) = std::fs::read_dir(&dir) else {
        eprintln!("skipped: {dir} not found");
        return;
    };
    let mut files: Vec<_> = rd
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
        .collect();
    files.sort();
    let (mut cases, mut ticks) = (0, 0);
    for f in &files {
        let (c, t) = replay_file(&f.to_string_lossy(), false);
        cases += c;
        ticks += t;
    }
    eprintln!("1.12.2 minecart fuzz cache through the engine: {cases} cases, {ticks} ticks");
    assert!(cases > 0);
}