ghast-inventory 0.5.5

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (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
//! The inventory state machine: what the vanilla client holds (player inventory, cursor, the
//! open window), fed by the server's window packets, plus click intents with vanilla's
//! prediction and the window confirm ("transaction") protocol.

use bytestring::ByteString;

use crate::crafting::RecipeBook;
use crate::rules::{Version, VersionNotEnabled};
use crate::sim::{Layout, Loc, Model, OUTSIDE, Screen, Sim};
use crate::stack::Stack;

/// Whether `l` is a crafting grid slot of the layout's screen.
fn is_grid(lay: Layout, l: Loc) -> bool {
    match (lay.screen, l) {
        (Screen::Player, Loc::Craft(_)) => true,
        (Screen::Container(WindowKind::Crafting), Loc::Container(k)) => (1..=9).contains(&k),
        _ => false,
    }
}
use crate::window::{SlotKind, WindowKind};

/// Version tags for loops monomorphised per version ([`Inventory::on_window_items`]).
const V18: u8 = 0;
const V112: u8 = 1;
const V1165: u8 = 2;
const V261: u8 = 3;
const V262: u8 = 4;
const V263: u8 = 5;

/// One incoming `window_items` slot: [`Incoming::settle`] stores it (normalised and clamped
/// like vanilla's handler) and says whether the slot changed.
trait Incoming {
    fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool;
}

impl Incoming for Option<Stack> {
    #[inline(always)]
    fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
        let s = normalize_as::<V>(self);
        let s = if clamp { clamp_as::<V>(s) } else { s };
        if same_slot(slot, &s) {
            false
        } else {
            *slot = s;
            true
        }
    }
}

#[cfg(any(feature = "v1_8", feature = "v1_12"))]
impl Incoming for &ghast_protocol::types::slot::legacy::Slot {
    #[inline(always)]
    fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
        if legacy_same::<V>(slot, self, clamp) {
            return false;
        }
        crate::stack::from_legacy_slot(self.clone()).settle::<V>(slot, clamp);
        true
    }
}

/// Whether `stored` equals the 1.8 / 1.12 wire slot `w` after normalising and clamping, i.e.
/// what [`Incoming::settle`] of the converted slot would compare.
#[cfg(any(feature = "v1_8", feature = "v1_12"))]
#[inline(always)]
fn legacy_same<const V: u8>(
    stored: &Option<Stack>,
    w: &ghast_protocol::types::slot::legacy::Slot,
    clamp: bool,
) -> bool {
    let Some(ws) = &w.0 else {
        return stored.is_none();
    };
    let id = i32::from(ws.id);
    let mut count = i32::from(ws.count);
    if V != V18 && (count <= 0 || id == 0) {
        return stored.is_none();
    }
    if V == V261 || V == V262 || V == V263 || V == V1165 {
        // legacy slots never reach these versions (see `on_window_items_legacy`)
        return false;
    }
    if clamp && count > 64 {
        count = 64;
    }
    let Some(st) = stored else {
        return false;
    };
    st.id == id
        && st.count == count
        && st.damage == ws.damage
        && match (&st.data, &ws.nbt) {
            (crate::stack::ItemData::None, None) => true,
            (crate::stack::ItemData::Nbt(a), Some(b)) => a == b,
            _ => false,
        }
}

/// [`Inventory::normalize`] with the version as a constant.
#[inline(always)]
fn normalize_as<const V: u8>(s: Option<Stack>) -> Option<Stack> {
    if V == V18 {
        return s;
    }
    let mut s = s.filter(|s| s.count > 0 && s.id != 0);
    if V != V112
        && let Some(st) = &mut s
    {
        st.damage = 0;
    }
    s
}

/// [`crate::sim::clamp_v`] with the version as a constant.
#[inline(always)]
fn clamp_as<const V: u8>(mut s: Option<Stack>) -> Option<Stack> {
    if V == V261 {
        crate::sim::clamp_v(Version::V26_1, &mut s);
    } else if V == V262 {
        crate::sim::clamp_v(Version::V26_2, &mut s);
    } else if V == V263 {
        crate::sim::clamp_v(Version::V26_3, &mut s);
    } else {
        crate::sim::clamp(&mut s);
    }
    s
}

