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
//! Per-version glue between the generated packets of `ghast-protocol` and the common layer.
//!
//! [`ClientVersion`] is implemented for the protocol marker types of the enabled versions
//! (`ghast_protocol::{V1_8, V1_12_2, V1_16_5, V26_1}`).
//! The connection and its tick loop are generic over it, so every hot path is monomorphised
//! per version (no trait objects); the bot API above it only sees [`crate::common`] types.

use std::fmt;
use std::str::FromStr;

use ghast_protocol::{DecodeError, EncodeError, FrameEncoder, PacketFilter, RawPacket, Version};

use crate::common::{
    ConfigInbound, ConfigOutbound, Inbound, LoginInbound, Outbound, Pose, Teleport,
};
use crate::interest::Interests;

mod caps;
#[cfg(ghast_modern)]
mod commands;
#[cfg(feature = "v1_12_2")]
mod v1_12_2;
#[cfg(feature = "v1_16_5")]
mod v1_16_5;
#[cfg(feature = "v1_8")]
mod v1_8;
#[cfg(feature = "v26_1")]
pub(crate) mod v26_1;
#[cfg(feature = "v26_2")]
pub(crate) mod v26_2;
#[cfg(feature = "v26_3")]
pub(crate) mod v26_3;

pub use caps::{
    Capabilities, CooldownReset, DataSet, InvulnerableEating, ItemCooldownRules, ItemModel,
    PhysicsRules, UseStop,
};
#[cfg(feature = "v1_8")]
pub use ghast_protocol::v1_8::V1_8;
#[cfg(feature = "v1_12_2")]
pub use ghast_protocol::v1_12_2::V1_12_2;
#[cfg(feature = "v1_16_5")]
pub use ghast_protocol::v1_16_5::V1_16_5;
#[cfg(feature = "v26_1")]
pub use ghast_protocol::v26_1::V26_1;
#[cfg(feature = "v26_2")]
pub use ghast_protocol::v26_2::V26_2;
#[cfg(feature = "v26_3")]
pub use ghast_protocol::v26_3::V26_3;
#[cfg(feature = "v1_12_2")]
pub use v1_12_2::Wire as Wire1_12;
#[cfg(feature = "v26_1")]
pub use v26_1::Wire as Wire26_1;
#[cfg(feature = "v26_2")]
pub use v26_2::Wire as Wire26_2;
#[cfg(feature = "v26_3")]
pub use v26_3::Wire as Wire26_3;

/// A protocol version the client supports, chosen at run time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GameVersion {
    /// 1.8 – 1.8.9 (protocol 47).
    V1_8_9,
    /// 1.12.2 (protocol 340).
    V1_12_2,
    /// 1.16.4 – 1.16.5 (protocol 754).
    V1_16_5,
    /// 26.1 – 26.1.2 (protocol 775).
    V26_1,
    /// 26.2 (protocol 776).
    V26_2,
    /// 1.12.1 (protocol 338). Served by the 1.12.2 code (feature `v1_12_2`): the wire
    /// differs only in the keep-alive id (a VarInt), the client game code is the same.
    V1_12_1,
    /// 1.16.2 (protocol 751). Served by the 1.16.5 code (feature `v1_16_5`) with its own
    /// handshake number: the packet layouts and the client game code are the same.
    V1_16_2,
    /// 1.16.3 (protocol 753). Served by the 1.16.5 code like [`GameVersion::V1_16_2`].
    V1_16_3,
    /// 26.3 (protocol 777).
    V26_3,
}

