Skip to main content

ghast_inventory/
attack.rs

1//! Attack attributes of a held stack: [`Stack::attack`] (legacy versions; the module exists
2//! when one of their features is on).
3
4use ghast_protocol::nbt::Tag;
5
6use crate::rules::Version;
7use crate::stack::{Stack, last};
8
9pub use ghast_data::ItemAttack;
10
11impl Stack {
12    /// The attack attributes this stack gives when held in the main hand, as the server applies
13    /// them: [`ItemAttack::attack_damage`] / [`ItemAttack::attack_speed`] are the player's
14    /// attribute values (base 1.0 / 4.0 plus the item's modifiers). 1.8.9, 1.12.2 and 1.16.5.
15    ///
16    /// `None` when the stack carries an `AttributeModifiers` list (the server then uses that
17    /// list instead of the item's modifiers; not modelled), on 26.x, or when the version's
18    /// feature is off. The bare hand is `ghast_data::<version>::item_attack(0)`.
19    #[must_use]
20    pub fn attack(&self, v: Version) -> Option<ItemAttack> {
21        if self.has_attribute_modifiers() {
22            return None;
23        }
24        let id = u16::try_from(self.id).ok()?;
25        match v {
26            #[cfg(feature = "v1_8")]
27            Version::V1_8 => Some(ghast_data::v1_8::item_attack(id)),
28            #[cfg(feature = "v1_12")]
29            Version::V1_12 => Some(ghast_data::v1_12::item_attack(id)),
30            #[cfg(feature = "v1_16_5")]
31            Version::V1_16_5 => Some(ghast_data::v1_16_5::item_attack(id)),
32            _ => {
33                let _ = id;
34                None
35            }
36        }
37    }
38
39    /// The NBT has an `AttributeModifiers` list (`contains("AttributeModifiers", 9)`), which
40    /// replaces the item's own modifiers.
41    fn has_attribute_modifiers(&self) -> bool {
42        let Some(Ok(Some(n))) = self.nbt().map(|n| n.parse()) else {
43            return false;
44        };
45        match &n.tag {
46            Tag::Compound(c) => matches!(last(c, "AttributeModifiers"), Some(Tag::List(_))),
47            _ => false,
48        }
49    }
50}