/// `a == b` for slots, written out so the common equal-NBT case stays a few compares and one
/// `memcmp` whatever variants `ItemData` has.
#[inline(always)]
fn same_slot(a: &Option<Stack>, b: &Option<Stack>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => {
            a.id == b.id && a.count == b.count && a.damage == b.damage && a.data == b.data
        }
        _ => false,
    }
}

/// The `Window::menu` of a 26.1 mount screen (`horse_screen_open`; not a `minecraft:menu` id).
#[cfg(modern)]
const MOUNT_MENU: i32 = 1000;

/// 26.1: ticks without a correcting container packet after which a click counts as accepted
/// (see [`Inventory::set_click_settle_ticks`]).
pub const DEFAULT_CLICK_SETTLE_TICKS: u32 = 4;

/// Ticks a click may wait for its confirm before it is given up ([`ClickOutcome::TimedOut`]).
pub const DEFAULT_CLICK_TIMEOUT_TICKS: u32 = 40;

/// A click intent: the vanilla GUI gestures a bot needs. Slot numbers are the open screen's
/// (window 0 when only the player inventory is open); [`OUTSIDE`] (-999) is a click outside the
/// window.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Click {
    /// Mode 0: left click (`right = false`: pick up / put down / swap the whole stack) or right
    /// click (pick up half / put down one). On [`OUTSIDE`] it drops the cursor stack (left) or
    /// one item of it (right).
    Pickup {
        /// Slot, or [`OUTSIDE`].
        slot: i16,
        /// Right mouse button.
        right: bool,
    },
    /// Mode 1: shift-click (move the stack to the other part of the window).
    QuickMove {
        /// Slot.
        slot: i16,
        /// Right mouse button (same effect).
        right: bool,
    },
    /// Mode 2: number key over a slot: swap it with hotbar slot `hotbar` (0..=8), or on 1.16.5
    /// `40` (the swap-hands key) with the offhand.
    Swap {
        /// Slot.
        slot: i16,
        /// Hotbar index 0..=8, or 40 (offhand, 1.16.5 only).
        hotbar: u8,
    },
    /// Mode 4: drop key over a slot (`all = false`: one item, Q; `all = true`: the stack,
    /// ctrl+Q). With an empty cursor and [`OUTSIDE`] this is what the vanilla GUI sends for a
    /// click outside the window (no effect).
    Drop {
        /// Slot, or [`OUTSIDE`].
        slot: i16,
        /// Whole stack.
        all: bool,
    },
    /// Mode 6: double click: gather items like the cursor stack into it.
    PickupAll {
        /// Slot (normally the now empty slot the stack was picked up from).
        slot: i16,
    },
    /// Mode 3: middle click in creative mode: a full stack of the slot's item onto the empty
    /// cursor (26.1; no effect outside creative mode).
    Clone {
        /// Slot.
        slot: i16,
    },
    /// Mode 5: one packet of a drag ("quick craft"): the GUI sends [`DragStage::Start`] (slot
    /// [`OUTSIDE`]), one [`DragStage::Slot`] per slot the mouse crosses, then
    /// [`DragStage::End`] (slot [`OUTSIDE`]), each its own click (26.1).
    QuickCraft {
        /// Slot ([`OUTSIDE`] for start and end).
        slot: i16,
        /// Which packet of the drag.
        stage: DragStage,
        /// How the carried stack is spread.
        kind: DragKind,
    },
}

/// The packet of a drag ([`Click::QuickCraft`]): vanilla's quick-craft header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DragStage {
    /// Mouse pressed over the screen (header 0).
    Start,
    /// The mouse crossed a slot (header 1).
    Slot,
    /// Mouse released: the stack is spread (header 2).
    End,
}