impl GameVersion {
    /// Every supported version, oldest first. A slice, so that adding a version is not a
    /// breaking change.
    pub const ALL: &'static [GameVersion] = &[
        GameVersion::V1_8_9,
        GameVersion::V1_12_1,
        GameVersion::V1_12_2,
        GameVersion::V1_16_2,
        GameVersion::V1_16_3,
        GameVersion::V1_16_5,
        GameVersion::V26_1,
        GameVersion::V26_2,
        GameVersion::V26_3,
    ];

    /// What this version can do (the row the client core reads instead of comparing
    /// versions).
    #[must_use]
    pub const fn caps(self) -> &'static Capabilities {
        match self {
            Self::V1_8_9 => &caps::V1_8_9,
            Self::V1_12_2 => &caps::V1_12_2,
            Self::V1_16_5 => &caps::V1_16_5,
            Self::V26_1 => &caps::V26_1,
            Self::V26_2 => &caps::V26_2,
            Self::V26_3 => &caps::V26_3,
            Self::V1_12_1 => &caps::V1_12_1,
            Self::V1_16_2 => &caps::V1_16_2,
            Self::V1_16_3 => &caps::V1_16_3,
        }
    }

    /// The version whose code serves this one: itself, or for a release that differs from
    /// another only in its handshake number (1.16.2, 1.16.3) or its keep-alive width
    /// (1.12.1), that release. The session runs that version's monomorphised instance with
    /// this version's capability row.
    pub(crate) const fn instance(self) -> GameVersion {
        match self {
            Self::V1_12_1 => Self::V1_12_2,
            Self::V1_16_2 | Self::V1_16_3 => Self::V1_16_5,
            v => v,
        }
    }

    /// Whether this build of the library includes the version (its cargo feature is on).
    #[must_use]
    pub const fn enabled(self) -> bool {
        match self {
            Self::V1_8_9 => cfg!(feature = "v1_8"),
            Self::V1_12_2 => cfg!(feature = "v1_12_2"),
            Self::V1_16_5 => cfg!(feature = "v1_16_5"),
            Self::V26_1 => cfg!(feature = "v26_1"),
            Self::V26_2 => cfg!(feature = "v26_2"),
            Self::V26_3 => cfg!(feature = "v26_3"),
            Self::V1_12_1 => cfg!(feature = "v1_12_2"),
            Self::V1_16_2 | Self::V1_16_3 => cfg!(feature = "v1_16_5"),
        }
    }

    /// Protocol number.
    #[must_use]
    pub const fn protocol(self) -> i32 {
        self.caps().protocol
    }

    /// This version's row in the protocol table ([`ghast_protocol::versions`]): module,
    /// feature, every game version sharing the protocol number, wire facts (the row exists
    /// whether or not the version is compiled in; see its `enabled`).
    #[must_use]
    pub fn protocol_info(self) -> &'static ghast_protocol::ProtocolVersion {
        ghast_protocol::versions::by_protocol(self.protocol())
            .expect("every GameVersion has a row in the protocol table")
    }

    /// Display name (`"1.8.9"`, `"1.12.2"`, `"1.16.5"`).
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::V1_8_9 => "1.8.9",
            Self::V1_12_2 => "1.12.2",
            Self::V1_16_5 => "1.16.5",
            Self::V26_1 => "26.1",
            Self::V26_2 => "26.2",
            Self::V26_3 => "26.3",
            Self::V1_12_1 => "1.12.1",
            Self::V1_16_2 => "1.16.2",
            Self::V1_16_3 => "1.16.3",
        }
    }

    /// `true` for 1.9 and later: the attack cooldown, the off hand, swinging after the click,
    /// no 0.1 targeting border on entity boxes ([`Capabilities::combat_1_9`]).
    #[must_use]
    pub const fn combat_1_9(self) -> bool {
        self.caps().combat_1_9
    }

    /// Eye height above the feet while standing ([`Capabilities::eye_height`]).
    #[must_use]
    pub const fn eye_height(self) -> f64 {
        self.caps().eye_height
    }

    /// Eye height while sneaking: 1.54 in 1.8 – 1.12 (`getEyeHeight` − 0.08), 1.27 in 1.16
    /// (the crouching pose) ([`Capabilities::sneak_eye_height`]).
    #[must_use]
    pub const fn sneak_eye_height(self) -> f64 {
        self.caps().sneak_eye_height
    }
}

impl fmt::Display for GameVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// Error parsing a [`GameVersion`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "unsupported Minecraft version `{0}` (supported: 1.8 - 1.8.9, 1.12.1, 1.12.2, 1.16.2 - 1.16.5, 26.1 - 26.1.2, 26.2, 26.3)"
)]
pub struct UnknownVersion(pub String);

impl FromStr for GameVersion {
    type Err = UnknownVersion;

