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
//! The deterministic client core: game state, the behaviour contract and the tick.
//!
//! No I/O and no clock here: the connection feeds decoded [`Inbound`] packets and the time
//! in, and takes the [`Outbound`] packets out, so the tick order can be tested without a
//! socket.
//!
//! # Tick model
//!
//! Mirrors 1.8.9 `MinecraftClient.tick` as recorded in vanilla-client packet traces (and is the same
//! in 1.16.5):
//!
//! 1. inbound packets that arrived since the last tick have been applied (on arrival, like
//!    vanilla's per-frame task queue; keep-alives, teleports and window confirms are
//!    answered then);
//! 2. [`Behavior::tick`] runs. Actions (`chat`, `select_slot`, `swing`, `respawn`, …) are
//!    written immediately, in call order, before this tick's movement packet;
//!    [`TickContext::set_aim`] / [`TickContext::set_controls`] only record intent;
//! 3. held slot sync → rotation step (whole mouse counts) → movement step → sprint change →
//!    sneak change → exactly one movement packet.
//!
//! The server therefore judges this tick's actions with the *previous* tick's sent pose
//! ([`TickContext::sent`]).
//!
//! # Files
//!
//! This file holds the core's state (`Core`, `CoreOptions`, `Engine`) and the engine's
//! surface for the connection; the rest is split by topic: `behavior.rs` (the contract),
//! `events.rs` ([`TickEvents`]), `inbound.rs` (`Engine::handle`), `tick.rs`
//! (`Engine::tick_with`), `context.rs`, `windows.rs` and `actions.rs` ([`TickContext`]),
//! `view.rs` ([`TickView`]), `items.rs` (the client's own item effects), `pick.rs` (the
//! crosshair), `creative.rs` (legacy creative inventory actions) and `tests/`.

use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::common::{
    Abilities, ChatMessage, ClientSettings, Controls, GameMode, Health, Inbound, MovePacket,
    Outbound, Pose, Vec3,
};
use crate::hands::{self, BlockHit, Buttons, DigFactors, Hands, HandsIo};
use crate::interest::Interests;
use crate::rotation::Rotation;
use crate::sim::{Crosshair, PickQuery, Sim, WorldView};
use crate::version::{Capabilities, GameVersion};

mod actions;
mod behavior;
mod context;
mod cooldowns;
mod creative;
mod events;
mod inbound;
mod items;
mod pick;
mod tick;
mod view;
mod windows;

pub use self::behavior::{Behavior, ClickRefused, ClickTicket, Idle};
pub use self::context::TickContext;
pub use self::events::{RawInbound, TeleportEvent, TickEvents};
pub(crate) use self::pick::legacy_pick_margin;
pub use self::view::TickView;
// The topic files share one namespace: each starts with `use super::*`.
use self::cooldowns::*;
use self::events::*;
use self::inbound::*;
use self::items::*;
use self::pick::*;
use self::tick::*;

/// Pending chat messages kept for the behaviour; more are dropped (and counted) while the
/// behaviour is not ticking.
const MAX_PENDING_CHAT: usize = 512;

/// Tunables of the core.
#[derive(Debug, Clone)]
pub(crate) struct CoreOptions {
    pub name: Arc<str>,
    /// The version's capability row (the core asks it instead of comparing versions).
    pub caps: &'static Capabilities,
    pub settings: ClientSettings,
    pub brand: Option<String>,
    pub sensitivity: f32,
    pub silent_hold: Duration,
    pub inventory: ghast_inventory::Version,
    /// Keep the look still on a tick that dug / placed when the turn would take the
    /// crosshair off the clicked block (Grim RotationPlace re-checks with the next look).
    pub hold_turn_on_action: bool,
    /// Accept server resource packs the server requires (optional ones are declined).
    pub accept_required_packs: bool,
    /// Entities push the player (vanilla: on; off is the non-vanilla opt-in of
    /// [`crate::Client::entity_push`]).
    pub entity_push: bool,
    /// The rotation's cap per tick (yaw, pitch degrees; [`crate::Client::turn_rate`]).
    pub turn_rate: (f64, f64),
    /// A screen releases the movement keys (vanilla; [`crate::Client::gui_releases_keys`]).
    pub gui_releases_keys: bool,
}