/// How a drag spreads the carried stack ([`Click::QuickCraft`]): vanilla's quick-craft type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DragKind {
    /// Left button: split evenly (type 0).
    Split,
    /// Right button: one item per slot (type 1).
    One,
    /// Middle button, creative mode: a full stack per slot (type 2).
    Clone,
}

impl Click {
    /// The wire `(slot, button, mode)`.
    #[must_use]
    pub fn wire(self) -> (i16, u8, u8) {
        match self {
            Click::Pickup { slot, right } => (slot, u8::from(right), 0),
            Click::QuickMove { slot, right } => (slot, u8::from(right), 1),
            Click::Swap { slot, hotbar } => (slot, hotbar, 2),
            Click::Drop { slot, all } => (slot, u8::from(all), 4),
            Click::PickupAll { slot } => (slot, 0, 6),
            Click::Clone { slot } => (slot, 2, 3),
            Click::QuickCraft { slot, stage, kind } => {
                let header = match stage {
                    DragStage::Start => 0,
                    DragStage::Slot => 1,
                    DragStage::End => 2,
                };
                let ty = match kind {
                    DragKind::Split => 0,
                    DragKind::One => 1,
                    DragKind::Clone => 2,
                };
                (slot, header | ty << 2, 5)
            }
        }
    }
}

/// Why a click (or open / close) was refused. Nothing was sent and nothing changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClickError {
    /// The previous click's confirm has not arrived yet (one click in flight).
    Pending,
    /// The server rejected a click and its full window resync has not arrived yet.
    Resyncing,
    /// Nothing is open: open the player inventory ([`Inventory::open_inventory`]) or wait for a
    /// container window.
    NoScreen,
    /// A container window is open (the player inventory cannot be opened over it).
    WindowOpen,
    /// Same-tick packet order vanilla never produces (and Grim's PacketOrder checks flag): a
    /// second click this tick, a click / close in the tick the inventory was opened, or the
    /// other way round. Retry next tick.
    SameTick,
    /// The slot does not exist in the open screen (or `OUTSIDE` where not allowed).
    InvalidSlot,
    /// Invalid hotbar index for [`Click::Swap`].
    InvalidButton,
    /// The result depends on data ghast does not model (recipes, fuel, brewing, trading,
    /// enchanting, an unknown crafting result); sending it would desynchronise the inventory.
    Unpredictable,
}

impl std::fmt::Display for ClickError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ClickError::Pending => "a click is waiting for its confirm",
            ClickError::Resyncing => "waiting for the window resync after a rejected click",
            ClickError::NoScreen => "no inventory screen is open",
            ClickError::WindowOpen => "a container window is open",
            ClickError::SameTick => "not allowed in the same tick",
            ClickError::InvalidSlot => "invalid slot",
            ClickError::InvalidButton => "invalid button",
            ClickError::Unpredictable => "click outcome cannot be predicted",
        })
    }
}

impl std::error::Error for ClickError {}

/// A window click as sent (`window_click`; 1.8 `ClickWindowC2SPacket`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ClickPacket {
    /// Window id (0 = player inventory).
    pub window_id: u8,
    /// Slot, or -999.
    pub slot: i16,
    /// Mouse button / hotbar key.
    pub button: u8,
    /// Click mode.
    pub mode: u8,
    /// Action number: the window's counter, incremented before each click.
    pub action: i16,
    /// What vanilla's `onSlotClick` returned (the server compares it with its own result).
    pub item: Option<Stack>,
    /// 1.16.5: arm swings (main hand) to send before the click: the client's
    /// `PlayerEntity.dropItem` swings for each stack the click drops (a throw, a click
    /// outside with a carried stack); 0 on the other versions.
    pub swings: u8,
}

