Skip to main content

voxel_framework/stats/
mod.rs

1//! Author-defined stat registries and runtime stat values.
2//!
3//! `stats` is the second gameplay-definition layer in `voxel-framework`.
4//! Like [`crate::content`], it does **not** ship a survival model, fixed body
5//! schema, or predefined list of stats. The game author decides whether a game
6//! has health, oxygen, stamina, mana, radiation, thirst, ship hull integrity, or
7//! no player stats at all.
8//!
9//! The framework provides three horizontal pieces:
10//!
11//! - [`StatRegistry`] — author-defined metadata and bounds for stats.
12//! - [`StatSet`] — runtime values keyed by [`StatId`], with clamping and simple
13//!   mutation and inspection helpers.
14//! - [`StatChanged`] plus [`set_stat`], [`add_stat`], [`drain_stat`], and
15//!   [`fill_stat`] — optional Bevy-message helpers for systems that want to
16//!   react when a stat actually changes.
17//!
18//! # Example
19//!
20//! ```rust
21//! use bevy::prelude::*;
22//! use bevy::ecs::message::MessageWriter;
23//! use voxel_framework::stats::{
24//!     drain_stat, StatChanged, StatDefinition, StatRegistry, StatSet, VoxelStatsPlugin,
25//! };
26//!
27//! fn register_stats(mut stats: ResMut<StatRegistry>) {
28//!     stats
29//!         .register(
30//!             StatDefinition::new("oxygen", 100.0)
31//!                 .named("Suit Oxygen")
32//!                 .bounds(0.0, 100.0)
33//!                 .tag("survival")
34//!                 .attribute("ui_hint", "bar"),
35//!         )
36//!         .expect("stat id should be unique");
37//! }
38//!
39//! fn drain_oxygen(
40//!     registry: Res<StatRegistry>,
41//!     mut values: ResMut<StatSet>,
42//!     mut changed: MessageWriter<StatChanged>,
43//! ) {
44//!     values.ensure_registered(&registry);
45//!     drain_stat("oxygen", 1.0, &registry, &mut values, &mut changed)
46//!         .expect("oxygen should exist");
47//! }
48//!
49//! App::new()
50//!     .add_plugins(MinimalPlugins)
51//!     .add_plugins(VoxelStatsPlugin)
52//!     .add_systems(Startup, register_stats)
53//!     .add_systems(Update, drain_oxygen);
54//! ```
55
56use std::collections::{BTreeMap, HashMap, HashSet};
57use std::fmt;
58
59use bevy::ecs::message::MessageWriter;
60use bevy::prelude::{App, Component, Message, Plugin, Resource};
61use serde::{Deserialize, Serialize};
62
63use crate::content::ContentValue;
64
65/// Stable identifier for an author-defined stat.
66#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
67pub struct StatId(String);
68
69impl StatId {
70    /// Creates a new stat id from any string-like value.
71    pub fn new(id: impl Into<String>) -> Self {
72        Self(id.into())
73    }
74
75    /// Returns the raw id string.
76    pub fn as_str(&self) -> &str {
77        &self.0
78    }
79}
80
81impl From<&str> for StatId {
82    fn from(value: &str) -> Self {
83        Self::new(value)
84    }
85}
86
87impl From<String> for StatId {
88    fn from(value: String) -> Self {
89        Self::new(value)
90    }
91}
92
93impl AsRef<str> for StatId {
94    fn as_ref(&self) -> &str {
95        self.as_str()
96    }
97}
98
99impl fmt::Display for StatId {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.write_str(self.as_str())
102    }
103}
104
105/// Author-defined stat metadata and bounds.
106#[derive(Debug, Clone, PartialEq)]
107pub struct StatDefinition {
108    id: StatId,
109    display_name: String,
110    default_value: f32,
111    min_value: f32,
112    max_value: f32,
113    attributes: HashMap<String, ContentValue>,
114    tags: HashSet<String>,
115}
116
117/// Serializable snapshot of one author-defined stat definition.
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub struct StatDefinitionSnapshot {
120    /// Stable author-defined id.
121    pub id: StatId,
122    /// Display name intended for UI/docs.
123    pub display_name: String,
124    /// Value inserted by [`StatSet::ensure_registered`] when the stat is absent.
125    pub default_value: f32,
126    /// Minimum allowed runtime value.
127    pub min_value: f32,
128    /// Maximum allowed runtime value.
129    pub max_value: f32,
130    /// Author-defined attributes in deterministic key order.
131    pub attributes: BTreeMap<String, ContentValue>,
132    /// Author-defined tags in deterministic lexical order.
133    pub tags: Vec<String>,
134}
135
136impl StatDefinition {
137    /// Creates a stat definition with default bounds `0.0..=default_value`.
138    pub fn new(id: impl Into<StatId>, default_value: f32) -> Self {
139        let default_value = finite_or_zero(default_value);
140        Self {
141            id: id.into(),
142            display_name: String::new(),
143            default_value,
144            min_value: 0.0_f32.min(default_value),
145            max_value: 0.0_f32.max(default_value),
146            attributes: HashMap::new(),
147            tags: HashSet::new(),
148        }
149    }
150
151    /// Returns the stable author-defined id.
152    pub fn id(&self) -> &StatId {
153        &self.id
154    }
155
156    /// Returns the display name intended for UI/docs.
157    pub fn display_name(&self) -> &str {
158        if self.display_name.is_empty() {
159            self.id.as_str()
160        } else {
161            &self.display_name
162        }
163    }
164
165    /// Replaces the display name.
166    pub fn named(mut self, name: impl Into<String>) -> Self {
167        self.display_name = name.into();
168        self
169    }
170
171    /// Returns the default runtime value.
172    pub fn default_value(&self) -> f32 {
173        self.default_value
174    }
175
176    /// Returns the minimum runtime value.
177    pub fn min_value(&self) -> f32 {
178        self.min_value
179    }
180
181    /// Returns the maximum runtime value.
182    pub fn max_value(&self) -> f32 {
183        self.max_value
184    }
185
186    /// Returns the absolute span between the minimum and maximum runtime values.
187    ///
188    /// A stat with equal bounds has a span of `0.0`.
189    pub fn span(&self) -> f32 {
190        self.max_value - self.min_value
191    }
192
193    /// Sets runtime bounds. Reversed bounds are normalized.
194    pub fn bounds(mut self, min_value: f32, max_value: f32) -> Self {
195        let min_value = finite_or_zero(min_value);
196        let max_value = finite_or_zero(max_value);
197        self.min_value = min_value.min(max_value);
198        self.max_value = min_value.max(max_value);
199        self.default_value = self.clamp(self.default_value);
200        self
201    }
202
203    /// Sets a new default runtime value, clamped into the current bounds.
204    pub fn initial_value(mut self, value: f32) -> Self {
205        self.default_value = self.clamp(finite_or_zero(value));
206        self
207    }
208
209    /// Clamps a runtime value to this stat's bounds.
210    pub fn clamp(&self, value: f32) -> f32 {
211        finite_or_zero(value).clamp(self.min_value, self.max_value)
212    }
213
214    /// Adds or replaces an author-defined gameplay attribute.
215    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
216        self.attributes.insert(key.into(), value.into());
217        self
218    }
219
220    /// Adds an author-defined tag.
221    pub fn tag(mut self, tag: impl Into<String>) -> Self {
222        self.tags.insert(tag.into());
223        self
224    }
225
226    /// Returns a gameplay attribute by key.
227    pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
228        self.attributes.get(key)
229    }
230
231    /// Returns a numeric gameplay attribute by key.
232    pub fn number_attribute(&self, key: &str) -> Option<f64> {
233        self.get_attribute(key).and_then(ContentValue::as_number)
234    }
235
236    /// Returns a boolean gameplay attribute by key.
237    pub fn bool_attribute(&self, key: &str) -> Option<bool> {
238        self.get_attribute(key).and_then(ContentValue::as_bool)
239    }
240
241    /// Returns a text gameplay attribute by key.
242    pub fn text_attribute(&self, key: &str) -> Option<&str> {
243        self.get_attribute(key).and_then(ContentValue::as_str)
244    }
245
246    /// Returns all gameplay attributes.
247    pub fn attributes(&self) -> &HashMap<String, ContentValue> {
248        &self.attributes
249    }
250
251    /// Returns true when the author-defined tag exists.
252    pub fn has_tag(&self, tag: &str) -> bool {
253        self.tags.contains(tag)
254    }
255
256    /// Returns all author-defined tags.
257    pub fn tags(&self) -> &HashSet<String> {
258        &self.tags
259    }
260
261    /// Creates a serializable, deterministic snapshot of this stat definition.
262    pub fn snapshot(&self) -> StatDefinitionSnapshot {
263        StatDefinitionSnapshot {
264            id: self.id.clone(),
265            display_name: self.display_name().to_owned(),
266            default_value: self.default_value,
267            min_value: self.min_value,
268            max_value: self.max_value,
269            attributes: ordered_attributes(&self.attributes),
270            tags: ordered_tags(&self.tags),
271        }
272    }
273}
274
275/// Errors returned by stat registries and runtime stat sets.
276#[derive(Debug, Clone, PartialEq)]
277pub enum StatError {
278    /// A stat with the same id already exists.
279    DuplicateId { id: StatId },
280    /// No stat exists for the requested id.
281    MissingId { id: StatId },
282}
283
284impl fmt::Display for StatError {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        match self {
287            Self::DuplicateId { id } => write!(f, "stat id `{id}` is already registered"),
288            Self::MissingId { id } => write!(f, "stat id `{id}` is not registered"),
289        }
290    }
291}
292
293impl std::error::Error for StatError {}
294
295/// Registry of author-defined stat definitions.
296#[derive(Debug, Clone, Default, Resource)]
297pub struct StatRegistry {
298    stats_by_id: HashMap<StatId, StatDefinition>,
299}
300
301impl StatRegistry {
302    /// Registers a new stat definition.
303    pub fn register(&mut self, definition: StatDefinition) -> Result<(), StatError> {
304        if self.stats_by_id.contains_key(definition.id()) {
305            return Err(StatError::DuplicateId {
306                id: definition.id().clone(),
307            });
308        }
309
310        self.stats_by_id.insert(definition.id().clone(), definition);
311        Ok(())
312    }
313
314    /// Inserts a definition, replacing any previous definition for the same id.
315    pub fn insert_or_replace(&mut self, definition: StatDefinition) {
316        self.stats_by_id.insert(definition.id().clone(), definition);
317    }
318
319    /// Returns a definition by stat id.
320    pub fn get(&self, id: impl AsRef<str>) -> Option<&StatDefinition> {
321        let id = StatId::new(id.as_ref());
322        self.stats_by_id.get(&id)
323    }
324
325    /// Returns a definition by id or an explicit error.
326    pub fn require(&self, id: impl AsRef<str>) -> Result<&StatDefinition, StatError> {
327        let id = StatId::new(id.as_ref());
328        self.stats_by_id.get(&id).ok_or(StatError::MissingId { id })
329    }
330
331    /// Returns true if an id exists.
332    pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
333        self.get(id).is_some()
334    }
335
336    /// Number of registered stat definitions.
337    pub fn len(&self) -> usize {
338        self.stats_by_id.len()
339    }
340
341    /// Returns true when no stat definitions are registered.
342    pub fn is_empty(&self) -> bool {
343        self.stats_by_id.is_empty()
344    }
345
346    /// Iterates definitions in unspecified hash-map order.
347    pub fn iter(&self) -> impl Iterator<Item = &StatDefinition> {
348        self.stats_by_id.values()
349    }
350
351    /// Returns deterministic serializable snapshots of all registered stats.
352    pub fn snapshot(&self) -> Vec<StatDefinitionSnapshot> {
353        let mut stats: Vec<_> = self.iter().map(StatDefinition::snapshot).collect();
354        stats.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
355        stats
356    }
357}
358
359/// Runtime stat values keyed by author-defined [`StatId`].
360///
361/// A `StatSet` can be used as the global stats [`Resource`] initialized by
362/// [`VoxelStatsPlugin`] or attached directly to entities as a [`Component`].
363/// The framework does not assign a meaning to the owner entity: it can be a
364/// player, mob, vehicle, machine, colony, or any author-defined subject.
365#[derive(Debug, Clone, Default, Component, Resource, Serialize, Deserialize)]
366pub struct StatSet {
367    values: HashMap<StatId, f32>,
368}
369
370impl StatSet {
371    /// Creates an empty stat set.
372    pub fn new() -> Self {
373        Self::default()
374    }
375
376    /// Creates a stat set initialized with every registered stat default.
377    pub fn from_registry(registry: &StatRegistry) -> Self {
378        let mut values = Self::new();
379        values.ensure_registered(registry);
380        values
381    }
382
383    /// Inserts any missing registered stats with their configured defaults.
384    pub fn ensure_registered(&mut self, registry: &StatRegistry) {
385        for definition in registry.iter() {
386            self.values
387                .entry(definition.id().clone())
388                .or_insert_with(|| definition.default_value());
389        }
390    }
391
392    /// Sets a stat value after resolving and clamping it through the registry.
393    pub fn set(
394        &mut self,
395        id: impl AsRef<str>,
396        value: f32,
397        registry: &StatRegistry,
398    ) -> Result<f32, StatError> {
399        let definition = registry.require(id.as_ref())?;
400        let value = definition.clamp(value);
401        self.values.insert(definition.id().clone(), value);
402        Ok(value)
403    }
404
405    /// Adds a delta to a stat and returns the clamped value.
406    pub fn add(
407        &mut self,
408        id: impl AsRef<str>,
409        delta: f32,
410        registry: &StatRegistry,
411    ) -> Result<f32, StatError> {
412        let definition = registry.require(id.as_ref())?;
413        let current = self.get(id.as_ref(), registry)?;
414        self.set(
415            definition.id().as_str(),
416            current + finite_or_zero(delta),
417            registry,
418        )
419    }
420
421    /// Removes from a stat and returns the clamped value.
422    pub fn drain(
423        &mut self,
424        id: impl AsRef<str>,
425        amount: f32,
426        registry: &StatRegistry,
427    ) -> Result<f32, StatError> {
428        self.add(id, -finite_or_zero(amount).abs(), registry)
429    }
430
431    /// Adds to a stat and returns the clamped value.
432    pub fn fill(
433        &mut self,
434        id: impl AsRef<str>,
435        amount: f32,
436        registry: &StatRegistry,
437    ) -> Result<f32, StatError> {
438        self.add(id, finite_or_zero(amount).abs(), registry)
439    }
440
441    /// Returns the current stat value, falling back to the registered default
442    /// when the stat is not yet stored in this set.
443    pub fn get(&self, id: impl AsRef<str>, registry: &StatRegistry) -> Result<f32, StatError> {
444        let definition = registry.require(id.as_ref())?;
445        Ok(self
446            .values
447            .get(definition.id())
448            .copied()
449            .unwrap_or_else(|| definition.default_value()))
450    }
451
452    /// Returns the current value normalized to `0.0..=1.0` across the
453    /// registered stat bounds.
454    ///
455    /// This is only an inspection helper: it does not imply HUD, rules, or
456    /// effects behavior. A stat whose minimum and maximum are equal normalizes
457    /// to `1.0` to avoid division by zero.
458    pub fn normalized(
459        &self,
460        id: impl AsRef<str>,
461        registry: &StatRegistry,
462    ) -> Result<f32, StatError> {
463        let definition = registry.require(id.as_ref())?;
464        let value = definition.clamp(self.get(definition.id().as_str(), registry)?);
465        Ok(normalize_value(definition, value))
466    }
467
468    /// Returns true when the current value is at or below an absolute threshold.
469    pub fn is_at_or_below(
470        &self,
471        id: impl AsRef<str>,
472        threshold: f32,
473        registry: &StatRegistry,
474    ) -> Result<bool, StatError> {
475        let definition = registry.require(id.as_ref())?;
476        Ok(self.get(definition.id().as_str(), registry)? <= finite_or_zero(threshold))
477    }
478
479    /// Returns true when the current value is at or above an absolute threshold.
480    pub fn is_at_or_above(
481        &self,
482        id: impl AsRef<str>,
483        threshold: f32,
484        registry: &StatRegistry,
485    ) -> Result<bool, StatError> {
486        let definition = registry.require(id.as_ref())?;
487        Ok(self.get(definition.id().as_str(), registry)? >= finite_or_zero(threshold))
488    }
489
490    /// Returns true when the normalized value is at or below `threshold`.
491    ///
492    /// `threshold` is clamped to `0.0..=1.0`; for example, `0.15` means 15%.
493    pub fn is_at_or_below_percent(
494        &self,
495        id: impl AsRef<str>,
496        threshold: f32,
497        registry: &StatRegistry,
498    ) -> Result<bool, StatError> {
499        Ok(self.normalized(id, registry)? <= normalized_threshold(threshold))
500    }
501
502    /// Returns true when the normalized value is at or above `threshold`.
503    ///
504    /// `threshold` is clamped to `0.0..=1.0`; for example, `0.85` means 85%.
505    pub fn is_at_or_above_percent(
506        &self,
507        id: impl AsRef<str>,
508        threshold: f32,
509        registry: &StatRegistry,
510    ) -> Result<bool, StatError> {
511        Ok(self.normalized(id, registry)? >= normalized_threshold(threshold))
512    }
513
514    /// Returns true when this stat value is at or below its minimum bound.
515    pub fn is_min(&self, id: impl AsRef<str>, registry: &StatRegistry) -> Result<bool, StatError> {
516        let definition = registry.require(id.as_ref())?;
517        Ok(self.get(definition.id().as_str(), registry)? <= definition.min_value())
518    }
519
520    /// Returns true when this stat value is at or above its maximum bound.
521    pub fn is_max(&self, id: impl AsRef<str>, registry: &StatRegistry) -> Result<bool, StatError> {
522        let definition = registry.require(id.as_ref())?;
523        Ok(self.get(definition.id().as_str(), registry)? >= definition.max_value())
524    }
525
526    /// Number of explicitly stored stat values.
527    pub fn len(&self) -> usize {
528        self.values.len()
529    }
530
531    /// Returns true when no values are explicitly stored.
532    pub fn is_empty(&self) -> bool {
533        self.values.is_empty()
534    }
535
536    /// Iterates explicitly stored values in unspecified hash-map order.
537    pub fn iter(&self) -> impl Iterator<Item = (&StatId, f32)> {
538        self.values.iter().map(|(id, value)| (id, *value))
539    }
540
541    /// Returns deterministic serializable snapshots of the explicitly stored values.
542    pub fn snapshot(&self) -> Vec<StatValueSnapshot> {
543        let mut values: Vec<_> = self
544            .iter()
545            .map(|(id, value)| StatValueSnapshot {
546                id: id.clone(),
547                value,
548            })
549            .collect();
550        values.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
551        values
552    }
553}
554
555/// Serializable snapshot of one stored runtime stat value.
556#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
557pub struct StatValueSnapshot {
558    /// Stable author-defined id.
559    pub id: StatId,
560    /// Current clamped runtime value.
561    pub value: f32,
562}
563
564/// Message emitted by stat helper functions when a runtime stat value changes.
565///
566/// The framework does not interpret the stat id. Systems in the consuming game
567/// decide whether a change means UI refresh, damage, an alarm, an achievement,
568/// or nothing at all.
569#[derive(Message, Debug, Clone, PartialEq, Serialize, Deserialize)]
570pub struct StatChanged {
571    /// Stable author-defined stat id.
572    pub id: StatId,
573    /// Value before the helper mutation.
574    pub previous: f32,
575    /// Value after clamping and applying the helper mutation.
576    pub current: f32,
577}
578
579/// Sets a stat and emits [`StatChanged`] when the clamped value differs.
580pub fn set_stat(
581    id: impl AsRef<str>,
582    value: f32,
583    registry: &StatRegistry,
584    values: &mut StatSet,
585    changed: &mut MessageWriter<StatChanged>,
586) -> Result<f32, StatError> {
587    let definition = registry.require(id.as_ref())?;
588    let previous = values.get(definition.id().as_str(), registry)?;
589    let current = values.set(definition.id().as_str(), value, registry)?;
590    write_stat_changed(definition, previous, current, changed);
591    Ok(current)
592}
593
594/// Adds a delta to a stat and emits [`StatChanged`] when the clamped value differs.
595pub fn add_stat(
596    id: impl AsRef<str>,
597    delta: f32,
598    registry: &StatRegistry,
599    values: &mut StatSet,
600    changed: &mut MessageWriter<StatChanged>,
601) -> Result<f32, StatError> {
602    let definition = registry.require(id.as_ref())?;
603    let previous = values.get(definition.id().as_str(), registry)?;
604    set_stat(
605        definition.id().as_str(),
606        previous + finite_or_zero(delta),
607        registry,
608        values,
609        changed,
610    )
611}
612
613/// Removes from a stat and emits [`StatChanged`] when the clamped value differs.
614pub fn drain_stat(
615    id: impl AsRef<str>,
616    amount: f32,
617    registry: &StatRegistry,
618    values: &mut StatSet,
619    changed: &mut MessageWriter<StatChanged>,
620) -> Result<f32, StatError> {
621    add_stat(id, -finite_or_zero(amount).abs(), registry, values, changed)
622}
623
624/// Adds to a stat and emits [`StatChanged`] when the clamped value differs.
625pub fn fill_stat(
626    id: impl AsRef<str>,
627    amount: f32,
628    registry: &StatRegistry,
629    values: &mut StatSet,
630    changed: &mut MessageWriter<StatChanged>,
631) -> Result<f32, StatError> {
632    add_stat(id, finite_or_zero(amount).abs(), registry, values, changed)
633}
634
635/// Horizontal plugin that initializes author-defined stat resources.
636///
637/// This plugin does not register default stats. The game author defines the
638/// stats their game needs and decides how systems interpret them.
639pub struct VoxelStatsPlugin;
640
641impl Plugin for VoxelStatsPlugin {
642    fn build(&self, app: &mut App) {
643        app.init_resource::<StatRegistry>();
644        app.init_resource::<StatSet>();
645        app.add_message::<StatChanged>();
646    }
647}
648
649fn write_stat_changed(
650    definition: &StatDefinition,
651    previous: f32,
652    current: f32,
653    changed: &mut MessageWriter<StatChanged>,
654) {
655    if previous == current {
656        return;
657    }
658
659    changed.write(StatChanged {
660        id: definition.id().clone(),
661        previous,
662        current,
663    });
664}
665
666fn finite_or_zero(value: f32) -> f32 {
667    if value.is_finite() { value } else { 0.0 }
668}
669
670fn normalize_value(definition: &StatDefinition, value: f32) -> f32 {
671    let span = definition.span();
672    if span <= f32::EPSILON {
673        return 1.0;
674    }
675
676    ((definition.clamp(value) - definition.min_value()) / span).clamp(0.0, 1.0)
677}
678
679fn normalized_threshold(threshold: f32) -> f32 {
680    finite_or_zero(threshold).clamp(0.0, 1.0)
681}
682
683fn ordered_attributes(
684    attributes: &HashMap<String, ContentValue>,
685) -> BTreeMap<String, ContentValue> {
686    attributes
687        .iter()
688        .map(|(key, value)| (key.clone(), value.clone()))
689        .collect()
690}
691
692fn ordered_tags(tags: &HashSet<String>) -> Vec<String> {
693    let mut tags: Vec<_> = tags.iter().cloned().collect();
694    tags.sort();
695    tags
696}
697
698#[cfg(test)]
699mod tests {
700    use bevy::ecs::message::{MessageReader, MessageWriter};
701    use bevy::prelude::{
702        App, Component, IntoScheduleConfigs, MinimalPlugins, Query, Res, ResMut, Resource, Startup,
703        Update, With,
704    };
705
706    use super::*;
707
708    #[test]
709    fn stat_definition_keeps_author_defined_metadata() {
710        let stat = StatDefinition::new("oxygen", 100.0)
711            .named("Suit Oxygen")
712            .bounds(0.0, 100.0)
713            .tag("survival")
714            .attribute("ui_hint", "bar")
715            .attribute("critical_threshold", 15.0);
716
717        assert_eq!(stat.id().as_str(), "oxygen");
718        assert_eq!(stat.display_name(), "Suit Oxygen");
719        assert_eq!(stat.default_value(), 100.0);
720        assert_eq!(stat.min_value(), 0.0);
721        assert_eq!(stat.max_value(), 100.0);
722        assert!(stat.has_tag("survival"));
723        assert_eq!(stat.text_attribute("ui_hint"), Some("bar"));
724        assert_eq!(stat.number_attribute("critical_threshold"), Some(15.0));
725    }
726
727    #[test]
728    fn stat_definition_normalizes_bounds_and_clamps_default() {
729        let stat = StatDefinition::new("temperature", 50.0).bounds(10.0, -10.0);
730
731        assert_eq!(stat.min_value(), -10.0);
732        assert_eq!(stat.max_value(), 10.0);
733        assert_eq!(stat.span(), 20.0);
734        assert_eq!(stat.default_value(), 10.0);
735        assert_eq!(stat.clamp(99.0), 10.0);
736        assert_eq!(stat.clamp(-99.0), -10.0);
737    }
738
739    #[test]
740    fn stat_definition_initial_value_is_clamped_to_bounds() {
741        let stat = StatDefinition::new("radiation", 0.0)
742            .bounds(0.0, 100.0)
743            .initial_value(250.0);
744
745        assert_eq!(stat.default_value(), 100.0);
746    }
747
748    #[test]
749    fn registry_rejects_duplicate_ids_and_requires_existing_stats() {
750        let mut registry = StatRegistry::default();
751        registry
752            .register(StatDefinition::new("oxygen", 100.0))
753            .expect("first stat should register");
754
755        assert!(matches!(
756            registry.register(StatDefinition::new("oxygen", 50.0)),
757            Err(StatError::DuplicateId { .. })
758        ));
759        assert!(registry.require("oxygen").is_ok());
760        assert!(matches!(
761            registry.require("missing"),
762            Err(StatError::MissingId { .. })
763        ));
764    }
765
766    #[test]
767    fn stat_set_uses_defaults_and_clamps_mutations() {
768        let mut registry = StatRegistry::default();
769        registry
770            .register(StatDefinition::new("oxygen", 100.0).bounds(0.0, 100.0))
771            .expect("stat should register");
772
773        let mut values = StatSet::new();
774        assert_eq!(values.get("oxygen", &registry), Ok(100.0));
775        assert!(values.is_empty());
776
777        assert_eq!(values.drain("oxygen", 125.0, &registry), Ok(0.0));
778        assert_eq!(values.get("oxygen", &registry), Ok(0.0));
779        assert_eq!(values.fill("oxygen", 250.0, &registry), Ok(100.0));
780        assert_eq!(values.add("oxygen", -40.0, &registry), Ok(60.0));
781    }
782
783    #[test]
784    fn stat_set_normalizes_current_value_against_registered_bounds() {
785        let mut registry = StatRegistry::default();
786        registry
787            .register(StatDefinition::new("oxygen", 100.0).bounds(0.0, 100.0))
788            .expect("stat should register");
789
790        let mut values = StatSet::new();
791
792        assert_eq!(values.normalized("oxygen", &registry), Ok(1.0));
793        assert_eq!(values.set("oxygen", 25.0, &registry), Ok(25.0));
794        assert_eq!(values.normalized("oxygen", &registry), Ok(0.25));
795        assert_eq!(values.set("oxygen", -25.0, &registry), Ok(0.0));
796        assert_eq!(values.normalized("oxygen", &registry), Ok(0.0));
797        assert_eq!(values.set("oxygen", f32::INFINITY, &registry), Ok(0.0));
798        assert_eq!(values.normalized("oxygen", &registry), Ok(0.0));
799    }
800
801    #[test]
802    fn stat_set_normalization_handles_equal_bounds_without_dividing_by_zero() {
803        let mut registry = StatRegistry::default();
804        registry
805            .register(StatDefinition::new("locked", 5.0).bounds(5.0, 5.0))
806            .expect("stat should register");
807
808        let mut values = StatSet::new();
809
810        assert_eq!(
811            registry.require("locked").map(StatDefinition::span),
812            Ok(0.0)
813        );
814        assert_eq!(values.normalized("locked", &registry), Ok(1.0));
815        assert_eq!(values.set("locked", f32::NAN, &registry), Ok(5.0));
816        assert_eq!(values.normalized("locked", &registry), Ok(1.0));
817    }
818
819    #[test]
820    fn stat_set_supports_absolute_threshold_checks() {
821        let mut registry = StatRegistry::default();
822        registry
823            .register(StatDefinition::new("oxygen", 100.0).bounds(0.0, 100.0))
824            .expect("stat should register");
825
826        let mut values = StatSet::new();
827        values
828            .set("oxygen", 15.0, &registry)
829            .expect("oxygen exists");
830
831        assert_eq!(values.is_at_or_below("oxygen", 15.0, &registry), Ok(true));
832        assert_eq!(values.is_at_or_below("oxygen", 14.0, &registry), Ok(false));
833        assert_eq!(values.is_at_or_above("oxygen", 15.0, &registry), Ok(true));
834        assert_eq!(values.is_at_or_above("oxygen", 16.0, &registry), Ok(false));
835        assert_eq!(
836            values.is_at_or_below("oxygen", f32::INFINITY, &registry),
837            Ok(false)
838        );
839    }
840
841    #[test]
842    fn stat_set_supports_normalized_threshold_checks() {
843        let mut registry = StatRegistry::default();
844        registry
845            .register(StatDefinition::new("oxygen", 100.0).bounds(0.0, 100.0))
846            .expect("stat should register");
847
848        let mut values = StatSet::new();
849        values
850            .set("oxygen", 15.0, &registry)
851            .expect("oxygen exists");
852
853        assert_eq!(
854            values.is_at_or_below_percent("oxygen", 0.15, &registry),
855            Ok(true)
856        );
857        assert_eq!(
858            values.is_at_or_below_percent("oxygen", 0.14, &registry),
859            Ok(false)
860        );
861        assert_eq!(
862            values.is_at_or_above_percent("oxygen", 0.15, &registry),
863            Ok(true)
864        );
865        assert_eq!(
866            values.is_at_or_above_percent("oxygen", 0.16, &registry),
867            Ok(false)
868        );
869        assert_eq!(
870            values.is_at_or_above_percent("oxygen", f32::INFINITY, &registry),
871            Ok(true)
872        );
873    }
874
875    #[test]
876    fn stat_read_helpers_return_missing_id_errors() {
877        let registry = StatRegistry::default();
878        let values = StatSet::new();
879
880        assert!(matches!(
881            values.normalized("missing", &registry),
882            Err(StatError::MissingId { .. })
883        ));
884        assert!(matches!(
885            values.is_at_or_below("missing", 1.0, &registry),
886            Err(StatError::MissingId { .. })
887        ));
888        assert!(matches!(
889            values.is_at_or_below_percent("missing", 0.5, &registry),
890            Err(StatError::MissingId { .. })
891        ));
892    }
893
894    #[test]
895    fn ensure_registered_inserts_missing_defaults_without_overwriting_existing_values() {
896        let mut registry = StatRegistry::default();
897        registry
898            .register(StatDefinition::new("oxygen", 100.0))
899            .expect("stat should register");
900        registry
901            .register(StatDefinition::new("mana", 50.0))
902            .expect("stat should register");
903
904        let mut values = StatSet::new();
905        values
906            .set("oxygen", 25.0, &registry)
907            .expect("oxygen exists");
908        values.ensure_registered(&registry);
909
910        assert_eq!(values.get("oxygen", &registry), Ok(25.0));
911        assert_eq!(values.get("mana", &registry), Ok(50.0));
912        assert_eq!(values.len(), 2);
913    }
914
915    #[test]
916    fn stat_set_from_registry_inserts_registered_defaults() {
917        let mut registry = StatRegistry::default();
918        registry
919            .register(StatDefinition::new("oxygen", 100.0))
920            .expect("stat should register");
921        registry
922            .register(StatDefinition::new("radiation", 0.0).bounds(0.0, 1_000.0))
923            .expect("stat should register");
924
925        let values = StatSet::from_registry(&registry);
926
927        assert_eq!(values.get("oxygen", &registry), Ok(100.0));
928        assert_eq!(values.get("radiation", &registry), Ok(0.0));
929        assert_eq!(values.len(), 2);
930    }
931
932    #[test]
933    fn snapshots_are_serializable_and_deterministic() {
934        let mut registry = StatRegistry::default();
935        registry
936            .register(
937                StatDefinition::new("oxygen", 100.0)
938                    .tag("survival")
939                    .tag("space_suit")
940                    .attribute("ui_hint", "bar"),
941            )
942            .expect("stat should register");
943
944        let definition_snapshot = registry.snapshot();
945        assert_eq!(
946            definition_snapshot[0].tags,
947            vec!["space_suit".to_owned(), "survival".to_owned()]
948        );
949
950        let mut values = StatSet::new();
951        values
952            .set("oxygen", 75.0, &registry)
953            .expect("oxygen exists");
954        let value_snapshot = values.snapshot();
955        assert_eq!(value_snapshot[0].id.as_str(), "oxygen");
956        assert_eq!(value_snapshot[0].value, 75.0);
957
958        serde_json::to_string(&definition_snapshot).expect("definitions should serialize");
959        serde_json::to_string(&value_snapshot).expect("values should serialize");
960    }
961
962    #[test]
963    fn stats_plugin_initializes_empty_resources_without_defaults() {
964        let mut app = App::new();
965        app.add_plugins(MinimalPlugins);
966        app.add_plugins(VoxelStatsPlugin);
967
968        assert!(app.world().resource::<StatRegistry>().is_empty());
969        assert!(app.world().resource::<StatSet>().is_empty());
970    }
971
972    #[derive(Resource, Default)]
973    struct ObservedStatChanges(Vec<StatChanged>);
974
975    #[derive(Resource, Default)]
976    struct ObservedStatErrors(Vec<StatError>);
977
978    #[derive(Component)]
979    struct StatSubject;
980
981    fn register_oxygen_stat(mut registry: ResMut<StatRegistry>, mut values: ResMut<StatSet>) {
982        registry
983            .register(StatDefinition::new("oxygen", 100.0).bounds(0.0, 100.0))
984            .expect("oxygen should register");
985        values.ensure_registered(&registry);
986    }
987
988    fn record_stat_changes(
989        mut reader: MessageReader<StatChanged>,
990        mut observed: ResMut<ObservedStatChanges>,
991    ) {
992        observed.0.extend(reader.read().cloned());
993    }
994
995    fn drain_oxygen_with_helper(
996        registry: Res<StatRegistry>,
997        mut values: ResMut<StatSet>,
998        mut changed: MessageWriter<StatChanged>,
999    ) {
1000        drain_stat("oxygen", 25.0, &registry, &mut values, &mut changed)
1001            .expect("oxygen should exist");
1002    }
1003
1004    fn set_oxygen_to_same_value_with_helper(
1005        registry: Res<StatRegistry>,
1006        mut values: ResMut<StatSet>,
1007        mut changed: MessageWriter<StatChanged>,
1008    ) {
1009        set_stat("oxygen", 100.0, &registry, &mut values, &mut changed)
1010            .expect("oxygen should exist");
1011    }
1012
1013    fn fill_oxygen_past_max_with_helper(
1014        registry: Res<StatRegistry>,
1015        mut values: ResMut<StatSet>,
1016        mut changed: MessageWriter<StatChanged>,
1017    ) {
1018        set_stat("oxygen", 90.0, &registry, &mut values, &mut changed)
1019            .expect("oxygen should exist");
1020        fill_stat("oxygen", 50.0, &registry, &mut values, &mut changed)
1021            .expect("oxygen should exist");
1022    }
1023
1024    fn add_missing_stat_with_helper(
1025        registry: Res<StatRegistry>,
1026        mut values: ResMut<StatSet>,
1027        mut changed: MessageWriter<StatChanged>,
1028        mut errors: ResMut<ObservedStatErrors>,
1029    ) {
1030        let error = add_stat("missing", 1.0, &registry, &mut values, &mut changed)
1031            .expect_err("missing stat should return an error");
1032        errors.0.push(error);
1033    }
1034
1035    fn drain_subject_oxygen_with_query(
1036        registry: Res<StatRegistry>,
1037        mut subjects: Query<&mut StatSet, With<StatSubject>>,
1038        mut changed: MessageWriter<StatChanged>,
1039    ) {
1040        for mut values in &mut subjects {
1041            drain_stat("oxygen", 25.0, &registry, &mut values, &mut changed)
1042                .expect("oxygen should exist");
1043        }
1044    }
1045
1046    #[test]
1047    fn stat_helpers_emit_changed_message_when_value_changes() {
1048        let mut app = App::new();
1049        app.add_plugins(MinimalPlugins);
1050        app.add_plugins(VoxelStatsPlugin);
1051        app.init_resource::<ObservedStatChanges>();
1052        app.add_systems(Startup, register_oxygen_stat);
1053        app.add_systems(
1054            Update,
1055            (drain_oxygen_with_helper, record_stat_changes).chain(),
1056        );
1057
1058        app.update();
1059
1060        let observed = app.world().resource::<ObservedStatChanges>();
1061        assert_eq!(
1062            observed.0,
1063            vec![StatChanged {
1064                id: StatId::new("oxygen"),
1065                previous: 100.0,
1066                current: 75.0,
1067            }]
1068        );
1069    }
1070
1071    #[test]
1072    fn stat_helpers_do_not_emit_when_clamped_value_is_unchanged() {
1073        let mut app = App::new();
1074        app.add_plugins(MinimalPlugins);
1075        app.add_plugins(VoxelStatsPlugin);
1076        app.init_resource::<ObservedStatChanges>();
1077        app.add_systems(Startup, register_oxygen_stat);
1078        app.add_systems(
1079            Update,
1080            (set_oxygen_to_same_value_with_helper, record_stat_changes).chain(),
1081        );
1082
1083        app.update();
1084
1085        let observed = app.world().resource::<ObservedStatChanges>();
1086        assert!(observed.0.is_empty());
1087        assert_eq!(
1088            app.world()
1089                .resource::<StatSet>()
1090                .get("oxygen", app.world().resource::<StatRegistry>()),
1091            Ok(100.0)
1092        );
1093    }
1094
1095    #[test]
1096    fn stat_helpers_emit_clamped_final_value() {
1097        let mut app = App::new();
1098        app.add_plugins(MinimalPlugins);
1099        app.add_plugins(VoxelStatsPlugin);
1100        app.init_resource::<ObservedStatChanges>();
1101        app.add_systems(Startup, register_oxygen_stat);
1102        app.add_systems(
1103            Update,
1104            (fill_oxygen_past_max_with_helper, record_stat_changes).chain(),
1105        );
1106
1107        app.update();
1108
1109        let observed = app.world().resource::<ObservedStatChanges>();
1110        assert_eq!(
1111            observed.0,
1112            vec![
1113                StatChanged {
1114                    id: StatId::new("oxygen"),
1115                    previous: 100.0,
1116                    current: 90.0,
1117                },
1118                StatChanged {
1119                    id: StatId::new("oxygen"),
1120                    previous: 90.0,
1121                    current: 100.0,
1122                },
1123            ]
1124        );
1125    }
1126
1127    #[test]
1128    fn stat_helpers_return_missing_id_without_emitting_message() {
1129        let mut app = App::new();
1130        app.add_plugins(MinimalPlugins);
1131        app.add_plugins(VoxelStatsPlugin);
1132        app.init_resource::<ObservedStatChanges>();
1133        app.init_resource::<ObservedStatErrors>();
1134        app.add_systems(Startup, register_oxygen_stat);
1135        app.add_systems(
1136            Update,
1137            (add_missing_stat_with_helper, record_stat_changes).chain(),
1138        );
1139
1140        app.update();
1141
1142        let observed = app.world().resource::<ObservedStatChanges>();
1143        assert!(observed.0.is_empty());
1144
1145        let errors = app.world().resource::<ObservedStatErrors>();
1146        assert_eq!(
1147            errors.0,
1148            vec![StatError::MissingId {
1149                id: StatId::new("missing"),
1150            }]
1151        );
1152    }
1153
1154    #[test]
1155    fn stat_set_can_be_attached_to_bevy_entities_as_component() {
1156        let mut registry = StatRegistry::default();
1157        registry
1158            .register(StatDefinition::new("oxygen", 100.0).bounds(0.0, 100.0))
1159            .expect("oxygen should register");
1160
1161        let mut app = App::new();
1162        app.add_plugins(MinimalPlugins);
1163        let entity = app
1164            .world_mut()
1165            .spawn((StatSubject, StatSet::from_registry(&registry)))
1166            .id();
1167
1168        let values = app
1169            .world()
1170            .get::<StatSet>(entity)
1171            .expect("entity should have stat set");
1172
1173        assert_eq!(values.get("oxygen", &registry), Ok(100.0));
1174    }
1175
1176    #[test]
1177    fn stat_helpers_can_mutate_query_stat_sets() {
1178        let mut registry = StatRegistry::default();
1179        registry
1180            .register(StatDefinition::new("oxygen", 100.0).bounds(0.0, 100.0))
1181            .expect("oxygen should register");
1182        let initial_values = StatSet::from_registry(&registry);
1183
1184        let mut app = App::new();
1185        app.add_plugins(MinimalPlugins);
1186        app.add_plugins(VoxelStatsPlugin);
1187        app.insert_resource(registry);
1188        app.init_resource::<ObservedStatChanges>();
1189        let entity = app.world_mut().spawn((StatSubject, initial_values)).id();
1190        app.add_systems(
1191            Update,
1192            (drain_subject_oxygen_with_query, record_stat_changes).chain(),
1193        );
1194
1195        app.update();
1196
1197        let registry = app.world().resource::<StatRegistry>();
1198        let values = app
1199            .world()
1200            .get::<StatSet>(entity)
1201            .expect("entity should have stat set");
1202        assert_eq!(values.get("oxygen", registry), Ok(75.0));
1203
1204        let observed = app.world().resource::<ObservedStatChanges>();
1205        assert_eq!(
1206            observed.0,
1207            vec![StatChanged {
1208                id: StatId::new("oxygen"),
1209                previous: 100.0,
1210                current: 75.0,
1211            }]
1212        );
1213    }
1214}