ghast-client 0.5.6

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
//! The engine replay of the sleep goldens (`tests/golden/<version>/sleep.jsonl.gz`, the
//! oracle's `Sleep` dumps): the server's real sleep packets (1.8 / 1.12 `bed` and `animation`
//! 2), block updates and velocity through the client's packet route, the leave-bed action of
//! the behaviour, the keys held while asleep. Per tick the player's position, box, velocity,
//! look, the sleeping state, the sleep timer, the eye height and every movement packet must
//! equal vanilla's.

use super::tests::opts;
use super::*;
use crate::common::{EntityAction, JoinGame};
use crate::version::ClientVersion;
use ghast_protocol::{PacketFilter, RawPacket};
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 i(v: &Value) -> i32 {
    v.as_i64().unwrap() as i32
}

fn pos(v: &Value) -> ghast_protocol::BlockPos {
    ghast_protocol::BlockPos::new(i(&v[0]), i(&v[1]), i(&v[2]))
}

/// Our entity id in the replays.
const ME: i32 = 1;

/// The 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::TeleportConfirm(id) | Outbound::TeleportConfirmPose { id, .. } => {
            serde_json::json!(["teleport_confirm", id])
        }
        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::LeaveBed => "stop_sleeping",
                _ => "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]),
        "teleport_confirm" => serde_json::json!(["teleport_confirm", p["teleport_id"]]),
        "entity_action" => serde_json::json!(["entity_action", p["action_name"]]),
        _ => return None,
    })
}

/// The case's keys, and the leave-bed button on its tick.
struct Keys {
    controls: Controls,
    leave: bool,
}

impl Behavior for Keys {
    fn name(&self) -> &str {
        "sleep-replay"
    }
    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        ctx.set_controls(self.controls);
        if self.leave {
            assert!(ctx.leave_bed(), "leave_bed refused");
        }
    }
}

/// What a version's replay needs besides the engine: the sim, its world setup and packets,
/// and the player state the golden compares.
trait Fixture {
    type V: ClientVersion;
    type S: Sim;
    /// The server's position packets carry a teleport id (1.9+).
    const TELEPORT_IDS: bool = true;
    fn sim() -> Self::S;
    /// The legacy join packet (our entity id); other versions: the sim learns the id.
    fn login() -> Option<RawPacket> {
        None
    }
    fn join(s: &mut Self::S) {
        match Self::login() {
            Some(raw) => s.world_packet(&raw).unwrap(),
            None => s.test_set_own_id(ME),
        }
    }
    fn chunk(x: i32, z: i32) -> RawPacket;
    /// Sets one block of a golden `fills` entry.
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value);
    /// The golden's `fills` in order.
    fn fill_world(e: &mut Engine<Self::S>, sc: &Value, filter: &PacketFilter) {
        let _ = filter;
        for fill in sc["fills"].as_array().unwrap() {
            let v: Vec<i32> = (0..6).map(|k| i(&fill[k])).collect();
            for x in v[0]..=v[3] {
                for y in v[1]..=v[4] {
                    for z in v[2]..=v[5] {
                        Self::set_block(&mut e.sim, x, y, z, fill);
                    }
                }
            }
        }
    }
    /// The player from the golden's header and tick 0.
    fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value);
    /// The server packet of a sleep event (`bed`, `wake`, `block`, `velocity`).
    fn packet(ev: &Value) -> RawPacket;
    /// Position, box, velocity, yaw, pitch.
    fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32);
}

/// A server packet through the client's route: the packet filter of a plain client, then the
/// sim, the inventory and the engine.
fn feed<F: Fixture>(e: &mut Engine<F::S>, filter: &PacketFilter, raw: &RawPacket) {
    if !filter.contains(raw.id) {
        return;
    }
    e.sim.world_packet(raw).unwrap();
    if let Some(o) = F::V::inventory_packet(e.inventory_mut(), raw).unwrap() {
        e.outbound().push(Outbound::Inventory(o));
    }
    let mut wire = <F::V as ClientVersion>::Wire::default();
    if let Some(p) = F::V::decode_play(raw, &mut wire).unwrap() {
        e.handle(p);
    }
}