/// Client state shared by the connection and the behaviour context.
#[derive(Debug)]
pub(crate) struct Core {
    opts: CoreOptions,
    tick: u64,
    entity_id: i32,
    joined: bool,
    teleported_once: bool,
    ready: bool,
    pose: Pose,
    sent: Pose,
    rotation: Rotation,
    aimed: bool,
    controls: Controls,
    health: Health,
    /// The world's clocks (`update_time`) and the network id of the dimension's day clock.
    clocks: crate::common::Clocks,
    day_clock: Option<i32>,
    dead: bool,
    abilities: Abilities,
    game_mode: GameMode,
    held_slot: u8,
    sent_slot: u8,
    /// The server set the held slot since the last slot sync (its echo is due).
    slot_from_server: bool,
    open_window: i32,
    dimension: String,
    respawn_screen: bool,
    /// The events gathered for the next behaviour tick and the ones it sees, boxed: each tick
    /// swaps them (two pointers, not two large structs).
    pending: Box<TickEvents>,
    current: Box<TickEvents>,
    out: Vec<Outbound>,
    last_inbound: Option<Instant>,
    silent: bool,
    quit: Option<String>,
    status: String,
    hands: Hands,
    buttons: Buttons,
    /// Left presses the behaviour queued for this tick's key handling
    /// ([`TickContext::press`]); consumed (or dropped) there.
    clicks: u8,
    /// Inventory and windows (ghast-inventory).
    inv: ghast_inventory::Inventory,
    /// The look changed in the last movement step (window clicks need a still player).
    turned: bool,
    /// Our active status effects: id → amplifier.
    effects: std::collections::BTreeMap<i8, i8>,
    /// Our active status effects with durations ([`TickContext::effects`]).
    active_effects: Vec<crate::common::ActiveEffect>,
    /// The world's spawn point (`spawn_position`).
    spawn_point: Option<crate::common::SpawnPoint>,
    /// The tick of our last hurt (status or damage event; [`TickContext::last_hurt_tick`]).
    last_hurt: Option<u64>,
    /// The scoreboard teams (with [`Interests::TEAMS`]).
    teams: Option<Box<crate::teams::Teams>>,
    /// The HUD (with [`Interests::HUD`]).
    hud: Option<Box<crate::hud::Hud>>,
    /// Chat messages are reported ([`Interests::CHAT`]; read only while the HUD is on, which
    /// decodes action bar chat for itself).
    chat_events: bool,
    /// Tab-completion requests and their answers.
    tabs: crate::hud::TabCompleter,
    /// Aqua affinity on the helmet (dig speed under water).
    aqua_affinity: bool,
    /// Blocks broken on the client this tick (predicted air until the server answers).
    broken_now: Vec<ghast_protocol::BlockPos>,
    /// The crosshair pick's entity list (kept to reuse the allocation).
    pick: PickList,
    /// Flight wanted by the behaviour this tick ([`TickContext::set_flying`]).
    want_flying: Option<bool>,
    /// Turns held back because they would have moved the crosshair off a clicked block.
    held_turns: u64,
    /// Arm swings (main and off hand) written in finished ticks.
    swings: u64,
    /// 1.21.4+ level loading: the server said the level's chunks are coming (game event 13).
    level_load_started: bool,
    /// 1.21.4+: `player_loaded` was sent for the current level.
    client_loaded: bool,
    /// 1.19.3+ signed chat: a chat session is ready to be announced (`setKeyPair`).
    chat_session_due: bool,
    /// 1.21.4+: this tick sent `player_loaded` (no mouse turn on it).
    gate_tick: bool,
    /// Test hook: the level-load gate's "section compiled" / "timed out" inputs.
    #[cfg(test)]
    test_gate: Option<(bool, bool)>,
    /// Ticks spent waiting for the level (vanilla lets the player in after 30 s).
    load_wait: u32,
    /// Consecutive ticks the 3x3 columns around the player have been loaded (vanilla compiles
    /// the player's section only then, and sees it compiled a tick later at the earliest).
    near_loaded: u8,
    /// Time origin for nanosecond timestamps (chunk batch timing).
    origin: Instant,
    /// Entities push the player ([`TickContext::set_entity_push`]).
    entity_push: bool,
    /// The switch as the sim has it.
    entity_push_sim: bool,
    /// The dialog open now (26.1+ `show_dialog`).
    dialog: Option<Arc<crate::dialog::Dialog>>,
    /// The sign editor open now (`open_sign_entity`).
    sign: Option<crate::sign::OpenSign>,
    /// The bed the player sleeps in (`PlayerEntity.isSleeping`).
    sleeping: Option<ghast_protocol::BlockPos>,
    /// `PlayerEntity.sleepTimer` / `Player.sleepCounter` (0 – 100 while asleep).
    sleep_ticks: u8,
    /// A sign editor is open, the player sleeps or is dead (`sign` or `sleeping` is set, or
    /// `dead`; [`Core::update_rare`]): the one flag the tick tests for all three, so a living
    /// bot that does none of them pays one branch where it would test each.
    rare: bool,
    /// The keys held in the first movement step of the own inventory screen opened last
    /// ([`Capabilities::own_inventory_passes_keys`]; still released until let go once).
    screen_keys: Option<Controls>,
    /// Dialog events since the behaviour's last tick, and those of its current tick (kept out
    /// of [`TickEvents`]: almost always empty, they cost nothing per tick this way).
    dialogs_pending: Vec<crate::dialog::DialogEvent>,
    dialogs: Vec<crate::dialog::DialogEvent>,
    /// The wire's block-prediction sequence after the last packets written (1.19+).
    sequence: Option<i32>,
    /// Test hook: this tick's look, set instead of a rotation step.
    #[cfg(test)]
    forced_look: Option<(f32, f32)>,
    /// Test hook: `forced_look` is where this tick's turn lands (set with `aimed`), instead of
    /// a rotation step: the look reaches the tick at the aim's turn point, not before the
    /// behaviour's actions. A flag on `forced_look` (one test on the tick, not two).
    #[cfg(test)]
    forced_aim: bool,
    /// 1.9+: our `attack_speed` attribute as the server synced it (the attack strength).
    /// The held slot and its server write count when the item use in progress was first
    /// seen ([`Capabilities::use_stop`]): use serial, then the hand's slot (255: off hand)
    /// and its server write count, or (0, item id).
    /// 1.9+: the held stack's (item, damage) as the last player tick saw it (the attack
    /// cooldown resets when it changes, [`Capabilities::cooldown_reset`]).
    cooldown_held: (i32, i16),
    /// 1.9+ item cooldowns ([`crate::cooldown`]).
    pub(crate) cooldowns: crate::cooldown::ItemCooldowns,
    use_mark: Option<(u32, u8, u16)>,
    /// 1.8: the head yaw the last movement step left (the key handling's pick turns with it,
    /// [`Capabilities::pick_head_yaw`]); `None` before the first step.
    head_yaw: Option<f32>,
    attack_speed: f64,
}

