bevy_gauge 0.5.1

A flexible attribute and stat system for Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use bevy::ecs::query::QueryFilter;
use bevy::prelude::*;

use crate::attributes_mut::AttributesMut;
use crate::node::ReduceFn;
use crate::tags::TagMask;

// ---------------------------------------------------------------------------
// AttributeBuilder trait
// ---------------------------------------------------------------------------

/// Trait for structural attribute operations that run during initialization.
///
/// Builders set up attribute structure (nodes, expressions, dependencies)
/// before modifier values are applied. Unlike modifier entries, builders
/// are not reversible via [`ModifierSet::remove`].
///
/// Implement this for custom attribute setup patterns. bevy_gauge provides
/// [`ComplexAttribute`] as a built-in builder.
pub trait AttributeBuilder: Send + Sync {
    /// Apply this builder's operations to the given entity.
    fn apply(&self, entity: Entity, attributes: &mut AttributesMut);

    /// Clone this builder into a boxed trait object.
    fn clone_box(&self) -> Box<dyn AttributeBuilder>;

    /// Format this builder for debug output.
    fn fmt_debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}

impl Clone for Box<dyn AttributeBuilder> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

impl std::fmt::Debug for Box<dyn AttributeBuilder> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_debug(f)
    }
}

// ---------------------------------------------------------------------------
// ComplexAttribute builder
// ---------------------------------------------------------------------------

/// A builder that creates a complex attribute with named parts and an expression.
///
/// When applied, this creates part nodes with the specified reduce functions
/// and wires up an expression modifier on the parent attribute.
///
/// # Example
///
/// ```ignore
/// let builder = ComplexAttribute::new("Damage",
///     &[("base", ReduceFn::Sum), ("increased", ReduceFn::Sum)],
///     "base * (1 + increased)",
/// );
/// ```
#[derive(Clone, Debug)]
pub struct ComplexAttribute {
    pub name: String,
    pub parts: Vec<(String, ReduceFn)>,
    pub expression: String,
}

impl ComplexAttribute {
    pub fn new(name: &str, parts: &[(&str, ReduceFn)], expression: &str) -> Self {
        Self {
            name: name.to_string(),
            parts: parts.iter().map(|(n, r)| (n.to_string(), r.clone())).collect(),
            expression: expression.to_string(),
        }
    }
}

impl AttributeBuilder for ComplexAttribute {
    fn apply(&self, entity: Entity, attributes: &mut AttributesMut) {
        let parts: Vec<(&str, ReduceFn)> = self.parts
            .iter()
            .map(|(n, r)| (n.as_str(), r.clone()))
            .collect();
        let _ = attributes.complex_attribute(entity, &self.name, &parts, &self.expression);
    }

    fn clone_box(&self) -> Box<dyn AttributeBuilder> {
        Box::new(self.clone())
    }

    fn fmt_debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(self, f)
    }
}

// ---------------------------------------------------------------------------
// ModifierValue
// ---------------------------------------------------------------------------

/// How a modifier value is stored before application.
///
/// - `Literal` values become `Modifier::Flat` when applied.
/// - `ExprSource` values are compiled to `Modifier::Expr` when applied (at
///   which point the `Interner` and `TagResolver` are available).
#[derive(Clone, Debug)]
pub enum ModifierValue {
    /// A constant f32 value.
    Literal(f32),
    /// An expression source string to be compiled at apply time.
    ExprSource(String),
}

impl From<f32> for ModifierValue {
    fn from(val: f32) -> Self {
        ModifierValue::Literal(val)
    }
}

impl From<&str> for ModifierValue {
    fn from(s: &str) -> Self {
        ModifierValue::ExprSource(s.to_string())
    }
}

impl From<String> for ModifierValue {
    fn from(s: String) -> Self {
        ModifierValue::ExprSource(s)
    }
}

/// A single entry in a [`ModifierSet`].
#[derive(Clone, Debug)]
pub struct ModifierEntry {
    /// The attribute path (e.g., `"Damage.Added"`).
    pub attribute: String,
    /// The modifier value - either a literal or an expression source string.
    pub value: ModifierValue,
    /// Tag mask for the modifier. `TagMask::NONE` means global.
    pub tag: TagMask,
}

// ---------------------------------------------------------------------------
// ModifierSet
// ---------------------------------------------------------------------------

