ghast-inventory 0.5.4

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
//! The server's inventory packets: held slot, open / close window, window items, set slot
//! (legacy and 26.x), cursor, player inventory, recipes, window properties and confirms.

use super::*;

impl Inventory {
    // ------------------------------------------------------------------ inbound

    /// `held_item_slot` from the server.
    pub fn on_held_slot(&mut self, slot: i8) {
        if (0..9).contains(&slot) {
            self.m.selected = slot as u8;
            self.m.player.touch();
        }
    }

    /// `open_window`: the server opened a window of this kind (`None`: a type the vanilla
    /// client has no screen for; ignored). Any open screen is closed client-side first.
    pub fn on_open_window(&mut self, id: i32, kind: Option<WindowKind>, title: ByteString) {
        let Some(kind) = kind else { return };
        if self.screen != ScreenState::None {
            self.close_screen();
        }
        let n = kind.container_len(self.version);
        self.m.container = vec![None; n];
        self.m.merchant = (kind == WindowKind::Merchant
            && crate::menus::modelled(self.version, kind))
        .then(Box::default);
        self.m.mount = None;
        self.m.furnace = 0;
        self.m.station = crate::station::Station::of(self.version, kind).map(Box::new);
        self.m.container_result_known = true;
        self.m.container_fresh = true;
        self.screen = ScreenState::Window(Window {
            id,
            kind,
            title,
            action: 0,
            properties: Vec::new(),
            menu: -1,
        });
        self.events.opened = Some(id);
        self.events.window_changed = true;
    }

    /// `close_window` from the server (closes whatever is open, whatever the id).
    pub fn on_close_window(&mut self) {
        if self.screen != ScreenState::None {
            let was_window = matches!(self.screen, ScreenState::Window(_));
            self.close_screen();
            if was_window {
                self.events.closed = true;
            }
        }
    }

    pub(super) fn open_id(&self) -> i32 {
        match &self.screen {
            ScreenState::Window(w) => w.id,
            _ => 0,
        }
    }

    /// `window_items`: replaces the window's slots (`window_id` as received, unsigned byte).
    pub fn on_window_items(
        &mut self,
        window_id: i32,
        items: impl IntoIterator<Item = Option<Stack>>,
    ) {
        // One loop per version: the per-slot normalising and clamping rules are constants
        // inside it, so the legacy hot path carries no version tests.
        let items = items.into_iter();
        match self.version {
            Version::V1_8 => self.window_items_as::<V18, _>(window_id, items),
            Version::V1_12 => self.window_items_as::<V112, _>(window_id, items),
            Version::V1_16_5 => self.window_items_as::<V1165, _>(window_id, items),
            Version::V26_1 => self.window_items_as::<V261, _>(window_id, items),
            #[cfg(feature = "v26_2")]
            Version::V26_2 => self.window_items_as::<V262, _>(window_id, items),
            // no inventory exists for a disabled version
            #[cfg(not(feature = "v26_2"))]
            Version::V26_2 => {}
            #[cfg(feature = "v26_3")]
            Version::V26_3 => self.window_items_as::<V263, _>(window_id, items),
            #[cfg(not(feature = "v26_3"))]
            Version::V26_3 => {}
        }
    }

    /// `window_items` straight from the 1.8 / 1.12 wire slots: a slot equal to the stored stack
    /// is compared without being converted (no NBT refcount traffic for unchanged slots, the
    /// common case of a refreshed shop window).
    #[cfg(any(feature = "v1_8", feature = "v1_12"))]
    pub(crate) fn on_window_items_legacy(
        &mut self,
        window_id: i32,
        items: &[ghast_protocol::types::slot::legacy::Slot],
    ) {
        match self.version {
            Version::V1_8 => self.window_items_as::<V18, _>(window_id, items.iter()),
            Version::V1_12 => self.window_items_as::<V112, _>(window_id, items.iter()),
            // not reached: the legacy packets belong to 1.8 / 1.12 connections
            _ => self.on_window_items(
                window_id,
                items.iter().cloned().map(crate::stack::from_legacy_slot),
            ),
        }
    }