/// Replays every case of `path`; returns (cases, ticks) or the failures.
fn replay<F: Fixture>(path: &str) -> (usize, usize, Vec<String>) {
    let f = std::fs::File::open(path).unwrap_or_else(|e| panic!("{path}: {e}"));
    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) = (0, 0);
    let mut failed = Vec::new();
    while let Some(sc) = lines.next() {
        let name = sc["name"].as_str().unwrap().to_owned();
        let mut ticks = Vec::new();
        while let Some(t) = lines.next_if(|l| l["type"] == "tick") {
            ticks.push(t);
        }
        if let Ok(only) = std::env::var("GHAST_SLEEP_CASES")
            && !only.split(',').any(|n| n == name)
        {
            continue;
        }
        cases += 1;
        let setup = &sc["setup"];
        let mut e = Engine::new(opts(F::V::GAME), F::sim());
        e.handle(Inbound::JoinGame(JoinGame {
            entity_id: ME,
            game_mode: GameMode::Survival,
            dimension: "0".into(),
            hardcore: false,
            dimension_nbt: None,
            respawn_screen: true,
        }));
        F::join(&mut e.sim);
        // The packet filter of a plain client (`Client::set_interests`).
        let mut filter = F::V::play_filter(Interests::default());
        for id in e.sim.entity_packet_ids() {
            filter.insert(id);
        }
        for id in e.sim.world_packet_ids() {
            filter.insert(id);
        }
        for &id in F::V::inventory_packet_ids(e.inventory_mut()) {
            filter.insert(id);
        }
        for r in sc["loaded_chunks"].as_array().unwrap() {
            let r: Vec<i32> = (0..4).map(|k| i(&r[k])).collect();
            for x in r[0]..=r[2] {
                for z in r[1]..=r[3] {
                    e.sim.world_packet(&F::chunk(x, z)).unwrap();
                }
            }
        }
        F::fill_world(&mut e, &sc, &filter);
        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()
        }));
        F::set_player(&mut e, &sc, &ticks[0]);
        e.core.ready = true;
        e.outbound().clear();
        let t0 = Instant::now();
        let mut teleport_id = 0;
        for (k, rec) in ticks.iter().enumerate().skip(1) {
            let input = &rec["input"];
            let mut leave = false;
            for ev in input["events"].as_array().into_iter().flatten() {
                match ev["type"].as_str().unwrap() {
                    "teleport" => {
                        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"]),
                            teleport_id: F::TELEPORT_IDS.then_some(teleport_id),
                            ..Default::default()
                        }));
                    }
                    "leave_bed" => leave = true,
                    _ => feed::<F>(&mut e, &filter, &F::packet(ev)),
                }
            }
            let keys = input["keys"].as_str().unwrap();
            let has = |k: &str| keys.split(',').any(|n| n == k);
            let mut b = Keys {
                controls: Controls {
                    forward: has("forward"),
                    back: has("back"),
                    left: has("left"),
                    right: has("right"),
                    jump: has("jump"),
                    sneak: has("sneak"),
                    sprint: has("sprint"),
                },
                leave,
            };
            let sleep = &rec["sleep"];
            let asleep = sleep["sleeping"].as_bool().unwrap();
            // The sleep screen holds the mouse: the case's look applies only while awake.
            if !asleep {
                e.core.forced_look = Some((f32v(&input["yaw"]), f32v(&input["pitch"])));
            }
            e.note_inbound(t0);
            e.tick(&mut b, t0);
            let out = std::mem::take(e.outbound());
            let got: Vec<Value> = out.iter().filter_map(ours).collect();
            let want: Vec<Value> = rec["packets"]
                .as_array()
                .unwrap()
                .iter()
                .filter_map(theirs)
                .collect();
            let st = &rec["state"];
            let (p, bb, vel, yaw, pitch) = F::state(&e.sim);
            let want_p = [0, 1, 2].map(|j| f64v(&st["pos"][j]));
            let want_bb = [0, 1, 2, 3, 4, 5].map(|j| f64v(&st["bb"][j]));
            let want_v = [0, 1, 2].map(|j| f64v(&st["vel"][j]));
            let want_look = (f32v(&st["yaw"]), f32v(&st["pitch"]));
            let eye = f64::from(f32v(&sleep["eye_height"]));
            let mut diffs = Vec::new();
            if got != want {
                diffs.push(format!("packets {got:?} want {want:?}"));
            }
            if p != want_p {
                diffs.push(format!("pos {p:?} want {want_p:?}"));
            }
            if bb != want_bb {
                diffs.push(format!("box {bb:?} want {want_bb:?}"));
            }
            if vel != want_v {
                diffs.push(format!("vel {vel:?} want {want_v:?}"));
            }
            if (yaw, pitch) != want_look {
                diffs.push(format!("look {:?} want {want_look:?}", (yaw, pitch)));
            }
            if e.core.sleeping.is_some() != asleep {
                diffs.push(format!("sleeping {:?} want {asleep}", e.core.sleeping));
            }
            if asleep {
                let timer = i(&sleep["timer"]);
                if i32::from(e.core.sleep_ticks) != timer {
                    diffs.push(format!("timer {} want {timer}", e.core.sleep_ticks));
                }
                if e.sim.eye_height() != Some(eye) {
                    diffs.push(format!("eye height {:?} want {eye}", e.sim.eye_height()));
                }
            } else if e.sim.eye_height().is_some_and(|h| h != eye) {
                diffs.push(format!("eye height {:?} want {eye}", e.sim.eye_height()));
            }
            if !diffs.is_empty() {
                failed.push(format!("{name} tick {k}: {}", diffs.join("; ")));
                break;
            }
            ticks_done += 1;
        }
    }
    eprintln!(
        "{path}: {cases} cases, {ticks_done} ticks identical, {} cases differ",
        failed.len()
    );
    (cases, ticks_done, failed)
}