/// A packet the inventory wants sent. Write it right away, in call order (before the tick's
/// movement packet when it comes from a behaviour action).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outgoing {
    /// `window_click`.
    Click(ClickPacket),
    /// `transaction` answer to a rejected confirm (always `accepted = true`, like vanilla).
    Confirm {
        /// Window id as received.
        window_id: i8,
        /// Action number as received.
        action: i16,
    },
    /// `close_window` with this id (0 = player inventory).
    CloseWindow(u8),
    /// 1.8 only: `client_command` "open inventory achievement" (vanilla sends it when E opens
    /// the inventory).
    OpenInventory,
    /// 26.1 `container_click` (no confirm exists: the server applies every click and resends
    /// the slots whose hashes differ from its own result).
    ContainerClick(ContainerClick),
    /// 26.1 creative inventory screen (window 0 in creative mode): the packets the real
    /// client sends, in order (often none). See [`CreativePacket`].
    Creative(Vec<CreativePacket>),
    /// 26.1 `rename_item`: the anvil's name field ([`Inventory::anvil_rename_modern`]).
    RenameItem(String),
    /// 26.1 `container_button_click` (a loom pattern: [`Inventory::select_loom_pattern_modern`]).
    ButtonClick {
        /// Container id.
        window_id: i32,
        /// Button id.
        button: i32,
    },
    /// 26.1 `select_trade` ([`Inventory::select_trade_modern`]).
    SelectTrade(i32),
    /// 1.16.5 `arm_animation` (main hand) outside a click: the client dropped a carried stack
    /// (`PlayerEntity.dropItem` swings), e.g. when a server window replaced the open screen.
    Swing,
}

/// One packet the 26.1 creative inventory screen sends (`Outgoing::Creative`): the server
/// trusts these stacks, so they are exactly what the real client sends.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CreativePacket {
    /// `swing` (main hand): a stack was dropped.
    Swing,
    /// `set_creative_mode_slot`: window 0 slot `slot` now holds `item` (`slot` -1: `item` is
    /// dropped).
    SetSlot {
        /// Window 0 slot, or -1 for a drop.
        slot: i16,
        /// The stack.
        item: Option<Stack>,
    },
}

/// A 26.1 click as sent: what vanilla `MultiPlayerGameMode.handleContainerInput` writes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContainerClick {
    /// Container id (0 = player inventory).
    pub window_id: i32,
    /// The screen's state id (from the last `container_set_content` / `container_set_slot`).
    pub state_id: i32,
    /// Slot, or -999.
    pub slot: i16,
    /// Mouse button / hotbar key.
    pub button: u8,
    /// Click mode (`ContainerInput`).
    pub mode: u8,
    /// Slots whose stack the prediction changed, with the new stack (vanilla compares every slot
    /// before and after the simulated click).
    pub changed: Vec<(i16, Option<Stack>)>,
    /// The cursor after the click.
    pub carried: Option<Stack>,
    /// `false` when ghast could not predict this click (see [`Inventory::click`]): nothing
    /// changed locally, `changed` is empty, and the server's corrections bring the result.
    pub predicted: bool,
    /// ghast's own number for the click (per screen, like the legacy action number, but never
    /// sent): the [`ClickResult::action`] that resolves it.
    pub action: i16,
    /// How many `swing` (main hand) packets the vanilla client sends right before this click:
    /// every stack the click drops (outside the window, the drop key, a remainder that does not
    /// fit) swings the arm. Send them first, then the click (0 when unpredicted; always 0 in
    /// 26.3, whose swing sends no packet).
    pub swings: u8,
}

/// What became of a click.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClickOutcome {
    /// The server agreed with the prediction.
    Accepted,
    /// The server disagreed; it resends the window (the inventory waits for it).
    Rejected,
    /// No confirm within the timeout (the server may not have had that window open).
    TimedOut,
}

/// A finished click.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ClickResult {
    /// Window id the click was sent for.
    pub window_id: i32,
    /// Its action number.
    pub action: i16,
    /// The outcome.
    pub outcome: ClickOutcome,
}

impl ClickResult {
    /// A result as [`Inventory::drain_events`] reports it (for tests and replays).
    #[must_use]
    pub fn new(window_id: i32, action: i16, outcome: ClickOutcome) -> ClickResult {
        ClickResult {
            window_id,
            action,
            outcome,
        }
    }
}