    #[inline]
    pub(super) fn window_items_as<const V: u8, W: Incoming>(
        &mut self,
        window_id: i32,
        items: impl Iterator<Item = W>,
    ) {
        let lay = if window_id == 0 {
            Layout::new(self.version, Screen::Player)
        } else if window_id == self.open_id() {
            self.layout()
        } else {
            return;
        };
        let mut player = false;
        let mut window = false;
        let mut touched_grid = false;
        // a workstation sees its slots set one by one
        let before = (lay.screen != Screen::Player && self.m.station.is_some())
            .then(|| self.m.container.clone());
        for (i, s) in items.enumerate() {
            let Some(l) = lay.loc(i) else { break };
            if let Some(k) = hand_writes_index(l) {
                self.hotbar_writes[k] = self.hotbar_writes[k].wrapping_add(1);
            }
            touched_grid |= is_grid(lay, l);
            let clamps = if V == V261 || V == V262 || V == V263 {
                lay.clamps_26(l)
            } else {
                lay.clamps(l)
            };
            let slot = self.m.at_mut(l);
            if s.settle::<V>(slot, clamps) {
                match l {
                    Loc::Container(_) => window = true,
                    _ => player = true,
                }
            }
        }
        if lay.screen == Screen::Player {
            self.m.craft_result_known = true;
            self.m.craft_fresh = true;
        } else {
            self.m.container_result_known = true;
            self.m.container_fresh = true;
        }
        // villager screen: every slot set marked the trading inventory dirty
        if lay.screen != Screen::Player && self.m.merchant.is_some() {
            crate::merchant::update(self.version, &mut self.m);
        }
        // workstation: the inputs were set (the menu looked its result up), then the result
        // slot got the packet's stack
        if let Some(before) = before {
            self.station_window_items(before);
        }
        // 1.16.5 beacon: the payment inventory caps at 1 (one check per packet, not per slot)
        if V == V1165 && window && lay.screen == Screen::Container(WindowKind::Beacon) {
            lay.clamp_menu(Loc::Container(0), self.m.at_mut(Loc::Container(0)));
        }
        // 1.8: setting the grid slots made the client compute the result itself
        if V == V18 && touched_grid {
            crate::sim::recompute_1_8(&mut self.m, lay);
        }
        self.events.player_changed |= player;
        self.events.window_changed |= window;
        if lay.screen == Screen::Player {
            self.events.player_synced = true;
        } else {
            self.events.window_synced = true;
        }
        if self.resync.is_some_and(|(w, _)| w == window_id) {
            self.resync = None;
        }
    }

    /// `set_slot` (`window_id` as received, signed byte): -1 sets the cursor, 1.12 / 1.16.5 -2 a
    /// `PlayerInventory` index, window 0 slots 36..45 always reach window 0, others only the
    /// current screen.
    pub fn on_set_slot(&mut self, window_id: i32, slot: i16, item: Option<Stack>) {
        if self.creative_items_ignore_legacy(window_id, slot) {
            return;
        }
        let item = self.normalize(item);
        if window_id == -1 {
            if self.m.cursor != item {
                self.m.cursor = item;
                self.events.cursor_changed = true;
            }
            return;
        }
        let loc = if window_id == -2 && self.version != Version::V1_8 {
            usize::try_from(slot)
                .ok()
                .filter(|&k| k < 41)
                .map(Loc::Player)
        } else if window_id == 0 && (36..45).contains(&slot) {
            Layout::new(self.version, Screen::Player).loc(slot as usize)
        } else if window_id == self.open_id() {
            usize::try_from(slot)
                .ok()
                .and_then(|i| self.layout().loc(i))
        } else {
            None
        };
        let Some(l) = loc else { return };
        if let Some(k) = hand_writes_index(l) {
            self.hotbar_writes[k] = self.hotbar_writes[k].wrapping_add(1);
        }
        let mut item = item;
        if self.layout().clamps(l) {
            crate::sim::clamp_v(self.version, &mut item);
            self.layout().clamp_menu(l, &mut item);
        }
        let crafting_table = matches!(
            self.layout().screen,
            Screen::Container(WindowKind::Crafting)
        );
        let anvil = !self.version.is_modern()
            && !matches!(
                self.version,
                Version::V1_16_5 | Version::V1_12 | Version::V1_8
            )
            && matches!(self.layout().screen, Screen::Container(WindowKind::Anvil));
        match l {
            Loc::CraftResult => {
                self.m.craft_result_known = true;
                self.m.craft_fresh = true;
            }
            Loc::Container(0) if crafting_table => {
                self.m.container_result_known = true;
                self.m.container_fresh = true;
            }
            // the server's anvil output; an input set by the server makes the client compute it
            Loc::Container(2) if anvil => self.m.container_result_known = true,
            Loc::Container(0 | 1) if anvil => {
                let first = if l == Loc::Container(0) {
                    item.is_none()
                } else {
                    self.m.container.first().is_none_or(Option::is_none)
                };
                if first {
                    if let Some(out) = self.m.container.get_mut(2) {
                        *out = None;
                    }
                    self.m.container_result_known = true;
                } else {
                    self.m.container_result_known = false;
                }
            }
            // 1.12: a grid slot changed under the result the client holds
            Loc::Craft(_) if self.version == Version::V1_12 => self.m.craft_fresh = false,
            Loc::Container(1..=9) if crafting_table && self.version == Version::V1_12 => {
                self.m.container_fresh = false;
            }
            _ => {}
        }
        let s = self.m.at_mut(l);
        if *s != item {
            *s = item;
            match l {
                Loc::Container(_) => self.events.window_changed = true,
                _ => self.events.player_changed = true,
            }
        }
        if self.version == Version::V1_8 {
            // the slot's screen: window 0 for its hotbar slots, else the current one
            let lay = if window_id == 0 && (36..45).contains(&slot) {
                Layout::new(self.version, Screen::Player)
            } else {
                self.layout()
            };
            if is_grid(lay, l) {
                crate::sim::recompute_1_8(&mut self.m, lay);
            }
        }
        // villager screen: `Slot.setStack` marks the trading inventory dirty
        if matches!(l, Loc::Container(0..=2)) && self.m.merchant.is_some() {
            crate::merchant::update(self.version, &mut self.m);
        }
        if let Loc::Container(k) = l {
            self.station_inbound(Some(k));
        }
    }