/// Behaviour bookkeeping of the engine.
#[derive(Debug, Default)]
struct BehaviorState {
    started: bool,
    failed: bool,
    /// The behaviour reported [`Behavior::running`] `false`.
    done: bool,
}

/// The core plus the behaviour's lifecycle.
#[derive(Debug)]
pub(crate) struct Engine<S> {
    pub core: Core,
    pub sim: S,
    state: BehaviorState,
}

impl Core {
    /// Stamps the entity store's clock for the packets that arrive before the next tick (the
    /// tick in which the behaviour sees them).
    #[inline]
    fn stamp_entities(&self, sim: &mut (impl Sim + ?Sized)) {
        if let Some(s) = sim.entities_mut() {
            s.set_tick(self.tick + 1);
        }
    }

    fn new(opts: CoreOptions) -> Self {
        let rotation =
            Rotation::new(opts.sensitivity).with_turn_rate(opts.turn_rate.0, opts.turn_rate.1);
        // a version module exists only with its feature, which enables its inventory
        let inv = ghast_inventory::Inventory::new(opts.inventory)
            .expect("the version's feature enables its ghast-inventory feature");
        let entity_push = opts.entity_push;
        Core {
            opts,
            tick: 0,
            entity_id: 0,
            joined: false,
            teleported_once: false,
            ready: false,
            pose: Pose::default(),
            sent: Pose::default(),
            rotation,
            aimed: false,
            controls: Controls::default(),
            health: Health::default(),
            clocks: crate::common::Clocks::default(),
            day_clock: None,
            dead: false,
            abilities: Abilities::default(),
            game_mode: GameMode::default(),
            held_slot: 0,
            sent_slot: 0,
            slot_from_server: false,
            open_window: 0,
            dimension: String::new(),
            respawn_screen: true,
            pending: Box::default(),
            current: Box::default(),
            out: Vec::with_capacity(16),
            last_inbound: None,
            silent: false,
            quit: None,
            status: String::new(),
            hands: Hands::default(),
            buttons: Buttons::default(),
            clicks: 0,
            inv,
            turned: false,
            effects: std::collections::BTreeMap::new(),
            active_effects: Vec::new(),
            spawn_point: None,
            last_hurt: None,
            teams: None,
            hud: None,
            chat_events: true,
            tabs: crate::hud::TabCompleter::default(),
            cooldown_held: (-1, 0),
            cooldowns: crate::cooldown::ItemCooldowns::default(),
            use_mark: None,
            head_yaw: None,
            attack_speed: 4.0,
            aqua_affinity: false,
            broken_now: Vec::new(),
            pick: PickList::default(),
            want_flying: None,
            held_turns: 0,
            swings: 0,
            level_load_started: false,
            client_loaded: false,
            chat_session_due: false,
            gate_tick: false,
            #[cfg(test)]
            test_gate: None,
            load_wait: 0,
            near_loaded: 0,
            origin: Instant::now(),
            entity_push,
            entity_push_sim: entity_push,
            dialog: None,
            sign: None,
            sleeping: None,
            sleep_ticks: 0,
            rare: false,
            screen_keys: None,
            dialogs_pending: Vec::new(),
            dialogs: Vec::new(),
            sequence: None,
            #[cfg(test)]
            forced_look: None,
            #[cfg(test)]
            forced_aim: false,
        }
    }