/// Changes since the last [`Inventory::drain_events`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Events {
    /// Something in the player's inventory (window 0, incl. crafting grid) changed.
    pub player_changed: bool,
    /// Something in the open window's own slots changed.
    pub window_changed: bool,
    /// The cursor stack changed.
    pub cursor_changed: bool,
    /// The server opened a window (its id).
    pub opened: Option<i32>,
    /// The open window was closed by the server.
    pub closed: bool,
    /// Clicks that were confirmed, rejected or timed out, in order.
    pub clicks: Vec<ClickResult>,
    /// The server sent the full contents of window 0 (`window_items` / 26.x
    /// `container_set_content` for the player inventory): every slot of it, armor and the
    /// crafting grid included, is the server's now. Servers send it at join, at respawn and
    /// after a rejected click; a kit given with single `set_slot`s does not set it.
    pub player_synced: bool,
    /// The server sent the full contents of the open window (its own slots and the player
    /// slots it shows).
    pub window_synced: bool,
}

/// An open container window.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Window {
    id: i32,
    kind: WindowKind,
    title: ByteString,
    action: i16,
    properties: Vec<(i16, i16)>,
    /// 26.1 `minecraft:menu` registry id (-1 for other versions).
    menu: i32,
}

impl Window {
    /// Window id (`syncId`).
    #[must_use]
    pub fn id(&self) -> i32 {
        self.id
    }
    /// Its type.
    #[must_use]
    pub fn kind(&self) -> WindowKind {
        self.kind
    }
    /// The title exactly as sent: a JSON chat component on both versions.
    #[must_use]
    pub fn title(&self) -> &ByteString {
        &self.title
    }
    /// A window property (`craft_progress_bar`: furnace progress, enchanting seeds, …).
    #[must_use]
    pub fn property(&self, id: i16) -> Option<i16> {
        self.properties.iter().find(|p| p.0 == id).map(|p| p.1)
    }
    /// 26.1: the `minecraft:menu` registry id of `open_screen` (`None` for other versions).
    #[must_use]
    pub fn menu_modern(&self) -> Option<i32> {
        (self.menu >= 0).then_some(self.menu)
    }
}

/// Which screen the client has open.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ScreenState {
    None,
    Inventory,
    Window(Window),
}

#[derive(Debug, Clone, Copy)]
struct PendingClick {
    window_id: i32,
    action: i16,
    age: u32,
}

#[derive(Debug, Clone, Copy, Default)]
struct TickFlags {
    clicked: bool,
    opened: bool,
    closed: bool,
}

/// The client's inventory: player inventory, cursor, the open window, click prediction and
/// the confirm protocol. Pure and deterministic: packets in, packets out, no I/O or clock
/// ([`tick`](Inventory::tick) counts time).
#[derive(Debug, Clone)]
pub struct Inventory {
    version: Version,
    m: Model,
    screen: ScreenState,
    player_action: i16,
    pending: Option<PendingClick>,
    resync: Option<(i32, u32)>,
    flags: TickFlags,
    timeout: u32,
    settle: u32,
    events: Events,
    /// Server writes of each hotbar slot and (last) the off hand (`set_slot`,
    /// `window_items`), changed or not.
    hotbar_writes: [u16; 10],
    book: RecipeBook,
    /// 1.16.5: the server's item tags (they belong to the connection, like the recipes).
    tags16: Option<std::sync::Arc<crate::tags16::ItemTags16>>,
    /// 26.1 state ids: window 0 (`inventoryMenu`) and the open container.
    state_player: i32,
    state_window: i32,
    /// 26.1 registry names for click hashes and the binding curse.
    #[cfg(modern)]
    reg26: crate::item26::HashRegistries,
    /// 26.1: recipe item sets, game mode, experience level.
    #[cfg(modern)]
    w26: crate::sim26::World26,
    /// 26.1: window 0's and the open container's per-screen click state (drags, …).
    #[cfg(modern)]
    s26: [crate::sim26::Screen26; 2],
    /// 26.1: window 0's `lastSlots` (what its last `broadcastChanges` saw; the creative
    /// screen's listener sends every slot that differs).
    #[cfg(modern)]
    creative_last: Vec<Option<Stack>>,
    /// 26.1: the creative inventory screen is open (window 0 in creative mode).
    #[cfg(modern)]
    creative_screen: bool,
    /// 26.1: packets the creative screen sends in answer to server packets
    /// ([`Inventory::take_creative_echo_modern`]).
    #[cfg(modern)]
    creative_echo: Vec<CreativePacket>,
    /// 26.1 `LocalPlayer.dropSpamThrottler`: +20 per creative drop, -1 per tick; drops are
    /// refused from 1280 (`canDropItems`).
    #[cfg(modern)]
    drop_throttle: i32,
    /// 26.1 `update_recipes` body, not parsed yet (parsed when a menu needs its item sets).
    #[cfg(modern)]
    recipes_raw: Option<bytes::Bytes>,
    /// 26.1 tags and enchantment definitions (raw until a menu needs them).
    #[cfg(modern)]
    d26: crate::data26::Data26,
    /// 1.8 – 1.16.5: the creative inventory screen, allocated at its first open.
    creative16: Option<Box<creative_legacy::CreativeLegacy>>,
}