    /// Accepts `1.8`, `1.8.x`, `47`, `1.12.1`, `338`, `1.12.2`, `340`, `1.16.2`, `751`,
    /// `1.16.3`, `753`, `1.16.4`, `1.16.5`, `754`, `26.1`, `26.1.1`, `26.1.2`, `775`, `26.2`,
    /// `776`, `26.3` and `777`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim() {
            "1.8" | "1.8.0" | "1.8.1" | "1.8.2" | "1.8.3" | "1.8.4" | "1.8.5" | "1.8.6"
            | "1.8.7" | "1.8.8" | "1.8.9" | "47" => Ok(Self::V1_8_9),
            "1.12.1" | "338" => Ok(Self::V1_12_1),
            "1.12.2" | "340" => Ok(Self::V1_12_2),
            "1.16.2" | "751" => Ok(Self::V1_16_2),
            "1.16.3" | "753" => Ok(Self::V1_16_3),
            "1.16.4" | "1.16.5" | "754" => Ok(Self::V1_16_5),
            "26.1" | "26.1.0" | "26.1.1" | "26.1.2" | "775" => Ok(Self::V26_1),
            "26.2" | "26.2.0" | "776" => Ok(Self::V26_2),
            "26.3" | "26.3.0" | "777" => Ok(Self::V26_3),
            other => Err(UnknownVersion(other.to_owned())),
        }
    }
}

/// What a protocol version needs to provide to the client.
///
/// Sealed: implemented for the enabled versions' markers (`ghast_protocol::{V1_8, V1_12_2,
/// V1_16_5, V26_1}`) only.
pub trait ClientVersion: Version + sealed::Sealed {
    /// The run-time tag of this version.
    const GAME: GameVersion;
    /// Longest chat line the server accepts, in UTF-16 units (vanilla truncates to it).
    const CHAT_LIMIT: usize;

    /// Queues the handshake packet (next state = login).
    fn write_handshake(enc: &mut FrameEncoder, host: &str, port: u16) -> Result<(), EncodeError>;
    /// Queues the handshake of `version`, a release this version's code serves
    /// ([`GameVersion::V1_16_2`] by 1.16.5's): the same packet with that release's protocol
    /// number. Default: [`ClientVersion::write_handshake`] (versions serving no other).
    #[doc(hidden)]
    fn write_handshake_for(
        enc: &mut FrameEncoder,
        version: GameVersion,
        host: &str,
        port: u16,
    ) -> Result<(), EncodeError> {
        debug_assert_eq!(version.protocol(), Self::GAME.protocol());
        Self::write_handshake(enc, host, port)
    }
    /// Per-connection state of the wire layer (block action sequence numbers, chat
    /// acknowledgements, cookies, 1.12.1's keep-alive width); `()` for versions without any.
    type Wire: Default + fmt::Debug + Send;
    /// The wire state of a connection to `version` (this version or a release its code
    /// serves, see [`ClientVersion::write_handshake_for`]). Default: `Default`.
    #[doc(hidden)]
    fn wire_for(version: GameVersion) -> Self::Wire {
        let _ = version;
        Self::Wire::default()
    }

