Skip to main content

voxel_framework/player/
effects.rs

1//! Status effect system for the player.
2//!
3//! # Design
4//!
5//! Follows the same generic-trait pattern as `VoxelType` / `ItemType`. Games
6//! implement the [`StatusEffect`] trait on their own enum and register
7//! [`StatusEffectsPlugin<E>`] once. The plugin:
8//!
9//! 1. Initialises [`ActiveEffects<E>`] and [`AppliedEffectModifiers`] resources.
10//! 2. Ticks effect timers and removes expired effects each frame.
11//! 3. Applies regen / poison to [`PlayerHealth`] each frame.
12//! 4. Computes the combined [`EffectModifiers`] into [`AppliedEffectModifiers`]
13//!    before the player movement systems run.
14//!
15//! [`player_move`](crate::player::player_move) and
16//! `hotbar_to_tool_system` read [`AppliedEffectModifiers`] via
17//! `Option<Res<AppliedEffectModifiers>>` so they work correctly even when no
18//! `StatusEffectsPlugin` is registered.
19
20use bevy::prelude::*;
21
22use crate::player::PlayerHealth;
23
24// ─── EffectModifiers ──────────────────────────────────────────────────────────
25
26/// Accumulated modifier values applied to the player each frame from active effects.
27///
28/// All multiplicative fields default to `1.0` (identity). Additive fields
29/// default to `0.0`.
30#[derive(Debug, Clone, Copy)]
31pub struct EffectModifiers {
32    /// Multiplied into horizontal movement speed.
33    pub speed_mult: f32,
34    /// Multiplied into the jump impulse.
35    pub jump_mult: f32,
36    /// Multiplied into gravity accumulation each frame.
37    pub gravity_mult: f32,
38    /// Multiplied into `ToolStats::tool_speed` (mining speed).
39    pub mining_speed_mult: f32,
40    /// Fraction of incoming damage blocked. Clamped to `[0.0, 1.0]`.
41    pub damage_resistance: f32,
42    /// HP healed per second (additive across all active effects).
43    pub regen_per_sec: f32,
44    /// HP dealt per second (poison). Additive. Does not kill below 1 HP.
45    pub damage_per_sec: f32,
46}
47
48impl Default for EffectModifiers {
49    fn default() -> Self {
50        Self {
51            speed_mult: 1.0,
52            jump_mult: 1.0,
53            gravity_mult: 1.0,
54            mining_speed_mult: 1.0,
55            damage_resistance: 0.0,
56            regen_per_sec: 0.0,
57            damage_per_sec: 0.0,
58        }
59    }
60}
61
62// ─── StatusEffect trait ───────────────────────────────────────────────────────
63
64/// Trait that game types implement to define a status effect.
65///
66/// # Example
67///
68/// ```rust,no_run
69/// # use voxel_framework::prelude::{StatusEffect, EffectModifiers};
70/// #[derive(Clone, PartialEq)]
71/// enum MyEffect { Speed, Poison }
72///
73/// impl StatusEffect for MyEffect {
74///     fn name(&self) -> &'static str {
75///         match self { Self::Speed => "Speed", Self::Poison => "Poison" }
76///     }
77///     fn modifiers(&self, amplifier: u8) -> EffectModifiers {
78///         let lvl = (amplifier + 1) as f32;
79///         match self {
80///             Self::Speed  => EffectModifiers { speed_mult: 1.0 + 0.2 * lvl, ..Default::default() },
81///             Self::Poison => EffectModifiers { damage_per_sec: 1.0 * lvl,   ..Default::default() },
82///         }
83///     }
84/// }
85/// ```
86pub trait StatusEffect: Send + Sync + Clone + PartialEq + 'static {
87    /// Human-readable name shown in HUD or debug output.
88    fn name(&self) -> &'static str;
89
90    /// Returns the [`EffectModifiers`] for the given amplifier level.
91    ///
92    /// `amplifier = 0` corresponds to level I, `amplifier = 1` to level II,
93    /// and so on.
94    fn modifiers(&self, amplifier: u8) -> EffectModifiers;
95
96    /// Particle / icon colour for HUD display. RGBA in `[0.0, 1.0]`.
97    ///
98    /// Defaults to opaque white.
99    fn color(&self) -> [f32; 4] {
100        [1.0, 1.0, 1.0, 1.0]
101    }
102
103    /// Whether this effect is beneficial (`true`) or harmful (`false`).
104    ///
105    /// Used by HUD code to pick a display colour (blue/green vs red).
106    /// Defaults to `true`.
107    fn is_beneficial(&self) -> bool {
108        true
109    }
110}
111
112// ─── ActiveEffect / ActiveEffects ─────────────────────────────────────────────
113
114/// A single active instance of a status effect on the player.
115#[derive(Debug, Clone)]
116pub struct ActiveEffect<E: StatusEffect> {
117    /// The effect type.
118    pub effect: E,
119    /// Amplifier level (0 = level I, 1 = level II, …).
120    pub amplifier: u8,
121    /// Remaining duration in seconds. Decremented each frame by [`tick_effects`].
122    pub remaining_secs: f32,
123}
124
125/// Resource holding all currently active status effects on the player.
126///
127/// Register [`StatusEffectsPlugin<E>`] to have this managed automatically.
128/// Games can also manipulate it directly via [`ActiveEffects::apply`] and
129/// [`ActiveEffects::remove`].
130#[derive(Resource)]
131pub struct ActiveEffects<E: StatusEffect> {
132    /// Currently active effects.
133    pub effects: Vec<ActiveEffect<E>>,
134}
135
136impl<E: StatusEffect> Default for ActiveEffects<E> {
137    fn default() -> Self {
138        Self {
139            effects: Vec::new(),
140        }
141    }
142}
143
144impl<E: StatusEffect> ActiveEffects<E> {
145    /// Apply or refresh an effect.
146    ///
147    /// If the same effect variant is already active, keeps the **higher
148    /// amplifier** and the **longer remaining duration**. Otherwise a new entry
149    /// is pushed.
150    pub fn apply(&mut self, effect: E, amplifier: u8, duration_secs: f32) {
151        if let Some(existing) = self.effects.iter_mut().find(|a| a.effect == effect) {
152            existing.amplifier = existing.amplifier.max(amplifier);
153            existing.remaining_secs = existing.remaining_secs.max(duration_secs);
154        } else {
155            self.effects.push(ActiveEffect {
156                effect,
157                amplifier,
158                remaining_secs: duration_secs,
159            });
160        }
161    }
162
163    /// Remove all instances of the given effect variant.
164    pub fn remove(&mut self, effect: &E) {
165        self.effects.retain(|a| &a.effect != effect);
166    }
167
168    /// Compute the combined [`EffectModifiers`] from all active effects.
169    ///
170    /// - **Multiplicative** fields (`speed_mult`, `jump_mult`, `gravity_mult`,
171    ///   `mining_speed_mult`): multiplied together across all effects.
172    /// - **Additive** fields (`regen_per_sec`, `damage_per_sec`): summed.
173    /// - `damage_resistance`: summed then clamped to `[0.0, 1.0]`.
174    pub fn combined_modifiers(&self) -> EffectModifiers {
175        let mut out = EffectModifiers::default();
176        for a in &self.effects {
177            let m = a.effect.modifiers(a.amplifier);
178            out.speed_mult *= m.speed_mult;
179            out.jump_mult *= m.jump_mult;
180            out.gravity_mult *= m.gravity_mult;
181            out.mining_speed_mult *= m.mining_speed_mult;
182            out.damage_resistance = (out.damage_resistance + m.damage_resistance).min(1.0);
183            out.regen_per_sec += m.regen_per_sec;
184            out.damage_per_sec += m.damage_per_sec;
185        }
186        out
187    }
188}
189
190// ─── AppliedEffectModifiers ───────────────────────────────────────────────────
191
192/// Precomputed combined modifiers from all active effects.
193///
194/// Updated every frame by [`update_applied_modifiers`] inside
195/// [`StatusEffectsPlugin`], before the player movement systems run. Systems
196/// such as [`player_move`](crate::player::player_move) and
197/// `hotbar_to_tool_system` read this via `Option<Res<AppliedEffectModifiers>>`
198/// so they degrade gracefully when no plugin is registered.
199#[derive(Resource, Default)]
200pub struct AppliedEffectModifiers(pub EffectModifiers);
201
202// ─── Systems ──────────────────────────────────────────────────────────────────
203
204/// Advances effect timers and removes expired effects.
205///
206/// Added automatically by [`StatusEffectsPlugin`].
207pub fn tick_effects<E: StatusEffect>(mut effects: ResMut<ActiveEffects<E>>, time: Res<Time>) {
208    let dt = time.delta_secs();
209    effects.effects.retain_mut(|a| {
210        a.remaining_secs -= dt;
211        a.remaining_secs > 0.0
212    });
213}
214
215/// Recomputes [`AppliedEffectModifiers`] from the active effects.
216///
217/// Must run before [`player_move`](crate::player::player_move) in the same
218/// frame so movement picks up the fresh modifiers. Added automatically by
219/// [`StatusEffectsPlugin`].
220pub fn update_applied_modifiers<E: StatusEffect>(
221    effects: Res<ActiveEffects<E>>,
222    mut applied: ResMut<AppliedEffectModifiers>,
223) {
224    applied.0 = effects.combined_modifiers();
225}
226
227/// Applies `regen_per_sec` and `damage_per_sec` to [`PlayerHealth`].
228///
229/// - Regeneration heals the player up to their maximum HP.
230/// - Poison reduces HP but never below `1.0` (non-lethal).
231///
232/// Added automatically by [`StatusEffectsPlugin`].
233pub fn apply_health_effects<E: StatusEffect>(
234    effects: Res<ActiveEffects<E>>,
235    mut health: ResMut<PlayerHealth>,
236    time: Res<Time>,
237) {
238    let m = effects.combined_modifiers();
239    let dt = time.delta_secs();
240
241    // Regeneration — capped at max HP.
242    if m.regen_per_sec > 0.0 {
243        health.health = (health.health + m.regen_per_sec * dt).min(health.max_health);
244    }
245
246    // Poison — does not reduce below 1 HP.
247    if m.damage_per_sec > 0.0 {
248        health.health = (health.health - m.damage_per_sec * dt).max(1.0_f32);
249    }
250}
251
252// ─── Plugin ───────────────────────────────────────────────────────────────────
253
254/// Bevy plugin that wires the status effect system for effect type `E`.
255///
256/// # What it registers
257///
258/// - [`ActiveEffects<E>`] resource (default: empty)
259/// - [`AppliedEffectModifiers`] resource (default: identity modifiers)
260/// - [`tick_effects<E>`] — advances timers, removes expired effects
261/// - [`update_applied_modifiers<E>`] — recomputes combined modifiers each frame
262/// - [`apply_health_effects<E>`] — applies regen / poison to [`PlayerHealth`]
263///
264/// # Example
265///
266/// ```rust,no_run
267/// # use bevy::prelude::*;
268/// # use voxel_framework::prelude::{StatusEffect, StatusEffectsPlugin, EffectModifiers};
269/// #[derive(Clone, PartialEq)]
270/// enum MyEffect { Speed }
271/// impl StatusEffect for MyEffect {
272///     fn name(&self) -> &'static str { "Speed" }
273///     fn modifiers(&self, _: u8) -> EffectModifiers { EffectModifiers { speed_mult: 1.4, ..Default::default() } }
274/// }
275///
276/// App::new().add_plugins(StatusEffectsPlugin::<MyEffect>::new());
277/// ```
278pub struct StatusEffectsPlugin<E: StatusEffect> {
279    _marker: std::marker::PhantomData<E>,
280}
281
282impl<E: StatusEffect> StatusEffectsPlugin<E> {
283    /// Creates a new [`StatusEffectsPlugin`] for effect type `E`.
284    pub fn new() -> Self {
285        Self {
286            _marker: std::marker::PhantomData,
287        }
288    }
289}
290
291impl<E: StatusEffect> Default for StatusEffectsPlugin<E> {
292    fn default() -> Self {
293        Self::new()
294    }
295}
296
297impl<E: StatusEffect> Plugin for StatusEffectsPlugin<E> {
298    fn build(&self, app: &mut App) {
299        app.init_resource::<ActiveEffects<E>>();
300        app.init_resource::<AppliedEffectModifiers>();
301        app.add_systems(
302            Update,
303            (
304                update_applied_modifiers::<E>,
305                tick_effects::<E>,
306                apply_health_effects::<E>,
307            ),
308        );
309    }
310}
311
312// ─── Tests ────────────────────────────────────────────────────────────────────
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    #[derive(Clone, PartialEq, Debug)]
319    enum TestEffect {
320        Speed,
321        Poison,
322        Resistance,
323    }
324
325    impl StatusEffect for TestEffect {
326        fn name(&self) -> &'static str {
327            match self {
328                Self::Speed => "Speed",
329                Self::Poison => "Poison",
330                Self::Resistance => "Resistance",
331            }
332        }
333
334        fn modifiers(&self, amplifier: u8) -> EffectModifiers {
335            let lvl = (amplifier + 1) as f32;
336            match self {
337                Self::Speed => EffectModifiers {
338                    speed_mult: 1.0 + 0.2 * lvl,
339                    ..Default::default()
340                },
341                Self::Poison => EffectModifiers {
342                    damage_per_sec: 1.0 * lvl,
343                    ..Default::default()
344                },
345                Self::Resistance => EffectModifiers {
346                    damage_resistance: 0.2 * lvl,
347                    ..Default::default()
348                },
349            }
350        }
351
352        fn is_beneficial(&self) -> bool {
353            !matches!(self, Self::Poison)
354        }
355    }
356
357    // ── EffectModifiers defaults ─────────────────────────────────────────────
358
359    #[test]
360    fn effect_modifiers_default_identity() {
361        let m = EffectModifiers::default();
362        assert_eq!(m.speed_mult, 1.0);
363        assert_eq!(m.jump_mult, 1.0);
364        assert_eq!(m.gravity_mult, 1.0);
365        assert_eq!(m.mining_speed_mult, 1.0);
366        assert_eq!(m.damage_resistance, 0.0);
367        assert_eq!(m.regen_per_sec, 0.0);
368        assert_eq!(m.damage_per_sec, 0.0);
369    }
370
371    // ── ActiveEffects::apply ─────────────────────────────────────────────────
372
373    #[test]
374    fn apply_adds_new_effect() {
375        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
376        ae.apply(TestEffect::Speed, 0, 10.0);
377        assert_eq!(ae.effects.len(), 1);
378        assert_eq!(ae.effects[0].amplifier, 0);
379        assert!((ae.effects[0].remaining_secs - 10.0).abs() < f32::EPSILON);
380    }
381
382    #[test]
383    fn apply_refreshes_existing_keeps_higher_amplifier_and_longer_duration() {
384        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
385        ae.apply(TestEffect::Speed, 1, 10.0);
386        ae.apply(TestEffect::Speed, 0, 20.0); // lower amplifier, longer duration
387        assert_eq!(ae.effects.len(), 1);
388        assert_eq!(ae.effects[0].amplifier, 1); // kept higher
389        assert!((ae.effects[0].remaining_secs - 20.0).abs() < f32::EPSILON); // kept longer
390    }
391
392    #[test]
393    fn apply_two_different_effects() {
394        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
395        ae.apply(TestEffect::Speed, 0, 5.0);
396        ae.apply(TestEffect::Poison, 0, 5.0);
397        assert_eq!(ae.effects.len(), 2);
398    }
399
400    // ── ActiveEffects::remove ────────────────────────────────────────────────
401
402    #[test]
403    fn remove_clears_matching_effect() {
404        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
405        ae.apply(TestEffect::Speed, 0, 10.0);
406        ae.apply(TestEffect::Poison, 0, 10.0);
407        ae.remove(&TestEffect::Speed);
408        assert_eq!(ae.effects.len(), 1);
409        assert_eq!(ae.effects[0].effect, TestEffect::Poison);
410    }
411
412    #[test]
413    fn remove_nonexistent_is_noop() {
414        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
415        ae.apply(TestEffect::Poison, 0, 5.0);
416        ae.remove(&TestEffect::Speed);
417        assert_eq!(ae.effects.len(), 1);
418    }
419
420    // ── combined_modifiers ───────────────────────────────────────────────────
421
422    #[test]
423    fn combined_modifiers_empty_is_identity() {
424        let ae: ActiveEffects<TestEffect> = ActiveEffects::default();
425        let m = ae.combined_modifiers();
426        assert_eq!(m.speed_mult, 1.0);
427        assert_eq!(m.damage_per_sec, 0.0);
428    }
429
430    #[test]
431    fn combined_modifiers_speed_multiplied() {
432        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
433        ae.apply(TestEffect::Speed, 0, 10.0); // lvl=1 → speed_mult=1.2
434        ae.apply(TestEffect::Speed, 0, 10.0); // same effect — refreshes, not doubled
435        let m = ae.combined_modifiers();
436        assert!((m.speed_mult - 1.2).abs() < 1e-5);
437    }
438
439    #[test]
440    fn combined_modifiers_damage_resistance_clamped_at_one() {
441        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
442        ae.apply(TestEffect::Resistance, 4, 10.0); // 0.2 * 5 = 1.0
443        ae.apply(TestEffect::Resistance, 4, 10.0); // same — refreshes
444        let m = ae.combined_modifiers();
445        // With a single Resistance lvl 5 (amplifier=4), damage_resistance = 1.0
446        assert!(m.damage_resistance <= 1.0);
447    }
448
449    #[test]
450    fn combined_modifiers_poison_additive() {
451        let mut ae: ActiveEffects<TestEffect> = ActiveEffects::default();
452        ae.apply(TestEffect::Poison, 0, 10.0); // 1.0 dps
453        ae.apply(TestEffect::Speed, 0, 10.0); // different effect
454        let m = ae.combined_modifiers();
455        assert!((m.damage_per_sec - 1.0).abs() < 1e-5);
456        assert!((m.speed_mult - 1.2).abs() < 1e-5);
457    }
458
459    // ── StatusEffect trait defaults ──────────────────────────────────────────
460
461    #[test]
462    fn status_effect_color_default() {
463        assert_eq!(TestEffect::Speed.color(), [1.0, 1.0, 1.0, 1.0]);
464    }
465
466    #[test]
467    fn status_effect_is_beneficial_poison_is_harmful() {
468        assert!(!TestEffect::Poison.is_beneficial());
469        assert!(TestEffect::Speed.is_beneficial());
470    }
471}