mod aliases;
mod click;
mod creative_legacy;
mod hands;
mod inbound;
#[cfg(modern)]
mod modern;
mod read;
mod screens;

pub use creative_legacy::CreativeTab;

/// The write counter of a hotbar slot (0 … 8) or the off hand (9) for a slot location.
#[inline]
fn hand_writes_index(l: Loc) -> Option<usize> {
    match l {
        Loc::Player(k @ 0..9) => Some(k),
        Loc::Player(40) => Some(9),
        _ => None,
    }
}

impl Inventory {
    /// An empty inventory (a fresh player entity).
    ///
    /// # Errors
    /// [`VersionNotEnabled`] when this build of the crate lacks the version's feature
    /// ([`Version::is_enabled`]).
    pub fn new(version: Version) -> Result<Inventory, VersionNotEnabled> {
        if version.is_enabled() {
            Ok(Inventory::empty(version))
        } else {
            Err(VersionNotEnabled(version))
        }
    }

    fn empty(version: Version) -> Inventory {
        Inventory {
            version,
            m: Model::default(),
            screen: ScreenState::None,
            player_action: 0,
            pending: None,
            resync: None,
            flags: TickFlags::default(),
            timeout: DEFAULT_CLICK_TIMEOUT_TICKS,
            settle: DEFAULT_CLICK_SETTLE_TICKS,
            events: Events::default(),
            hotbar_writes: [0; 10],
            book: RecipeBook::default(),
            tags16: None,
            state_player: 0,
            state_window: 0,
            #[cfg(modern)]
            reg26: crate::item26::HashRegistries::default(),
            #[cfg(modern)]
            w26: crate::sim26::World26::default(),
            #[cfg(modern)]
            s26: Default::default(),
            #[cfg(modern)]
            creative_last: Vec::new(),
            #[cfg(modern)]
            creative_screen: false,
            #[cfg(modern)]
            creative_echo: Vec::new(),
            #[cfg(modern)]
            drop_throttle: 0,
            #[cfg(modern)]
            recipes_raw: None,
            #[cfg(modern)]
            d26: Default::default(),
            creative16: None,
        }
    }

    /// Sets how many ticks a click may wait for its confirm.
    pub fn set_click_timeout(&mut self, ticks: u32) {
        self.timeout = ticks.max(1);
    }

    /// 26.1: how many ticks after a click without a correcting container packet make it
    /// [`ClickOutcome::Accepted`]. 26.1 has no confirm: the server applies the click when it
    /// receives it and answers in the same moment, with `container_set_slot` /
    /// `container_set_content` / `set_cursor_item` only for slots its result disagrees with, and
    /// with nothing when the client predicted right. So silence is the acceptance; set this to
    /// cover the round trip (`ceil(rtt / 50 ms) + 1`; default
    /// [`DEFAULT_CLICK_SETTLE_TICKS`]). A correction before that makes the click
    /// [`ClickOutcome::Rejected`] (already applied: no resync wait).
    pub fn set_click_settle_ticks(&mut self, ticks: u32) {
        self.settle = ticks.max(1);
    }