    /// Queues the login start packet (1.19+ also send the profile id).
    fn write_login_start(
        enc: &mut FrameEncoder,
        username: &str,
        uuid: uuid::Uuid,
    ) -> Result<(), EncodeError>;
    /// Queues the encryption response.
    fn write_encryption_response(
        enc: &mut FrameEncoder,
        shared_secret: &[u8],
        verify_token: &[u8],
    ) -> Result<(), EncodeError>;
    /// Queues a "not understood" answer to a login plugin request.
    fn write_plugin_response(enc: &mut FrameEncoder, message_id: i32) -> Result<(), EncodeError>;
    /// Decodes a login-state packet; `Ok(None)` for packets the client ignores.
    fn decode_login(raw: &RawPacket) -> Result<Option<LoginInbound>, DecodeError>;
    /// Queues the handshake of a connection that follows a server transfer (1.20.5+ intent 3,
    /// `transfer`); older versions have no transfers.
    fn write_transfer_handshake(
        enc: &mut FrameEncoder,
        host: &str,
        port: u16,
    ) -> Result<(), EncodeError> {
        Self::write_handshake(enc, host, port)
    }
    /// The cookies the server stored (carried to a transfer target, vanilla `TransferState`).
    fn take_cookies(
        wire: &mut Self::Wire,
    ) -> Vec<(ghast_protocol::types::ByteString, bytes::Bytes)> {
        let _ = wire;
        Vec::new()
    }
    /// Restores carried cookies into a new connection's wire state.
    fn put_cookies(
        wire: &mut Self::Wire,
        cookies: Vec<(ghast_protocol::types::ByteString, bytes::Bytes)>,
    ) {
        let _ = (wire, cookies);
    }
    /// A login-state cookie answer from the wire's cookies (a transferred connection has the
    /// previous server's); default: [`ClientVersion::write_login_cookie_response`].
    fn write_login_cookie_response_from(
        enc: &mut FrameEncoder,
        key: &str,
        wire: &mut Self::Wire,
    ) -> Result<(), EncodeError> {
        let _ = wire;
        Self::write_login_cookie_response(enc, key)
    }
    /// Queues a login-state cookie answer (1.20.5+; never called for older versions).
    fn write_login_cookie_response(enc: &mut FrameEncoder, key: &str) -> Result<(), EncodeError> {
        let _ = (enc, key);
        Ok(())
    }
    /// Queues `login_acknowledged` (1.20.2+; never called for older versions).
    fn write_login_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
        let _ = enc;
        Ok(())
    }
    /// Decodes a configuration-state packet (1.20.2+); `Ok(None)` for packets the client
    /// ignores. Registry data is returned raw ([`ConfigInbound::RegistryData`]).
    fn decode_configuration(
        raw: &RawPacket,
        wire: &mut Self::Wire,
    ) -> Result<Option<ConfigInbound>, DecodeError> {
        let _ = (raw, wire);
        Ok(None)
    }
    /// Queues a configuration-state packet (1.20.2+).
    fn write_configuration(
        enc: &mut FrameEncoder,
        out: &ConfigOutbound,
        wire: &mut Self::Wire,
    ) -> Result<(), EncodeError> {
        let _ = (enc, out, wire);
        Ok(())
    }
    /// A `registry_data` packet of the configuration state, for the wire layer (chat types).
    fn note_registry(raw: &RawPacket, wire: &mut Self::Wire) {
        let _ = (raw, wire);
    }
    /// Queues `configuration_acknowledged` (play → configuration, 1.20.2+).
    fn write_configuration_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
        let _ = enc;
        Ok(())
    }
    /// Gives the inventory what the configuration state carried for it (26.1: registry and tag
    /// bodies, kept raw by the inventory until a screen needs them), once per configuration.
    fn feed_inventory_config(inv: &mut ghast_inventory::Inventory, wire: &mut Self::Wire) {
        let _ = (inv, wire);
    }
    /// The entity a mount screen (`horse_screen_open`) belongs to; `None` for other packets
    /// and versions without one.
    #[inline(always)]
    fn mount_screen_entity(raw: &RawPacket) -> Option<i32> {
        let _ = raw;
        None
    }
    /// Opens the mount screen of [`ClientVersion::mount_screen_entity`] with what it reads off
    /// the entity (type id, `canUseSlot(SADDLE)`, `canUseSlot(BODY)`; `None`: unknown).
    fn open_mount_screen(
        inv: &mut ghast_inventory::Inventory,
        raw: &RawPacket,
        mount: Option<(i32, bool, bool)>,
    ) -> Result<(), DecodeError> {
        let _ = (inv, raw, mount);
        Ok(())
    }
    /// Sees a batch of outbound packets before they are written (26.1: the rotation of this
    /// tick's movement packet, which `use_item` carries).
    #[inline(always)]
    fn prepare_play(out: &[crate::common::Outbound], wire: &mut Self::Wire) {
        let _ = (out, wire);
    }
    /// Starts a chat session with these profile keys (1.19.3+ `setKeyPair`: a new random
    /// session id, a new signature chain); `false` when the version has no signed chat. The
    /// core then announces it ([`crate::common::Outbound::ChatSessionUpdate`]).
    fn begin_chat_session(
        wire: &mut Self::Wire,
        keys: &std::sync::Arc<ghast_auth::chat::ProfileKeys>,
        profile_id: uuid::Uuid,
    ) -> bool {
        let _ = (wire, keys, profile_id);
        false
    }
    /// The session is in online mode, so the client starts a chat session (`prepareKeyPair`):
    /// up to 26.1 when the connection is encrypted, since 26.2 when the play login says so
    /// (`onlineMode`).
    #[inline]
    fn online_mode(wire: &Self::Wire, encrypted: bool) -> bool {
        let _ = wire;
        encrypted
    }
    /// What the client sends on `start_configuration` before `configuration_acknowledged`
    /// (26.1 `handleConfigurationStart`: the pending chat acknowledgement).
    fn write_configuration_start_replies(
        enc: &mut FrameEncoder,
        wire: &mut Self::Wire,
    ) -> Result<(), EncodeError> {
        let _ = (enc, wire);
        Ok(())
    }
    /// Packets the wire layer itself owes the server after decoding (chat acknowledgements).
    fn write_wire_replies(
        enc: &mut FrameEncoder,
        wire: &mut Self::Wire,
    ) -> Result<(), EncodeError> {
        let _ = (enc, wire);
        Ok(())
    }

    /// The block-prediction sequence number of the last predicting packet written (1.19+
    /// `BlockStatePredictionHandler`; `None` on versions without one).
    fn prediction_sequence(wire: &Self::Wire) -> Option<i32> {
        let _ = wire;
        None
    }

    /// `ClientPacketListener.verifyCommand` for a dialog command (versions without dialogs:
    /// never asked).
    fn check_command(wire: &mut Self::Wire, command: &str) -> crate::dialog::CommandCheck {
        let _ = (wire, command);
        crate::dialog::CommandCheck::ParseErrors
    }

    /// The play-state packet filter for the given interests: everything the core needs plus
    /// what the interests ask for. Everything else is dropped before it is decoded.
    fn play_filter(interests: Interests) -> PacketFilter;
    /// Decodes a play-state packet; `Ok(None)` for packets the core does not use.
    fn decode_play(raw: &RawPacket, wire: &mut Self::Wire) -> Result<Option<Inbound>, DecodeError>;
    /// A 1.8 – 1.16 server resource pack (`resource_pack_send`, no pack id): pushes the answers
    /// the vanilla client sends (`ClientPlayNetworkHandler.onResourcePackSend` with the server
    /// entry's pack policy set; see `legacy_pack_statuses`) as raw packets. Other packets and
    /// versions with pack ids (those arrive as [`Inbound::ResourcePackPush`]) push nothing.
    #[inline]
    fn resource_pack(
        raw: &RawPacket,
        accept: bool,
        out: &mut Vec<crate::common::Outbound>,
    ) -> Result<(), DecodeError> {
        let _ = (raw, accept, out);
        Ok(())
    }
    /// Applies an inventory packet (windows, slots, confirms, held slot, login / respawn
    /// reset) to the inventory; returns the confirm answer to send now, if any. Other packets
    /// are ignored.
    fn inventory_packet(
        inv: &mut ghast_inventory::Inventory,
        raw: &RawPacket,
    ) -> Result<Option<ghast_inventory::Outgoing>, DecodeError>;
    /// Packets the inventory reads only in its current state (an open merchant window: its
    /// offers); the client adds them to the filter while this returns them.
    fn inventory_packet_ids(inv: &ghast_inventory::Inventory) -> &'static [i32] {
        let _ = inv;
        &[]
    }
    /// The inventory version.
    const INVENTORY: ghast_inventory::Version;
    /// Hands the wire layer's registry facts to the inventory (1.20.5+ hashed stacks).
    fn configure_inventory(inv: &mut ghast_inventory::Inventory, wire: &Self::Wire) {
        let _ = (inv, wire);
    }
    /// Queues a play-state packet.
    fn write_play(
        enc: &mut FrameEncoder,
        out: &Outbound,
        wire: &mut Self::Wire,
    ) -> Result<(), EncodeError>;
    /// Applies a server teleport to the pose the way this version's client does
    /// (`onPlayerPositionLook` + `Entity.updatePositionAndAngles`).
    fn apply_teleport(pose: &mut Pose, t: &Teleport);
}

