azalea_registry/registry_holder/
value.rs1use azalea_codec::Codec;
2use azalea_core::{
3 attribute_modifier_operation::AttributeModifierOperation, identifier::Identifier,
4};
5
6use crate::builtin::{Attribute, EnchantmentLevelBasedValueKind, EnchantmentValueEffectKind};
7
8#[derive(Clone, Debug, PartialEq, Codec)]
9#[codec(tag = "type", tag_as = EnchantmentValueEffectKind)]
10#[codec(default_snake_case_key)]
11pub enum ValueEffect {
12 Set {
13 value: LevelBasedValue,
14 },
15 Add {
16 value: LevelBasedValue,
17 },
18 Multiply {
19 factor: LevelBasedValue,
20 },
21 RemoveBinomial {
22 chance: LevelBasedValue,
23 },
24 AllOf {
25 effects: Vec<ValueEffect>,
26 },
27 Exponential {
28 base: LevelBasedValue,
29 exponent: LevelBasedValue,
30 },
31}
32
33#[derive(Clone, Debug, PartialEq, Codec)]
34pub struct AttributeEffect {
35 pub id: Identifier,
36 pub attribute: Attribute,
37 pub amount: LevelBasedValue,
38 pub operation: AttributeModifierOperation,
39}
40
41#[derive(Clone, Debug, PartialEq, Codec)]
42pub enum LevelBasedValue {
43 Constant(f32),
44 Dispatch(DispatchLevelBasedValue),
45}
46
47#[derive(Clone, Debug, PartialEq, Codec)]
48#[codec(tag = "type", tag_as = EnchantmentLevelBasedValueKind)]
49#[codec(default_snake_case_key)]
50pub enum DispatchLevelBasedValue {
51 Exponent {
52 base: Box<LevelBasedValue>,
53 power: Box<LevelBasedValue>,
54 },
55 Linear {
56 base: f32,
57 per_level_above_first: f32,
58 },
59 LevelsSquared {
60 added: f32,
61 },
62 Clamped {
63 value: Box<LevelBasedValue>,
64 min: f32,
65 max: f32,
66 },
67 Fraction {
68 numerator: Box<LevelBasedValue>,
69 denominator: Box<LevelBasedValue>,
70 },
71 Lookup {
72 values: Vec<f32>,
73 fallback: Box<LevelBasedValue>,
74 },
75}
76impl LevelBasedValue {
77 pub fn calculate(&self, n: i32) -> f32 {
78 match self {
79 Self::Constant(v) => *v,
80 Self::Dispatch(v) => v.calculate(n),
81 }
82 }
83}
84impl DispatchLevelBasedValue {
85 pub fn calculate(&self, n: i32) -> f32 {
86 match self {
87 Self::Exponent { base, power } => {
88 (base.calculate(n) as f64).powf(power.calculate(n) as f64) as f32
89 }
90 Self::Linear {
91 base,
92 per_level_above_first,
93 } => *base + *per_level_above_first * ((n - 1) as f32),
94 Self::LevelsSquared { added } => (n * n) as f32 + *added,
95 Self::Clamped { value, min, max } => value.calculate(n).clamp(*min, *max),
96 Self::Fraction {
97 numerator,
98 denominator,
99 } => {
100 let value = denominator.calculate(n);
101 if value == 0. {
102 0.
103 } else {
104 numerator.calculate(n) / value
105 }
106 }
107 Self::Lookup { values, fallback } => values
108 .get((n - 1) as usize)
109 .copied()
110 .unwrap_or_else(|| fallback.calculate(n)),
111 }
112 }
113}
114
115impl Default for LevelBasedValue {
116 fn default() -> Self {
117 Self::Constant(0.)
118 }
119}