fn check<F: Fixture>(version: &str) {
    let path = format!(
        "{}/../../tests/golden/{version}/sleep.jsonl.gz",
        env!("CARGO_MANIFEST_DIR")
    );
    let (cases, ticks, failed) = replay::<F>(&path);
    assert!(
        failed.is_empty(),
        "{} of {cases} cases differ:\n{}",
        failed.len(),
        failed.join("\n")
    );
    assert!(cases >= 10 && ticks > 300, "{cases} cases, {ticks} ticks");
}

// ---- 1.8.9 ----

struct F18;

impl Fixture for F18 {
    type V = crate::version::V1_8;
    type S = crate::sim::Sim18;
    const TELEPORT_IDS: bool = false;
    fn sim() -> Self::S {
        crate::sim::Sim18::new()
    }
    fn login() -> Option<RawPacket> {
        // entity id, game mode, dimension, difficulty, max players, level type, reduced debug
        let mut b = ME.to_be_bytes().to_vec();
        b.extend_from_slice(&[0, 0, 1, 20, 4]);
        b.extend_from_slice(b"flat");
        b.push(0);
        Some(RawPacket {
            id: ghast_protocol::v1_8::play::clientbound::id::LOGIN,
            body: bytes::Bytes::from(b),
        })
    }
    fn chunk(x: i32, z: i32) -> RawPacket {
        crate::sim::test_chunks::v1_8(x, z)
    }
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
        let st = ghast_data::v1_8::BlockState::from_raw_vanilla(
            ((i(&fill[6]) as u16) << 4) | (i(&fill[7]) as u16 & 15),
        );
        s.test_set_block(x, y, z, st);
    }
    fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
        let p = crate::phys_golden::player_of(sc, t0);
        let mut pose = e.core.pose;
        e.sim.test_set_player(&mut pose, p);
        e.core.pose = pose;
    }
    fn packet(ev: &Value) -> RawPacket {
        use ghast_protocol::v1_8::play::clientbound as cb;
        match ev["type"].as_str().unwrap() {
            "bed" => RawPacket::from_packet(&cb::Bed {
                entity_id: ME,
                location: pos(&ev["pos"]),
            }),
            "wake" => RawPacket::from_packet(&cb::Animation {
                entity_id: ME,
                animation: 2,
            }),
            "block" => RawPacket::from_packet(&cb::BlockChange {
                location: pos(&ev["pos"]),
                r#type: i(&ev["id"]) << 4 | i(&ev["meta"]),
            }),
            "velocity" => RawPacket::from_packet(&cb::EntityVelocity {
                entity_id: ME,
                velocity: ghast_protocol::v1_8::types::Vec3i16 {
                    x: i(&ev["x"]) as i16,
                    y: i(&ev["y"]) as i16,
                    z: i(&ev["z"]) as i16,
                },
            }),
            other => panic!("event {other}"),
        }
        .unwrap()
    }
    fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
        let p = s.test_player();
        let b = p.bb;
        (
            p.pos,
            [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
            p.vel,
            p.yaw,
            p.pitch,
        )
    }
}