    /// Recomputes [`Core::rare`] after `sign`, `sleeping` or `dead` changed.
    #[inline]
    pub(super) fn update_rare(&mut self) {
        self.rare = self.sign.is_some() || self.sleeping.is_some() || self.dead;
    }

    /// A new client player entity (join, respawn): `lastReported*` zero, nothing held down,
    /// waiting for the server's position.
    fn reset_player(&mut self, why: &str) {
        self.teleported_once = false;
        self.ready = false;
        self.pose = Pose::default();
        self.sent = Pose::default();
        self.controls = Controls::default();
        self.aimed = false;
        self.open_window = 0;
        self.dead = false;
        self.update_rare();
        self.hands.reset();
        // a new player entity has a new cooldown manager
        self.cooldowns.clear();
        self.buttons = Buttons::default();
        self.effects.clear();
        if !self.active_effects.is_empty() {
            self.active_effects.clear();
            self.pending
                .more()
                .effects
                .push(crate::common::EffectEvent::Cleared);
        }
        self.last_hurt = None;
        // A new level waits for its chunks again (1.21.4+ LevelLoadTracker).
        self.level_load_started = false;
        self.client_loaded = false;
        self.load_wait = 0;
        self.near_loaded = 0;
        log::debug!(
            "[{}] t{} {why}: waiting for the server position",
            self.opts.name,
            self.tick
        );
    }