/// The world and movement implementation of a version (crate-internal).
pub(crate) trait HasSim {
    /// World + mover.
    type Sim: crate::sim::Sim;
    /// A fresh world and player.
    fn new_sim(opts: &crate::sim::SimOptions) -> Self::Sim;
}

mod sealed {
    // Deliberately unnameable: downstream crates cannot implement `ClientVersion`.
    #[allow(unnameable_types, reason = "sealed trait pattern")]
    pub trait Sealed {}
    #[cfg(feature = "v1_8")]
    impl Sealed for super::V1_8 {}
    #[cfg(feature = "v1_12_2")]
    impl Sealed for super::V1_12_2 {}
    #[cfg(feature = "v1_16_5")]
    impl Sealed for super::V1_16_5 {}
    #[cfg(feature = "v26_1")]
    impl Sealed for super::V26_1 {}
    #[cfg(feature = "v26_2")]
    impl Sealed for super::V26_2 {}
    #[cfg(feature = "v26_3")]
    impl Sealed for super::V26_3 {}
}

/// 1.8 / 1.12 `animation`: the entity id when the animation is the wake-up (2; the client's
/// `onEntityAnimation` → `awaken`), `None` for the rest (arm swings, hurts, crits) without
/// reading further.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(crate) fn legacy_wake_up(raw: &RawPacket) -> Result<Option<i32>, DecodeError> {
    let mut r = ghast_protocol::Reader::new(&raw.body);
    let id = r.read_varint()?;
    Ok((r.read_u8()? == 2).then_some(id))
}