/// A portable collection of modifiers and builders that can be applied to an entity.
///
/// Build one manually or via the [`attributes!`] / [`mod_set!`] macros.
/// Apply it to an entity by spawning it as [`AttributeInitializer`] or by
/// calling [`apply`](Self::apply) directly with an [`AttributesMut`].
///
/// # Example
///
/// ```ignore
/// let mut set = ModifierSet::new();
/// set.add("Strength", 50.0);
/// set.add_tagged("Damage.Added", 25.0, FIRE | MELEE);
/// set.add_expr("Health", "Strength * 2.0");
/// set.add_builder(ComplexAttribute::new("Damage",
///     &[("base", ReduceFn::Sum), ("increased", ReduceFn::Sum)],
///     "base * (1 + increased)",
/// ));
/// set.apply(entity, &mut attributes);
/// ```
#[derive(Clone, Debug, Default)]
pub struct ModifierSet {
    pub(crate) entries: Vec<ModifierEntry>,
    pub(crate) builders: Vec<Box<dyn AttributeBuilder>>,
}

impl ModifierSet {
    /// Create a new empty modifier set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns a slice of all modifier entries in this set.
    pub fn entries(&self) -> &[ModifierEntry] {
        &self.entries
    }

    /// Add an untagged modifier (literal f32 or expression string).
    pub fn add(&mut self, attribute: &str, value: impl Into<ModifierValue>) {
        self.entries.push(ModifierEntry {
            attribute: attribute.to_string(),
            value: value.into(),
            tag: TagMask::NONE,
        });
    }

    /// Add a tagged modifier (literal f32 or expression string).
    pub fn add_tagged(&mut self, attribute: &str, value: impl Into<ModifierValue>, tag: TagMask) {
        self.entries.push(ModifierEntry {
            attribute: attribute.to_string(),
            value: value.into(),
            tag,
        });
    }

    /// Add an untagged expression modifier from a source string.
    pub fn add_expr(&mut self, attribute: &str, expr_source: &str) {
        self.add(
            attribute,
            ModifierValue::ExprSource(expr_source.to_string()),
        );
    }

    /// Add a tagged expression modifier from a source string.
    pub fn add_expr_tagged(&mut self, attribute: &str, expr_source: &str, tag: TagMask) {
        self.add_tagged(
            attribute,
            ModifierValue::ExprSource(expr_source.to_string()),
            tag,
        );
    }

    /// Add an [`AttributeBuilder`] for structural attribute setup.
    ///
    /// Builders run before modifier entries during [`apply_all`](Self::apply_all),
    /// so attribute structure (nodes, expressions) is in place before values flow in.
    pub fn add_builder(&mut self, builder: impl AttributeBuilder + 'static) {
        self.builders.push(Box::new(builder));
    }

    /// Run all builders on an entity. Called before modifier entries so that
    /// attribute structure is wired up before values are applied.
    pub fn apply_builders(&self, entity: Entity, attributes: &mut AttributesMut) {
        for builder in &self.builders {
            builder.apply(entity, attributes);
        }
    }

    /// Apply all modifiers in this set to an entity via `AttributesMut`.
    ///
    /// Literal values are added as flat modifiers. Expression strings are
    /// compiled and added as expression modifiers (compilation errors are
    /// silently ignored - use `try_apply` for error handling).
    ///
    /// **Note:** this does not run builders. The [`AttributeInitializer`]
    /// observer calls [`apply_builders`](Self::apply_builders) before this
    /// method automatically. If calling manually, use [`apply_all`](Self::apply_all).
    pub fn apply<F: QueryFilter>(&self, entity: Entity, attributes: &mut AttributesMut<'_, '_, F>) {
        for entry in &self.entries {
            match &entry.value {
                ModifierValue::Literal(val) => {
                    attributes.add_modifier_tagged(entity, &entry.attribute, *val, entry.tag);
                }
                ModifierValue::ExprSource(src) => {
                    if entry.tag.is_empty() {
                        let _ = attributes.add_expr_modifier(entity, &entry.attribute, src);
                    } else {
                        let _ = attributes.add_expr_modifier_tagged(
                            entity,
                            &entry.attribute,
                            src,
                            entry.tag,
                        );
                    }
                }
            }
        }
    }