    /// The protocol version.
    #[must_use]
    pub fn version(&self) -> Version {
        self.version
    }

    /// The level of enchantment `name` (`sharpness` or `minecraft:sharpness`) on `stack`, on
    /// every version (1.8 / 1.12 numeric ids, 1.16.5 names, 26.x the server's enchantment
    /// registry from [`Inventory::set_registries_modern`]); 0 when it has none.
    #[must_use]
    pub fn enchantment_level(&self, stack: &crate::Stack, name: &str) -> i32 {
        let want = name.strip_prefix("minecraft:").unwrap_or(name);
        #[cfg(modern)]
        let registry: &[String] = self.reg26.enchantments();
        #[cfg(not(modern))]
        let registry: &[String] = &[];
        stack
            .enchantments(self.version)
            .iter()
            .find(|e| e.id.plain_name(registry) == Some(want))
            .map_or(0, |e| e.level)
    }

    /// The modern table set of this inventory's version (a placeholder for a legacy one: only
    /// modern code paths read it).
    #[cfg(modern)]
    #[inline]
    pub(crate) fn mv(&self) -> crate::tables::Mv {
        crate::tables::Mv::of(self.version).unwrap_or(crate::tables::Mv::ANY)
    }

    /// A new player entity (join, respawn, dimension change): everything is cleared,
    /// including the action counters; the server resends the inventory.
    /// The selected hotbar slot restarts at 0 too (a new `PlayerInventory`).
    pub fn reset(&mut self) {
        // the recipe book belongs to the connection, not to the player entity
        #[cfg(modern)]
        let reg26 = std::mem::take(&mut self.reg26);
        #[cfg(modern)]
        let w26 = std::mem::take(&mut self.w26);
        #[cfg(modern)]
        let recipes_raw = self.recipes_raw.take();
        #[cfg(modern)]
        let d26 = std::mem::take(&mut self.d26);
        *self = Inventory {
            timeout: self.timeout,
            settle: self.settle,
            book: std::mem::take(&mut self.book),
            hotbar_writes: self.hotbar_writes,
            tags16: self.tags16.take(),
            #[cfg(modern)]
            reg26,
            #[cfg(modern)]
            w26,
            #[cfg(modern)]
            recipes_raw,
            #[cfg(modern)]
            d26,
            creative16: self
                .creative16
                .take()
                .map(creative_legacy::CreativeLegacy::respawned),
            ..Inventory::empty(self.version)
        };
        self.events.player_changed = true;
    }

    /// Call once at the start of every client tick: resets the per-tick packet-order guard
    /// and ages the pending click.
    pub fn tick(&mut self) {
        self.flags = TickFlags::default();
        #[cfg(modern)]
        if self.drop_throttle > 0 {
            self.drop_throttle -= 1;
        }
        if let Some(p) = &mut self.pending {
            p.age += 1;
            if self.version.is_modern() && p.age >= self.settle {
                self.events.clicks.push(ClickResult {
                    window_id: p.window_id,
                    action: p.action,
                    outcome: ClickOutcome::Accepted,
                });
                self.pending = None;
            } else if p.age >= self.timeout {
                self.events.clicks.push(ClickResult {
                    window_id: p.window_id,
                    action: p.action,
                    outcome: ClickOutcome::TimedOut,
                });
                self.pending = None;
            }
        }
        if let Some((_, age)) = &mut self.resync {
            *age += 1;
            if *age >= self.timeout {
                self.resync = None;
            }
        }
    }

    /// Takes the accumulated change flags and click results.
    pub fn drain_events(&mut self) -> Events {
        std::mem::take(&mut self.events)
    }
}