/// Truncates `s` to at most `max` UTF-16 units (Java's `String.length()`), at a character
/// boundary.
pub(crate) fn truncate_utf16(s: &str, max: usize) -> &str {
    let mut units = 0;
    for (i, c) in s.char_indices() {
        units += c.len_utf16();
        if units > max {
            return &s[..i];
        }
    }
    s
}

/// The statuses the 1.8 – 1.16 client answers a server pack with (0 loaded, 1 declined,
/// 2 failed download, 3 accepted). With the server entry's policy ENABLED it answers accepted
/// and, once the download ends, loaded (a bot never downloads); DISABLED answers declined. A
/// pack it cannot load (`loadable` false: a `level://` pack of a world save, which a bot does
/// not have, or a URL the 1.12+ check rejects) gets "failed download" alone. These packs carry
/// no "required" flag, so `accept` decides for every pack (a server that needs one kicks on
/// decline).
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) const fn legacy_pack_statuses(loadable: bool, accept: bool) -> &'static [i32] {
    if !loadable {
        &[2]
    } else if accept {
        &[3, 0]
    } else {
        &[1]
    }
}

/// The 1.12 – 1.16 client's resource pack URL check (`ClientPlayNetworkHandler`
/// `method_12229` / `validateResourcePackUrl`): `new URI(url)` must parse and its scheme be
/// exactly `http`, `https` or `level`; a `level` URL must not contain `..` and must end in
/// `/resources.zip`. `java.net.URI` syntax is approximated: a scheme-specific part is present
/// (and not a bare `//`), every `%` starts a two-digit hex escape, no ASCII control character,
/// space, backtick or one of `"<>\^{|}`, no non-ASCII control or space, at most one `#`, and `[` `]`
/// only inside the authority (the IPv6 literal itself is not checked).
#[cfg(any(feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn pack_url_valid(url: &str) -> bool {
    let Some((scheme, rest)) = url.split_once(':') else {
        return false;
    };
    let level = scheme == "level";
    if !(scheme == "http" || scheme == "https" || level) || rest.is_empty() || rest == "//" {
        return false;
    }
    let authority_end = rest
        .strip_prefix("//")
        .map_or(0, |a| 2 + a.find(['/', '?', '#']).unwrap_or(a.len()));
    let bytes = rest.as_bytes();
    let mut fragments = 0;
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'%' => {
                let hex = |j: usize| bytes.get(j).is_some_and(u8::is_ascii_hexdigit);
                if !(hex(i + 1) && hex(i + 2)) {
                    return false;
                }
            }
            b'#' => {
                fragments += 1;
                if fragments > 1 {
                    return false;
                }
            }
            b'[' | b']' if i >= authority_end => return false,
            0..=0x20 | 0x7f | b'"' | b'<' | b'>' | b'\\' | b'^' | b'`' | b'{' | b'|' | b'}' => {
                return false;
            }
            _ => {}
        }
    }
    // Non-ASCII "other" characters are legal unless they are controls or spaces.
    if !rest.is_ascii() && rest.chars().any(|c| c.is_control() || c.is_whitespace()) {
        return false;
    }
    !level || (!url.contains("..") && url.ends_with("/resources.zip"))
}