    /// 26.1: a container packet arrived while a click waits to settle: the server disagreed.
    pub(super) fn correction_modern(&mut self, window_id: Option<i32>) {
        if let Some(p) = self.pending
            && window_id.is_none_or(|w| w == p.window_id || w == 0)
        {
            self.pending = None;
            self.events.clicks.push(ClickResult {
                window_id: p.window_id,
                action: p.action,
                outcome: ClickOutcome::Rejected,
            });
        }
    }

    /// 26.1 `container_set_content` (vanilla `initializeContents`): window 0 or the open
    /// container's slots, its carried stack and its state id. Window 0's carried stack only
    /// shows while no container is open (the client keeps one per menu).
    pub fn on_window_items_modern(
        &mut self,
        window_id: i32,
        state_id: i32,
        items: impl IntoIterator<Item = Option<Stack>>,
        carried: Option<Stack>,
    ) {
        let current = window_id == self.open_id();
        if window_id != 0 && !current {
            return;
        }
        self.correction_modern(Some(window_id));
        #[cfg(modern)]
        let old = (window_id != 0 && self.hooks_modern()).then(|| self.m.container.clone());
        self.on_window_items(window_id, items);
        if window_id == 0 {
            self.state_player = state_id;
        } else {
            self.state_window = state_id;
            #[cfg(modern)]
            if let Some(old) = old {
                let n = old.len();
                self.inbound_modern(old, 0..n);
            }
        }
        if current {
            self.on_set_cursor(carried);
        }
    }

    /// 26.1 `container_set_slot`: window 0 slots always reach window 0 (any slot), the open
    /// container's only that container; the menu's state id follows.
    pub fn on_set_slot_modern(
        &mut self,
        window_id: i32,
        state_id: i32,
        slot: i16,
        item: Option<Stack>,
    ) {
        let item = self.normalize(item);
        let lay = if window_id == 0 {
            Layout::new(self.version, Screen::Player)
        } else if window_id == self.open_id() {
            self.layout()
        } else {
            return;
        };
        if window_id == 0 {
            self.state_player = state_id;
        } else {
            self.state_window = state_id;
        }
        self.correction_modern(Some(window_id));
        let Some(l) = usize::try_from(slot).ok().and_then(|i| lay.loc(i)) else {
            return;
        };
        let mut item = item;
        if lay.clamps_26(l) {
            crate::sim::clamp_v(self.version, &mut item);
        }
        match l {
            Loc::CraftResult => self.m.craft_result_known = true,
            Loc::Container(0) if lay.screen == Screen::Container(WindowKind::Crafting) => {
                self.m.container_result_known = true;
            }
            _ => {}
        }
        #[cfg(modern)]
        let old = (matches!(l, Loc::Container(_)) && self.hooks_modern())
            .then(|| self.m.container.clone());
        let s = self.m.at_mut(l);
        if *s != item {
            *s = item;
            match l {
                Loc::Container(_) => self.events.window_changed = true,
                _ => self.events.player_changed = true,
            }
        }
        #[cfg(modern)]
        if let (Loc::Container(k), Some(old)) = (l, old)
            && window_id != 0
        {
            self.inbound_modern(old, k..k + 1);
        }
        // the creative screen broadcasts window 0 after every server slot
        #[cfg(modern)]
        if window_id == 0 && self.creative_screen {
            let mut out = std::mem::take(&mut self.creative_echo);
            self.creative_broadcast(&mut out);
            self.creative_echo = out;
        }
    }

    /// 26.1 `set_cursor_item`: the open menu's carried stack.
    pub fn on_set_cursor(&mut self, item: Option<Stack>) {
        if self.version.is_modern() {
            self.correction_modern(None);
            // the creative screen keeps its own cursor
            #[cfg(modern)]
            if self.creative_screen {
                return;
            }
        }
        let item = self.normalize(item);
        if self.m.cursor != item {
            self.m.cursor = item;
            self.events.cursor_changed = true;
        }
    }