    /// Apply all modifiers, returning errors for any expression compilation failures.
    pub fn try_apply<F: QueryFilter>(
        &self,
        entity: Entity,
        attributes: &mut AttributesMut<'_, '_, F>,
    ) -> Result<(), crate::expr::CompileError> {
        for entry in &self.entries {
            match &entry.value {
                ModifierValue::Literal(val) => {
                    attributes.add_modifier_tagged(entity, &entry.attribute, *val, entry.tag);
                }
                ModifierValue::ExprSource(src) => {
                    if entry.tag.is_empty() {
                        attributes.add_expr_modifier(entity, &entry.attribute, src)?;
                    } else {
                        attributes.add_expr_modifier_tagged(
                            entity,
                            &entry.attribute,
                            src,
                            entry.tag,
                        )?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Convenience: run builders then apply modifiers in one call.
    ///
    /// Equivalent to calling [`apply_builders`](Self::apply_builders) followed
    /// by [`apply`](Self::apply). Only works with unfiltered `AttributesMut`.
    pub fn apply_all(&self, entity: Entity, attributes: &mut AttributesMut) {
        self.apply_builders(entity, attributes);
        self.apply(entity, attributes);
    }

    /// Remove all modifiers in this set from an entity via `AttributesMut`.
    ///
    /// This is the inverse of [`apply`](Self::apply). Literal values are removed
    /// as flat modifiers. Expression strings are recompiled and removed as
    /// expression modifiers (compilation errors are silently ignored).
    ///
    /// Builders are not reversed - they define structure, not removable modifiers.
    pub fn remove<F: QueryFilter>(
        &self,
        entity: Entity,
        attributes: &mut AttributesMut<'_, '_, F>,
    ) {
        for entry in &self.entries {
            match &entry.value {
                ModifierValue::Literal(val) => {
                    let modifier = crate::modifier::Modifier::Flat(*val);
                    attributes.remove_modifier_tagged(
                        entity,
                        &entry.attribute,
                        &modifier,
                        entry.tag,
                    );
                }
                ModifierValue::ExprSource(src) => {
                    if let Ok(expr) =
                        crate::expr::Expr::compile(src, Some(attributes.tag_resolver()))
                    {
                        let modifier = crate::modifier::Modifier::Expr(expr);
                        attributes.remove_modifier_tagged(
                            entity,
                            &entry.attribute,
                            &modifier,
                            entry.tag,
                        );
                    }
                }
            }
        }
    }

    /// Remove all modifiers, returning errors for any expression compilation failures.
    pub fn try_remove<F: QueryFilter>(
        &self,
        entity: Entity,
        attributes: &mut AttributesMut<'_, '_, F>,
    ) -> Result<(), crate::expr::CompileError> {
        for entry in &self.entries {
            match &entry.value {
                ModifierValue::Literal(val) => {
                    let modifier = crate::modifier::Modifier::Flat(*val);
                    attributes.remove_modifier_tagged(
                        entity,
                        &entry.attribute,
                        &modifier,
                        entry.tag,
                    );
                }
                ModifierValue::ExprSource(src) => {
                    let expr = crate::expr::Expr::compile(src, Some(attributes.tag_resolver()))?;
                    let modifier = crate::modifier::Modifier::Expr(expr);
                    attributes.remove_modifier_tagged(
                        entity,
                        &entry.attribute,
                        &modifier,
                        entry.tag,
                    );
                }
            }
        }
        Ok(())
    }

    /// Append all entries and builders from another modifier set into this one.
    pub fn combine(&mut self, other: &ModifierSet) {
        self.entries.extend(other.entries.iter().cloned());
        self.builders.extend(other.builders.iter().map(|b| b.clone_box()));
    }

    /// Number of modifier entries in this set (excludes builders).
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether this set has no entries and no builders.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty() && self.builders.is_empty()
    }
}

// ---------------------------------------------------------------------------
// AttributeInitializer
// ---------------------------------------------------------------------------

/// A component that carries a [`ModifierSet`] to be applied on spawn.
///
/// When this component is added to an entity that also has [`Attributes`],
/// the builders and modifiers are automatically applied via an observer,
/// and the `AttributeInitializer` component is removed.
///
/// # Example
///
/// ```ignore
/// commands.spawn((
///     Attributes::new(),
///     AttributeInitializer::new(my_modifier_set),
/// ));
/// ```
///
/// Or with the [`attributes!`] macro:
///
/// ```ignore
/// commands.spawn((
///     Attributes::new(),
///     attributes! {
///         "Strength" => 50.0,
///         "Health" => "Strength * 2.0",
///     },
/// ));
/// ```
#[derive(Component, Clone, Debug, Default)]
#[require(crate::prelude::Attributes)]
pub struct AttributeInitializer(pub ModifierSet);

impl AttributeInitializer {
    /// Create a new `AttributeInitializer` from a modifier set.
    pub fn new(set: ModifierSet) -> Self {
        Self(set)
    }
}

/// Observer that applies `AttributeInitializer` when the component is added.
pub(crate) fn apply_initial_attributes(
    trigger: On<Add, AttributeInitializer>,
    initial_query: Query<&AttributeInitializer>,
    mut attributes: AttributesMut,
    mut commands: Commands,
) {
    let entity = trigger.entity;
    if let Ok(initial) = initial_query.get(entity) {
        initial.0.apply_builders(entity, &mut attributes);
        initial.0.apply(entity, &mut attributes);
    }
    // Remove the component now that it's been applied
    commands.entity(entity).remove::<AttributeInitializer>();
}