/// The common part of vanilla's teleport handling: relative axes are added, absolute axes
/// zero that axis' motion; rotations are added when relative. Returns the new yaw / pitch
/// before the version's `updatePositionAndAngles` normalisation.
pub(crate) fn teleport_target(pose: &mut Pose, t: &Teleport) -> (f32, f32) {
    use crate::common::teleport_flags as fl;
    let mut x = t.x;
    let mut y = t.y;
    let mut z = t.z;
    if t.flags & fl::X != 0 {
        x += pose.pos.x;
    } else {
        pose.motion.x = 0.0;
    }
    if t.flags & fl::Y != 0 {
        y += pose.pos.y;
    } else {
        pose.motion.y = 0.0;
    }
    if t.flags & fl::Z != 0 {
        z += pose.pos.z;
    } else {
        pose.motion.z = 0.0;
    }
    pose.pos = crate::common::Vec3::new(x, y, z);
    let mut yaw = t.yaw;
    let mut pitch = t.pitch;
    if t.flags & fl::PITCH != 0 {
        pitch += pose.pitch;
    }
    if t.flags & fl::YAW != 0 {
        yaw += pose.yaw;
    }
    (yaw, pitch)
}

/// Whether a 1.8 / 1.12 `custom_payload` body is on `channel` (its leading string), read
/// without decoding (or allocating) the rest.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(crate) fn payload_channel_is(body: &[u8], channel: &[u8]) -> bool {
    let mut len = 0usize;
    for (k, &b) in body.iter().take(5).enumerate() {
        len |= usize::from(b & 0x7f) << (7 * k);
        if b & 0x80 == 0 {
            return body.get(k + 1..k + 1 + len) == Some(channel);
        }
    }
    false
}

/// A 1.8 – 1.16.5 `title` packet as the version's client applies it (`onTitle` →
/// `InGameHud.setTitles`): `action_bar` — the 1.9+ action list with the action bar at 2;
/// `legacy_reset` — 1.8 / 1.12 `reset` (an empty title with the old times) instead of the
/// 1.16.5 clear. A packet read without its time fields carries 0 for them, so `clear` sets the
/// times to 0 (`setTitles(null, null, 0, 0, 0)`).
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn legacy_title(
    action: i32,
    text: Option<ghast_protocol::types::ByteString>,
    times: (Option<i32>, Option<i32>, Option<i32>),
    action_bar: bool,
    legacy_reset: bool,
) -> Option<crate::common::Inbound> {
    use crate::common::Inbound;
    use crate::hud::{Text, TitleOp, TitleTimes};
    // 1.9+: TITLE, SUBTITLE, ACTIONBAR, TIMES, CLEAR, RESET; 1.8 has no ACTIONBAR.
    let a = if action_bar || action < 2 {
        action
    } else {
        action + 1
    };
    let text = || Text::from_json(text.clone().unwrap_or_default());
    let (i, s, o) = (
        times.0.unwrap_or(0),
        times.1.unwrap_or(0),
        times.2.unwrap_or(0),
    );
    Some(match a {
        0 => Inbound::Title(TitleOp::Title(text())),
        1 => Inbound::Title(TitleOp::Subtitle(text())),
        2 => Inbound::ActionBar(text()),
        // setTitles(null, null, i, s, o): all negative clears, otherwise the times.
        3 if i < 0 && s < 0 && o < 0 => Inbound::Title(TitleOp::Clear),
        3 => Inbound::Title(TitleOp::Times(TitleTimes::new(i, s, o))),
        4 => Inbound::Title(TitleOp::Times(TitleTimes::new(0, 0, 0))),
        5 if legacy_reset => Inbound::Title(TitleOp::LegacyReset),
        5 => Inbound::Title(TitleOp::Reset),
        _ => return None,
    })
}

