Skip to main content

azalea_entity/
attributes.rs

1//! Attributes and modifiers for entities.
2//!
3//! Also see <https://minecraft.wiki/w/Attribute>.
4
5use std::collections::{HashMap, hash_map};
6
7use azalea_core::{
8    attribute_modifier_operation::AttributeModifierOperation, identifier::Identifier,
9};
10use azalea_registry::{builtin::Attribute, item::components::AttributeModifier};
11use thiserror::Error;
12
13/// The current attribute values for an entity.
14///
15/// Each attribute can have multiple modifiers, and these modifiers are the
16/// result of things like sprinting or enchantments.
17#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
18#[derive(Clone, Debug)]
19pub struct Attributes {
20    pub movement_speed: AttributeInstance,
21    pub sneaking_speed: AttributeInstance,
22    pub attack_speed: AttributeInstance,
23    pub water_movement_efficiency: AttributeInstance,
24    pub mining_efficiency: AttributeInstance,
25    pub block_break_speed: AttributeInstance,
26
27    pub block_interaction_range: AttributeInstance,
28    pub entity_interaction_range: AttributeInstance,
29
30    pub step_height: AttributeInstance,
31}
32
33impl Attributes {
34    /// Returns a mutable reference to the [`AttributeInstance`] for the given
35    /// attribute, or `None` if the attribute isn't implemented.
36    pub fn get_mut(&mut self, attribute: Attribute) -> Option<&mut AttributeInstance> {
37        let value = match attribute {
38            Attribute::MovementSpeed => &mut self.movement_speed,
39            Attribute::SneakingSpeed => &mut self.sneaking_speed,
40            Attribute::AttackSpeed => &mut self.attack_speed,
41            Attribute::WaterMovementEfficiency => &mut self.water_movement_efficiency,
42            Attribute::MiningEfficiency => &mut self.mining_efficiency,
43            Attribute::BlockInteractionRange => &mut self.block_interaction_range,
44            Attribute::EntityInteractionRange => &mut self.entity_interaction_range,
45            Attribute::StepHeight => &mut self.step_height,
46            Attribute::BlockBreakSpeed => &mut self.block_break_speed,
47            _ => return None,
48        };
49        Some(value)
50    }
51}
52
53/// An individual attribute for an entity, which may have any number of
54/// modifiers attached to it.
55#[derive(Clone, Debug)]
56pub struct AttributeInstance {
57    pub base: f64,
58    modifiers_by_id: HashMap<Identifier, AttributeModifier>,
59    // TODO: add cache
60}
61
62/// An error for when we try to call [`AttributeInstance::try_insert`] when the
63/// modifier is already present.
64#[derive(Clone, Debug, Error)]
65#[error("A modifier with this ID is already present.")]
66pub struct AlreadyPresentError;
67
68impl AttributeInstance {
69    pub fn new(base: f64) -> Self {
70        Self {
71            base,
72            modifiers_by_id: HashMap::new(),
73        }
74    }
75
76    pub fn calculate(&self) -> f64 {
77        let mut total = self.base;
78        for modifier in self.modifiers_by_id.values() {
79            match modifier.operation {
80                AttributeModifierOperation::AddValue => total += modifier.amount,
81                AttributeModifierOperation::AddMultipliedBase => {
82                    total += modifier.amount * self.base
83                }
84                AttributeModifierOperation::AddMultipliedTotal => total *= 1. + modifier.amount,
85            };
86        }
87        total
88    }
89
90    /// Add a new modifier to this attribute and return the previous value, if
91    /// present.
92    pub fn insert(&mut self, modifier: AttributeModifier) -> Option<AttributeModifier> {
93        self.modifiers_by_id.insert(modifier.id.clone(), modifier)
94    }
95
96    /// Insert the given modifier if it's not already present, otherwise returns
97    /// [`AlreadyPresentError`].
98    pub fn try_insert(&mut self, modifier: AttributeModifier) -> Result<(), AlreadyPresentError> {
99        match self.modifiers_by_id.entry(modifier.id.clone()) {
100            hash_map::Entry::Occupied(_) => Err(AlreadyPresentError),
101            hash_map::Entry::Vacant(entry) => {
102                entry.insert(modifier);
103                Ok(())
104            }
105        }
106    }
107
108    /// Remove the modifier with the given ID from this attribute, returning
109    /// the previous modifier is present.
110    pub fn remove(&mut self, id: &Identifier) -> Option<AttributeModifier> {
111        self.modifiers_by_id.remove(id)
112    }
113}
114
115pub fn sprinting_modifier() -> AttributeModifier {
116    AttributeModifier {
117        id: Identifier::new("sprinting"),
118        amount: 0.3f32 as f64,
119        operation: AttributeModifierOperation::AddMultipliedTotal,
120    }
121}
122pub fn base_attack_speed_modifier(amount: f64) -> AttributeModifier {
123    AttributeModifier {
124        id: Identifier::new("base_attack_speed"),
125        amount,
126        operation: AttributeModifierOperation::AddValue,
127    }
128}
129pub fn creative_block_interaction_range_modifier() -> AttributeModifier {
130    AttributeModifier {
131        id: Identifier::new("creative_mode_block_range"),
132        amount: 0.5,
133        operation: AttributeModifierOperation::AddValue,
134    }
135}
136
137pub fn creative_entity_interaction_range_modifier() -> AttributeModifier {
138    AttributeModifier {
139        id: Identifier::new("creative_mode_entity_range"),
140        amount: 2.0,
141        operation: AttributeModifierOperation::AddValue,
142    }
143}