ghast-inventory 0.5.6

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
//! The 26.1 simulation's slot layer: slot access, the `Slot` rules (may place / pick up,
//! stack limits) and the containers' `setItem` / `removeItem` / `setChanged`.

use super::*;

// ------------------------------------------------------------------ the simulation

impl Sim26<'_> {
    pub(super) fn len(&self) -> usize {
        self.kind.len()
    }

    pub(super) fn loc(&self, i: usize) -> Loc {
        self.kind.loc(i).unwrap_or(Loc::Player(0))
    }

    pub(super) fn get(&self, i: usize) -> Option<&Stack> {
        self.m.at(self.loc(i)).as_ref()
    }

    pub(super) fn slot_mut(&mut self, i: usize) -> &mut Option<Stack> {
        let l = self.loc(i);
        self.m.at_mut(l)
    }

    pub(super) fn ty(&self, i: usize) -> Ty {
        ty(self.kind, i)
    }

    /// The menu's container slot `k` (container index, not screen index).
    pub(super) fn c(&self, k: usize) -> Option<&Stack> {
        self.m.container.get(k).and_then(Option::as_ref)
    }

    pub(super) fn c_set_raw(&mut self, k: usize, s: Option<Stack>) {
        if let Some(x) = self.m.container.get_mut(k) {
            *x = s;
        }
    }

    // ---------------------------------------------------------- Slot rules

    /// Furnace `isFuel`: the item's fuel value (26.1 / 26.2 `FuelValues`, an item fact) or, in
    /// 26.3, whether the stack has the `cooking_fuel` component (a patch can add or remove it).
    pub(super) fn fuel(&self, s: &Stack) -> bool {
        let f = fact(self.mv, s.id, v::FUEL);
        if self.mv.data_brewing() {
            has_component(self.mv, s, c::COOKING_FUEL, f)
        } else {
            f
        }
    }

    /// Brewing `FuelSlot.mayPlaceItem`: blaze powder (an item fact) or, in 26.3, the
    /// `brewing_fuel` component.
    pub(super) fn brew_fuel(&self, s: &Stack) -> bool {
        let f = fact(self.mv, s.id, v::BREWING_FUEL);
        if self.mv.data_brewing() {
            has_component(self.mv, s, c::BREWING_FUEL, f)
        } else {
            f
        }
    }

    /// Brewing `IngredientsSlot.mayPlace`: `PotionBrewing.isIngredient` (an item fact) or, in
    /// 26.3, the synced `brewing_reagent` recipe property set.
    pub(super) fn brew_ingredient(&self, s: &Stack) -> bool {
        if self.mv.data_brewing() {
            has(&self.w.brewing_reagent, s.id)
        } else {
            fact(self.mv, s.id, v::BREWING_INGREDIENT)
        }
    }

    /// Brewing `PotionSlot.mayPlaceItem` / 26.3 `PotionIngredient.isPotionInput`: the synced
    /// `brewing_input` recipe property set or the `brewing_potion_inputs` item tag.
    pub(super) fn potion_input(&self, s: &Stack) -> bool {
        if self.mv.data_brewing() {
            has(&self.w.brewing_input, s.id)
                || self
                    .d
                    .tag(Reg::Item, "brewing_potion_inputs")
                    .is_some_and(|t| t.contains(&s.id))
        } else {
            potion_slot(self.mv, s)
        }
    }

    /// `Slot.mayPlace`.
    pub(super) fn may_place(&self, i: usize, s: &Stack) -> R<bool> {
        let mv = self.mv;
        let id = s.id;
        Ok(match self.ty(i) {
            Ty::Inv | Ty::Grid | Ty::Plain | Ty::EnchantItem => true,
            Ty::Armor(a) => wears(mv, s, a)?,
            Ty::Result
            | Ty::Fixed
            | Ty::FurnaceResult
            | Ty::CombinerResult
            | Ty::GrindResult
            | Ty::CutterResult
            | Ty::LoomResult
            | Ty::MapResult
            | Ty::TradeResult => false,
            Ty::CrafterGrid => self.s.crafter_locked & (1 << i) == 0,
            Ty::Shulker => fact(mv, id, v::FITS_CONTAINER),
            Ty::FurnaceFuel => self.fuel(s) || is_item(mv, s, "bucket"),
            Ty::Potion => self.potion_input(s),
            Ty::BrewIngredient => self.brew_ingredient(s),
            Ty::BrewFuel => self.brew_fuel(s),
            Ty::Lapis => is_item(mv, s, "lapis_lazuli"),
            Ty::Payment => fact(mv, id, v::BEACON_PAYMENT),
            Ty::CombinerIn(k) => match self.kind {
                Kind::Smithing => match k {
                    0 => has(&self.w.smithing_template, id),
                    1 => has(&self.w.smithing_base, id),
                    _ => has(&self.w.smithing_addition, id),
                },
                _ => true,
            },
            Ty::GrindIn => v::is_damageable(mv, s) || enchanted(mv, s),
            Ty::CutterIn | Ty::TradeIn => true,
            Ty::LoomBanner => fact(mv, id, v::BANNER),
            Ty::LoomDye => loom_dye(mv, s),
            Ty::LoomPattern => loom_pattern(mv, s),
            Ty::MapIn => has_component(mv, s, c::MAP_ID, false),
            Ty::MapExtra => {
                is_item(mv, s, "paper") || is_item(mv, s, "map") || is_item(mv, s, "glass_pane")
            }
            Ty::MountSaddle => self.mount_equips(s, Equip::Saddle, self.s.mount_saddle)?,
            Ty::MountBody => self.mount_equips(s, Equip::Body, self.s.mount_body)?,
        })
    }

    /// `isEquippableInSlot(stack, slot)` for the mount: the `equippable` slot, the slot usable
    /// and the mount allowed by `allowed_entities`.
    pub(super) fn mount_equips(&self, s: &Stack, slot: Equip, usable: bool) -> R<bool> {
        let mv = self.mv;
        let (e, allowed) = match v::patched(mv, s, c::EQUIPPABLE) {
            Some(Some(b)) => equip_allowed(&b).ok_or(Unpredictable)?,
            Some(None) => return Ok(false),
            None => {
                let Some(d) = v::row(mv, s.id) else {
                    return Ok(false);
                };
                let allowed = if d.allowed(mv).is_empty() {
                    None
                } else {
                    Some(
                        crate::data26::holders_from_names(d.allowed(mv), |n| {
                            let n = n.strip_prefix("minecraft:").unwrap_or(n);
                            v::entity_type_id(mv, n)
                        })
                        .ok_or(Unpredictable)?,
                    )
                };
                (d.equip, allowed)
            }
        };
        if e != slot || !usable {
            return Ok(false);
        }
        match allowed {
            None => Ok(true),
            Some(h) => self
                .d
                .contains(Reg::EntityType, &h, self.s.mount_type)
                .ok_or(Unpredictable),
        }
    }

    /// `Slot.getMaxStackSize()`.
    pub(super) fn slot_max(&self, i: usize) -> i32 {
        match self.ty(i) {
            Ty::Armor(_)
            | Ty::Potion
            | Ty::EnchantItem
            | Ty::Payment
            | Ty::MountSaddle
            | Ty::MountBody => 1,
            _ => 99,
        }
    }

    /// `Slot.getMaxStackSize(stack)`.
    pub(super) fn max_for(&self, i: usize, s: &Stack) -> i32 {
        let mv = self.mv;
        if self.ty(i) == Ty::FurnaceFuel && is_item(mv, s, "bucket") {
            return 1;
        }
        self.slot_max(i).min(max_size(mv, s))
    }

    /// `Slot.mayPickup`.
    pub(super) fn may_pickup(&self, i: usize) -> R<bool> {
        let mv = self.mv;
        Ok(match self.ty(i) {
            Ty::Armor(_) | Ty::MountSaddle | Ty::MountBody => match self.get(i) {
                Some(s) if !self.w.creative => !bound(mv, s, self.w.binding_curse)?,
                _ => true,
            },
            Ty::Fixed => false,
            // MerchantResultSlot.mayPickup (26.3): the active offer must still be paid for
            Ty::TradeResult if mv.trade_pickup_checks_payment() => match self.s.trade_active {
                None => false,
                Some(o) => {
                    let (a, b) = (self.c(0), self.c(1));
                    self.satisfied(o, a, b)? || self.satisfied(o, b, a)?
                }
            },
            Ty::CombinerResult if self.kind == Kind::Anvil => {
                let cost = self.s.anvil_cost;
                if cost <= 0 {
                    false
                } else if self.w.creative {
                    true
                } else {
                    self.w.xp_level.ok_or(Unpredictable)? >= cost
                }
            }
            _ => true,
        })
    }

    /// `Slot.allowModification`.
    pub(super) fn allow_modification(&self, i: usize) -> R<bool> {
        if self.ty(i) == Ty::Fixed {
            return Ok(false);
        }
        if !self.may_pickup(i)? {
            return Ok(false);
        }
        match self.get(i) {
            Some(s) => self.may_place(i, s),
            // mayPlace(EMPTY): only reached for empty slots, which never need it
            None => Ok(true),
        }
    }

    // ---------------------------------------------------------- containers

    /// `Slot.set(stack)`: the container's `setItem` (with its cap and hooks), then
    /// `setChanged`.
    pub(super) fn set(&mut self, i: usize, mut s: Option<Stack>) -> R<()> {
        let mv = self.mv;
        let l = self.loc(i);
        if let Some(cap) = self.kind.cap(l)
            && let Some(st) = &mut s
        {
            let max = cap.min(max_size(mv, st));
            if st.count > max {
                st.count = max;
            }
        }
        *self.m.at_mut(l) = s;
        if self.ty(i) == Ty::TradeIn {
            self.trade_update()?;
        }
        self.changed(i)
    }

    /// `Slot.setChanged` → the container's `setChanged` (the menus' result hooks).
    pub(super) fn changed(&mut self, i: usize) -> R<()> {
        match self.ty(i) {
            Ty::CombinerIn(_) => self.combiner_result(),
            Ty::GrindIn => self.grind_result(),
            Ty::CutterIn => self.cutter_changed(),
            Ty::LoomBanner | Ty::LoomDye | Ty::LoomPattern => self.loom_changed(),
            Ty::MapIn | Ty::MapExtra | Ty::MapResult => {
                self.map_changed();
                Ok(())
            }
            Ty::TradeIn | Ty::TradeResult => self.trade_update(),
            _ => Ok(()),
        }
    }

    /// `Slot.remove(n)` → the container's `removeItem`.
    pub(super) fn remove(&mut self, i: usize, n: i32) -> R<Option<Stack>> {
        match self.ty(i) {
            Ty::Fixed => Ok(None),
            // ResultContainer: the whole stack; MerchantContainer slot 2: the whole stack
            Ty::Result
            | Ty::CombinerResult
            | Ty::GrindResult
            | Ty::CutterResult
            | Ty::MapResult
            | Ty::TradeResult => Ok(self.slot_mut(i).take()),
            t => {
                if n <= 0 {
                    return Ok(None);
                }
                let out = split(self.slot_mut(i), n);
                if out.is_some() {
                    match t {
                        // SimpleContainer.removeItem: setChanged; MerchantContainer: update
                        Ty::Inv | Ty::Armor(_) | Ty::Grid | Ty::CrafterGrid => {}
                        _ => self.changed(i)?,
                    }
                }
                Ok(out)
            }
        }
    }

    /// `Slot.tryRemove(amount, maxAmount)`.
    pub(super) fn try_remove(&mut self, i: usize, amount: i32, max: i32) -> R<Option<Stack>> {
        if self.ty(i) == Ty::Fixed || !self.may_pickup(i)? {
            return Ok(None);
        }
        let count = self.get(i).map_or(0, |s| s.count);
        if !self.allow_modification(i)? && max < count {
            return Ok(None);
        }
        let out = self.remove(i, amount.min(max))?;
        if out.is_none() {
            return Ok(None);
        }
        if self.get(i).is_none() {
            self.set(i, None)?;
        }
        Ok(out)
    }

    /// `Slot.safeTake`.
    pub(super) fn safe_take(&mut self, i: usize, amount: i32, max: i32) -> R<Option<Stack>> {
        let out = self.try_remove(i, amount, max)?;
        if let Some(t) = &out {
            let t = t.clone();
            self.on_take(i, Some(&t))?;
        }
        Ok(out)
    }

    /// `Slot.safeInsert(stack, amount)`: puts up to `amount` of `input` into the slot.
    pub(super) fn safe_insert(
        &mut self,
        i: usize,
        input: &mut Option<Stack>,
        amount: i32,
    ) -> R<()> {
        if self.ty(i) == Ty::Fixed {
            return Ok(());
        }
        let Some(inp) = input.as_ref() else {
            return Ok(());
        };
        if !self.may_place(i, inp)? {
            return Ok(());
        }
        let have = self.get(i).map_or(0, |s| s.count);
        let n = amount.min(inp.count).min(self.max_for(i, inp) - have);
        if n <= 0 {
            return Ok(());
        }
        match self.get(i).cloned() {
            None => {
                let part = split(input, n);
                self.set(i, part)?;
            }
            Some(mut cur) => {
                if same(&cur, inp) {
                    let _ = split(input, n);
                    cur.count += n;
                    self.set(i, Some(cur))?;
                }
            }
        }
        Ok(())
    }

    /// `Slot.onTake`.
    pub(super) fn on_take(&mut self, i: usize, _taken: Option<&Stack>) -> R<()> {
        match self.ty(i) {
            Ty::Result => self.craft_take(i),
            Ty::CombinerResult => match self.kind {
                Kind::Smithing => {
                    for k in 0..3 {
                        if let Some(mut st) = self.c(k).cloned() {
                            st.count -= 1;
                            self.c_set(k, norm(st))?;
                        }
                    }
                    Ok(())
                }
                _ => self.anvil_take(),
            },
            Ty::GrindResult => {
                self.c_set(0, None)?;
                self.c_set(1, None)
            }
            Ty::CutterResult => {
                // inputSlot.remove(1) (its slotsChanged resets a changed input); with an item
                // removed `setupResultSlot`: the client has no recipe, so the result is empty
                if self.remove_container(0, 1)?.is_some() {
                    self.c_set_raw(1, None);
                }
                Ok(())
            }
            Ty::MapResult => {
                let _ = self.remove_container(0, 1)?;
                let _ = self.remove_container(1, 1)?;
                self.map_changed();
                Ok(())
            }
            Ty::LoomResult => {
                // banner and dye one each (each removal runs slotsChanged)
                let _ = self.remove_container(0, 1)?;
                let _ = self.remove_container(1, 1)?;
                if self.c(0).is_none() || self.c(1).is_none() {
                    self.s.loom_selected = -1;
                }
                Ok(())
            }
            Ty::TradeResult => self.trade_take(),
            _ => {
                // Slot.onTake: setChanged
                self.changed(i)
            }
        }
    }

    /// A server packet sets container slot `k` (`Slot.set`: the cap, then the menu's hooks).
    pub(crate) fn inbound_set(&mut self, k: usize, s: Option<Stack>) -> R<()> {
        self.c_set(k, s)
    }

    /// `setItem(k, s)` on the menu's own container (slot `k` of the container part).
    pub(super) fn c_set(&mut self, k: usize, s: Option<Stack>) -> R<()> {
        let i = self.screen_of_container(k);
        self.set(i, s)
    }

    pub(super) fn remove_container(&mut self, k: usize, n: i32) -> R<Option<Stack>> {
        let i = self.screen_of_container(k);
        self.remove(i, n)
    }

    pub(super) fn screen_of_container(&self, k: usize) -> usize {
        match self.kind {
            Kind::Crafter if k == 9 => 45,
            _ => k,
        }
    }
}