/// A 1.9 – 1.16.5 `boss_bar` packet as the version's client reads it (`BossBarS2CPacket.read`
/// then `ClientBossBar`): `fog_bit` is the flag bit the client reads "thicken fog" from (1.12
/// reads the music bit, 2; 1.16.5 bit 4). Property updates keep the fog flag on both. Unknown
/// colours, divisions and actions fail the read in vanilla; the packet is dropped here.
#[cfg(any(feature = "v1_12_2", feature = "v1_16_5"))]
#[allow(clippy::too_many_arguments)]
pub(crate) fn legacy_boss_bar(
    id: uuid::Uuid,
    action: i32,
    title: Option<ghast_protocol::types::ByteString>,
    health: Option<f32>,
    color: Option<i32>,
    division: Option<i32>,
    flags: Option<u8>,
    fog_bit: u8,
) -> Option<crate::common::Inbound> {
    use crate::hud::{BossBar, BossBarColor, BossBarOp, BossBarStyle, Text};
    let text = || Text::from_json(title.clone().unwrap_or_default());
    let style = || {
        Some((
            BossBarColor::from_wire(color?)?,
            BossBarStyle::from_wire(division?)?,
        ))
    };
    let f = flags.unwrap_or(0);
    Some(crate::common::Inbound::BossBar(match action {
        0 => {
            let (color, style) = style()?;
            let mut bar = BossBar::new(id, text(), health.unwrap_or(0.0), color, style);
            bar.darken_screen = f & 1 != 0;
            bar.play_music = f & 2 != 0;
            bar.create_fog = f & fog_bit != 0;
            BossBarOp::Add(bar)
        }
        1 => BossBarOp::Remove(id),
        2 => BossBarOp::Progress(id, health.unwrap_or(0.0)),
        3 => BossBarOp::Title(id, text()),
        4 => {
            let (color, style) = style()?;
            BossBarOp::Style { id, color, style }
        }
        5 => BossBarOp::Flags {
            id,
            darken_screen: f & 1 != 0,
            play_music: f & 2 != 0,
            create_fog: None,
        },
        _ => return None,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sub_versions_share_their_row() {
        for &v in GameVersion::ALL {
            let (c, base) = (v.caps(), v.instance().caps());
            assert_eq!(v.instance().instance(), v.instance());
            assert_eq!(v.enabled(), v.instance().enabled());
            // Everything but the identity is the serving row's.
            let row = Capabilities {
                version: c.version,
                protocol: c.protocol,
                ..*base
            };
            assert_eq!(*c, row, "{v}");
        }
    }

    /// The two spectator facts as the jars have them (checked 2026-11-16: 1.12.2 / 1.16.5
    /// `interactBlock` SUCCESS for spectators, 26.1 `performUseItemOn` CONSUME; only 26.1's
    /// `ServerPlayer.setGameMode` calls `stopUsingItem`; 26.2's bytecode of both equals 26.1's).
    #[test]
    fn spectator_rows() {
        for &v in GameVersion::ALL {
            let modern = v.caps().configuration_state;
            assert_eq!(v.caps().spectator_block_click_swings, !modern, "{v}");
            assert_eq!(v.caps().spectator_switch_stops_use, modern, "{v}");
        }
    }

    #[test]
    fn protocol_rows() {
        for &v in GameVersion::ALL {
            assert_eq!(v.caps().version, v);
            let row = v.protocol_info();
            assert_eq!(row.protocol, v.protocol());
            assert!(row.enabled || !v.enabled());
            assert!(row.game_versions.contains(&v.name()));
        }
    }

    #[test]
    fn parse_versions() {
        assert_eq!("1.8.8".parse::<GameVersion>().unwrap(), GameVersion::V1_8_9);
        assert_eq!("754".parse::<GameVersion>().unwrap(), GameVersion::V1_16_5);
        assert_eq!(
            "1.12.2".parse::<GameVersion>().unwrap(),
            GameVersion::V1_12_2
        );
        assert_eq!("340".parse::<GameVersion>().unwrap(), GameVersion::V1_12_2);
        assert!("1.12".parse::<GameVersion>().is_err());
        assert!("1.16.1".parse::<GameVersion>().is_err());
        for (s, v, p) in [
            ("1.12.1", GameVersion::V1_12_1, 338),
            ("338", GameVersion::V1_12_1, 338),
            ("1.16.2", GameVersion::V1_16_2, 751),
            ("751", GameVersion::V1_16_2, 751),
            ("1.16.3", GameVersion::V1_16_3, 753),
            ("753", GameVersion::V1_16_3, 753),
            ("1.16.4", GameVersion::V1_16_5, 754),
        ] {
            assert_eq!(s.parse::<GameVersion>().unwrap(), v, "{s}");
            assert_eq!(v.protocol(), p);
        }
        assert_eq!(GameVersion::V1_8_9.protocol(), 47);
        assert_eq!(GameVersion::V1_12_2.protocol(), 340);
        assert_eq!(GameVersion::V1_16_5.protocol(), 754);
    }

    #[test]
    fn utf16_truncation() {
        assert_eq!(truncate_utf16("hello", 3), "hel");
        assert_eq!(truncate_utf16("hello", 10), "hello");
        // U+1F600 is two UTF-16 units: never split.
        assert_eq!(truncate_utf16("a\u{1F600}b", 2), "a");
        assert_eq!(truncate_utf16("a\u{1F600}b", 3), "a\u{1F600}");
    }
}