Skip to main content

ghast_inventory/
rules.rs

1//! Per-version item facts the click logic needs: stack limits, damageability, which items
2//! have subtypes (1.8, 1.12), which go into armor / offhand slots, and which crafting ingredients
3//! leave something behind.
4//!
5//! Stack sizes and durability come from `ghast-data` (checked against the vanilla 1.8.9, 1.12.2
6//! and 1.16.5 item registries; the two 1.12.2 differences are fixed below); the short lists below were read off the vanilla registries
7//! (the damage-variant flag, which Legacy Yarn names `Item.isUnbreakable`; `getRecipeRemainder`;
8//! `MobEntity.getPreferredEquipmentSlot`).
9
10use crate::stack::Stack;
11
12/// Protocol version of the connection; selects the vanilla rules being reproduced.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum Version {
16    /// 1.8 – 1.8.9 (protocol 47).
17    V1_8,
18    /// 1.12 – 1.12.2 (protocol 335 – 340).
19    V1_12,
20    /// 1.16.4 – 1.16.5 (protocol 754).
21    V1_16_5,
22    /// 26.1 – 26.1.2 (protocol 775).
23    V26_1,
24    /// 26.2 (protocol 776).
25    V26_2,
26    /// 26.3 (protocol 777).
27    V26_3,
28}
29
30/// [`crate::Inventory::new`] for a [`Version`] whose crate feature (`v1_8`, `v1_12`, `v1_16_5`,
31/// `v26_1`, `v26_2`, `v26_3`) is off in this build.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub struct VersionNotEnabled(pub Version);
35
36impl std::fmt::Display for VersionNotEnabled {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(
39            f,
40            "ghast-inventory was built without the feature of {:?}",
41            self.0
42        )
43    }
44}
45
46impl std::error::Error for VersionNotEnabled {}
47
48/// 1.8.9 items with damage variants (Legacy Yarn `Item.isUnbreakable()` is true; the damage value selects a variant, so merging
49/// compares it). Sorted.
50const SUBTYPES_1_8: &[i32] = &[
51    1, 3, 5, 6, 12, 17, 18, 19, 24, 31, 35, 37, 38, 44, 78, 95, 97, 98, 126, 139, 145, 155, 159,
52    160, 161, 162, 168, 171, 175, 179, 182, 263, 322, 349, 350, 351, 358, 373, 383, 397, 425,
53];
54
55/// 1.12.2 items with damage variants (`Item.isUnbreakable()` in Legacy Yarn, read off the vanilla
56/// 1.12.2 item registry). Sorted.
57const SUBTYPES_1_12: &[i32] = &[
58    1, 3, 5, 6, 12, 17, 18, 19, 24, 31, 35, 37, 38, 44, 95, 97, 98, 126, 139, 145, 155, 159, 160,
59    161, 162, 168, 171, 175, 179, 182, 205, 251, 252, 263, 322, 349, 350, 351, 355, 358, 397, 425,
60];
61
62/// Equipment slot index used by every version: 0 head, 1 chest, 2 legs, 3 feet. Window 0 slot
63/// `5 + index` is that armor slot.
64pub(crate) type ArmorIndex = u8;
65
66impl Version {
67    /// Whether this crate was built with the version's feature (`v1_8`, `v1_12`, `v1_16_5`,
68    /// `v26_1`, `v26_2`, `v26_3`). An [`Inventory`](crate::Inventory) can only be created for enabled versions.
69    #[must_use]
70    pub const fn is_enabled(self) -> bool {
71        match self {
72            Version::V1_8 => cfg!(feature = "v1_8"),
73            Version::V1_12 => cfg!(feature = "v1_12"),
74            Version::V1_16_5 => cfg!(feature = "v1_16_5"),
75            Version::V26_1 => cfg!(feature = "v26_1"),
76            Version::V26_2 => cfg!(feature = "v26_2"),
77            Version::V26_3 => cfg!(feature = "v26_3"),
78        }
79    }
80
81    /// Whether this is a modern (26.x) version: data components, hashed clicks, no confirms.
82    #[must_use]
83    pub const fn is_modern(self) -> bool {
84        matches!(self, Version::V26_1 | Version::V26_2 | Version::V26_3)
85    }
86
87    /// Item facts from `ghast-data` (1.8 – 1.16.5; modern items come from the generated tables).
88    #[allow(unused_variables)]
89    fn info(self, id: i32) -> Option<&'static ghast_data::ItemInfo> {
90        let id = u16::try_from(id).ok()?;
91        match self {
92            #[cfg(feature = "v1_8")]
93            Version::V1_8 => ghast_data::v1_8::Item::from_id(id).map(|i| i.info()),
94            #[cfg(feature = "v1_12")]
95            Version::V1_12 => ghast_data::v1_12::Item::from_id(id).map(|i| i.info()),
96            #[cfg(feature = "v1_16_5")]
97            Version::V1_16_5 => ghast_data::v1_16_5::Item::from_id(id).map(|i| i.info()),
98            _ => None,
99        }
100    }
101
102    /// Registry name of an item id (`""` when unknown).
103    pub(crate) fn name(self, id: i32) -> &'static str {
104        #[cfg(modern)]
105        if let Some(mv) = crate::tables::Mv::of(self) {
106            return crate::item26::item_name(mv, id).unwrap_or("");
107        }
108        self.info(id).map_or("", |i| i.name)
109    }
110
111    /// Whether the item id exists in this version.
112    pub(crate) fn known(self, id: i32) -> bool {
113        #[cfg(modern)]
114        if let Some(mv) = crate::tables::Mv::of(self) {
115            return crate::item26::row(mv, id).is_some();
116        }
117        self.info(id).is_some()
118    }
119
120    /// `Item.getMaxCount()` (26.1: the stack's `max_stack_size` component). Unknown ids get 64.
121    pub(crate) fn max_count(self, s: &Stack) -> i32 {
122        #[cfg(modern)]
123        if let Some(mv) = crate::tables::Mv::of(self) {
124            return crate::item26::max_stack_size(mv, s);
125        }
126        if self == Version::V1_16_5 && s.id == 843 {
127            // warped_fungus_on_a_stick: minecraft-data says 64, vanilla 1.16.5 says 1.
128            return 1;
129        }
130        if self == Version::V1_12 && matches!(s.id, 453 | 2256) {
131            // knowledge_book and record_13: minecraft-data says 64, vanilla 1.12.2 says 1.
132            return 1;
133        }
134        self.info(s.id).map_or(64, |i| i32::from(i.stack_size))
135    }
136
137    /// Durability from `ghast-data` (1.8 – 1.16.5).
138    pub(crate) fn max_durability(self, id: i32) -> Option<i32> {
139        self.info(id)
140            .and_then(|i| i.max_durability)
141            .map(i32::from)
142            .filter(|&d| d > 0)
143    }
144
145    /// Whether the item has damage variants (1.8 / 1.12; 1.16 has no damage-selected variants).
146    pub(crate) fn has_subtypes(self, id: i32) -> bool {
147        match self {
148            Version::V1_8 => SUBTYPES_1_8.binary_search(&id).is_ok(),
149            Version::V1_12 => SUBTYPES_1_12.binary_search(&id).is_ok(),
150            Version::V1_16_5 | Version::V26_1 | Version::V26_2 | Version::V26_3 => false,
151        }
152    }
153
154    /// `ItemStack.isDamageable()`: the item has durability and the stack is not `Unbreakable`.
155    pub(crate) fn is_damageable(self, s: &Stack) -> bool {
156        #[cfg(modern)]
157        if let Some(mv) = crate::tables::Mv::of(self) {
158            return crate::item26::is_damageable(mv, s);
159        }
160        self.info(s.id)
161            .and_then(|i| i.max_durability)
162            .is_some_and(|d| d > 0)
163            && !s.nbt_bool("Unbreakable")
164    }
165
166    /// `ItemStack.isDamaged()` (1.8 / 1.12: damage value; 1.16: `Damage` tag).
167    pub(crate) fn is_damaged(self, s: &Stack) -> bool {
168        self.is_damageable(s)
169            && match self {
170                Version::V1_8 | Version::V1_12 => s.damage > 0,
171                Version::V1_16_5 => s.nbt_int("Damage") > 0,
172                Version::V26_1 | Version::V26_2 | Version::V26_3 => damage_26(self, s) > 0,
173            }
174    }
175
176    /// `ItemStack.isStackable()`.
177    pub(crate) fn is_stackable(self, s: &Stack) -> bool {
178        self.max_count(s) > 1 && (!self.is_damageable(s) || !self.is_damaged(s))
179    }
180
181    /// The armor slot an `ArmorItem` belongs to (1.8: `ArmorItem.slot`; 1.16: the preferred
182    /// equipment slot when it is an armor slot, which includes elytra, carved pumpkins and
183    /// heads). Used by window 0's shift-click.
184    pub(crate) fn armor_target(self, s: &Stack) -> Option<ArmorIndex> {
185        match self {
186            Version::V1_8 => (298..=317)
187                .contains(&s.id)
188                .then(|| ((s.id - 298) % 4) as u8),
189            Version::V1_12 => equipment_1_12(s.id).filter(|&e| e < 4),
190            Version::V1_16_5 => self.equipment_1_16(s.id).filter(|&e| e < 4),
191            Version::V26_1 | Version::V26_2 | Version::V26_3 => {
192                equip_26(self, s).and_then(|e| e.filter(|&e| e < 4))
193            }
194        }
195    }
196
197    /// The armor slot a right-click use of the stack equips (`None`: the use does not equip):
198    /// 1.8 `ArmorItem.onStartUse`; 1.12.2 / 1.16.5 `ArmorItem.use` and `ElytraItem.use` (the
199    /// armor pieces, the turtle helmet, the elytra; pumpkins and heads only go on by clicks);
200    /// 26.x `Item.use` with a swappable `equippable` for a humanoid armor slot (pumpkins and
201    /// heads are not swappable; a stack patching `equippable` is not predicted).
202    pub(crate) fn use_equip_target(self, s: &Stack) -> Option<ArmorIndex> {
203        match self {
204            Version::V1_8 => self.armor_target(s),
205            Version::V1_12 => equipment_1_12(s.id).filter(|_| matches!(s.id, 298..=317 | 443)),
206            Version::V1_16_5 | Version::V26_1 | Version::V26_2 | Version::V26_3 => {
207                let n = self.name(s.id);
208                if n == "carved_pumpkin" || n.ends_with("_skull") || n.ends_with("_head") {
209                    None
210                } else {
211                    self.armor_target(s)
212                }
213            }
214        }
215    }
216
217    /// Whether window 0's armor slot `a` accepts the stack (`Slot.canInsert`).
218    pub(crate) fn armor_accepts(self, a: ArmorIndex, s: &Stack) -> bool {
219        match self {
220            Version::V1_8 => {
221                if (298..=317).contains(&s.id) {
222                    ((s.id - 298) % 4) as u8 == a
223                } else {
224                    // pumpkin (block item 86) and skull (397) fit the helmet slot
225                    (s.id == 86 || s.id == 397) && a == 0
226                }
227            }
228            Version::V1_12 => equipment_1_12(s.id) == Some(a),
229            Version::V1_16_5 => self.equipment_1_16(s.id) == Some(a),
230            Version::V26_1 | Version::V26_2 | Version::V26_3 => equip_26(self, s) == Some(Some(a)),
231        }
232    }
233
234    /// 1.12 / 1.16.5 shift-click target "offhand" (`getPreferredEquipmentSlot == OFFHAND`: the
235    /// shield).
236    pub(crate) fn prefers_offhand(self, s: &Stack) -> bool {
237        match self {
238            Version::V1_8 => false,
239            Version::V1_12 => equipment_1_12(s.id) == Some(4),
240            Version::V1_16_5 => self.equipment_1_16(s.id) == Some(4),
241            Version::V26_1 | Version::V26_2 | Version::V26_3 => equip_26(self, s) == Some(Some(4)),
242        }
243    }
244
245    /// 1.16.5 `MobEntity.getPreferredEquipmentSlot`: 0..=3 armor (head, chest, legs, feet),
246    /// 4 offhand, `None` main hand.
247    fn equipment_1_16(self, id: i32) -> Option<u8> {
248        let n = self.name(id);
249        if n == "carved_pumpkin" || n.ends_with("_skull") || n.ends_with("_head") {
250            // every *_skull / *_head item is an AbstractSkullBlock item in 1.16.5
251            return Some(0);
252        }
253        if n == "elytra" {
254            return Some(1);
255        }
256        if n == "shield" {
257            return Some(4);
258        }
259        // ArmorItem: leather/chainmail/iron/golden/diamond/netherite pieces and turtle_helmet
260        if n.ends_with("_helmet") {
261            Some(0)
262        } else if n.ends_with("_chestplate") {
263            Some(1)
264        } else if n.ends_with("_leggings") {
265            Some(2)
266        } else if n.ends_with("_boots") {
267            Some(3)
268        } else {
269            None
270        }
271    }
272
273    /// 1.12 / 1.16.5 shulker box slots refuse shulker boxes.
274    pub(crate) fn is_shulker_box(self, s: &Stack) -> bool {
275        self != Version::V1_8 && self.name(s.id).ends_with("shulker_box")
276    }
277}
278
279/// Modern `ItemStack.getDamageValue()`.
280fn damage_26(v: Version, s: &Stack) -> i32 {
281    #[cfg(modern)]
282    if let Some(mv) = crate::tables::Mv::of(v) {
283        return crate::item26::damage_value(mv, s);
284    }
285    let _ = (v, s);
286    0
287}
288
289/// Modern equipment slot of the `equippable` component as 0..=3 armor, 4 offhand; `None`
290/// (outer) when the stack patches `equippable` (unknown to ghast).
291fn equip_26(v: Version, s: &Stack) -> Option<Option<u8>> {
292    #[cfg(modern)]
293    {
294        use crate::item26::Equip;
295        let e = crate::item26::equip(crate::tables::Mv::of(v)?, s).ok()?;
296        Some(match e {
297            Equip::Offhand => Some(4),
298            e => e.armor_index(),
299        })
300    }
301    #[cfg(not(modern))]
302    {
303        let _ = (v, s);
304        None
305    }
306}
307
308/// 1.12.2 `MobEntity.method_13083` (preferred equipment slot): pumpkin and skull on the head,
309/// armor pieces by type, elytra on the chest, the shield in the offhand. 0..=3 armor (head,
310/// chest, legs, feet), 4 offhand, `None` main hand.
311fn equipment_1_12(id: i32) -> Option<u8> {
312    match id {
313        86 | 397 => Some(0),
314        298..=317 => Some(((id - 298) % 4) as u8),
315        443 => Some(1),
316        442 => Some(4),
317        _ => None,
318    }
319}
320
321#[cfg(all(test, feature = "v1_8", feature = "v1_16_5"))]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn tables_sorted_and_facts() {
327        assert!(SUBTYPES_1_8.windows(2).all(|w| w[0] < w[1]));
328        assert!(SUBTYPES_1_12.windows(2).all(|w| w[0] < w[1]));
329        let v = Version::V1_8;
330        assert!(v.has_subtypes(351)); // dye
331        assert!(!v.has_subtypes(276)); // diamond sword
332        assert_eq!(v.max_count(&Stack::new(276, 1, 0)), 1);
333        assert_eq!(v.max_count(&Stack::new(368, 1, 0)), 16); // ender pearl
334        assert_eq!(v.armor_target(&Stack::new(310, 1, 0)), Some(0));
335        assert_eq!(v.armor_target(&Stack::new(317, 1, 0)), Some(3));
336        assert!(v.armor_accepts(0, &Stack::new(86, 1, 0)));
337        assert!(v.is_damaged(&Stack::new(276, 1, 3)));
338        assert!(!v.is_stackable(&Stack::new(276, 1, 3)));
339        let w = Version::V1_16_5;
340        let id = |n: &str| i32::from(ghast_data::v1_16_5::Item::from_name(n).unwrap().id());
341        assert_eq!(w.armor_target(&Stack::new(id("elytra"), 1, 0)), Some(1));
342        assert_eq!(
343            w.armor_target(&Stack::new(id("turtle_helmet"), 1, 0)),
344            Some(0)
345        );
346        assert_eq!(
347            w.armor_target(&Stack::new(id("dragon_head"), 1, 0)),
348            Some(0)
349        );
350        assert_eq!(
351            w.armor_target(&Stack::new(id("netherite_boots"), 1, 0)),
352            Some(3)
353        );
354        assert_eq!(w.armor_target(&Stack::new(id("shield"), 1, 0)), None);
355        assert!(w.prefers_offhand(&Stack::new(id("shield"), 1, 0)));
356        assert!(w.is_shulker_box(&Stack::new(id("red_shulker_box"), 1, 0)));
357        assert_eq!(w.max_count(&Stack::new(843, 1, 0)), 1);
358        assert_eq!(w.name(843), "warped_fungus_on_a_stick");
359    }
360}