// ---- 1.12.2 ----

struct F112;

impl Fixture for F112 {
    type V = crate::version::V1_12_2;
    type S = crate::sim::Sim12;
    fn sim() -> Self::S {
        crate::sim::Sim12::new()
    }
    fn login() -> Option<RawPacket> {
        // entity id, game mode, dimension (int), difficulty, max players, level type, reduced
        // debug
        let mut b = ME.to_be_bytes().to_vec();
        b.push(0);
        b.extend_from_slice(&0i32.to_be_bytes());
        b.extend_from_slice(&[1, 20, 4]);
        b.extend_from_slice(b"flat");
        b.push(0);
        Some(RawPacket {
            id: ghast_protocol::v1_12_2::play::clientbound::id::LOGIN,
            body: bytes::Bytes::from(b),
        })
    }
    fn chunk(x: i32, z: i32) -> RawPacket {
        crate::sim::test_chunks::v1_12_2(x, z)
    }
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
        let st = ghast_data::v1_12::BlockState::from_raw_vanilla(
            ((i(&fill[6]) as u16) << 4) | (i(&fill[7]) as u16 & 15),
        );
        s.test_set_block(x, y, z, st);
    }
    fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
        let mut p = crate::phys_golden::v112::player_of(sc, t0);
        p.added_to_chunk = true;
        e.sim.test_set_player(p);
        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;
    }
    fn packet(ev: &Value) -> RawPacket {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        match ev["type"].as_str().unwrap() {
            "bed" => RawPacket::from_packet(&cb::Bed {
                entity_id: ME,
                location: pos(&ev["pos"]),
            }),
            "wake" => RawPacket::from_packet(&cb::Animation {
                entity_id: ME,
                animation: 2,
            }),
            "block" => RawPacket::from_packet(&cb::BlockChange {
                location: pos(&ev["pos"]),
                r#type: i(&ev["id"]) << 4 | i(&ev["meta"]),
            }),
            "velocity" => RawPacket::from_packet(&cb::EntityVelocity {
                entity_id: ME,
                velocity: ghast_protocol::v1_12_2::types::Vec3i16 {
                    x: i(&ev["x"]) as i16,
                    y: i(&ev["y"]) as i16,
                    z: i(&ev["z"]) as i16,
                },
            }),
            other => panic!("event {other}"),
        }
        .unwrap()
    }
    fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
        let p = s.test_player();
        let b = p.bb;
        (
            p.pos,
            [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
            p.vel,
            p.yaw,
            p.pitch,
        )
    }
}

/// 1.12.2: the 1.8.9 cases (the bed's bounce shows while the sleeper lands on it).
#[test]
fn sleep_matches_the_oracle_1_12_2() {
    check::<F112>("1.12.2");
}

// ---- 1.16.5 ----