    /// 26.1 `set_player_inventory`: a `PlayerInventory` index (0..=40; the body armor and saddle
    /// slots 41 and 42 are not kept).
    pub fn on_set_player_inventory(&mut self, slot: i32, item: Option<Stack>) {
        self.correction_modern(None);
        let item = self.normalize(item);
        let Some(k) = usize::try_from(slot).ok().filter(|&k| k < 41) else {
            return;
        };
        if self.m.player[k] != item {
            self.m.player[k] = item;
            self.events.player_changed = true;
        }
    }

    /// The crafting recipes the server declared (1.16.5; 1.8 clients know theirs).
    #[must_use]
    pub fn recipes(&self) -> &RecipeBook {
        &self.book
    }

    /// Forgets the server's recipes and item tags (1.16.5): what reads them is refused again
    /// until they are sent anew (ghast-client calls this when `Interests::RECIPES` is
    /// switched off).
    pub fn clear_server_data(&mut self) {
        self.book = RecipeBook::default();
        self.tags16 = None;
    }

    /// 1.16.5 `declare_recipes`: replaces the client's recipes (the remainders of a taken
    /// crafting result, a furnace's shift-click, the smithing table, the stonecutter; until a
    /// declared book arrives those are refused as unpredictable).
    pub fn on_declare_recipes(&mut self, book: RecipeBook) {
        self.book = book;
    }

    /// `craft_progress_bar` (window property).
    pub fn on_window_property(&mut self, window_id: i32, property: i16, value: i16) {
        if let ScreenState::Window(w) = &mut self.screen
            && w.id == window_id
        {
            match w.properties.iter_mut().find(|p| p.0 == property) {
                Some(p) => p.1 = value,
                None => w.properties.push((property, value)),
            }
            // 1.16.5 anvil: the level cost
            if property == 0
                && let Some(crate::station::Station::Anvil(a)) = self.m.station.as_deref_mut()
            {
                a.cost = i32::from(value);
            }
            // 1.16.5 stonecutter / loom: the selected recipe / pattern (no result update)
            if property == 0
                && let Some(
                    crate::station::Station::Stonecutter { selected, .. }
                    | crate::station::Station::Loom { selected },
                ) = self.m.station.as_deref_mut()
            {
                *selected = i32::from(value);
            }
            #[cfg(modern)]
            match w.menu {
                // anvil: the cost data slot
                8 if property == 0 => self.s26[1].anvil_cost = i32::from(value),
                // loom: the selected pattern
                18 if property == 0 => self.s26[1].loom_selected = i32::from(value),
                // crafter: slot locks
                7 if (0..9).contains(&property) => {
                    let bit = 1u16 << property;
                    if value == 1 {
                        self.s26[1].crafter_locked |= bit;
                    } else {
                        self.s26[1].crafter_locked &= !bit;
                    }
                }
                _ => {}
            }
        }
    }

    /// `transaction` (window confirm) from the server. Returns the answer to send now, exactly
    /// when vanilla answers (not accepted, and the window is 0 or the open one); resolves the
    /// pending click when it is its confirm. Route every confirm through here and answer
    /// nowhere else, so each is answered exactly once.
    pub fn on_transaction(
        &mut self,
        window_id: i8,
        action: i16,
        accepted: bool,
    ) -> Option<Outgoing> {
        let w = i32::from(window_id);
        if let Some(p) = self.pending
            && p.window_id == w
            && p.action == action
        {
            self.pending = None;
            let outcome = if accepted {
                ClickOutcome::Accepted
            } else {
                self.resync = Some((w, 0));
                ClickOutcome::Rejected
            };
            self.events.clicks.push(ClickResult {
                window_id: w,
                action,
                outcome,
            });
        }
        let known = w == 0 || w == self.open_id();
        (known && !accepted).then_some(Outgoing::Confirm { window_id, action })
    }

    /// 1.12 / 1.16.5 drop empty stacks (1.16.5 also has no damage field); 1.8 keeps zero-count
    /// stacks.
    ///
    /// Works in place: moving an `Option<Stack>` through a `match` per slot cost the legacy
    /// `window_items` path measurably once `Stack` grew the 26.1 variant.
    #[inline]
    pub(super) fn normalize(&self, mut s: Option<Stack>) -> Option<Stack> {
        self.normalize_in_place(&mut s);
        s
    }

    #[inline]
    pub(super) fn normalize_in_place(&self, s: &mut Option<Stack>) {
        if self.version == Version::V1_8 {
            return;
        }
        if s.as_ref().is_some_and(|s| s.count <= 0 || s.id == 0) {
            *s = None;
        } else if self.version != Version::V1_12
            && let Some(st) = s
        {
            st.damage = 0;
        }
    }
}