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