/// Our entity data of a sleep (`Some(bed)`) or wake-up (`None`) as the server's
/// `LivingEntity.sleep` / `wakeUp` dirty it: the pose (index 6, `SLEEPING` / `STANDING`) and
/// the sleeping position (1.16.5: index 13, serializer 10; 26.x: index 14, serializer 11).
fn sleep_data(
    id: i32,
    pos_index: u8,
    pos_type: i32,
    pose_type: i32,
    bed: Option<ghast_protocol::BlockPos>,
) -> RawPacket {
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    let mut b = bytes::BytesMut::new();
    b.put_varint(ME);
    b.put_u8(6);
    b.put_varint(pose_type);
    b.put_varint(if bed.is_some() { 2 } else { 0 });
    b.put_u8(pos_index);
    b.put_varint(pos_type);
    match bed {
        Some(p) => {
            b.put_u8(1);
            let x = (i64::from(p.x) & 0x3ff_ffff) << 38;
            let z = (i64::from(p.z) & 0x3ff_ffff) << 12;
            b.put_i64(x | z | (i64::from(p.y) & 0xfff));
        }
        None => b.put_u8(0),
    }
    b.put_u8(0xff);
    RawPacket::new(id, b.freeze())
}

struct F116;

impl Fixture for F116 {
    type V = crate::version::V1_16_5;
    type S = crate::sim::Sim16;
    fn sim() -> Self::S {
        crate::sim::Sim16::new()
    }
    fn chunk(x: i32, z: i32) -> RawPacket {
        crate::sim::test_chunks::v1_16_5(x, z)
    }
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
        let st = ghast_data::v1_16_5::BlockState::from_id(i(&fill[6]) as u16).unwrap();
        s.test_set_block(x, y, z, st);
    }
    fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
        let p = crate::phys_golden::v116::player_of(sc, t0);
        e.sim.test_set_player(p);
        e.core.pose.pos = Vec3::new(p.pos[0], p.pos[1], p.pos[2]);
        e.core.pose.yaw = p.yaw;
        e.core.pose.pitch = p.pitch;
    }
    fn packet(ev: &Value) -> RawPacket {
        use ghast_protocol::v1_16_5::play::clientbound as cb;
        match ev["type"].as_str().unwrap() {
            "bed" => sleep_data(cb::id::ENTITY_METADATA, 13, 10, 18, Some(pos(&ev["pos"]))),
            "wake" => sleep_data(cb::id::ENTITY_METADATA, 13, 10, 18, None),
            "block" => RawPacket::from_packet(&cb::BlockChange {
                location: pos(&ev["pos"]),
                r#type: i(&ev["state"]),
            })
            .unwrap(),
            "velocity" => RawPacket::from_packet(&cb::EntityVelocity {
                entity_id: ME,
                velocity: ghast_protocol::v1_16_5::types::Vec3i16 {
                    x: i(&ev["x"]) as i16,
                    y: i(&ev["y"]) as i16,
                    z: i(&ev["z"]) as i16,
                },
            })
            .unwrap(),
            other => panic!("event {other}"),
        }
    }
    fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
        let p = s.test_player();
        let b = p.bb;
        (
            p.pos,
            [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
            p.vel,
            p.yaw,
            p.pitch,
        )
    }
}

/// 1.16.5: the same cases through our entity data (pose and sleeping position).
#[test]
fn sleep_matches_the_oracle_1_16_5() {
    check::<F116>("1.16.5");
}

// ---- 26.x ----

