Skip to main content

voxel_framework/effects/
mod.rs

1//! Author-defined effect registries and active effect state.
2//!
3//! `effects` is a horizontal gameplay-definition layer. It does **not** ship
4//! poison, speed, regeneration, potion, survival, or player-specific behavior.
5//! The game author defines effect ids, metadata, tags, stacks, durations, and
6//! the systems that interpret active effects.
7//!
8//! The framework provides three generic pieces:
9//!
10//! - [`EffectRegistry`] — author-defined metadata for effects.
11//! - [`ActiveEffectSet`] — runtime effect instances, usable globally or as a
12//!   component on any entity.
13//! - [`EffectApplied`] / [`EffectExpired`] plus helper functions for Bevy
14//!   systems that want to react to effect lifecycle changes.
15//!
16//! # Example
17//!
18//! ```rust
19//! use bevy::ecs::message::MessageWriter;
20//! use bevy::prelude::*;
21//! use voxel_framework::effects::{
22//!     ActiveEffectSet, EffectApplied, EffectDefinition, EffectRegistry, VoxelEffectsPlugin,
23//!     apply_effect,
24//! };
25//!
26//! fn register_effects(mut effects: ResMut<EffectRegistry>) {
27//!     effects
28//!         .register(
29//!             EffectDefinition::new("low_oxygen")
30//!                 .named("Low Oxygen")
31//!                 .duration_secs(10.0)
32//!                 .max_stacks(3)
33//!                 .tag("space_suit"),
34//!         )
35//!         .expect("effect id should be unique");
36//! }
37//!
38//! fn apply_low_oxygen(
39//!     registry: Res<EffectRegistry>,
40//!     mut active: ResMut<ActiveEffectSet>,
41//!     mut applied: MessageWriter<EffectApplied>,
42//! ) {
43//!     apply_effect("low_oxygen", &registry, &mut active, &mut applied)
44//!         .expect("effect should exist");
45//! }
46//!
47//! App::new()
48//!     .add_plugins(MinimalPlugins)
49//!     .add_plugins(VoxelEffectsPlugin)
50//!     .add_systems(Startup, register_effects)
51//!     .add_systems(Update, apply_low_oxygen);
52//! ```
53
54use std::collections::{BTreeMap, HashMap, HashSet};
55use std::fmt;
56
57use bevy::ecs::message::MessageWriter;
58use bevy::prelude::{App, Component, Message, Plugin, Resource};
59use serde::{Deserialize, Serialize};
60
61use crate::content::ContentValue;
62
63/// Stable identifier for an author-defined effect.
64#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
65pub struct EffectId(String);
66
67impl EffectId {
68    /// Creates a new effect id from any string-like value.
69    pub fn new(id: impl Into<String>) -> Self {
70        Self(id.into())
71    }
72
73    /// Returns the raw id string.
74    pub fn as_str(&self) -> &str {
75        &self.0
76    }
77}
78
79impl From<&str> for EffectId {
80    fn from(value: &str) -> Self {
81        Self::new(value)
82    }
83}
84
85impl From<String> for EffectId {
86    fn from(value: String) -> Self {
87        Self::new(value)
88    }
89}
90
91impl AsRef<str> for EffectId {
92    fn as_ref(&self) -> &str {
93        self.as_str()
94    }
95}
96
97impl fmt::Display for EffectId {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.write_str(self.as_str())
100    }
101}
102
103/// Author-defined effect metadata.
104#[derive(Debug, Clone, PartialEq)]
105pub struct EffectDefinition {
106    id: EffectId,
107    display_name: String,
108    default_duration_secs: Option<f32>,
109    max_stacks: u32,
110    attributes: HashMap<String, ContentValue>,
111    tags: HashSet<String>,
112}
113
114/// Serializable snapshot of one author-defined effect definition.
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116pub struct EffectDefinitionSnapshot {
117    /// Stable author-defined id.
118    pub id: EffectId,
119    /// Display name intended for UI/docs.
120    pub display_name: String,
121    /// Default duration for newly applied instances. `None` means indefinite.
122    pub default_duration_secs: Option<f32>,
123    /// Maximum stack count when repeatedly applying this effect.
124    pub max_stacks: u32,
125    /// Author-defined attributes in deterministic key order.
126    pub attributes: BTreeMap<String, ContentValue>,
127    /// Author-defined tags in deterministic lexical order.
128    pub tags: Vec<String>,
129}
130
131impl EffectDefinition {
132    /// Creates an indefinite, single-stack effect definition.
133    pub fn new(id: impl Into<EffectId>) -> Self {
134        Self {
135            id: id.into(),
136            display_name: String::new(),
137            default_duration_secs: None,
138            max_stacks: 1,
139            attributes: HashMap::new(),
140            tags: HashSet::new(),
141        }
142    }
143
144    /// Returns the stable author-defined id.
145    pub fn id(&self) -> &EffectId {
146        &self.id
147    }
148
149    /// Returns the display name intended for UI/docs.
150    pub fn display_name(&self) -> &str {
151        if self.display_name.is_empty() {
152            self.id.as_str()
153        } else {
154            &self.display_name
155        }
156    }
157
158    /// Replaces the display name.
159    pub fn named(mut self, name: impl Into<String>) -> Self {
160        self.display_name = name.into();
161        self
162    }
163
164    /// Returns the default duration for newly applied instances.
165    pub fn default_duration_secs(&self) -> Option<f32> {
166        self.default_duration_secs
167    }
168
169    /// Sets the default duration for newly applied instances.
170    pub fn duration_secs(mut self, duration_secs: f32) -> Self {
171        self.default_duration_secs = Some(non_negative_finite_or_zero(duration_secs));
172        self
173    }
174
175    /// Makes newly applied instances indefinite.
176    pub fn indefinite(mut self) -> Self {
177        self.default_duration_secs = None;
178        self
179    }
180
181    /// Returns the maximum stack count for this effect.
182    pub fn max_stacks_value(&self) -> u32 {
183        self.max_stacks
184    }
185
186    /// Sets the maximum stack count. Values below `1` are normalized to `1`.
187    pub fn max_stacks(mut self, max_stacks: u32) -> Self {
188        self.max_stacks = max_stacks.max(1);
189        self
190    }
191
192    /// Adds or replaces an author-defined gameplay attribute.
193    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
194        self.attributes.insert(key.into(), value.into());
195        self
196    }
197
198    /// Adds an author-defined tag.
199    pub fn tag(mut self, tag: impl Into<String>) -> Self {
200        self.tags.insert(tag.into());
201        self
202    }
203
204    /// Returns a gameplay attribute by key.
205    pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
206        self.attributes.get(key)
207    }
208
209    /// Returns a numeric gameplay attribute by key.
210    pub fn number_attribute(&self, key: &str) -> Option<f64> {
211        self.get_attribute(key).and_then(ContentValue::as_number)
212    }
213
214    /// Returns a boolean gameplay attribute by key.
215    pub fn bool_attribute(&self, key: &str) -> Option<bool> {
216        self.get_attribute(key).and_then(ContentValue::as_bool)
217    }
218
219    /// Returns a text gameplay attribute by key.
220    pub fn text_attribute(&self, key: &str) -> Option<&str> {
221        self.get_attribute(key).and_then(ContentValue::as_str)
222    }
223
224    /// Returns all gameplay attributes.
225    pub fn attributes(&self) -> &HashMap<String, ContentValue> {
226        &self.attributes
227    }
228
229    /// Returns true when the author-defined tag exists.
230    pub fn has_tag(&self, tag: &str) -> bool {
231        self.tags.contains(tag)
232    }
233
234    /// Returns all author-defined tags.
235    pub fn tags(&self) -> &HashSet<String> {
236        &self.tags
237    }
238
239    /// Creates a serializable, deterministic snapshot of this effect definition.
240    pub fn snapshot(&self) -> EffectDefinitionSnapshot {
241        EffectDefinitionSnapshot {
242            id: self.id.clone(),
243            display_name: self.display_name().to_owned(),
244            default_duration_secs: self.default_duration_secs,
245            max_stacks: self.max_stacks,
246            attributes: ordered_attributes(&self.attributes),
247            tags: ordered_tags(&self.tags),
248        }
249    }
250}
251
252/// Errors returned by effect registries and active effect sets.
253#[derive(Debug, Clone, PartialEq)]
254pub enum EffectError {
255    /// An effect with the same id already exists.
256    DuplicateId { id: EffectId },
257    /// No effect exists for the requested id.
258    MissingId { id: EffectId },
259}
260
261impl fmt::Display for EffectError {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        match self {
264            Self::DuplicateId { id } => write!(f, "effect id `{id}` is already registered"),
265            Self::MissingId { id } => write!(f, "effect id `{id}` is not registered"),
266        }
267    }
268}
269
270impl std::error::Error for EffectError {}
271
272/// Registry of author-defined effect definitions.
273#[derive(Debug, Clone, Default, Resource)]
274pub struct EffectRegistry {
275    effects_by_id: HashMap<EffectId, EffectDefinition>,
276}
277
278impl EffectRegistry {
279    /// Registers a new effect definition.
280    pub fn register(&mut self, definition: EffectDefinition) -> Result<(), EffectError> {
281        if self.effects_by_id.contains_key(definition.id()) {
282            return Err(EffectError::DuplicateId {
283                id: definition.id().clone(),
284            });
285        }
286
287        self.effects_by_id
288            .insert(definition.id().clone(), definition);
289        Ok(())
290    }
291
292    /// Inserts a definition, replacing any previous definition for the same id.
293    pub fn insert_or_replace(&mut self, definition: EffectDefinition) {
294        self.effects_by_id
295            .insert(definition.id().clone(), definition);
296    }
297
298    /// Returns a definition by effect id.
299    pub fn get(&self, id: impl AsRef<str>) -> Option<&EffectDefinition> {
300        let id = EffectId::new(id.as_ref());
301        self.effects_by_id.get(&id)
302    }
303
304    /// Returns a definition by id or an explicit error.
305    pub fn require(&self, id: impl AsRef<str>) -> Result<&EffectDefinition, EffectError> {
306        let id = EffectId::new(id.as_ref());
307        self.effects_by_id
308            .get(&id)
309            .ok_or(EffectError::MissingId { id })
310    }
311
312    /// Returns true if an id exists.
313    pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
314        self.get(id).is_some()
315    }
316
317    /// Number of registered effect definitions.
318    pub fn len(&self) -> usize {
319        self.effects_by_id.len()
320    }
321
322    /// Returns true when no effect definitions are registered.
323    pub fn is_empty(&self) -> bool {
324        self.effects_by_id.is_empty()
325    }
326
327    /// Iterates definitions in unspecified hash-map order.
328    pub fn iter(&self) -> impl Iterator<Item = &EffectDefinition> {
329        self.effects_by_id.values()
330    }
331
332    /// Returns deterministic serializable snapshots of all registered effects.
333    pub fn snapshot(&self) -> Vec<EffectDefinitionSnapshot> {
334        let mut effects: Vec<_> = self.iter().map(EffectDefinition::snapshot).collect();
335        effects.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
336        effects
337    }
338}
339
340/// Runtime instance of an author-defined effect.
341#[derive(Debug, Clone, PartialEq, Serialize)]
342pub struct EffectInstance {
343    id: EffectId,
344    duration_secs: Option<f32>,
345    remaining_secs: Option<f32>,
346    stacks: u32,
347}
348
349/// Serializable snapshot of one active effect instance.
350#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
351pub struct EffectInstanceSnapshot {
352    /// Stable author-defined id.
353    pub id: EffectId,
354    /// Initial duration captured when the instance was applied. `None` means indefinite.
355    pub duration_secs: Option<f32>,
356    /// Remaining duration. `None` means indefinite.
357    pub remaining_secs: Option<f32>,
358    /// Current stack count.
359    pub stacks: u32,
360}
361
362impl EffectInstance {
363    /// Creates an effect instance with an initial duration and stack count.
364    ///
365    /// The provided duration is stored as both the original duration and the
366    /// current remaining duration. `None` means indefinite.
367    pub fn new(id: impl Into<EffectId>, duration_secs: Option<f32>, stacks: u32) -> Self {
368        let duration_secs = duration_secs.map(non_negative_finite_or_zero);
369        Self::with_runtime_state(id, duration_secs, duration_secs, stacks)
370    }
371
372    /// Creates an effect instance with explicit original and remaining durations.
373    ///
374    /// This is useful when hydrating effect state from author-owned save data or
375    /// when forwarding an already-ticked instance. Durations are normalized to
376    /// finite, non-negative values; `None` means indefinite.
377    pub fn with_runtime_state(
378        id: impl Into<EffectId>,
379        duration_secs: Option<f32>,
380        remaining_secs: Option<f32>,
381        stacks: u32,
382    ) -> Self {
383        Self {
384            id: id.into(),
385            duration_secs: duration_secs.map(non_negative_finite_or_zero),
386            remaining_secs: remaining_secs.map(non_negative_finite_or_zero),
387            stacks: stacks.max(1),
388        }
389    }
390
391    /// Creates an instance from a registered definition's defaults.
392    pub fn from_definition(definition: &EffectDefinition) -> Self {
393        Self::new(
394            definition.id().clone(),
395            definition.default_duration_secs(),
396            1,
397        )
398    }
399
400    /// Returns the stable author-defined id.
401    pub fn id(&self) -> &EffectId {
402        &self.id
403    }
404
405    /// Returns the initial duration captured when the instance was applied.
406    ///
407    /// `None` means the effect is indefinite.
408    pub fn duration_secs(&self) -> Option<f32> {
409        self.duration_secs
410    }
411
412    /// Returns remaining duration. `None` means indefinite.
413    pub fn remaining_secs(&self) -> Option<f32> {
414        self.remaining_secs
415    }
416
417    /// Returns the remaining fraction of the original duration.
418    ///
419    /// Timed effects return a value clamped to `0.0..=1.0`. Indefinite effects
420    /// return `None` because they have no finite denominator.
421    pub fn remaining_ratio(&self) -> Option<f32> {
422        let duration_secs = self.duration_secs?;
423        if duration_secs <= f32::EPSILON {
424            return Some(0.0);
425        }
426
427        Some((self.remaining_secs.unwrap_or(0.0) / duration_secs).clamp(0.0, 1.0))
428    }
429
430    /// Returns the current stack count.
431    pub fn stacks(&self) -> u32 {
432        self.stacks
433    }
434
435    /// Returns true when the instance has a finite duration.
436    pub fn is_timed(&self) -> bool {
437        self.remaining_secs.is_some()
438    }
439
440    /// Returns a serializable snapshot of this effect instance.
441    pub fn snapshot(&self) -> EffectInstanceSnapshot {
442        EffectInstanceSnapshot {
443            id: self.id.clone(),
444            duration_secs: self.duration_secs,
445            remaining_secs: self.remaining_secs,
446            stacks: self.stacks,
447        }
448    }
449}
450
451impl<'de> Deserialize<'de> for EffectInstance {
452    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
453    where
454        D: serde::Deserializer<'de>,
455    {
456        #[derive(Deserialize)]
457        struct SerializedEffectInstance {
458            id: EffectId,
459            #[serde(default)]
460            duration_secs: Option<f32>,
461            remaining_secs: Option<f32>,
462            stacks: u32,
463        }
464
465        let serialized = SerializedEffectInstance::deserialize(deserializer)?;
466        let duration_secs = serialized.duration_secs.or(serialized.remaining_secs);
467        Ok(Self::with_runtime_state(
468            serialized.id,
469            duration_secs,
470            serialized.remaining_secs,
471            serialized.stacks,
472        ))
473    }
474}
475
476/// Active author-defined effect instances.
477///
478/// An `ActiveEffectSet` can be used as a global [`Resource`] or attached to
479/// entities as a [`Component`]. The framework does not assign meaning to the
480/// owner: it can be a player, mob, vehicle, machine, region, settlement, or any
481/// author-defined subject.
482#[derive(Debug, Clone, Default, Component, Resource, Serialize, Deserialize)]
483pub struct ActiveEffectSet {
484    effects_by_id: HashMap<EffectId, EffectInstance>,
485}
486
487impl ActiveEffectSet {
488    /// Creates an empty active effect set.
489    pub fn new() -> Self {
490        Self::default()
491    }
492
493    /// Applies an effect by id using registry defaults.
494    ///
495    /// Re-applying an active effect refreshes its duration from the definition
496    /// and increments stacks up to the definition's `max_stacks`.
497    pub fn apply(
498        &mut self,
499        id: impl AsRef<str>,
500        registry: &EffectRegistry,
501    ) -> Result<EffectInstance, EffectError> {
502        let definition = registry.require(id.as_ref())?;
503        let next = match self.effects_by_id.get(definition.id()) {
504            Some(current) => EffectInstance::new(
505                definition.id().clone(),
506                definition.default_duration_secs(),
507                (current.stacks() + 1).min(definition.max_stacks_value()),
508            ),
509            None => EffectInstance::from_definition(definition),
510        };
511        self.effects_by_id
512            .insert(definition.id().clone(), next.clone());
513        Ok(next)
514    }
515
516    /// Applies an explicit instance after resolving and clamping it through the registry.
517    pub fn apply_instance(
518        &mut self,
519        instance: EffectInstance,
520        registry: &EffectRegistry,
521    ) -> Result<EffectInstance, EffectError> {
522        let definition = registry.require(instance.id().as_str())?;
523        let next = EffectInstance::with_runtime_state(
524            definition.id().clone(),
525            instance.duration_secs(),
526            instance.remaining_secs(),
527            instance.stacks().min(definition.max_stacks_value()),
528        );
529        self.effects_by_id
530            .insert(definition.id().clone(), next.clone());
531        Ok(next)
532    }
533
534    /// Removes an active effect by id.
535    pub fn remove(&mut self, id: impl AsRef<str>) -> Option<EffectInstance> {
536        let id = EffectId::new(id.as_ref());
537        self.effects_by_id.remove(&id)
538    }
539
540    /// Advances finite durations and returns expired instances.
541    ///
542    /// Indefinite effects are not affected. Non-finite or negative deltas are
543    /// normalized to `0.0`.
544    pub fn tick(&mut self, delta_secs: f32) -> Vec<EffectInstance> {
545        let delta_secs = non_negative_finite_or_zero(delta_secs);
546        if delta_secs == 0.0 {
547            return Vec::new();
548        }
549
550        let mut expired_ids = Vec::new();
551        for (id, instance) in &mut self.effects_by_id {
552            let Some(remaining_secs) = &mut instance.remaining_secs else {
553                continue;
554            };
555            *remaining_secs = non_negative_finite_or_zero(*remaining_secs - delta_secs);
556            if *remaining_secs <= f32::EPSILON {
557                expired_ids.push(id.clone());
558            }
559        }
560
561        let mut expired = Vec::with_capacity(expired_ids.len());
562        for id in expired_ids {
563            if let Some(instance) = self.effects_by_id.remove(&id) {
564                expired.push(instance);
565            }
566        }
567        expired.sort_by(|left, right| left.id().as_str().cmp(right.id().as_str()));
568        expired
569    }
570
571    /// Returns true when an effect id is active.
572    pub fn has(&self, id: impl AsRef<str>) -> bool {
573        self.get(id).is_some()
574    }
575
576    /// Returns true when an effect id is active.
577    ///
578    /// This is a read-side alias for [`ActiveEffectSet::has`].
579    pub fn is_active(&self, id: impl AsRef<str>) -> bool {
580        self.has(id)
581    }
582
583    /// Returns an active effect by id.
584    pub fn get(&self, id: impl AsRef<str>) -> Option<&EffectInstance> {
585        let id = EffectId::new(id.as_ref());
586        self.effects_by_id.get(&id)
587    }
588
589    /// Returns the current stack count for an active effect id, or `0` when inactive.
590    pub fn stacks(&self, id: impl AsRef<str>) -> u32 {
591        self.get(id).map_or(0, EffectInstance::stacks)
592    }
593
594    /// Returns the remaining duration for an active effect id.
595    ///
596    /// `None` means the effect is inactive or indefinite.
597    pub fn remaining_secs(&self, id: impl AsRef<str>) -> Option<f32> {
598        self.get(id).and_then(EffectInstance::remaining_secs)
599    }
600
601    /// Returns the remaining fraction for an active timed effect id.
602    ///
603    /// `None` means the effect is inactive or indefinite.
604    pub fn remaining_ratio(&self, id: impl AsRef<str>) -> Option<f32> {
605        self.get(id).and_then(EffectInstance::remaining_ratio)
606    }
607
608    /// Number of active effects.
609    pub fn len(&self) -> usize {
610        self.effects_by_id.len()
611    }
612
613    /// Returns true when no effects are active.
614    pub fn is_empty(&self) -> bool {
615        self.effects_by_id.is_empty()
616    }
617
618    /// Iterates active effects in unspecified hash-map order.
619    pub fn iter(&self) -> impl Iterator<Item = &EffectInstance> {
620        self.effects_by_id.values()
621    }
622
623    /// Returns deterministic serializable snapshots of all active effects.
624    pub fn snapshot(&self) -> Vec<EffectInstanceSnapshot> {
625        let mut effects: Vec<_> = self.iter().map(EffectInstance::snapshot).collect();
626        effects.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
627        effects
628    }
629}
630
631/// Message emitted by [`apply_effect`] and [`apply_effect_instance`].
632///
633/// The framework does not interpret the effect id. Systems in the consuming
634/// game decide whether an applied effect changes stats, UI, audio, physics,
635/// abilities, AI, or nothing at all.
636#[derive(Message, Debug, Clone, PartialEq, Serialize, Deserialize)]
637pub struct EffectApplied {
638    /// Stable author-defined effect id.
639    pub id: EffectId,
640    /// Previous active instance, if the effect was already active.
641    pub previous: Option<EffectInstance>,
642    /// Current active instance after applying.
643    pub current: EffectInstance,
644}
645
646/// Message emitted by [`tick_effects`] when finite effects expire.
647#[derive(Message, Debug, Clone, PartialEq, Serialize, Deserialize)]
648pub struct EffectExpired {
649    /// Stable author-defined effect id.
650    pub id: EffectId,
651    /// Runtime instance removed from the active set.
652    pub expired: EffectInstance,
653}
654
655/// Applies an effect and emits [`EffectApplied`].
656pub fn apply_effect(
657    id: impl AsRef<str>,
658    registry: &EffectRegistry,
659    effects: &mut ActiveEffectSet,
660    applied: &mut MessageWriter<EffectApplied>,
661) -> Result<EffectInstance, EffectError> {
662    let definition = registry.require(id.as_ref())?;
663    let previous = effects.get(definition.id().as_str()).cloned();
664    let current = effects.apply(definition.id().as_str(), registry)?;
665    applied.write(EffectApplied {
666        id: definition.id().clone(),
667        previous,
668        current: current.clone(),
669    });
670    Ok(current)
671}
672
673/// Applies an explicit effect instance and emits [`EffectApplied`].
674pub fn apply_effect_instance(
675    instance: EffectInstance,
676    registry: &EffectRegistry,
677    effects: &mut ActiveEffectSet,
678    applied: &mut MessageWriter<EffectApplied>,
679) -> Result<EffectInstance, EffectError> {
680    let definition = registry.require(instance.id().as_str())?;
681    let previous = effects.get(definition.id().as_str()).cloned();
682    let current = effects.apply_instance(instance, registry)?;
683    applied.write(EffectApplied {
684        id: definition.id().clone(),
685        previous,
686        current: current.clone(),
687    });
688    Ok(current)
689}
690
691/// Advances finite effect durations and emits [`EffectExpired`] for each expired effect.
692pub fn tick_effects(
693    delta_secs: f32,
694    effects: &mut ActiveEffectSet,
695    expired: &mut MessageWriter<EffectExpired>,
696) -> Vec<EffectInstance> {
697    let expired_instances = effects.tick(delta_secs);
698    for instance in &expired_instances {
699        expired.write(EffectExpired {
700            id: instance.id().clone(),
701            expired: instance.clone(),
702        });
703    }
704    expired_instances
705}
706
707/// Horizontal plugin that initializes author-defined effect resources.
708///
709/// This plugin does not register default effects. The game author defines the
710/// effects their game needs and decides how systems interpret them.
711pub struct VoxelEffectsPlugin;
712
713impl Plugin for VoxelEffectsPlugin {
714    fn build(&self, app: &mut App) {
715        app.init_resource::<EffectRegistry>();
716        app.init_resource::<ActiveEffectSet>();
717        app.add_message::<EffectApplied>();
718        app.add_message::<EffectExpired>();
719    }
720}
721
722fn non_negative_finite_or_zero(value: f32) -> f32 {
723    if value.is_finite() {
724        value.max(0.0)
725    } else {
726        0.0
727    }
728}
729
730fn ordered_attributes(
731    attributes: &HashMap<String, ContentValue>,
732) -> BTreeMap<String, ContentValue> {
733    attributes
734        .iter()
735        .map(|(key, value)| (key.clone(), value.clone()))
736        .collect()
737}
738
739fn ordered_tags(tags: &HashSet<String>) -> Vec<String> {
740    let mut tags: Vec<_> = tags.iter().cloned().collect();
741    tags.sort();
742    tags
743}
744
745#[cfg(test)]
746mod tests {
747    use bevy::ecs::message::{MessageReader, MessageWriter};
748    use bevy::prelude::{
749        App, Component, IntoScheduleConfigs, MinimalPlugins, Query, Res, ResMut, Resource, Startup,
750        Update, With,
751    };
752
753    use super::*;
754
755    #[test]
756    fn effect_definition_keeps_author_defined_metadata() {
757        let effect = EffectDefinition::new("low_oxygen")
758            .named("Low Oxygen")
759            .duration_secs(10.0)
760            .max_stacks(3)
761            .tag("space_suit")
762            .attribute("ui_hint", "warning")
763            .attribute("severity", 2.0);
764
765        assert_eq!(effect.id().as_str(), "low_oxygen");
766        assert_eq!(effect.display_name(), "Low Oxygen");
767        assert_eq!(effect.default_duration_secs(), Some(10.0));
768        assert_eq!(effect.max_stacks_value(), 3);
769        assert!(effect.has_tag("space_suit"));
770        assert_eq!(effect.text_attribute("ui_hint"), Some("warning"));
771        assert_eq!(effect.number_attribute("severity"), Some(2.0));
772    }
773
774    #[test]
775    fn effect_definition_normalizes_duration_and_stack_bounds() {
776        let effect = EffectDefinition::new("glitch")
777            .duration_secs(f32::INFINITY)
778            .max_stacks(0);
779
780        assert_eq!(effect.default_duration_secs(), Some(0.0));
781        assert_eq!(effect.max_stacks_value(), 1);
782    }
783
784    #[test]
785    fn registry_rejects_duplicate_ids_and_requires_existing_effects() {
786        let mut registry = EffectRegistry::default();
787        registry
788            .register(EffectDefinition::new("low_oxygen"))
789            .expect("first effect should register");
790
791        assert!(matches!(
792            registry.register(EffectDefinition::new("low_oxygen")),
793            Err(EffectError::DuplicateId { .. })
794        ));
795        assert!(registry.require("low_oxygen").is_ok());
796        assert!(matches!(
797            registry.require("missing"),
798            Err(EffectError::MissingId { .. })
799        ));
800    }
801
802    #[test]
803    fn active_effect_set_applies_refreshes_and_caps_stacks() {
804        let mut registry = EffectRegistry::default();
805        registry
806            .register(
807                EffectDefinition::new("low_oxygen")
808                    .duration_secs(10.0)
809                    .max_stacks(2),
810            )
811            .expect("effect should register");
812        let mut effects = ActiveEffectSet::new();
813
814        let first = effects
815            .apply("low_oxygen", &registry)
816            .expect("effect should exist");
817        assert_eq!(first.duration_secs(), Some(10.0));
818        assert_eq!(first.remaining_secs(), Some(10.0));
819        assert_eq!(first.remaining_ratio(), Some(1.0));
820        assert_eq!(first.stacks(), 1);
821
822        effects.tick(4.0);
823        assert_eq!(effects.remaining_secs("low_oxygen"), Some(6.0));
824        assert_eq!(effects.remaining_ratio("low_oxygen"), Some(0.6));
825        let second = effects
826            .apply("low_oxygen", &registry)
827            .expect("effect should exist");
828        assert_eq!(second.duration_secs(), Some(10.0));
829        assert_eq!(second.remaining_secs(), Some(10.0));
830        assert_eq!(second.remaining_ratio(), Some(1.0));
831        assert_eq!(second.stacks(), 2);
832
833        let third = effects
834            .apply("low_oxygen", &registry)
835            .expect("effect should exist");
836        assert_eq!(third.stacks(), 2);
837    }
838
839    #[test]
840    fn apply_instance_clamps_stacks_to_definition() {
841        let mut registry = EffectRegistry::default();
842        registry
843            .register(EffectDefinition::new("shielded").max_stacks(3))
844            .expect("effect should register");
845        let mut effects = ActiveEffectSet::new();
846
847        let applied = effects
848            .apply_instance(EffectInstance::new("shielded", Some(5.0), 99), &registry)
849            .expect("effect should exist");
850
851        assert_eq!(applied.stacks(), 3);
852        assert_eq!(applied.duration_secs(), Some(5.0));
853        assert_eq!(applied.remaining_secs(), Some(5.0));
854    }
855
856    #[test]
857    fn apply_instance_preserves_original_duration_for_ticked_instances() {
858        let mut registry = EffectRegistry::default();
859        registry
860            .register(EffectDefinition::new("shielded").duration_secs(10.0))
861            .expect("effect should register");
862
863        let mut source = ActiveEffectSet::new();
864        source.apply("shielded", &registry).expect("effect exists");
865        source.tick(4.0);
866        let ticked = source
867            .get("shielded")
868            .expect("effect should still be active")
869            .clone();
870
871        let mut target = ActiveEffectSet::new();
872        let applied = target
873            .apply_instance(ticked, &registry)
874            .expect("effect should exist");
875
876        assert_eq!(applied.duration_secs(), Some(10.0));
877        assert_eq!(applied.remaining_secs(), Some(6.0));
878        assert_eq!(applied.remaining_ratio(), Some(0.6));
879    }
880
881    #[test]
882    fn active_effect_set_ticks_and_expires_timed_effects_only() {
883        let mut registry = EffectRegistry::default();
884        registry
885            .register(EffectDefinition::new("timed").duration_secs(2.0))
886            .expect("effect should register");
887        registry
888            .register(EffectDefinition::new("indefinite"))
889            .expect("effect should register");
890
891        let mut effects = ActiveEffectSet::new();
892        effects.apply("timed", &registry).expect("timed exists");
893        effects
894            .apply("indefinite", &registry)
895            .expect("indefinite exists");
896
897        assert!(effects.tick(f32::NAN).is_empty());
898        assert_eq!(
899            effects
900                .get("timed")
901                .expect("timed should still be active")
902                .duration_secs(),
903            Some(2.0)
904        );
905        assert_eq!(
906            effects
907                .get("timed")
908                .expect("timed should still be active")
909                .remaining_secs(),
910            Some(2.0)
911        );
912        assert_eq!(effects.remaining_ratio("timed"), Some(1.0));
913        assert_eq!(effects.remaining_ratio("indefinite"), None);
914        assert!(effects.tick(1.0).is_empty());
915        assert_eq!(
916            effects
917                .get("timed")
918                .expect("timed should still be active")
919                .remaining_secs(),
920            Some(1.0)
921        );
922        assert_eq!(effects.remaining_ratio("timed"), Some(0.5));
923
924        let expired = effects.tick(1.0);
925        assert_eq!(expired.len(), 1);
926        assert_eq!(expired[0].id().as_str(), "timed");
927        assert!(!effects.has("timed"));
928        assert!(effects.has("indefinite"));
929    }
930
931    #[test]
932    fn active_effect_read_helpers_cover_finite_indefinite_inactive_and_missing() {
933        let mut registry = EffectRegistry::default();
934        registry
935            .register(
936                EffectDefinition::new("timed")
937                    .duration_secs(8.0)
938                    .max_stacks(3),
939            )
940            .expect("effect should register");
941        registry
942            .register(EffectDefinition::new("indefinite").max_stacks(2))
943            .expect("effect should register");
944
945        let mut effects = ActiveEffectSet::new();
946        assert!(!effects.is_active("timed"));
947        assert_eq!(effects.stacks("timed"), 0);
948        assert_eq!(effects.remaining_secs("timed"), None);
949        assert_eq!(effects.remaining_ratio("timed"), None);
950        assert_eq!(effects.stacks("missing"), 0);
951        assert_eq!(effects.remaining_secs("missing"), None);
952        assert_eq!(effects.remaining_ratio("missing"), None);
953
954        effects.apply("timed", &registry).expect("timed exists");
955        effects.apply("timed", &registry).expect("timed exists");
956        effects
957            .apply("indefinite", &registry)
958            .expect("indefinite exists");
959        effects.tick(2.0);
960
961        assert!(effects.is_active("timed"));
962        assert_eq!(effects.stacks("timed"), 2);
963        assert_eq!(effects.remaining_secs("timed"), Some(6.0));
964        assert_eq!(effects.remaining_ratio("timed"), Some(0.75));
965        assert!(effects.is_active("indefinite"));
966        assert_eq!(effects.stacks("indefinite"), 1);
967        assert_eq!(effects.remaining_secs("indefinite"), None);
968        assert_eq!(effects.remaining_ratio("indefinite"), None);
969
970        effects.remove("timed");
971        assert!(!effects.is_active("timed"));
972        assert_eq!(effects.stacks("timed"), 0);
973        assert_eq!(effects.remaining_secs("timed"), None);
974        assert_eq!(effects.remaining_ratio("timed"), None);
975    }
976
977    #[test]
978    fn remaining_ratio_clamps_to_original_duration_bounds() {
979        let expired = EffectInstance::with_runtime_state("expired", Some(10.0), Some(-2.0), 1);
980        let overfull = EffectInstance::with_runtime_state("overfull", Some(10.0), Some(12.0), 1);
981        let instant = EffectInstance::new("instant", Some(0.0), 1);
982        let indefinite = EffectInstance::new("indefinite", None, 1);
983
984        assert_eq!(expired.remaining_ratio(), Some(0.0));
985        assert_eq!(overfull.remaining_ratio(), Some(1.0));
986        assert_eq!(instant.remaining_ratio(), Some(0.0));
987        assert_eq!(indefinite.remaining_ratio(), None);
988    }
989
990    #[test]
991    fn effect_instance_deserializes_legacy_runtime_state_without_duration() {
992        let instance: EffectInstance =
993            serde_json::from_str(r#"{"id":"legacy_timed","remaining_secs":6.0,"stacks":2}"#)
994                .expect("legacy effect instance should deserialize");
995
996        assert_eq!(instance.id().as_str(), "legacy_timed");
997        assert_eq!(instance.duration_secs(), Some(6.0));
998        assert_eq!(instance.remaining_secs(), Some(6.0));
999        assert_eq!(instance.remaining_ratio(), Some(1.0));
1000        assert_eq!(instance.stacks(), 2);
1001    }
1002
1003    #[test]
1004    fn active_effect_set_removes_effects() {
1005        let mut registry = EffectRegistry::default();
1006        registry
1007            .register(EffectDefinition::new("low_oxygen"))
1008            .expect("effect should register");
1009        let mut effects = ActiveEffectSet::new();
1010        effects
1011            .apply("low_oxygen", &registry)
1012            .expect("effect should exist");
1013
1014        let removed = effects
1015            .remove("low_oxygen")
1016            .expect("effect should be active");
1017        assert_eq!(removed.id().as_str(), "low_oxygen");
1018        assert!(effects.is_empty());
1019        assert!(effects.remove("low_oxygen").is_none());
1020    }
1021
1022    #[test]
1023    fn snapshots_are_serializable_and_deterministic() {
1024        let mut registry = EffectRegistry::default();
1025        registry
1026            .register(
1027                EffectDefinition::new("low_oxygen")
1028                    .duration_secs(10.0)
1029                    .tag("space_suit")
1030                    .tag("survival")
1031                    .attribute("ui_hint", "warning"),
1032            )
1033            .expect("effect should register");
1034        registry
1035            .register(EffectDefinition::new("magnetic_boots").indefinite())
1036            .expect("effect should register");
1037
1038        let definition_snapshot = registry.snapshot();
1039        assert_eq!(definition_snapshot[0].id.as_str(), "low_oxygen");
1040        assert_eq!(definition_snapshot[1].id.as_str(), "magnetic_boots");
1041        assert_eq!(
1042            definition_snapshot[0].tags,
1043            vec!["space_suit".to_owned(), "survival".to_owned()]
1044        );
1045
1046        let mut effects = ActiveEffectSet::new();
1047        effects
1048            .apply("low_oxygen", &registry)
1049            .expect("effect should exist");
1050        effects
1051            .apply("magnetic_boots", &registry)
1052            .expect("effect should exist");
1053        let active_snapshot = effects.snapshot();
1054        assert_eq!(active_snapshot[0].id.as_str(), "low_oxygen");
1055        assert_eq!(active_snapshot[0].duration_secs, Some(10.0));
1056        assert_eq!(active_snapshot[0].remaining_secs, Some(10.0));
1057        assert_eq!(active_snapshot[1].id.as_str(), "magnetic_boots");
1058        assert_eq!(active_snapshot[1].duration_secs, None);
1059        assert_eq!(active_snapshot[1].remaining_secs, None);
1060
1061        serde_json::to_string(&definition_snapshot).expect("definitions should serialize");
1062        serde_json::to_string(&active_snapshot).expect("active effects should serialize");
1063    }
1064
1065    #[test]
1066    fn plugin_initializes_empty_resources_without_defaults() {
1067        let mut app = App::new();
1068        app.add_plugins(MinimalPlugins);
1069        app.add_plugins(VoxelEffectsPlugin);
1070
1071        assert!(app.world().resource::<EffectRegistry>().is_empty());
1072        assert!(app.world().resource::<ActiveEffectSet>().is_empty());
1073    }
1074
1075    #[derive(Resource, Default)]
1076    struct ObservedApplied(Vec<EffectApplied>);
1077
1078    #[derive(Resource, Default)]
1079    struct ObservedExpired(Vec<EffectExpired>);
1080
1081    #[derive(Resource, Default)]
1082    struct ObservedErrors(Vec<EffectError>);
1083
1084    #[derive(Component)]
1085    struct EffectSubject;
1086
1087    fn register_test_effect(mut registry: ResMut<EffectRegistry>) {
1088        registry
1089            .register(
1090                EffectDefinition::new("low_oxygen")
1091                    .duration_secs(1.0)
1092                    .max_stacks(2),
1093            )
1094            .expect("effect should register");
1095    }
1096
1097    fn record_applied(
1098        mut reader: MessageReader<EffectApplied>,
1099        mut observed: ResMut<ObservedApplied>,
1100    ) {
1101        observed.0.extend(reader.read().cloned());
1102    }
1103
1104    fn record_expired(
1105        mut reader: MessageReader<EffectExpired>,
1106        mut observed: ResMut<ObservedExpired>,
1107    ) {
1108        observed.0.extend(reader.read().cloned());
1109    }
1110
1111    fn apply_test_effect(
1112        registry: Res<EffectRegistry>,
1113        mut effects: ResMut<ActiveEffectSet>,
1114        mut applied: MessageWriter<EffectApplied>,
1115    ) {
1116        apply_effect("low_oxygen", &registry, &mut effects, &mut applied)
1117            .expect("effect should exist");
1118    }
1119
1120    fn apply_missing_effect(
1121        registry: Res<EffectRegistry>,
1122        mut effects: ResMut<ActiveEffectSet>,
1123        mut applied: MessageWriter<EffectApplied>,
1124        mut errors: ResMut<ObservedErrors>,
1125    ) {
1126        let error = apply_effect("missing", &registry, &mut effects, &mut applied)
1127            .expect_err("missing effect should error");
1128        errors.0.push(error);
1129    }
1130
1131    fn tick_test_effects(
1132        mut effects: ResMut<ActiveEffectSet>,
1133        mut expired: MessageWriter<EffectExpired>,
1134    ) {
1135        tick_effects(1.0, &mut effects, &mut expired);
1136    }
1137
1138    fn apply_query_effect(
1139        registry: Res<EffectRegistry>,
1140        mut subjects: Query<&mut ActiveEffectSet, With<EffectSubject>>,
1141        mut applied: MessageWriter<EffectApplied>,
1142    ) {
1143        for mut effects in &mut subjects {
1144            apply_effect("low_oxygen", &registry, &mut effects, &mut applied)
1145                .expect("effect should exist");
1146        }
1147    }
1148
1149    #[test]
1150    fn effect_helpers_emit_applied_messages() {
1151        let mut app = App::new();
1152        app.add_plugins(MinimalPlugins);
1153        app.add_plugins(VoxelEffectsPlugin);
1154        app.init_resource::<ObservedApplied>();
1155        app.add_systems(Startup, register_test_effect);
1156        app.add_systems(Update, (apply_test_effect, record_applied).chain());
1157
1158        app.update();
1159
1160        let observed = app.world().resource::<ObservedApplied>();
1161        assert_eq!(observed.0.len(), 1);
1162        assert_eq!(observed.0[0].id.as_str(), "low_oxygen");
1163        assert_eq!(observed.0[0].previous, None);
1164        assert_eq!(observed.0[0].current.stacks(), 1);
1165    }
1166
1167    #[test]
1168    fn effect_helpers_emit_expired_messages() {
1169        let mut app = App::new();
1170        app.add_plugins(MinimalPlugins);
1171        app.add_plugins(VoxelEffectsPlugin);
1172        app.init_resource::<ObservedExpired>();
1173        app.add_systems(Startup, register_test_effect);
1174        app.add_systems(
1175            Update,
1176            (apply_test_effect, tick_test_effects, record_expired).chain(),
1177        );
1178
1179        app.update();
1180
1181        let observed = app.world().resource::<ObservedExpired>();
1182        assert_eq!(observed.0.len(), 1);
1183        assert_eq!(observed.0[0].id.as_str(), "low_oxygen");
1184        assert!(app.world().resource::<ActiveEffectSet>().is_empty());
1185    }
1186
1187    #[test]
1188    fn helpers_return_missing_id_without_emitting_messages() {
1189        let mut app = App::new();
1190        app.add_plugins(MinimalPlugins);
1191        app.add_plugins(VoxelEffectsPlugin);
1192        app.init_resource::<ObservedApplied>();
1193        app.init_resource::<ObservedErrors>();
1194        app.add_systems(Startup, register_test_effect);
1195        app.add_systems(Update, (apply_missing_effect, record_applied).chain());
1196
1197        app.update();
1198
1199        assert!(app.world().resource::<ObservedApplied>().0.is_empty());
1200        assert_eq!(
1201            app.world().resource::<ObservedErrors>().0,
1202            vec![EffectError::MissingId {
1203                id: EffectId::new("missing"),
1204            }]
1205        );
1206    }
1207
1208    #[test]
1209    fn active_effect_set_can_be_attached_to_bevy_entities_as_component() {
1210        let mut registry = EffectRegistry::default();
1211        registry
1212            .register(EffectDefinition::new("low_oxygen").duration_secs(5.0))
1213            .expect("effect should register");
1214
1215        let mut app = App::new();
1216        app.add_plugins(MinimalPlugins);
1217        let entity = app.world_mut().spawn(ActiveEffectSet::new()).id();
1218        app.world_mut()
1219            .get_mut::<ActiveEffectSet>(entity)
1220            .expect("entity should have effect set")
1221            .apply("low_oxygen", &registry)
1222            .expect("effect should exist");
1223
1224        let effects = app
1225            .world()
1226            .get::<ActiveEffectSet>(entity)
1227            .expect("entity should have effect set");
1228        assert!(effects.has("low_oxygen"));
1229    }
1230
1231    #[test]
1232    fn helpers_can_mutate_query_effect_sets() {
1233        let mut app = App::new();
1234        app.add_plugins(MinimalPlugins);
1235        app.add_plugins(VoxelEffectsPlugin);
1236        app.init_resource::<ObservedApplied>();
1237        app.add_systems(Startup, register_test_effect);
1238        let entity = app
1239            .world_mut()
1240            .spawn((EffectSubject, ActiveEffectSet::new()))
1241            .id();
1242        app.add_systems(Update, (apply_query_effect, record_applied).chain());
1243
1244        app.update();
1245
1246        let effects = app
1247            .world()
1248            .get::<ActiveEffectSet>(entity)
1249            .expect("entity should have effect set");
1250        assert!(effects.has("low_oxygen"));
1251        assert_eq!(app.world().resource::<ObservedApplied>().0.len(), 1);
1252    }
1253}