    /// The last inbound time in nanoseconds from the core's origin.
    fn now_nanos(&self) -> i64 {
        self.last_inbound.map_or(0, |t| {
            t.saturating_duration_since(self.origin).as_nanos() as i64
        })
    }

    fn column_loaded(&self, world: &dyn WorldView) -> bool {
        // BlockPos(posX, 0, posZ) floors the coordinates.
        let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
        let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
        world.is_column_loaded(cx, cz)
    }

    /// The player's column and its 8 neighbours are loaded (`RenderSection.hasAllNeighbors`:
    /// the condition for vanilla's first compile of the player's section).
    fn neighbourhood_loaded(&self, world: &dyn WorldView) -> bool {
        let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
        let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
        (-1..=1).all(|dx| (-1..=1).all(|dz| world.is_column_loaded(cx + dx, cz + dz)))
    }
}

#[cfg(all(test, feature = "v1_8"))]
impl Core {
    /// Test hook: the held slot as both the client and the server have it (no sync packet).
    pub(crate) fn test_set_slot(&mut self, slot: u8) {
        self.held_slot = slot;
        self.sent_slot = slot;
        self.inv.select(slot);
    }

    /// Test hook: the pose and the sent pose.
    pub(crate) fn test_poses(&mut self) -> (&mut Pose, &mut Pose) {
        (&mut self.pose, &mut self.sent)
    }

    /// Test hook: turns held back by the post-look check.
    pub(crate) fn test_held_turns(&self) -> u64 {
        self.held_turns
    }
}

impl<S: Sim> Engine<S> {
    pub(crate) fn new(opts: CoreOptions, mut sim: S) -> Self {
        sim.set_entity_push(opts.entity_push);
        Engine {
            core: Core::new(opts),
            sim,
            state: BehaviorState::default(),
        }
    }

    /// A chat session was started in the wire layer: announce it on the next tick, from the
    /// connection tick like vanilla (`ClientPacketListener.tick` → `setKeyPair`).
    pub(crate) fn request_chat_session(&mut self) {
        self.core.chat_session_due = true;
    }

    /// A join game arrived and no reconfiguration dropped the level since.
    pub(crate) fn joined(&self) -> bool {
        self.core.joined
    }

    /// Bytes arrived from the server (liveness for the silent-server guard).
    pub(crate) fn note_inbound(&mut self, now: Instant) {
        self.core.last_inbound = Some(now);
    }

    /// Time of the last inbound bytes.
    pub(crate) fn last_inbound(&self) -> Option<Instant> {
        self.core.last_inbound
    }

    /// Keeps the scoreboard teams from now on ([`Interests::TEAMS`]; off frees them).
    pub(crate) fn track_teams(&mut self, on: bool) {
        if on != self.core.teams.is_some() {
            self.core.teams = on.then(Box::default);
        }
    }

    /// Keeps the HUD from now on ([`Interests::HUD`]; off frees it); `chat`: the behaviour
    /// wants chat messages ([`Interests::CHAT`]).
    pub(crate) fn track_hud(&mut self, on: bool, chat: bool) {
        if on != self.core.hud.is_some() {
            self.core.hud = on.then(Box::default);
        }
        self.core.chat_events = chat;
    }

    /// The wire layer's prediction sequence after writing packets.
    pub(crate) fn note_sequence(&mut self, sequence: Option<i32>) {
        self.core.sequence = sequence;
    }

    /// After a world packet: a prediction answer that moved the player back
    /// ([`Sim::take_snap`]) moves the engine's pose with it.
    #[inline]
    pub(crate) fn sync_snap(&mut self) {
        if let Some(p) = self.sim.take_snap() {
            log::debug!(
                "[{}] t{} moved back to {:.3} {:.3} {:.3}: a restored block holds the player",
                self.core.opts.name,
                self.core.tick,
                p.x,
                p.y,
                p.z
            );
            self.core.pose.pos = p;
        }
    }