/// A 26.x fixture: `$f` the type, `$v` the version marker, `$s` the sim, `$proto` / `$data` /
/// `$chunk` the row's crates.
macro_rules! modern_fixture {
    ($f:ident, $v:ty, $s:ty, $proto:ident, $data:ident, $chunk:ident) => {
        struct $f;

        impl Fixture for $f {
            type V = $v;
            type S = $s;
            fn sim() -> Self::S {
                <$s>::test_overworld()
            }
            fn chunk(x: i32, z: i32) -> RawPacket {
                crate::sim::test_chunks::$chunk(x, z)
            }
            fn set_block(_: &mut Self::S, _: i32, _: i32, _: i32, _: &Value) {
                unreachable!("26.x blocks arrive as block updates")
            }
            fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
                let p = crate::phys_golden::v261::player_of(sc, t0);
                e.sim
                    .test_set_modern(p, crate::phys_golden::v261::ext_of(sc, t0));
                e.core.pose.pos = Vec3::new(p.pos[0], p.pos[1], p.pos[2]);
                e.core.pose.yaw = p.yaw;
                e.core.pose.pitch = p.pitch;
                e.core.level_load_started = true;
                e.core.client_loaded = true;
            }
            fn packet(ev: &Value) -> RawPacket {
                use ghast_protocol::$proto::play::clientbound as cb;
                match ev["type"].as_str().unwrap() {
                    "bed" => sleep_data(cb::id::ENTITY_METADATA, 14, 11, 20, Some(pos(&ev["pos"]))),
                    "wake" => sleep_data(cb::id::ENTITY_METADATA, 14, 11, 20, None),
                    "block" => RawPacket::from_packet(&cb::BlockChange {
                        location: pos(&ev["pos"]),
                        r#type: i(&ev["state"]),
                    })
                    .unwrap(),
                    "velocity" => RawPacket::from_packet(&cb::EntityVelocity {
                        entity_id: ME,
                        velocity: ghast_protocol::types::LpVec3::from_vec3(
                            ["x", "y", "z"].map(|k| f64::from(i(&ev[k])) / 8000.0),
                        ),
                    })
                    .unwrap(),
                    other => panic!("event {other}"),
                }
            }
            fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
                let p = s.modern_player().unwrap();
                let b = p.bb;
                (
                    p.pos,
                    [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
                    p.vel,
                    p.yaw,
                    p.pitch,
                )
            }
            fn fill_world(e: &mut Engine<Self::S>, sc: &Value, filter: &PacketFilter) {
                // The stone layer y 63 is the test chunks' own; the other fills as block
                // updates.
                for fill in sc["fills"].as_array().unwrap() {
                    let v: Vec<i32> = (0..7).map(|k| i(&fill[k])).collect();
                    let state = sc["states"][v[6].to_string()].as_str().unwrap();
                    if state == "minecraft:stone" && v[1] == 63 && v[4] == 63 {
                        continue;
                    }
                    let id = ghast_data::$data::BlockState::parse(
                        state.strip_prefix("minecraft:").unwrap_or(state),
                    )
                    .or_else(|| ghast_data::$data::BlockState::parse(state))
                    .unwrap()
                    .id();
                    for x in v[0]..=v[3] {
                        for y in v[1]..=v[4] {
                            for z in v[2]..=v[5] {
                                let ev = serde_json::json!({
                                    "type": "block", "pos": [x, y, z], "state": id
                                });
                                feed::<Self>(e, filter, &Self::packet(&ev));
                            }
                        }
                    }
                }
            }
        }
    };
}

modern_fixture!(
    F261,
    crate::version::V26_1,
    crate::sim::Sim26,
    v26_1,
    v26_1,
    v26_1
);
modern_fixture!(
    F262,
    crate::version::V26_2,
    crate::sim::Sim262,
    v26_2,
    v26_2,
    v26_2
);
modern_fixture!(
    F263,
    crate::version::V26_3,
    crate::sim::Sim263,
    v26_3,
    v26_3,
    v26_3
);

/// 26.1: the legacy cases plus a sleeping position without a bed (26.1 / 26.2 put the player
/// at the block's centre + 0.6875 anyway).
#[test]
fn sleep_matches_the_oracle_26_1() {
    check::<F261>("26.1");
}

/// 26.2: as 26.1.
#[test]
fn sleep_matches_the_oracle_26_2() {
    check::<F262>("26.2");
}

/// 26.3: as 26.1, but without a bed the player is not moved.
#[test]
fn sleep_matches_the_oracle_26_3() {
    check::<F263>("26.3");
}

/// 1.8.9: asleep in a bed facing each way (with and without walls at head height), keys held,
/// a server push, the wake-up with the server's position packet, the leave-bed action, the
/// bed broken under the sleeper, the full sleep timer.
#[test]
fn sleep_matches_the_oracle_1_8_9() {
    check::<F18>("1.8.9");
}