    /// The bot's name (for logs).
    pub(crate) fn name(&self) -> &str {
        &self.core.opts.name
    }

    /// Queues a raw packet copy for the behaviour's next tick.
    pub(crate) fn push_raw(&mut self, p: RawInbound) {
        let ev = &mut self.core.pending;
        if ev.raw.len() < MAX_PENDING_RAW {
            ev.raw.push(p);
        } else {
            ev.raw_dropped += 1;
        }
    }

    /// The raw packet ids the behaviour wants (none once it failed or finished).
    pub(crate) fn raw_packets<B: Behavior>(&self, b: &B) -> std::borrow::Cow<'static, [i32]> {
        if self.state.failed || self.state.done {
            std::borrow::Cow::Borrowed(&[])
        } else {
            b.raw_packets(self.core.opts.caps.version)
        }
    }

    /// The inventory (the connection feeds it its packets).
    pub(crate) fn inventory_mut(&mut self) -> &mut ghast_inventory::Inventory {
        &mut self.core.inv
    }

    /// An inventory packet was applied: the sim takes the hands now when it reads them at
    /// packet time (`Sim::hands_at_packet`).
    pub(crate) fn hands_changed(&mut self) {
        self.sim.hands_at_packet(&self.core.inv);
    }

    /// 1.8 – 1.16.5: the inventory has just opened the mount screen of entity `entity_id`; its
    /// slot rules are read off the tracked entity when the sim can (a behaviour's
    /// `TickContext::set_mount_rules` later still wins).
    pub(crate) fn mount_screen_opened(&mut self, entity_id: i32) {
        if let Some(r) = self.sim.mount_rules(entity_id) {
            self.core.inv.set_mount_rules(Some(r));
        }
    }

    /// Outbound packets produced since the last call, in send order.
    pub(crate) fn outbound(&mut self) -> &mut Vec<Outbound> {
        &mut self.core.out
    }

    /// Set when the behaviour asked to disconnect.
    pub(crate) fn quit_requested(&self) -> Option<&str> {
        self.core.quit.as_deref()
    }

    pub(crate) fn core_name(&self) -> &str {
        &self.core.opts.name
    }

    /// [`crate::Client::accept_required_resource_packs`].
    pub(crate) fn accept_required_packs(&self) -> bool {
        self.core.opts.accept_required_packs
    }

    pub(crate) fn tick_count(&self) -> u64 {
        self.core.tick
    }
}

/// Test helper: the clientbound packet id `$name` of a modern version (26.2 for any version
/// that is neither 26.1 nor 26.3).
#[cfg(test)]
#[allow(unused_macros)]
macro_rules! modern_cb_id {
    ($v:expr, $name:ident) => {
        match $v {
            crate::version::GameVersion::V26_1 => {
                ghast_protocol::v26_1::play::clientbound::id::$name
            }
            #[cfg(feature = "v26_3")]
            crate::version::GameVersion::V26_3 => {
                ghast_protocol::v26_3::play::clientbound::id::$name
            }
            _ => ghast_protocol::v26_2::play::clientbound::id::$name,
        }
    };
}

/// Test helper: a modern version's entity type id by name (as [`modern_cb_id`]).
#[cfg(test)]
#[allow(unused_macros)]
macro_rules! modern_entity_type {
    ($v:expr, $name:expr) => {
        match $v {
            crate::version::GameVersion::V26_1 => {
                ghast_data::v26_1::entity_by_name($name).unwrap().id
            }
            #[cfg(feature = "v26_3")]
            crate::version::GameVersion::V26_3 => {
                ghast_data::v26_3::entity_by_name($name).unwrap().id
            }
            _ => ghast_data::v26_2::entity_by_name($name).unwrap().id,
        }
    };
}

/// The engine replays of the modern versions' oracle goldens (`tests/modern.rs`), compiled
/// once per version with that version's modules.
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/v26_1.rs"]
mod tests_26_1;

#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2"
))]
#[path = "tests/v26_2.rs"]
mod tests_26_2;

/// The 26.3 engine replays (`tests/v26_3.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_3"
))]
#[path = "tests/v26_3.rs"]
mod tests_26_3;

/// Resource packs and the drop / swap actions on 1.8 – 1.16 (`tests/actions.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/actions.rs"]
mod tests_actions;

/// Attacks' effect on the player, our flags byte, released keys (`tests/combat.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2"
))]
#[path = "tests/combat.rs"]
mod tests_combat;

/// The client view of other entities: drawn-box picks, entity events, clocks
/// (`tests/entities.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2"
))]
#[path = "tests/entities.rs"]
mod tests_entities;

/// The bot's own fishing bobber on every version (`tests/fishing.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/fishing.rs"]
mod tests_fishing;
/// The HUD and tab completion on every version (`tests/hud.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2"
))]
#[path = "tests/hud.rs"]
mod tests_hud;

/// The sign editor (and the other screens of the sign / book / bed wave) on every version
/// (`tests/screens.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2"
))]
#[path = "tests/screens.rs"]
mod tests_screens;
/// The sleep goldens through the engine (`tests/sleep.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2",
    feature = "v26_3"
))]
#[path = "tests/sleep.rs"]
mod tests_sleep;

/// The legacy non-living entity physics goldens through the sim (`tests/nonliving_legacy.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "tests/nonliving_legacy.rs"]
mod tests_nonliving_legacy;

/// The player's own effects, absorption, spawn point, hurts and death (`tests/self.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2"
))]
#[path = "tests/self.rs"]
mod tests_self;

/// Armor equips, item use events, click checks, resync signal, press preview
/// (`tests/hands.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1",
    feature = "v26_2"
))]
#[path = "tests/hands.rs"]
mod tests_hands;

/// The legacy attack and item-use goldens through the engine (`tests/combat_legacy.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/combat_legacy.rs"]
mod tests_combat_legacy;

/// The legacy creative mode actions through the engine (`tests/creative.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "tests/creative.rs"]
mod tests_creative;

/// The 1.8.9 piston goldens through the engine (`tests/pistons_1_8.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "tests/pistons_1_8.rs"]
mod tests_pistons_1_8;

/// Mount screen rules read off the tracked entity (`tests/mounts.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "tests/mounts.rs"]
mod tests_mounts;

/// Item cooldowns through the engine (`tests/cooldowns.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "tests/cooldowns.rs"]
mod tests_cooldowns;

/// The world's time on the legacy versions (`tests/time.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "tests/time.rs"]
mod tests_time;

/// The legacy special menus through the open-window path (`tests/menus.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "tests/menus.rs"]
mod tests_menus;

/// `Client::record` on every version (`tests/record.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/record.rs"]
mod tests_record;

/// The engine replay of the 1.12.2 entity goldens (`tests/v1_12.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/v1_12.rs"]
mod tests_1_12;

/// The engine replay of the 1.12.2 living mount goldens (`tests/mounts_1_12.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/mounts_1_12.rs"]
mod tests_mounts_1_12;

/// The engine replay of the 1.8.9 boat goldens (`tests/v1_8.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/v1_8.rs"]
mod tests_1_8;

/// The engine replay of the 1.8.9 living mount goldens (`tests/mounts_1_8.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/mounts_1_8.rs"]
mod tests_mounts_1_8;

/// The engine replay of the 1.16.5 entity goldens (`tests/v1_16_5.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/v1_16_5.rs"]
mod tests_1_16_5;

/// Block predictions and the server's answers (26.x acks, 1.16.5 dig answers).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/predict.rs"]
mod tests_predict;

/// The engine's own tests and the shared test helpers (`tests/general.rs`).
#[cfg(all(
    test,
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    feature = "v26_1"
))]
#[path = "tests/general.rs"]
mod tests;