Skip to main content

voxel_framework/ui/
hud.rs

1//! Author-defined, game-neutral HUD data model and stores.
2//!
3//! This module deliberately contains no gameplay-domain assumptions. Authors
4//! register presentation definitions and publish already-resolved view values.
5
6use std::collections::{HashMap, HashSet};
7use std::fmt;
8
9use bevy::asset::{AssetPath, LoadState};
10use bevy::ecs::message::MessageWriter;
11use bevy::prelude::*;
12use serde::{Deserialize, Deserializer, Serialize};
13
14/// Maximum number of retained children supported by a segments presentation.
15pub const MAX_HUD_SEGMENTS: u32 = 64;
16
17macro_rules! hud_id {
18    ($name:ident, $description:literal) => {
19        #[doc = $description]
20        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
21        pub struct $name(String);
22
23        impl $name {
24            /// Creates an id from any string-like value.
25            pub fn new(id: impl Into<String>) -> Self {
26                Self(id.into())
27            }
28
29            /// Returns the raw id string.
30            pub fn as_str(&self) -> &str {
31                &self.0
32            }
33        }
34
35        impl From<&str> for $name {
36            fn from(value: &str) -> Self {
37                Self::new(value)
38            }
39        }
40
41        impl From<String> for $name {
42            fn from(value: String) -> Self {
43                Self::new(value)
44            }
45        }
46
47        impl AsRef<str> for $name {
48            fn as_ref(&self) -> &str {
49                self.as_str()
50            }
51        }
52
53        impl fmt::Display for $name {
54            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55                f.write_str(self.as_str())
56            }
57        }
58    };
59}
60
61hud_id!(
62    HudElementId,
63    "Stable identifier for an author-defined HUD element."
64);
65hud_id!(
66    HudValueId,
67    "Stable identifier for an author-published HUD value."
68);
69
70/// A finite scalar with normalized, non-degenerate bounds.
71#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
72pub struct HudScalar {
73    value: f32,
74    min: f32,
75    max: f32,
76}
77
78impl HudScalar {
79    /// Creates a scalar, normalizing reversed bounds.
80    ///
81    /// Values outside the range remain intact; [`HudScalar::clamped_ratio`]
82    /// performs the presentation clamp. Equal bounds are rejected because they
83    /// cannot define a proportion.
84    pub fn new(value: f32, min: f32, max: f32) -> Result<Self, HudValueError> {
85        for (field, candidate) in [
86            (HudScalarField::Value, value),
87            (HudScalarField::Min, min),
88            (HudScalarField::Max, max),
89        ] {
90            if !candidate.is_finite() {
91                return Err(HudValueError::NonFinite { field });
92            }
93        }
94
95        let (min, max) = if min <= max { (min, max) } else { (max, min) };
96        if min == max {
97            return Err(HudValueError::InvalidRange { min, max });
98        }
99
100        Ok(Self { value, min, max })
101    }
102
103    /// Returns the unmodified published value.
104    pub fn value(self) -> f32 {
105        self.value
106    }
107
108    /// Returns the normalized lower bound.
109    pub fn min(self) -> f32 {
110        self.min
111    }
112
113    /// Returns the normalized upper bound.
114    pub fn max(self) -> f32 {
115        self.max
116    }
117
118    /// Returns the value resolved to a bounded `0.0..=1.0` proportion.
119    pub fn clamped_ratio(self) -> f32 {
120        // Finite `f32` endpoints can still overflow their subtraction in
121        // `f32` (for example, `f32::MIN..=f32::MAX`). Resolve in `f64` so the
122        // validated finite inputs always produce a finite bounded ratio.
123        (((self.value as f64 - self.min as f64) / (self.max as f64 - self.min as f64))
124            .clamp(0.0, 1.0)) as f32
125    }
126}
127
128#[derive(Deserialize)]
129struct HudScalarRepresentation {
130    value: f32,
131    min: f32,
132    max: f32,
133}
134
135impl<'de> Deserialize<'de> for HudScalar {
136    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
137    where
138        D: Deserializer<'de>,
139    {
140        let scalar = HudScalarRepresentation::deserialize(deserializer)?;
141        Self::new(scalar.value, scalar.min, scalar.max).map_err(serde::de::Error::custom)
142    }
143}
144
145/// Scalar field associated with a validation failure.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum HudScalarField {
148    /// Published scalar value.
149    Value,
150    /// Lower range bound.
151    Min,
152    /// Upper range bound.
153    Max,
154}
155
156impl fmt::Display for HudScalarField {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.write_str(match self {
159            Self::Value => "value",
160            Self::Min => "min",
161            Self::Max => "max",
162        })
163    }
164}
165
166/// Errors returned while constructing a HUD value.
167#[derive(Debug, Clone, PartialEq)]
168pub enum HudValueError {
169    /// A scalar field was NaN or infinite.
170    NonFinite { field: HudScalarField },
171    /// Equal bounds cannot define a scalar proportion.
172    InvalidRange { min: f32, max: f32 },
173}
174
175impl fmt::Display for HudValueError {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        match self {
178            Self::NonFinite { field } => write!(f, "HUD scalar {field} must be finite"),
179            Self::InvalidRange { min, max } => {
180                write!(
181                    f,
182                    "HUD scalar range `{min}..={max}` must have a nonzero span"
183                )
184            }
185        }
186    }
187}
188
189impl std::error::Error for HudValueError {}
190
191/// Closed set of author-published, screen-ready HUD values.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193pub enum HudValue {
194    /// Display-ready text.
195    Text(String),
196    /// Finite scalar with explicit bounds.
197    Scalar(HudScalar),
198    /// Unsigned count used by repeated segments or text.
199    Count(u32),
200    /// Boolean state, including conditional visibility bindings.
201    Bool(bool),
202    /// Owned path to an image asset.
203    Icon(AssetPath<'static>),
204}
205
206impl HudValue {
207    /// Returns this value's closed kind.
208    pub fn kind(&self) -> HudValueKind {
209        match self {
210            Self::Text(_) => HudValueKind::Text,
211            Self::Scalar(_) => HudValueKind::Scalar,
212            Self::Count(_) => HudValueKind::Count,
213            Self::Bool(_) => HudValueKind::Bool,
214            Self::Icon(_) => HudValueKind::Icon,
215        }
216    }
217
218    /// Creates an icon value while forcing the asset path to be owned.
219    pub fn icon(path: impl Into<AssetPath<'static>>) -> Self {
220        Self::Icon(path.into().into_owned())
221    }
222}
223
224impl From<String> for HudValue {
225    fn from(value: String) -> Self {
226        Self::Text(value)
227    }
228}
229
230impl From<&str> for HudValue {
231    fn from(value: &str) -> Self {
232        Self::Text(value.to_owned())
233    }
234}
235
236impl From<HudScalar> for HudValue {
237    fn from(value: HudScalar) -> Self {
238        Self::Scalar(value)
239    }
240}
241
242impl From<u32> for HudValue {
243    fn from(value: u32) -> Self {
244        Self::Count(value)
245    }
246}
247
248impl From<bool> for HudValue {
249    fn from(value: bool) -> Self {
250        Self::Bool(value)
251    }
252}
253
254impl From<AssetPath<'static>> for HudValue {
255    fn from(value: AssetPath<'static>) -> Self {
256        Self::Icon(value.into_owned())
257    }
258}
259
260/// Discriminant for the closed [`HudValue`] vocabulary.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
262pub enum HudValueKind {
263    /// Display-ready text.
264    Text,
265    /// Finite scalar with explicit bounds.
266    Scalar,
267    /// Unsigned count.
268    Count,
269    /// Boolean state.
270    Bool,
271    /// Owned image asset path.
272    Icon,
273}
274
275/// Text presentation bound to one published value.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct HudText {
278    value: HudValueId,
279    prefix: String,
280    suffix: String,
281    precision: Option<u8>,
282}
283
284impl HudText {
285    /// Creates a text presentation bound to `value`.
286    pub fn new(value: impl Into<HudValueId>) -> Self {
287        Self {
288            value: value.into(),
289            prefix: String::new(),
290            suffix: String::new(),
291            precision: None,
292        }
293    }
294
295    /// Sets text prepended to the resolved value.
296    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
297        self.prefix = prefix.into();
298        self
299    }
300
301    /// Sets text appended to the resolved value.
302    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
303        self.suffix = suffix.into();
304        self
305    }
306
307    /// Sets decimal precision used when formatting scalar values.
308    pub fn precision(mut self, precision: u8) -> Self {
309        self.precision = Some(precision);
310        self
311    }
312
313    /// Returns the bound value id.
314    pub fn value_id(&self) -> &HudValueId {
315        &self.value
316    }
317
318    /// Returns the configured prefix.
319    pub fn prefix_value(&self) -> &str {
320        &self.prefix
321    }
322
323    /// Returns the configured suffix.
324    pub fn suffix_value(&self) -> &str {
325        &self.suffix
326    }
327
328    /// Returns the configured scalar precision, if any.
329    pub fn precision_value(&self) -> Option<u8> {
330        self.precision
331    }
332}
333
334/// Continuous bar presentation bound to a scalar value.
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336pub struct HudBar {
337    value: HudValueId,
338}
339
340impl HudBar {
341    /// Creates a continuous bar bound to `value`.
342    pub fn new(value: impl Into<HudValueId>) -> Self {
343        Self {
344            value: value.into(),
345        }
346    }
347
348    /// Returns the bound scalar value id.
349    pub fn value_id(&self) -> &HudValueId {
350        &self.value
351    }
352}
353
354/// Static or value-bound icon source.
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356pub enum HudIconSource {
357    /// Fixed image asset path.
358    Asset(AssetPath<'static>),
359    /// Id of an author-published [`HudValue::Icon`].
360    Bound(HudValueId),
361}
362
363/// Icon presentation using an owned asset path or a bound icon value.
364#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
365pub struct HudIcon {
366    source: HudIconSource,
367}
368
369impl HudIcon {
370    /// Creates an icon with an owned fixed asset path.
371    pub fn asset(path: impl Into<AssetPath<'static>>) -> Self {
372        Self {
373            source: HudIconSource::Asset(path.into().into_owned()),
374        }
375    }
376
377    /// Creates an icon bound to an author-published icon value.
378    pub fn bound(value: impl Into<HudValueId>) -> Self {
379        Self {
380            source: HudIconSource::Bound(value.into()),
381        }
382    }
383
384    /// Returns the fixed or value-bound icon source.
385    pub fn source(&self) -> &HudIconSource {
386        &self.source
387    }
388}
389
390/// Bounded repeated-segment presentation bound to a count value.
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392pub struct HudSegments {
393    value: HudValueId,
394    capacity: u32,
395    filled_asset: Option<AssetPath<'static>>,
396    empty_asset: Option<AssetPath<'static>>,
397}
398
399impl HudSegments {
400    /// Creates a repeated-segment presentation with a bounded child capacity.
401    ///
402    /// Capacity is validated when the containing definition is registered.
403    pub fn new(value: impl Into<HudValueId>, capacity: u32) -> Self {
404        Self {
405            value: value.into(),
406            capacity,
407            filled_asset: None,
408            empty_asset: None,
409        }
410    }
411
412    /// Sets the owned asset path used for filled segments.
413    pub fn filled_asset(mut self, path: impl Into<AssetPath<'static>>) -> Self {
414        self.filled_asset = Some(path.into().into_owned());
415        self
416    }
417
418    /// Sets the owned asset path used for empty segments.
419    pub fn empty_asset(mut self, path: impl Into<AssetPath<'static>>) -> Self {
420        self.empty_asset = Some(path.into().into_owned());
421        self
422    }
423
424    /// Returns the bound count value id.
425    pub fn value_id(&self) -> &HudValueId {
426        &self.value
427    }
428
429    /// Returns the configured segment capacity.
430    pub fn capacity(&self) -> u32 {
431        self.capacity
432    }
433
434    /// Returns the filled-segment asset path, if configured.
435    pub fn filled_asset_path(&self) -> Option<&AssetPath<'static>> {
436        self.filled_asset.as_ref()
437    }
438
439    /// Returns the empty-segment asset path, if configured.
440    pub fn empty_asset_path(&self) -> Option<&AssetPath<'static>> {
441        self.empty_asset.as_ref()
442    }
443}
444
445/// Supported retained HUD presentation kinds.
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
447pub enum HudPresentation {
448    /// Text resolved from text, scalar, count, or boolean values.
449    Text(HudText),
450    /// Continuous bar resolved from a scalar value.
451    Bar(HudBar),
452    /// Fixed or value-bound image icon.
453    Icon(HudIcon),
454    /// Bounded repeated segments resolved from a count value.
455    Segments(HudSegments),
456}
457
458impl HudPresentation {
459    /// Returns the dynamic value binding, if this presentation has one.
460    pub fn value_id(&self) -> Option<&HudValueId> {
461        match self {
462            Self::Text(text) => Some(text.value_id()),
463            Self::Bar(bar) => Some(bar.value_id()),
464            Self::Icon(HudIcon {
465                source: HudIconSource::Bound(value),
466            }) => Some(value),
467            Self::Icon(HudIcon {
468                source: HudIconSource::Asset(_),
469            }) => None,
470            Self::Segments(segments) => Some(segments.value_id()),
471        }
472    }
473
474    /// Returns whether this presentation can consume a value kind.
475    pub fn accepts_kind(&self, kind: HudValueKind) -> bool {
476        match self {
477            Self::Text(_) => matches!(
478                kind,
479                HudValueKind::Text
480                    | HudValueKind::Scalar
481                    | HudValueKind::Count
482                    | HudValueKind::Bool
483            ),
484            Self::Bar(_) => kind == HudValueKind::Scalar,
485            Self::Icon(HudIcon {
486                source: HudIconSource::Bound(_),
487            }) => kind == HudValueKind::Icon,
488            Self::Icon(HudIcon {
489                source: HudIconSource::Asset(_),
490            }) => false,
491            Self::Segments(_) => kind == HudValueKind::Count,
492        }
493    }
494}
495
496/// One of the nine supported screen anchors.
497#[derive(
498    Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
499)]
500pub enum HudAnchor {
501    #[default]
502    /// Top-left screen corner.
503    TopLeft,
504    /// Horizontal center of the top edge.
505    TopCenter,
506    /// Top-right screen corner.
507    TopRight,
508    /// Vertical center of the left edge.
509    CenterLeft,
510    /// Screen center.
511    Center,
512    /// Vertical center of the right edge.
513    CenterRight,
514    /// Bottom-left screen corner.
515    BottomLeft,
516    /// Horizontal center of the bottom edge.
517    BottomCenter,
518    /// Bottom-right screen corner.
519    BottomRight,
520}
521
522/// Direction in which elements sharing an anchor are stacked.
523#[derive(
524    Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
525)]
526pub enum HudStackDirection {
527    /// Lay out elements from left to right.
528    Horizontal,
529    #[default]
530    /// Lay out elements from top to bottom.
531    Vertical,
532}
533
534/// Bounded placement vocabulary for one HUD element.
535#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
536pub struct HudPlacement {
537    /// Screen location used as the element's layout anchor.
538    pub anchor: HudAnchor,
539    /// Logical-pixel offset from the anchor.
540    pub offset: [f32; 2],
541    /// Direction used to stack elements sharing the anchor.
542    pub stack_direction: HudStackDirection,
543}
544
545impl HudPlacement {
546    /// Creates default placement at `anchor`.
547    pub fn new(anchor: HudAnchor) -> Self {
548        Self {
549            anchor,
550            ..Self::default()
551        }
552    }
553
554    /// Sets a logical-pixel offset from the anchor.
555    pub fn offset(mut self, x: f32, y: f32) -> Self {
556        self.offset = [x, y];
557        self
558    }
559
560    /// Sets the stacking direction for this anchor group.
561    pub fn stack_direction(mut self, direction: HudStackDirection) -> Self {
562        self.stack_direction = direction;
563        self
564    }
565}
566
567impl Default for HudPlacement {
568    fn default() -> Self {
569        Self {
570            anchor: HudAnchor::TopLeft,
571            offset: [16.0, 16.0],
572            stack_direction: HudStackDirection::Vertical,
573        }
574    }
575}
576
577/// Default visual values used by the retained HUD renderer.
578#[derive(Debug, Clone, PartialEq, Resource, Serialize, Deserialize)]
579pub struct HudTheme {
580    /// Default text size in logical pixels.
581    pub font_size: f32,
582    /// Default linear RGBA text color.
583    pub text_color: [f32; 4],
584    /// Default linear RGBA background color.
585    pub background_color: [f32; 4],
586    /// Default linear RGBA foreground color.
587    pub foreground_color: [f32; 4],
588    /// Default logical-pixel padding in left, right, top, bottom order.
589    pub padding: [f32; 4],
590    /// Default logical-pixel gap between retained children.
591    pub gap: f32,
592    /// Default bar width and height in logical pixels.
593    pub bar_size: [f32; 2],
594    /// Default icon width and height in logical pixels.
595    pub icon_size: [f32; 2],
596    /// Default segment width and height in logical pixels.
597    pub segment_size: [f32; 2],
598    /// Default UI z-index; loading and debug overlays use higher values.
599    pub z_index: i32,
600}
601
602impl Default for HudTheme {
603    fn default() -> Self {
604        Self {
605            font_size: 18.0,
606            text_color: [1.0, 1.0, 1.0, 1.0],
607            background_color: [0.0, 0.0, 0.0, 0.65],
608            foreground_color: [0.2, 0.8, 1.0, 1.0],
609            padding: [8.0, 8.0, 6.0, 6.0],
610            gap: 6.0,
611            bar_size: [220.0, 18.0],
612            icon_size: [32.0, 32.0],
613            segment_size: [18.0, 18.0],
614            z_index: 50,
615        }
616    }
617}
618
619/// Narrow optional overrides corresponding to [`HudTheme`] fields.
620#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
621pub struct HudStyleOverride {
622    /// Optional text size override in logical pixels.
623    pub font_size: Option<f32>,
624    /// Optional linear RGBA text-color override.
625    pub text_color: Option<[f32; 4]>,
626    /// Optional linear RGBA background-color override.
627    pub background_color: Option<[f32; 4]>,
628    /// Optional linear RGBA foreground-color override.
629    pub foreground_color: Option<[f32; 4]>,
630    /// Optional logical-pixel padding override in left, right, top, bottom order.
631    pub padding: Option<[f32; 4]>,
632    /// Optional logical-pixel child-gap override.
633    pub gap: Option<f32>,
634    /// Optional logical-pixel bar size override.
635    pub bar_size: Option<[f32; 2]>,
636    /// Optional logical-pixel icon size override.
637    pub icon_size: Option<[f32; 2]>,
638    /// Optional logical-pixel segment size override.
639    pub segment_size: Option<[f32; 2]>,
640    /// Optional UI z-index override.
641    pub z_index: Option<i32>,
642}
643
644/// Author-defined presentation and placement for one HUD element.
645#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
646pub struct HudElementDefinition {
647    id: HudElementId,
648    presentation: HudPresentation,
649    placement: HudPlacement,
650    order: i32,
651    visible_when: Option<HudValueId>,
652    fallback: Option<HudValue>,
653    style: HudStyleOverride,
654}
655
656impl HudElementDefinition {
657    /// Creates a definition with default placement, order, visibility, and style.
658    pub fn new(id: impl Into<HudElementId>, presentation: HudPresentation) -> Self {
659        Self {
660            id: id.into(),
661            presentation,
662            placement: HudPlacement::default(),
663            order: 0,
664            visible_when: None,
665            fallback: None,
666            style: HudStyleOverride::default(),
667        }
668    }
669
670    /// Sets the element's screen placement.
671    pub fn placement(mut self, placement: HudPlacement) -> Self {
672        self.placement = placement;
673        self
674    }
675
676    /// Sets signed ordering within the anchor group.
677    pub fn order(mut self, order: i32) -> Self {
678        self.order = order;
679        self
680    }
681
682    /// Makes visibility conditional on a published boolean value.
683    pub fn visible_when(mut self, value: impl Into<HudValueId>) -> Self {
684        self.visible_when = Some(value.into());
685        self
686    }
687
688    /// Sets a compatible value used when the primary binding cannot resolve.
689    pub fn fallback(mut self, value: impl Into<HudValue>) -> Self {
690        self.fallback = Some(value.into());
691        self
692    }
693
694    /// Sets narrow visual overrides for this element.
695    pub fn style(mut self, style: HudStyleOverride) -> Self {
696        self.style = style;
697        self
698    }
699
700    /// Returns the stable element id.
701    pub fn id(&self) -> &HudElementId {
702        &self.id
703    }
704
705    /// Returns the element presentation.
706    pub fn presentation(&self) -> &HudPresentation {
707        &self.presentation
708    }
709
710    /// Returns the element placement.
711    pub fn placement_value(&self) -> HudPlacement {
712        self.placement
713    }
714
715    /// Returns signed ordering within the anchor group.
716    pub fn order_value(&self) -> i32 {
717        self.order
718    }
719
720    /// Returns the optional boolean visibility binding.
721    pub fn visibility_value_id(&self) -> Option<&HudValueId> {
722        self.visible_when.as_ref()
723    }
724
725    /// Returns the optional compatible fallback value.
726    pub fn fallback_value(&self) -> Option<&HudValue> {
727        self.fallback.as_ref()
728    }
729
730    /// Returns this element's narrow style overrides.
731    pub fn style_override(&self) -> &HudStyleOverride {
732        &self.style
733    }
734
735    /// Creates a serializable, definition-only inspection snapshot.
736    pub fn snapshot(&self) -> HudElementSnapshot {
737        HudElementSnapshot {
738            id: self.id.clone(),
739            presentation: self.presentation.clone(),
740            placement: self.placement,
741            order: self.order,
742            visible_when: self.visible_when.clone(),
743            fallback: self.fallback.clone(),
744            style: self.style.clone(),
745        }
746    }
747}
748
749/// Serializable inspection snapshot of one HUD element definition.
750#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
751pub struct HudElementSnapshot {
752    /// Stable element id.
753    pub id: HudElementId,
754    /// Presentation definition.
755    pub presentation: HudPresentation,
756    /// Screen placement.
757    pub placement: HudPlacement,
758    /// Signed ordering within the anchor group.
759    pub order: i32,
760    /// Optional boolean visibility binding.
761    pub visible_when: Option<HudValueId>,
762    /// Optional compatible fallback value.
763    pub fallback: Option<HudValue>,
764    /// Narrow visual overrides.
765    pub style: HudStyleOverride,
766}
767
768/// Serializable inspection snapshot of one published HUD value.
769#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
770pub struct HudValueSnapshot {
771    /// Stable published value id.
772    pub id: HudValueId,
773    /// Screen-ready published value.
774    pub value: HudValue,
775}
776
777/// Definition validation reason returned through [`HudRegistryError`].
778#[derive(Debug, Clone, PartialEq, Eq)]
779pub enum HudDefinitionError {
780    /// A fallback value cannot be consumed by the presentation.
781    InvalidFallbackKind {
782        /// Human-readable set of accepted kinds.
783        expected: &'static str,
784        /// Actual fallback kind.
785        actual: HudValueKind,
786    },
787    /// A fixed icon cannot use a value fallback because it has no binding.
788    StaticIconFallback,
789    /// Segment capacity is zero or exceeds [`MAX_HUD_SEGMENTS`].
790    InvalidSegmentCapacity {
791        /// Rejected capacity.
792        capacity: u32,
793        /// Maximum supported capacity.
794        maximum: u32,
795    },
796    /// At least one placement offset is NaN or infinite.
797    NonFinitePlacement,
798    /// A style field contains a non-finite or disallowed negative value.
799    InvalidStyleValue {
800        /// Name of the rejected field.
801        field: &'static str,
802    },
803}
804
805impl fmt::Display for HudDefinitionError {
806    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
807        match self {
808            Self::InvalidFallbackKind { expected, actual } => {
809                write!(
810                    f,
811                    "fallback kind {actual:?} is incompatible; expected {expected}"
812                )
813            }
814            Self::StaticIconFallback => {
815                f.write_str("a static icon has no value binding and cannot use a fallback")
816            }
817            Self::InvalidSegmentCapacity { capacity, maximum } => write!(
818                f,
819                "segment capacity {capacity} must be within 1..={maximum}"
820            ),
821            Self::NonFinitePlacement => f.write_str("HUD placement offsets must be finite"),
822            Self::InvalidStyleValue { field } => {
823                write!(
824                    f,
825                    "HUD style field `{field}` must be finite and non-negative"
826                )
827            }
828        }
829    }
830}
831
832/// Errors returned by [`HudRegistry`].
833#[derive(Debug, Clone, PartialEq, Eq)]
834pub enum HudRegistryError {
835    /// An element already exists under this id.
836    DuplicateId {
837        /// Duplicate element id.
838        id: HudElementId,
839    },
840    /// No element exists under this id.
841    MissingId {
842        /// Missing element id.
843        id: HudElementId,
844    },
845    /// The definition violates a model invariant.
846    InvalidDefinition {
847        /// Invalid element id.
848        id: HudElementId,
849        /// Specific invariant violation.
850        reason: HudDefinitionError,
851    },
852}
853
854impl fmt::Display for HudRegistryError {
855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856        match self {
857            Self::DuplicateId { id } => write!(f, "HUD element id `{id}` is already registered"),
858            Self::MissingId { id } => write!(f, "HUD element id `{id}` is not registered"),
859            Self::InvalidDefinition { id, reason } => {
860                write!(f, "HUD element `{id}` is invalid: {reason}")
861            }
862        }
863    }
864}
865
866impl std::error::Error for HudRegistryError {}
867
868/// Author-defined HUD element registry with revision-based change tracking.
869#[derive(Debug, Clone, Default, Resource)]
870pub struct HudRegistry {
871    elements_by_id: HashMap<HudElementId, HudElementDefinition>,
872    revision: u64,
873}
874
875impl HudRegistry {
876    /// Creates an empty registry at revision zero.
877    pub fn new() -> Self {
878        Self::default()
879    }
880
881    /// Registers a valid definition under a previously unused id.
882    ///
883    /// Duplicate ids return [`HudRegistryError::DuplicateId`] without changing
884    /// the registry or its revision. Use [`HudRegistry::insert_or_replace`] for
885    /// intentional replacement.
886    pub fn register(&mut self, definition: HudElementDefinition) -> Result<(), HudRegistryError> {
887        if self.elements_by_id.contains_key(definition.id()) {
888            return Err(HudRegistryError::DuplicateId {
889                id: definition.id().clone(),
890            });
891        }
892        validate_definition(&definition)?;
893        self.elements_by_id
894            .insert(definition.id().clone(), definition);
895        bump_revision(&mut self.revision);
896        Ok(())
897    }
898
899    /// Inserts a valid definition or replaces a different definition with the same id.
900    ///
901    /// An identical definition is a no-op. The returned value is the previous
902    /// different definition when replacement occurred; new insertion and an
903    /// identical no-op both return `None`.
904    pub fn insert_or_replace(
905        &mut self,
906        definition: HudElementDefinition,
907    ) -> Result<Option<HudElementDefinition>, HudRegistryError> {
908        validate_definition(&definition)?;
909        if self.elements_by_id.get(definition.id()) == Some(&definition) {
910            return Ok(None);
911        }
912        let previous = self
913            .elements_by_id
914            .insert(definition.id().clone(), definition);
915        bump_revision(&mut self.revision);
916        Ok(previous)
917    }
918
919    /// Removes and returns a definition, or reports a missing id.
920    pub fn remove(
921        &mut self,
922        id: impl AsRef<str>,
923    ) -> Result<HudElementDefinition, HudRegistryError> {
924        let id = HudElementId::new(id.as_ref());
925        let definition = self
926            .elements_by_id
927            .remove(&id)
928            .ok_or_else(|| HudRegistryError::MissingId { id: id.clone() })?;
929        bump_revision(&mut self.revision);
930        Ok(definition)
931    }
932
933    /// Returns a definition by element id.
934    pub fn get(&self, id: impl AsRef<str>) -> Option<&HudElementDefinition> {
935        self.elements_by_id.get(&HudElementId::new(id.as_ref()))
936    }
937
938    /// Returns a definition by id or an explicit missing-id error.
939    pub fn require(&self, id: impl AsRef<str>) -> Result<&HudElementDefinition, HudRegistryError> {
940        let id = HudElementId::new(id.as_ref());
941        self.elements_by_id
942            .get(&id)
943            .ok_or(HudRegistryError::MissingId { id })
944    }
945
946    /// Returns whether an element id is registered.
947    pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
948        self.get(id).is_some()
949    }
950
951    /// Returns the number of registered definitions.
952    pub fn len(&self) -> usize {
953        self.elements_by_id.len()
954    }
955
956    /// Returns whether the registry contains no definitions.
957    pub fn is_empty(&self) -> bool {
958        self.elements_by_id.is_empty()
959    }
960
961    /// Returns the current monotonic change revision.
962    pub fn revision(&self) -> u64 {
963        self.revision
964    }
965
966    /// Iterates definitions in unspecified hash-map order.
967    pub fn iter(&self) -> impl Iterator<Item = &HudElementDefinition> {
968        self.elements_by_id.values()
969    }
970
971    /// Returns deterministic id-ordered inspection snapshots.
972    pub fn snapshot(&self) -> Vec<HudElementSnapshot> {
973        let mut elements: Vec<_> = self.iter().map(HudElementDefinition::snapshot).collect();
974        elements.sort_by(|left, right| left.id.cmp(&right.id));
975        elements
976    }
977}
978
979/// Author-published screen-ready HUD values with revision-based change tracking.
980#[derive(Debug, Clone, Default, Resource)]
981pub struct HudValueSet {
982    values_by_id: HashMap<HudValueId, HudValue>,
983    revision: u64,
984}
985
986impl HudValueSet {
987    /// Creates an empty value set at revision zero.
988    pub fn new() -> Self {
989        Self::default()
990    }
991
992    /// Inserts or replaces a value. Equal replacement is a no-op.
993    ///
994    /// Returns the previous different value on replacement. New insertion and
995    /// an identical no-op both return `None`; use [`set_hud_value`] when the
996    /// caller needs an explicit changed flag and message emission.
997    pub fn insert_or_replace(
998        &mut self,
999        id: impl Into<HudValueId>,
1000        value: impl Into<HudValue>,
1001    ) -> Option<HudValue> {
1002        self.set_internal(id.into(), value.into()).0
1003    }
1004
1005    /// Removes and returns a value, or returns `None` without changing revision.
1006    pub fn remove(&mut self, id: impl AsRef<str>) -> Option<HudValue> {
1007        let removed = self.values_by_id.remove(&HudValueId::new(id.as_ref()));
1008        if removed.is_some() {
1009            bump_revision(&mut self.revision);
1010        }
1011        removed
1012    }
1013
1014    /// Returns a published value by id.
1015    pub fn get(&self, id: impl AsRef<str>) -> Option<&HudValue> {
1016        self.values_by_id.get(&HudValueId::new(id.as_ref()))
1017    }
1018
1019    /// Returns whether a value id is present.
1020    pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
1021        self.get(id).is_some()
1022    }
1023
1024    /// Returns the number of published values.
1025    pub fn len(&self) -> usize {
1026        self.values_by_id.len()
1027    }
1028
1029    /// Returns whether no values are published.
1030    pub fn is_empty(&self) -> bool {
1031        self.values_by_id.is_empty()
1032    }
1033
1034    /// Returns the current monotonic change revision.
1035    pub fn revision(&self) -> u64 {
1036        self.revision
1037    }
1038
1039    /// Iterates ids and values in unspecified hash-map order.
1040    pub fn iter(&self) -> impl Iterator<Item = (&HudValueId, &HudValue)> {
1041        self.values_by_id.iter()
1042    }
1043
1044    /// Returns deterministic id-ordered inspection snapshots.
1045    pub fn snapshot(&self) -> Vec<HudValueSnapshot> {
1046        let mut values: Vec<_> = self
1047            .iter()
1048            .map(|(id, value)| HudValueSnapshot {
1049                id: id.clone(),
1050                value: value.clone(),
1051            })
1052            .collect();
1053        values.sort_by(|left, right| left.id.cmp(&right.id));
1054        values
1055    }
1056
1057    fn set_internal(&mut self, id: HudValueId, value: HudValue) -> (Option<HudValue>, bool) {
1058        if self.values_by_id.get(&id) == Some(&value) {
1059            return (None, false);
1060        }
1061        let previous = self.values_by_id.insert(id, value);
1062        bump_revision(&mut self.revision);
1063        (previous, true)
1064    }
1065}
1066
1067/// Message emitted when a helper changes or removes a published value.
1068#[derive(Message, Debug, Clone, PartialEq, Serialize, Deserialize)]
1069pub struct HudValueChanged {
1070    /// Stable id of the changed value.
1071    pub id: HudValueId,
1072    /// Previous value, or `None` for first publication.
1073    pub previous: Option<HudValue>,
1074    /// Current value, or `None` after removal.
1075    pub current: Option<HudValue>,
1076}
1077
1078/// Current resolution problem for one HUD element.
1079///
1080/// Diagnostics describe author input without attaching game meaning to ids or
1081/// values. The renderer emits them only when an element enters a different
1082/// failure state.
1083#[derive(Debug, Clone, PartialEq, Eq)]
1084pub enum HudDiagnosticKind {
1085    /// A required published value is absent.
1086    MissingValue {
1087        /// Missing value id.
1088        value: HudValueId,
1089        /// How the element uses the missing value.
1090        binding: HudBindingKind,
1091    },
1092    /// A published value has a kind the binding cannot consume.
1093    MismatchedValue {
1094        /// Mismatched value id.
1095        value: HudValueId,
1096        /// How the element uses the mismatched value.
1097        binding: HudBindingKind,
1098        /// Actual published kind.
1099        actual: HudValueKind,
1100    },
1101    /// A presentation received no consumable value after validation.
1102    InvalidValue {
1103        /// How the element attempted to use the value.
1104        binding: HudBindingKind,
1105        /// Actual kind when a value was present.
1106        actual: Option<HudValueKind>,
1107    },
1108    /// A definition bypassed registry validation or became otherwise invalid.
1109    InvalidDefinition {
1110        /// Validation failure.
1111        reason: HudDefinitionError,
1112    },
1113    /// A merged theme/style field cannot be rendered safely.
1114    InvalidStyle {
1115        /// Name of the invalid resolved field.
1116        field: &'static str,
1117    },
1118    /// A segment count exceeds its registered capacity.
1119    ExcessiveSegments {
1120        /// Published segment count.
1121        count: u32,
1122        /// Definition capacity.
1123        capacity: u32,
1124    },
1125    /// A configured image path is not currently available.
1126    AssetUnavailable {
1127        /// Owned unavailable path.
1128        path: AssetPath<'static>,
1129    },
1130}
1131
1132/// Role of a published value in HUD resolution.
1133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1134pub enum HudBindingKind {
1135    /// Value consumed by the element presentation.
1136    Presentation,
1137    /// Boolean value controlling element visibility.
1138    Visibility,
1139}
1140
1141/// Message emitted when an element enters a new resolution failure state.
1142#[derive(Message, Debug, Clone, PartialEq, Eq)]
1143pub struct HudDiagnostic {
1144    /// Element whose resolution failed.
1145    pub element: HudElementId,
1146    /// Newly active failure state.
1147    pub kind: HudDiagnosticKind,
1148}
1149
1150/// Public scheduling boundary for author publication and retained HUD updates.
1151///
1152/// Put systems that call [`set_hud_value`] or [`remove_hud_value`] in
1153/// [`HudSystemSet::Publish`] when their changes must be visible in the same
1154/// update. Reconciliation and rendering are ordered after that set.
1155#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
1156pub enum HudSystemSet {
1157    /// Author-owned systems publish screen-ready values here.
1158    Publish,
1159    /// Retained entity structure is reconciled after publication.
1160    Reconcile,
1161    /// Changed resolved state is applied after deferred reconciliation.
1162    Render,
1163}
1164
1165/// Explicit, domain-neutral retained renderer for author-defined HUD elements.
1166///
1167/// The plugin is intentionally independent from [`crate::ui::UiPlugin`] and
1168/// every convenience bundle. It can run with `MinimalPlugins`, initializes an
1169/// empty HUD, and performs no asset I/O unless a registered presentation
1170/// actually references an image path and an [`AssetServer`] is available.
1171pub struct VoxelHudPlugin;
1172
1173impl Plugin for VoxelHudPlugin {
1174    fn build(&self, app: &mut App) {
1175        app.init_resource::<HudRegistry>()
1176            .init_resource::<HudValueSet>()
1177            .init_resource::<HudTheme>()
1178            .init_resource::<HudRuntimeState>()
1179            .init_resource::<HudDiagnosticTracker>()
1180            .init_resource::<HudAssetCache>()
1181            .add_message::<HudValueChanged>()
1182            .add_message::<HudDiagnostic>()
1183            .configure_sets(
1184                Update,
1185                (
1186                    HudSystemSet::Publish,
1187                    HudSystemSet::Reconcile,
1188                    HudSystemSet::Render,
1189                )
1190                    .chain(),
1191            )
1192            .configure_sets(
1193                PostStartup,
1194                (
1195                    HudSystemSet::Publish,
1196                    HudSystemSet::Reconcile,
1197                    HudSystemSet::Render,
1198                )
1199                    .chain(),
1200            )
1201            .add_systems(
1202                PostStartup,
1203                (
1204                    reconcile_hud_entities.in_set(HudSystemSet::Reconcile),
1205                    ApplyDeferred,
1206                    render_hud_entities.in_set(HudSystemSet::Render),
1207                )
1208                    .chain(),
1209            )
1210            .add_systems(
1211                Update,
1212                (
1213                    reconcile_hud_entities.in_set(HudSystemSet::Reconcile),
1214                    ApplyDeferred,
1215                    render_hud_entities.in_set(HudSystemSet::Render),
1216                )
1217                    .chain(),
1218            );
1219    }
1220}
1221
1222#[derive(Component)]
1223struct HudCanvas;
1224
1225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1226struct HudAnchorKey {
1227    anchor: HudAnchor,
1228    direction: HudStackDirection,
1229}
1230
1231#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
1232struct HudAnchorRoot(HudAnchorKey);
1233
1234#[derive(Component, Debug, Clone, PartialEq, Eq)]
1235struct HudElementRoot(HudElementId);
1236
1237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1238enum HudTreeKind {
1239    Text,
1240    Bar,
1241    Icon,
1242    Segments(u32),
1243}
1244
1245impl HudTreeKind {
1246    fn from_presentation(presentation: &HudPresentation) -> Self {
1247        match presentation {
1248            HudPresentation::Text(_) => Self::Text,
1249            HudPresentation::Bar(_) => Self::Bar,
1250            HudPresentation::Icon(_) => Self::Icon,
1251            HudPresentation::Segments(segments) => Self::Segments(segments.capacity()),
1252        }
1253    }
1254}
1255
1256#[derive(Component, Debug, Clone, PartialEq)]
1257struct HudDefinitionFingerprint {
1258    definition: HudElementSnapshot,
1259    tree: HudTreeKind,
1260}
1261
1262#[derive(Component, Debug, Default, Clone, PartialEq)]
1263struct HudResolvedFingerprint(Option<ResolvedHudElement>);
1264
1265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1266enum HudChildKind {
1267    Text,
1268    BarTrack,
1269    BarFill,
1270    Icon,
1271    Segment(u32),
1272}
1273
1274#[derive(Component, Debug, Clone, PartialEq, Eq)]
1275struct HudChildIdentity {
1276    element: HudElementId,
1277    kind: HudChildKind,
1278}
1279
1280#[derive(Component, Debug, Default, Clone, PartialEq)]
1281struct HudCachedImage {
1282    path: Option<AssetPath<'static>>,
1283    handle: Option<Handle<Image>>,
1284}
1285
1286#[derive(Resource, Debug, Default)]
1287struct HudRuntimeState {
1288    registry_revision: Option<u64>,
1289    value_revision: Option<u64>,
1290    render_all: bool,
1291    pending_assets: bool,
1292    asset_server_present: bool,
1293    image_events: bevy::ecs::message::MessageCursor<bevy::asset::AssetEvent<Image>>,
1294    image_failures: bevy::ecs::message::MessageCursor<bevy::asset::AssetLoadFailedEvent<Image>>,
1295}
1296
1297#[derive(Resource, Debug, Default)]
1298struct HudAssetCache {
1299    handles: HashMap<AssetPath<'static>, Handle<Image>>,
1300}
1301
1302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1303enum HudAxisAnchor {
1304    Start,
1305    Center,
1306    End,
1307}
1308
1309#[derive(Debug, Clone, PartialEq)]
1310struct ResolvedHudLayout {
1311    anchor: HudAnchor,
1312    horizontal: HudAxisAnchor,
1313    vertical: HudAxisAnchor,
1314    offset: [f32; 2],
1315    stack_direction: HudStackDirection,
1316    order: i32,
1317}
1318
1319#[derive(Debug, Clone, PartialEq)]
1320struct ResolvedHudStyle {
1321    font_size: f32,
1322    text_color: [f32; 4],
1323    background_color: [f32; 4],
1324    foreground_color: [f32; 4],
1325    padding: [f32; 4],
1326    gap: f32,
1327    bar_size: [f32; 2],
1328    icon_size: [f32; 2],
1329    segment_size: [f32; 2],
1330    z_index: i32,
1331}
1332
1333#[derive(Debug, Clone, PartialEq)]
1334enum ResolvedHudPresentation {
1335    Text(String),
1336    Bar {
1337        ratio: f32,
1338    },
1339    Icon {
1340        path: Option<AssetPath<'static>>,
1341    },
1342    Segments {
1343        filled: u32,
1344        capacity: u32,
1345        filled_asset: Option<AssetPath<'static>>,
1346        empty_asset: Option<AssetPath<'static>>,
1347    },
1348}
1349
1350#[derive(Debug, Clone, PartialEq)]
1351struct ResolvedHudElement {
1352    id: HudElementId,
1353    visible: bool,
1354    used_fallback: bool,
1355    layout: ResolvedHudLayout,
1356    style: ResolvedHudStyle,
1357    presentation: ResolvedHudPresentation,
1358}
1359
1360#[derive(Resource, Debug, Default)]
1361struct HudDiagnosticTracker {
1362    active_by_element: HashMap<HudElementId, HudDiagnosticKind>,
1363}
1364
1365impl HudDiagnosticTracker {
1366    fn transition(
1367        &mut self,
1368        element: &HudElementId,
1369        current: Option<HudDiagnosticKind>,
1370    ) -> Option<HudDiagnostic> {
1371        match current {
1372            Some(kind) if self.active_by_element.get(element) == Some(&kind) => None,
1373            Some(kind) => {
1374                self.active_by_element.insert(element.clone(), kind.clone());
1375                Some(HudDiagnostic {
1376                    element: element.clone(),
1377                    kind,
1378                })
1379            }
1380            None => {
1381                self.active_by_element.remove(element);
1382                None
1383            }
1384        }
1385    }
1386
1387    fn retain_elements(&mut self, ids: &HashSet<HudElementId>) {
1388        self.active_by_element.retain(|id, _| ids.contains(id));
1389    }
1390}
1391
1392#[derive(Debug, Default)]
1393struct ResolvedHud {
1394    elements: Vec<ResolvedHudElement>,
1395    diagnostics: Vec<HudDiagnostic>,
1396}
1397
1398/// Publishes a value and emits [`HudValueChanged`] only when stored state changes.
1399pub fn set_hud_value(
1400    id: impl Into<HudValueId>,
1401    value: impl Into<HudValue>,
1402    values: &mut HudValueSet,
1403    changed: &mut MessageWriter<HudValueChanged>,
1404) -> bool {
1405    let id = id.into();
1406    let value = value.into();
1407    let (previous, did_change) = values.set_internal(id.clone(), value.clone());
1408    if did_change {
1409        changed.write(HudValueChanged {
1410            id,
1411            previous,
1412            current: Some(value),
1413        });
1414    }
1415    did_change
1416}
1417
1418/// Removes a value and emits [`HudValueChanged`] only when it existed.
1419pub fn remove_hud_value(
1420    id: impl AsRef<str>,
1421    values: &mut HudValueSet,
1422    changed: &mut MessageWriter<HudValueChanged>,
1423) -> bool {
1424    let id = HudValueId::new(id.as_ref());
1425    let Some(previous) = values.remove(id.as_str()) else {
1426        return false;
1427    };
1428    changed.write(HudValueChanged {
1429        id,
1430        previous: Some(previous),
1431        current: None,
1432    });
1433    true
1434}
1435
1436const HUD_ANCHORS: [HudAnchor; 9] = [
1437    HudAnchor::TopLeft,
1438    HudAnchor::TopCenter,
1439    HudAnchor::TopRight,
1440    HudAnchor::CenterLeft,
1441    HudAnchor::Center,
1442    HudAnchor::CenterRight,
1443    HudAnchor::BottomLeft,
1444    HudAnchor::BottomCenter,
1445    HudAnchor::BottomRight,
1446];
1447const HUD_STACK_DIRECTIONS: [HudStackDirection; 2] =
1448    [HudStackDirection::Horizontal, HudStackDirection::Vertical];
1449
1450fn hud_anchor_keys() -> impl Iterator<Item = HudAnchorKey> {
1451    HUD_ANCHORS.into_iter().flat_map(|anchor| {
1452        HUD_STACK_DIRECTIONS
1453            .into_iter()
1454            .map(move |direction| HudAnchorKey { anchor, direction })
1455    })
1456}
1457
1458fn reconcile_hud_entities(
1459    mut commands: Commands,
1460    registry: Res<HudRegistry>,
1461    theme: Res<HudTheme>,
1462    mut runtime: ResMut<HudRuntimeState>,
1463    canvases: Query<(Entity, Option<&Children>), With<HudCanvas>>,
1464    anchors: Query<(Entity, &HudAnchorRoot, Option<&Children>, Option<&ChildOf>)>,
1465    roots: Query<(
1466        Entity,
1467        &HudElementRoot,
1468        &HudDefinitionFingerprint,
1469        Option<&Children>,
1470    )>,
1471    child_identities: Query<&HudChildIdentity>,
1472) {
1473    let structure_missing = canvases.iter().count() != 1 || anchors.iter().count() != 18;
1474    if runtime.registry_revision == Some(registry.revision())
1475        && !theme.is_changed()
1476        && !structure_missing
1477    {
1478        return;
1479    }
1480
1481    let mut canvas_entities: Vec<_> = canvases
1482        .iter()
1483        .map(|(entity, children)| (entity, children.map(|children| children.to_vec())))
1484        .collect();
1485    canvas_entities.sort_by_key(|(entity, _)| entity.to_bits());
1486    let canvas_children = canvas_entities
1487        .first()
1488        .and_then(|(_, children)| children.clone())
1489        .unwrap_or_default();
1490    let canvas = canvas_entities
1491        .first()
1492        .map(|(entity, _)| *entity)
1493        .unwrap_or_else(|| {
1494            commands
1495                .spawn((
1496                    HudCanvas,
1497                    Node {
1498                        position_type: PositionType::Absolute,
1499                        width: Val::Percent(100.0),
1500                        height: Val::Percent(100.0),
1501                        ..default()
1502                    },
1503                ))
1504                .id()
1505        });
1506    for (duplicate, children) in canvas_entities.into_iter().skip(1) {
1507        for child in children.into_iter().flatten() {
1508            commands.entity(canvas).add_child(child);
1509        }
1510        commands.entity(duplicate).despawn();
1511    }
1512
1513    let mut anchors_by_kind: HashMap<HudAnchorKey, Vec<(Entity, Vec<Entity>, Option<Entity>)>> =
1514        HashMap::new();
1515    for (entity, anchor, children, parent) in &anchors {
1516        anchors_by_kind.entry(anchor.0).or_default().push((
1517            entity,
1518            children.map_or_else(Vec::new, |children| children.to_vec()),
1519            parent.map(ChildOf::parent),
1520        ));
1521    }
1522
1523    let mut anchor_entities = HashMap::new();
1524    let mut anchor_children = HashMap::new();
1525    for key in hud_anchor_keys() {
1526        let mut candidates = anchors_by_kind.remove(&key).unwrap_or_default();
1527        candidates.sort_by_key(|(entity, _, _)| entity.to_bits());
1528        let anchor_entity = candidates
1529            .first()
1530            .map(|(entity, _, _)| *entity)
1531            .unwrap_or_else(|| {
1532                commands
1533                    .spawn((HudAnchorRoot(key), anchor_node(key), ChildOf(canvas)))
1534                    .id()
1535            });
1536        anchor_children.insert(
1537            key,
1538            candidates
1539                .first()
1540                .map(|(_, children, _)| children.clone())
1541                .unwrap_or_default(),
1542        );
1543
1544        if candidates.first().and_then(|(_, _, parent)| *parent) != Some(canvas) {
1545            commands.entity(canvas).add_child(anchor_entity);
1546        }
1547        for (duplicate, children, _) in candidates.into_iter().skip(1) {
1548            for child in children {
1549                commands.entity(anchor_entity).add_child(child);
1550            }
1551            commands.entity(duplicate).despawn();
1552        }
1553        anchor_entities.insert(key, anchor_entity);
1554    }
1555    let ordered_anchors: Vec<_> = hud_anchor_keys().map(|key| anchor_entities[&key]).collect();
1556    if canvas_children != ordered_anchors {
1557        commands.entity(canvas).replace_children(&ordered_anchors);
1558    }
1559
1560    let mut root_candidates: HashMap<
1561        HudElementId,
1562        Vec<(Entity, HudDefinitionFingerprint, Vec<Entity>)>,
1563    > = HashMap::new();
1564    for (entity, root, fingerprint, children) in &roots {
1565        root_candidates.entry(root.0.clone()).or_default().push((
1566            entity,
1567            fingerprint.clone(),
1568            children.map_or_else(Vec::new, |children| children.to_vec()),
1569        ));
1570    }
1571    for candidates in root_candidates.values_mut() {
1572        candidates.sort_by_key(|(entity, _, _)| entity.to_bits());
1573    }
1574
1575    let mut definitions: Vec<_> = registry.iter().collect();
1576    definitions.sort_by(|left, right| {
1577        left.placement
1578            .anchor
1579            .cmp(&right.placement.anchor)
1580            .then_with(|| left.order.cmp(&right.order))
1581            .then_with(|| left.id.cmp(&right.id))
1582    });
1583    let active_ids: HashSet<_> = definitions
1584        .iter()
1585        .map(|definition| definition.id().clone())
1586        .collect();
1587
1588    for (id, candidates) in &root_candidates {
1589        if !active_ids.contains(id) {
1590            for (entity, _, _) in candidates {
1591                commands.entity(*entity).despawn();
1592            }
1593        } else {
1594            for (entity, _, _) in candidates.iter().skip(1) {
1595                commands.entity(*entity).despawn();
1596            }
1597        }
1598    }
1599
1600    let mut roots_by_id = HashMap::new();
1601    for definition in &definitions {
1602        let id = definition.id().clone();
1603        let tree = HudTreeKind::from_presentation(definition.presentation());
1604        let snapshot = definition.snapshot();
1605        let root = if let Some((entity, old_fingerprint, children)) = root_candidates
1606            .get(&id)
1607            .and_then(|candidates| candidates.first())
1608        {
1609            reconcile_hud_tree(
1610                &mut commands,
1611                *entity,
1612                &id,
1613                old_fingerprint.tree,
1614                tree,
1615                children,
1616                &child_identities,
1617            );
1618            if old_fingerprint.definition != snapshot || old_fingerprint.tree != tree {
1619                commands.entity(*entity).insert(HudDefinitionFingerprint {
1620                    definition: snapshot,
1621                    tree,
1622                });
1623            }
1624            *entity
1625        } else {
1626            let entity = commands
1627                .spawn((
1628                    HudElementRoot(id.clone()),
1629                    HudDefinitionFingerprint {
1630                        definition: snapshot,
1631                        tree,
1632                    },
1633                    HudResolvedFingerprint::default(),
1634                    Node::default(),
1635                    UiTransform::default(),
1636                    BackgroundColor(Color::NONE),
1637                    Visibility::Hidden,
1638                    ZIndex(0),
1639                ))
1640                .id();
1641            spawn_hud_tree(&mut commands, entity, &id, tree);
1642            entity
1643        };
1644        roots_by_id.insert(id, root);
1645    }
1646
1647    let mut desired_by_anchor: HashMap<HudAnchorKey, Vec<Entity>> = HashMap::new();
1648    for definition in definitions {
1649        let placement = definition.placement_value();
1650        desired_by_anchor
1651            .entry(HudAnchorKey {
1652                anchor: placement.anchor,
1653                direction: placement.stack_direction,
1654            })
1655            .or_default()
1656            .push(roots_by_id[definition.id()]);
1657    }
1658    for key in hud_anchor_keys() {
1659        let desired = desired_by_anchor.remove(&key).unwrap_or_default();
1660        if anchor_children[&key] != desired {
1661            commands
1662                .entity(anchor_entities[&key])
1663                .replace_children(&desired);
1664        }
1665    }
1666
1667    runtime.registry_revision = Some(registry.revision());
1668    runtime.render_all = true;
1669}
1670
1671fn anchor_node(key: HudAnchorKey) -> Node {
1672    let horizontal = match key.anchor {
1673        HudAnchor::TopLeft | HudAnchor::CenterLeft | HudAnchor::BottomLeft => HudAxisAnchor::Start,
1674        HudAnchor::TopCenter | HudAnchor::Center | HudAnchor::BottomCenter => HudAxisAnchor::Center,
1675        HudAnchor::TopRight | HudAnchor::CenterRight | HudAnchor::BottomRight => HudAxisAnchor::End,
1676    };
1677    let vertical = match key.anchor {
1678        HudAnchor::TopLeft | HudAnchor::TopCenter | HudAnchor::TopRight => HudAxisAnchor::Start,
1679        HudAnchor::CenterLeft | HudAnchor::Center | HudAnchor::CenterRight => HudAxisAnchor::Center,
1680        HudAnchor::BottomLeft | HudAnchor::BottomCenter | HudAnchor::BottomRight => {
1681            HudAxisAnchor::End
1682        }
1683    };
1684    let axis_to_align = |axis| match axis {
1685        HudAxisAnchor::Start => AlignItems::FlexStart,
1686        HudAxisAnchor::Center => AlignItems::Center,
1687        HudAxisAnchor::End => AlignItems::FlexEnd,
1688    };
1689    let axis_to_justify = |axis| match axis {
1690        HudAxisAnchor::Start => JustifyContent::FlexStart,
1691        HudAxisAnchor::Center => JustifyContent::Center,
1692        HudAxisAnchor::End => JustifyContent::FlexEnd,
1693    };
1694    let (align_items, justify_content) = match key.direction {
1695        HudStackDirection::Horizontal => (axis_to_align(vertical), axis_to_justify(horizontal)),
1696        HudStackDirection::Vertical => (axis_to_align(horizontal), axis_to_justify(vertical)),
1697    };
1698    Node {
1699        position_type: PositionType::Absolute,
1700        width: Val::Percent(100.0),
1701        height: Val::Percent(100.0),
1702        flex_direction: match key.direction {
1703            HudStackDirection::Horizontal => FlexDirection::Row,
1704            HudStackDirection::Vertical => FlexDirection::Column,
1705        },
1706        align_items,
1707        justify_content,
1708        ..default()
1709    }
1710}
1711
1712fn reconcile_hud_tree(
1713    commands: &mut Commands,
1714    root: Entity,
1715    id: &HudElementId,
1716    old: HudTreeKind,
1717    new: HudTreeKind,
1718    children: &[Entity],
1719    child_identities: &Query<&HudChildIdentity>,
1720) {
1721    match (old, new) {
1722        (HudTreeKind::Segments(_), HudTreeKind::Segments(capacity)) => {
1723            let mut segments = Vec::new();
1724            let mut malformed = false;
1725            for child in children {
1726                match child_identities.get(*child) {
1727                    Ok(HudChildIdentity {
1728                        element,
1729                        kind: HudChildKind::Segment(index),
1730                    }) if element == id => segments.push((*index, *child)),
1731                    _ => malformed = true,
1732                }
1733            }
1734            segments.sort_by_key(|(index, entity)| (*index, entity.to_bits()));
1735            let unique = segments.windows(2).all(|pair| pair[0].0 != pair[1].0);
1736            if malformed || !unique {
1737                commands.entity(root).despawn_children();
1738                spawn_hud_tree(commands, root, id, new);
1739                return;
1740            }
1741
1742            let mut desired = Vec::with_capacity(capacity as usize);
1743            for index in 0..capacity {
1744                if let Some((_, entity)) = segments.iter().find(|(existing, _)| *existing == index)
1745                {
1746                    desired.push(*entity);
1747                } else {
1748                    desired.push(spawn_segment(commands, root, id, index));
1749                }
1750            }
1751            for (index, entity) in segments {
1752                if index >= capacity {
1753                    commands.entity(entity).despawn();
1754                }
1755            }
1756            commands.entity(root).replace_children(&desired);
1757        }
1758        (HudTreeKind::Text, HudTreeKind::Text)
1759        | (HudTreeKind::Bar, HudTreeKind::Bar)
1760        | (HudTreeKind::Icon, HudTreeKind::Icon) => {}
1761        _ => {
1762            commands.entity(root).despawn_children();
1763            spawn_hud_tree(commands, root, id, new);
1764        }
1765    }
1766}
1767
1768fn spawn_hud_tree(commands: &mut Commands, root: Entity, id: &HudElementId, tree: HudTreeKind) {
1769    match tree {
1770        HudTreeKind::Text => {
1771            commands.spawn((
1772                HudChildIdentity {
1773                    element: id.clone(),
1774                    kind: HudChildKind::Text,
1775                },
1776                Text::new(""),
1777                TextFont::default(),
1778                TextColor(Color::WHITE),
1779                Node::default(),
1780                ChildOf(root),
1781            ));
1782        }
1783        HudTreeKind::Bar => {
1784            let track = commands
1785                .spawn((
1786                    HudChildIdentity {
1787                        element: id.clone(),
1788                        kind: HudChildKind::BarTrack,
1789                    },
1790                    Node::default(),
1791                    BackgroundColor(Color::NONE),
1792                    ChildOf(root),
1793                ))
1794                .id();
1795            commands.spawn((
1796                HudChildIdentity {
1797                    element: id.clone(),
1798                    kind: HudChildKind::BarFill,
1799                },
1800                Node::default(),
1801                BackgroundColor(Color::NONE),
1802                ChildOf(track),
1803            ));
1804        }
1805        HudTreeKind::Icon => {
1806            commands.spawn((
1807                HudChildIdentity {
1808                    element: id.clone(),
1809                    kind: HudChildKind::Icon,
1810                },
1811                HudCachedImage::default(),
1812                Node::default(),
1813                ImageNode::default(),
1814                ChildOf(root),
1815            ));
1816        }
1817        HudTreeKind::Segments(capacity) => {
1818            for index in 0..capacity {
1819                spawn_segment(commands, root, id, index);
1820            }
1821        }
1822    }
1823}
1824
1825fn spawn_segment(commands: &mut Commands, root: Entity, id: &HudElementId, index: u32) -> Entity {
1826    commands
1827        .spawn((
1828            HudChildIdentity {
1829                element: id.clone(),
1830                kind: HudChildKind::Segment(index),
1831            },
1832            HudCachedImage::default(),
1833            Node::default(),
1834            BackgroundColor(Color::NONE),
1835            ImageNode::default(),
1836            ChildOf(root),
1837        ))
1838        .id()
1839}
1840
1841#[allow(clippy::too_many_arguments, clippy::type_complexity)]
1842fn render_hud_entities(
1843    registry: Res<HudRegistry>,
1844    values: Res<HudValueSet>,
1845    theme: Res<HudTheme>,
1846    asset_server: Option<Res<AssetServer>>,
1847    image_events: Option<Res<Messages<bevy::asset::AssetEvent<Image>>>>,
1848    image_failures: Option<Res<Messages<bevy::asset::AssetLoadFailedEvent<Image>>>>,
1849    mut asset_cache: ResMut<HudAssetCache>,
1850    mut runtime: ResMut<HudRuntimeState>,
1851    mut tracker: ResMut<HudDiagnosticTracker>,
1852    mut diagnostics: MessageWriter<HudDiagnostic>,
1853    mut roots: Query<
1854        (
1855            &HudElementRoot,
1856            &mut HudResolvedFingerprint,
1857            &mut Node,
1858            &mut UiTransform,
1859            &mut BackgroundColor,
1860            &mut Visibility,
1861            &mut ZIndex,
1862        ),
1863        Without<HudChildIdentity>,
1864    >,
1865    mut children: Query<
1866        (
1867            &HudChildIdentity,
1868            &mut Node,
1869            Option<&mut Text>,
1870            Option<&mut TextFont>,
1871            Option<&mut TextColor>,
1872            Option<&mut BackgroundColor>,
1873            Option<&mut ImageNode>,
1874            Option<&mut HudCachedImage>,
1875        ),
1876        Without<HudElementRoot>,
1877    >,
1878) {
1879    let asset_server_present = asset_server.is_some();
1880    // Failed loads stop pending polling, but are not permanently unavailable:
1881    // AssetServer::reload can add the same Image later without any HUD edits.
1882    // Consume only events for cached handles; unrelated assets do not render HUD.
1883    let assets_changed = image_events.as_ref().is_some_and(|events| {
1884        runtime
1885            .image_events
1886            .read(events)
1887            .fold(false, |changed, event| {
1888                let relevant = asset_cache.handles.values().any(|handle| {
1889                    event.is_added(handle.id())
1890                        || event.is_modified(handle.id())
1891                        || event.is_removed(handle.id())
1892                        || event.is_loaded_with_dependencies(handle.id())
1893                });
1894                changed || relevant
1895            })
1896    });
1897    let assets_failed = image_failures.as_ref().is_some_and(|events| {
1898        runtime
1899            .image_failures
1900            .read(events)
1901            .fold(false, |changed, event| {
1902                let relevant = asset_cache
1903                    .handles
1904                    .values()
1905                    .any(|handle| handle.id() == event.id);
1906                changed || relevant
1907            })
1908    });
1909    if !runtime.render_all
1910        && runtime.value_revision == Some(values.revision())
1911        && !runtime.pending_assets
1912        && !assets_changed
1913        && !assets_failed
1914        && runtime.asset_server_present == asset_server_present
1915    {
1916        return;
1917    }
1918
1919    let mut pending_assets = false;
1920    let mut touched_assets = HashSet::new();
1921    let resolved = resolve_hud(
1922        &registry,
1923        &values,
1924        &theme,
1925        |path| {
1926            touched_assets.insert(path.clone().into_owned());
1927            asset_server.as_ref().is_some_and(|server| {
1928                asset_cache.ensure_available(path, server, &mut pending_assets)
1929            })
1930        },
1931        &mut tracker,
1932    );
1933    asset_cache
1934        .handles
1935        .retain(|path, _| touched_assets.contains(path));
1936    for diagnostic in resolved.diagnostics.iter().cloned() {
1937        diagnostics.write(diagnostic);
1938    }
1939
1940    let resolved_by_id: HashMap<_, _> = resolved
1941        .elements
1942        .iter()
1943        .map(|element| (element.id.clone(), element))
1944        .collect();
1945    let mut changed_elements = HashSet::new();
1946    for (
1947        root,
1948        mut fingerprint,
1949        mut node,
1950        mut transform,
1951        mut background,
1952        mut visibility,
1953        mut z_index,
1954    ) in &mut roots
1955    {
1956        let Some(element) = resolved_by_id.get(&root.0).copied() else {
1957            continue;
1958        };
1959        if fingerprint.0.as_ref() == Some(element) {
1960            continue;
1961        }
1962
1963        replace_if_changed(&mut node, hud_root_node(element));
1964        replace_if_changed(&mut transform, hud_root_transform(&element.layout));
1965        replace_if_changed(
1966            &mut background,
1967            BackgroundColor(root_background_color(element)),
1968        );
1969        replace_if_changed(
1970            &mut visibility,
1971            if element.visible {
1972                Visibility::Inherited
1973            } else {
1974                Visibility::Hidden
1975            },
1976        );
1977        replace_if_changed(&mut z_index, ZIndex(element.style.z_index));
1978        fingerprint.0 = Some(element.clone());
1979        changed_elements.insert(root.0.clone());
1980    }
1981
1982    for (identity, mut node, text, font, text_color, background, image, cached_image) in
1983        &mut children
1984    {
1985        if !changed_elements.contains(&identity.element) {
1986            continue;
1987        }
1988        let Some(element) = resolved_by_id.get(&identity.element).copied() else {
1989            continue;
1990        };
1991        render_hud_child(
1992            identity.kind,
1993            element,
1994            &asset_cache,
1995            &mut node,
1996            text,
1997            font,
1998            text_color,
1999            background,
2000            image,
2001            cached_image,
2002        );
2003    }
2004
2005    runtime.value_revision = Some(values.revision());
2006    runtime.render_all = false;
2007    runtime.pending_assets = pending_assets;
2008    runtime.asset_server_present = asset_server_present;
2009}
2010
2011impl HudAssetCache {
2012    fn ensure_available(
2013        &mut self,
2014        path: &AssetPath<'static>,
2015        asset_server: &AssetServer,
2016        pending: &mut bool,
2017    ) -> bool {
2018        let handle = self
2019            .handles
2020            .entry(path.clone().into_owned())
2021            .or_insert_with(|| asset_server.load::<Image>(path.clone().into_owned()));
2022        match asset_server.load_state(handle.id()) {
2023            LoadState::Loaded => true,
2024            LoadState::NotLoaded | LoadState::Loading => {
2025                *pending = true;
2026                false
2027            }
2028            LoadState::Failed(_) => false,
2029        }
2030    }
2031
2032    fn handle(&self, path: &AssetPath<'static>) -> Option<Handle<Image>> {
2033        self.handles.get(path).cloned()
2034    }
2035}
2036
2037#[allow(clippy::too_many_arguments)]
2038fn render_hud_child(
2039    kind: HudChildKind,
2040    element: &ResolvedHudElement,
2041    asset_cache: &HudAssetCache,
2042    node: &mut Mut<Node>,
2043    mut text: Option<Mut<Text>>,
2044    mut font: Option<Mut<TextFont>>,
2045    mut text_color: Option<Mut<TextColor>>,
2046    mut background: Option<Mut<BackgroundColor>>,
2047    mut image: Option<Mut<ImageNode>>,
2048    mut cached_image: Option<Mut<HudCachedImage>>,
2049) {
2050    match (kind, &element.presentation) {
2051        (HudChildKind::Text, ResolvedHudPresentation::Text(value)) => {
2052            replace_if_changed(node, Node::default());
2053            if let Some(text) = text.as_mut() {
2054                replace_if_changed(text, Text::new(value.clone()));
2055            }
2056            if let Some(font) = font.as_mut() {
2057                replace_if_changed(font, TextFont::from_font_size(element.style.font_size));
2058            }
2059            if let Some(text_color) = text_color.as_mut() {
2060                replace_if_changed(
2061                    text_color,
2062                    TextColor(color_from_array(element.style.text_color)),
2063                );
2064            }
2065        }
2066        (HudChildKind::BarTrack, ResolvedHudPresentation::Bar { .. }) => {
2067            replace_if_changed(
2068                node,
2069                Node {
2070                    width: Val::Px(element.style.bar_size[0]),
2071                    height: Val::Px(element.style.bar_size[1]),
2072                    ..default()
2073                },
2074            );
2075            if let Some(background) = background.as_mut() {
2076                replace_if_changed(
2077                    background,
2078                    BackgroundColor(color_from_array(element.style.background_color)),
2079                );
2080            }
2081        }
2082        (HudChildKind::BarFill, ResolvedHudPresentation::Bar { ratio }) => {
2083            replace_if_changed(
2084                node,
2085                Node {
2086                    width: Val::Px(element.style.bar_size[0] * ratio),
2087                    height: Val::Percent(100.0),
2088                    ..default()
2089                },
2090            );
2091            if let Some(background) = background.as_mut() {
2092                replace_if_changed(
2093                    background,
2094                    BackgroundColor(color_from_array(element.style.foreground_color)),
2095                );
2096            }
2097        }
2098        (HudChildKind::Icon, ResolvedHudPresentation::Icon { path }) => {
2099            replace_if_changed(
2100                node,
2101                Node {
2102                    width: Val::Px(element.style.icon_size[0]),
2103                    height: Val::Px(element.style.icon_size[1]),
2104                    ..default()
2105                },
2106            );
2107            render_image(path.as_ref(), asset_cache, &mut image, &mut cached_image);
2108        }
2109        (
2110            HudChildKind::Segment(index),
2111            ResolvedHudPresentation::Segments {
2112                filled,
2113                filled_asset,
2114                empty_asset,
2115                ..
2116            },
2117        ) => {
2118            replace_if_changed(
2119                node,
2120                Node {
2121                    width: Val::Px(element.style.segment_size[0]),
2122                    height: Val::Px(element.style.segment_size[1]),
2123                    ..default()
2124                },
2125            );
2126            let is_filled = index < *filled;
2127            let path = if is_filled {
2128                filled_asset.as_ref()
2129            } else {
2130                empty_asset.as_ref()
2131            };
2132            render_image(path, asset_cache, &mut image, &mut cached_image);
2133            if let Some(background) = background.as_mut() {
2134                let color = if path.is_some() {
2135                    Color::NONE
2136                } else if is_filled {
2137                    color_from_array(element.style.foreground_color)
2138                } else {
2139                    color_from_array(element.style.background_color)
2140                };
2141                replace_if_changed(background, BackgroundColor(color));
2142            }
2143        }
2144        _ => {}
2145    }
2146}
2147
2148fn render_image(
2149    path: Option<&AssetPath<'static>>,
2150    asset_cache: &HudAssetCache,
2151    image: &mut Option<Mut<ImageNode>>,
2152    cached: &mut Option<Mut<HudCachedImage>>,
2153) {
2154    let handle = path.and_then(|path| asset_cache.handle(path));
2155    let next = HudCachedImage {
2156        path: path.cloned(),
2157        handle: handle.clone(),
2158    };
2159    let changed = cached.as_ref().is_none_or(|cached| **cached != next);
2160    if changed && let Some(image) = image.as_mut() {
2161        **image = handle
2162            .map(ImageNode::new)
2163            .unwrap_or_else(ImageNode::default);
2164    }
2165    if let Some(cached) = cached.as_mut() {
2166        replace_if_changed(cached, next);
2167    }
2168}
2169
2170fn hud_root_node(element: &ResolvedHudElement) -> Node {
2171    let mut node = Node {
2172        flex_direction: FlexDirection::Row,
2173        padding: UiRect {
2174            left: Val::Px(element.style.padding[0]),
2175            right: Val::Px(element.style.padding[1]),
2176            top: Val::Px(element.style.padding[2]),
2177            bottom: Val::Px(element.style.padding[3]),
2178        },
2179        row_gap: Val::Px(element.style.gap),
2180        column_gap: Val::Px(element.style.gap),
2181        ..default()
2182    };
2183    match element.layout.horizontal {
2184        HudAxisAnchor::Start | HudAxisAnchor::Center => {
2185            node.margin.left = Val::Px(element.layout.offset[0]);
2186        }
2187        HudAxisAnchor::End => node.margin.right = Val::Px(element.layout.offset[0]),
2188    }
2189    match element.layout.vertical {
2190        HudAxisAnchor::Start | HudAxisAnchor::Center => {
2191            node.margin.top = Val::Px(element.layout.offset[1]);
2192        }
2193        HudAxisAnchor::End => node.margin.bottom = Val::Px(element.layout.offset[1]),
2194    }
2195    node
2196}
2197
2198fn hud_root_transform(_layout: &ResolvedHudLayout) -> UiTransform {
2199    UiTransform::default()
2200}
2201
2202fn root_background_color(element: &ResolvedHudElement) -> Color {
2203    match element.presentation {
2204        ResolvedHudPresentation::Bar { .. } | ResolvedHudPresentation::Segments { .. } => {
2205            Color::NONE
2206        }
2207        _ => color_from_array(element.style.background_color),
2208    }
2209}
2210
2211fn color_from_array(color: [f32; 4]) -> Color {
2212    Color::linear_rgba(color[0], color[1], color[2], color[3])
2213}
2214
2215fn replace_if_changed<T: PartialEq>(current: &mut Mut<T>, next: T) {
2216    if **current != next {
2217        **current = next;
2218    }
2219}
2220
2221fn resolve_hud(
2222    registry: &HudRegistry,
2223    values: &HudValueSet,
2224    theme: &HudTheme,
2225    mut asset_available: impl FnMut(&AssetPath<'static>) -> bool,
2226    tracker: &mut HudDiagnosticTracker,
2227) -> ResolvedHud {
2228    let mut definitions: Vec<_> = registry.iter().collect();
2229    definitions.sort_by(|left, right| {
2230        left.placement
2231            .anchor
2232            .cmp(&right.placement.anchor)
2233            .then_with(|| left.order.cmp(&right.order))
2234            .then_with(|| left.id.cmp(&right.id))
2235    });
2236
2237    let active_ids: HashSet<_> = definitions
2238        .iter()
2239        .map(|definition| definition.id().clone())
2240        .collect();
2241    tracker.retain_elements(&active_ids);
2242
2243    let mut resolved = ResolvedHud::default();
2244    for definition in definitions {
2245        let (element, failure) =
2246            resolve_hud_element(definition, values, theme, &mut asset_available);
2247        if let Some(diagnostic) = tracker.transition(definition.id(), failure) {
2248            resolved.diagnostics.push(diagnostic);
2249        }
2250        resolved.elements.push(element);
2251    }
2252    resolved
2253}
2254
2255fn resolve_hud_element(
2256    definition: &HudElementDefinition,
2257    values: &HudValueSet,
2258    theme: &HudTheme,
2259    asset_available: &mut impl FnMut(&AssetPath<'static>) -> bool,
2260) -> (ResolvedHudElement, Option<HudDiagnosticKind>) {
2261    let safe_presentation = safe_presentation(definition.presentation());
2262
2263    if let Err(HudRegistryError::InvalidDefinition { reason, .. }) = validate_definition(definition)
2264    {
2265        return (
2266            ResolvedHudElement {
2267                id: definition.id().clone(),
2268                visible: false,
2269                used_fallback: false,
2270                layout: safe_default_layout(),
2271                style: safe_default_style(),
2272                presentation: safe_presentation,
2273            },
2274            Some(HudDiagnosticKind::InvalidDefinition { reason }),
2275        );
2276    }
2277
2278    let layout = resolve_layout(definition);
2279    let style = match resolve_style(theme, definition.style_override()) {
2280        Ok(style) => style,
2281        Err(field) => {
2282            return (
2283                ResolvedHudElement {
2284                    id: definition.id().clone(),
2285                    visible: false,
2286                    used_fallback: false,
2287                    layout,
2288                    style: safe_default_style(),
2289                    presentation: safe_presentation,
2290                },
2291                Some(HudDiagnosticKind::InvalidStyle { field }),
2292            );
2293        }
2294    };
2295
2296    match resolve_visibility(definition, values) {
2297        Ok(false) => {
2298            return (
2299                ResolvedHudElement {
2300                    id: definition.id().clone(),
2301                    visible: false,
2302                    used_fallback: false,
2303                    layout,
2304                    style,
2305                    presentation: safe_presentation,
2306                },
2307                None,
2308            );
2309        }
2310        Err(failure) => {
2311            return (
2312                ResolvedHudElement {
2313                    id: definition.id().clone(),
2314                    visible: false,
2315                    used_fallback: false,
2316                    layout,
2317                    style,
2318                    presentation: safe_presentation,
2319                },
2320                Some(failure),
2321            );
2322        }
2323        Ok(true) => {}
2324    }
2325
2326    match resolve_presentation(definition, values, asset_available) {
2327        PresentationResolution::Visible {
2328            presentation,
2329            used_fallback,
2330            failure,
2331        } => (
2332            ResolvedHudElement {
2333                id: definition.id().clone(),
2334                visible: true,
2335                used_fallback,
2336                layout,
2337                style,
2338                presentation,
2339            },
2340            failure,
2341        ),
2342        PresentationResolution::Hidden { failure } => (
2343            ResolvedHudElement {
2344                id: definition.id().clone(),
2345                visible: false,
2346                used_fallback: false,
2347                layout,
2348                style,
2349                presentation: safe_presentation,
2350            },
2351            Some(failure),
2352        ),
2353    }
2354}
2355
2356enum PresentationResolution {
2357    Visible {
2358        presentation: ResolvedHudPresentation,
2359        used_fallback: bool,
2360        failure: Option<HudDiagnosticKind>,
2361    },
2362    Hidden {
2363        failure: HudDiagnosticKind,
2364    },
2365}
2366
2367fn resolve_presentation(
2368    definition: &HudElementDefinition,
2369    values: &HudValueSet,
2370    asset_available: &mut impl FnMut(&AssetPath<'static>) -> bool,
2371) -> PresentationResolution {
2372    let presentation = definition.presentation();
2373    let Some(value_id) = presentation.value_id() else {
2374        return match resolve_with_value(presentation, None, asset_available) {
2375            Ok(presentation) => PresentationResolution::Visible {
2376                presentation,
2377                used_fallback: false,
2378                failure: None,
2379            },
2380            Err(failure) => PresentationResolution::Hidden { failure },
2381        };
2382    };
2383
2384    let primary = match values.get(value_id.as_str()) {
2385        Some(value) if presentation.accepts_kind(value.kind()) => {
2386            resolve_with_value(presentation, Some(value), asset_available)
2387        }
2388        Some(value) => Err(HudDiagnosticKind::MismatchedValue {
2389            value: value_id.clone(),
2390            binding: HudBindingKind::Presentation,
2391            actual: value.kind(),
2392        }),
2393        None => Err(HudDiagnosticKind::MissingValue {
2394            value: value_id.clone(),
2395            binding: HudBindingKind::Presentation,
2396        }),
2397    };
2398
2399    match primary {
2400        Ok(presentation) => PresentationResolution::Visible {
2401            presentation,
2402            used_fallback: false,
2403            failure: None,
2404        },
2405        Err(primary_failure) => {
2406            let fallback = definition.fallback_value().and_then(|fallback| {
2407                presentation
2408                    .accepts_kind(fallback.kind())
2409                    .then(|| resolve_with_value(presentation, Some(fallback), asset_available))
2410            });
2411            match fallback {
2412                Some(Ok(presentation)) => PresentationResolution::Visible {
2413                    presentation,
2414                    used_fallback: true,
2415                    failure: Some(primary_failure),
2416                },
2417                Some(Err(fallback_failure)) => PresentationResolution::Hidden {
2418                    failure: fallback_failure,
2419                },
2420                None => PresentationResolution::Hidden {
2421                    failure: primary_failure,
2422                },
2423            }
2424        }
2425    }
2426}
2427
2428fn resolve_with_value(
2429    presentation: &HudPresentation,
2430    value: Option<&HudValue>,
2431    asset_available: &mut impl FnMut(&AssetPath<'static>) -> bool,
2432) -> Result<ResolvedHudPresentation, HudDiagnosticKind> {
2433    match (presentation, value) {
2434        (
2435            HudPresentation::Text(text),
2436            Some(
2437                value @ (HudValue::Text(_)
2438                | HudValue::Scalar(_)
2439                | HudValue::Count(_)
2440                | HudValue::Bool(_)),
2441            ),
2442        ) => Ok(ResolvedHudPresentation::Text(format_text_value(
2443            text, value,
2444        ))),
2445        (HudPresentation::Bar(_), Some(HudValue::Scalar(scalar))) => {
2446            Ok(ResolvedHudPresentation::Bar {
2447                ratio: scalar.clamped_ratio(),
2448            })
2449        }
2450        (
2451            HudPresentation::Icon(HudIcon {
2452                source: HudIconSource::Asset(path),
2453            }),
2454            None,
2455        )
2456        | (
2457            HudPresentation::Icon(HudIcon {
2458                source: HudIconSource::Bound(_),
2459            }),
2460            Some(HudValue::Icon(path)),
2461        ) => {
2462            if asset_available(path) {
2463                Ok(ResolvedHudPresentation::Icon {
2464                    path: Some(path.clone().into_owned()),
2465                })
2466            } else {
2467                Err(HudDiagnosticKind::AssetUnavailable {
2468                    path: path.clone().into_owned(),
2469                })
2470            }
2471        }
2472        (HudPresentation::Segments(segments), Some(HudValue::Count(count))) => {
2473            if *count > segments.capacity() {
2474                return Err(HudDiagnosticKind::ExcessiveSegments {
2475                    count: *count,
2476                    capacity: segments.capacity(),
2477                });
2478            }
2479            for path in [segments.filled_asset_path(), segments.empty_asset_path()]
2480                .into_iter()
2481                .flatten()
2482            {
2483                if !asset_available(path) {
2484                    return Err(HudDiagnosticKind::AssetUnavailable {
2485                        path: path.clone().into_owned(),
2486                    });
2487                }
2488            }
2489            Ok(ResolvedHudPresentation::Segments {
2490                filled: *count,
2491                capacity: segments.capacity(),
2492                filled_asset: segments.filled_asset_path().cloned(),
2493                empty_asset: segments.empty_asset_path().cloned(),
2494            })
2495        }
2496        (_, value) => Err(HudDiagnosticKind::InvalidValue {
2497            binding: HudBindingKind::Presentation,
2498            actual: value.map(HudValue::kind),
2499        }),
2500    }
2501}
2502
2503fn format_text_value(text: &HudText, value: &HudValue) -> String {
2504    let value = match value {
2505        HudValue::Text(value) => value.clone(),
2506        HudValue::Scalar(scalar) => match text.precision_value() {
2507            Some(precision) => format!("{:.*}", usize::from(precision), scalar.value()),
2508            None => scalar.value().to_string(),
2509        },
2510        HudValue::Count(value) => value.to_string(),
2511        HudValue::Bool(value) => value.to_string(),
2512        HudValue::Icon(_) => String::new(),
2513    };
2514    format!("{}{}{}", text.prefix_value(), value, text.suffix_value())
2515}
2516
2517fn resolve_visibility(
2518    definition: &HudElementDefinition,
2519    values: &HudValueSet,
2520) -> Result<bool, HudDiagnosticKind> {
2521    let Some(value_id) = definition.visibility_value_id() else {
2522        return Ok(true);
2523    };
2524    match values.get(value_id.as_str()) {
2525        Some(HudValue::Bool(visible)) => Ok(*visible),
2526        Some(value) => Err(HudDiagnosticKind::MismatchedValue {
2527            value: value_id.clone(),
2528            binding: HudBindingKind::Visibility,
2529            actual: value.kind(),
2530        }),
2531        None => Err(HudDiagnosticKind::MissingValue {
2532            value: value_id.clone(),
2533            binding: HudBindingKind::Visibility,
2534        }),
2535    }
2536}
2537
2538fn resolve_layout(definition: &HudElementDefinition) -> ResolvedHudLayout {
2539    let placement = definition.placement_value();
2540    let (horizontal, vertical) = match placement.anchor {
2541        HudAnchor::TopLeft => (HudAxisAnchor::Start, HudAxisAnchor::Start),
2542        HudAnchor::TopCenter => (HudAxisAnchor::Center, HudAxisAnchor::Start),
2543        HudAnchor::TopRight => (HudAxisAnchor::End, HudAxisAnchor::Start),
2544        HudAnchor::CenterLeft => (HudAxisAnchor::Start, HudAxisAnchor::Center),
2545        HudAnchor::Center => (HudAxisAnchor::Center, HudAxisAnchor::Center),
2546        HudAnchor::CenterRight => (HudAxisAnchor::End, HudAxisAnchor::Center),
2547        HudAnchor::BottomLeft => (HudAxisAnchor::Start, HudAxisAnchor::End),
2548        HudAnchor::BottomCenter => (HudAxisAnchor::Center, HudAxisAnchor::End),
2549        HudAnchor::BottomRight => (HudAxisAnchor::End, HudAxisAnchor::End),
2550    };
2551    ResolvedHudLayout {
2552        anchor: placement.anchor,
2553        horizontal,
2554        vertical,
2555        offset: placement.offset,
2556        stack_direction: placement.stack_direction,
2557        order: definition.order_value(),
2558    }
2559}
2560
2561fn safe_default_layout() -> ResolvedHudLayout {
2562    ResolvedHudLayout {
2563        anchor: HudAnchor::TopLeft,
2564        horizontal: HudAxisAnchor::Start,
2565        vertical: HudAxisAnchor::Start,
2566        offset: HudPlacement::default().offset,
2567        stack_direction: HudStackDirection::Vertical,
2568        order: 0,
2569    }
2570}
2571
2572fn resolve_style(
2573    theme: &HudTheme,
2574    style: &HudStyleOverride,
2575) -> Result<ResolvedHudStyle, &'static str> {
2576    let resolved = ResolvedHudStyle {
2577        font_size: style.font_size.unwrap_or(theme.font_size),
2578        text_color: style.text_color.unwrap_or(theme.text_color),
2579        background_color: style.background_color.unwrap_or(theme.background_color),
2580        foreground_color: style.foreground_color.unwrap_or(theme.foreground_color),
2581        padding: style.padding.unwrap_or(theme.padding),
2582        gap: style.gap.unwrap_or(theme.gap),
2583        bar_size: style.bar_size.unwrap_or(theme.bar_size),
2584        icon_size: style.icon_size.unwrap_or(theme.icon_size),
2585        segment_size: style.segment_size.unwrap_or(theme.segment_size),
2586        z_index: style.z_index.unwrap_or(theme.z_index),
2587    };
2588    validate_resolved_style(&resolved)?;
2589    Ok(resolved)
2590}
2591
2592fn validate_resolved_style(style: &ResolvedHudStyle) -> Result<(), &'static str> {
2593    for (field, values) in [
2594        ("padding", style.padding.as_slice()),
2595        ("bar_size", style.bar_size.as_slice()),
2596        ("icon_size", style.icon_size.as_slice()),
2597        ("segment_size", style.segment_size.as_slice()),
2598    ] {
2599        if values
2600            .iter()
2601            .any(|value| !value.is_finite() || *value < 0.0)
2602        {
2603            return Err(field);
2604        }
2605    }
2606    for (field, value) in [("font_size", style.font_size), ("gap", style.gap)] {
2607        if !value.is_finite() || value < 0.0 {
2608            return Err(field);
2609        }
2610    }
2611    for (field, values) in [
2612        ("text_color", style.text_color.as_slice()),
2613        ("background_color", style.background_color.as_slice()),
2614        ("foreground_color", style.foreground_color.as_slice()),
2615    ] {
2616        if values.iter().any(|value| !value.is_finite()) {
2617            return Err(field);
2618        }
2619    }
2620    Ok(())
2621}
2622
2623fn safe_default_style() -> ResolvedHudStyle {
2624    let theme = HudTheme::default();
2625    ResolvedHudStyle {
2626        font_size: theme.font_size,
2627        text_color: theme.text_color,
2628        background_color: theme.background_color,
2629        foreground_color: theme.foreground_color,
2630        padding: theme.padding,
2631        gap: theme.gap,
2632        bar_size: theme.bar_size,
2633        icon_size: theme.icon_size,
2634        segment_size: theme.segment_size,
2635        z_index: theme.z_index,
2636    }
2637}
2638
2639fn safe_presentation(presentation: &HudPresentation) -> ResolvedHudPresentation {
2640    match presentation {
2641        HudPresentation::Text(_) => ResolvedHudPresentation::Text(String::new()),
2642        HudPresentation::Bar(_) => ResolvedHudPresentation::Bar { ratio: 0.0 },
2643        HudPresentation::Icon(_) => ResolvedHudPresentation::Icon { path: None },
2644        HudPresentation::Segments(segments) => ResolvedHudPresentation::Segments {
2645            filled: 0,
2646            capacity: segments.capacity().min(MAX_HUD_SEGMENTS),
2647            filled_asset: None,
2648            empty_asset: None,
2649        },
2650    }
2651}
2652
2653fn validate_definition(definition: &HudElementDefinition) -> Result<(), HudRegistryError> {
2654    let invalid = |reason| HudRegistryError::InvalidDefinition {
2655        id: definition.id().clone(),
2656        reason,
2657    };
2658
2659    if !definition.placement.offset.into_iter().all(f32::is_finite) {
2660        return Err(invalid(HudDefinitionError::NonFinitePlacement));
2661    }
2662
2663    if let HudPresentation::Segments(segments) = definition.presentation() {
2664        if !(1..=MAX_HUD_SEGMENTS).contains(&segments.capacity()) {
2665            return Err(invalid(HudDefinitionError::InvalidSegmentCapacity {
2666                capacity: segments.capacity(),
2667                maximum: MAX_HUD_SEGMENTS,
2668            }));
2669        }
2670    }
2671
2672    if let Some(fallback) = definition.fallback_value() {
2673        if matches!(
2674            definition.presentation(),
2675            HudPresentation::Icon(HudIcon {
2676                source: HudIconSource::Asset(_),
2677            })
2678        ) {
2679            return Err(invalid(HudDefinitionError::StaticIconFallback));
2680        }
2681        if !definition.presentation().accepts_kind(fallback.kind()) {
2682            return Err(invalid(HudDefinitionError::InvalidFallbackKind {
2683                expected: expected_kinds(definition.presentation()),
2684                actual: fallback.kind(),
2685            }));
2686        }
2687    }
2688
2689    validate_style(&definition.style).map_err(invalid)
2690}
2691
2692fn expected_kinds(presentation: &HudPresentation) -> &'static str {
2693    match presentation {
2694        HudPresentation::Text(_) => "text, scalar, count, or bool",
2695        HudPresentation::Bar(_) => "scalar",
2696        HudPresentation::Icon(_) => "icon",
2697        HudPresentation::Segments(_) => "count",
2698    }
2699}
2700
2701fn validate_style(style: &HudStyleOverride) -> Result<(), HudDefinitionError> {
2702    validate_non_negative_scalar("font_size", style.font_size)?;
2703    validate_non_negative_scalar("gap", style.gap)?;
2704    validate_non_negative_array(
2705        "padding",
2706        style.padding.as_ref().map(|value| value.as_slice()),
2707    )?;
2708    validate_non_negative_array(
2709        "bar_size",
2710        style.bar_size.as_ref().map(|value| value.as_slice()),
2711    )?;
2712    validate_non_negative_array(
2713        "icon_size",
2714        style.icon_size.as_ref().map(|value| value.as_slice()),
2715    )?;
2716    validate_non_negative_array(
2717        "segment_size",
2718        style.segment_size.as_ref().map(|value| value.as_slice()),
2719    )?;
2720    validate_finite_array(
2721        "text_color",
2722        style.text_color.as_ref().map(|value| value.as_slice()),
2723    )?;
2724    validate_finite_array(
2725        "background_color",
2726        style
2727            .background_color
2728            .as_ref()
2729            .map(|value| value.as_slice()),
2730    )?;
2731    validate_finite_array(
2732        "foreground_color",
2733        style
2734            .foreground_color
2735            .as_ref()
2736            .map(|value| value.as_slice()),
2737    )?;
2738    Ok(())
2739}
2740
2741fn validate_non_negative_scalar(
2742    field: &'static str,
2743    value: Option<f32>,
2744) -> Result<(), HudDefinitionError> {
2745    if value.is_some_and(|value| !value.is_finite() || value < 0.0) {
2746        return Err(HudDefinitionError::InvalidStyleValue { field });
2747    }
2748    Ok(())
2749}
2750
2751fn validate_non_negative_array(
2752    field: &'static str,
2753    values: Option<&[f32]>,
2754) -> Result<(), HudDefinitionError> {
2755    if values.is_some_and(|values| {
2756        values
2757            .iter()
2758            .any(|value| !value.is_finite() || *value < 0.0)
2759    }) {
2760        return Err(HudDefinitionError::InvalidStyleValue { field });
2761    }
2762    Ok(())
2763}
2764
2765fn validate_finite_array(
2766    field: &'static str,
2767    values: Option<&[f32]>,
2768) -> Result<(), HudDefinitionError> {
2769    if values.is_some_and(|values| values.iter().any(|value| !value.is_finite())) {
2770        return Err(HudDefinitionError::InvalidStyleValue { field });
2771    }
2772    Ok(())
2773}
2774
2775fn bump_revision(revision: &mut u64) {
2776    *revision = revision.saturating_add(1);
2777}
2778
2779#[cfg(test)]
2780mod tests {
2781    use bevy::ecs::message::{MessageReader, MessageWriter};
2782
2783    use super::*;
2784
2785    pub(super) fn text_definition(id: &str, value: &str) -> HudElementDefinition {
2786        HudElementDefinition::new(id, HudPresentation::Text(HudText::new(value)))
2787    }
2788
2789    #[test]
2790    fn ids_keep_string_ergonomics_and_ordering() {
2791        let id = HudElementId::new("status");
2792        assert_eq!(id.as_str(), "status");
2793        assert_eq!(id.to_string(), "status");
2794        assert_eq!(HudValueId::from(String::from("value")).as_ref(), "value");
2795        assert!(HudElementId::from("a") < HudElementId::from("b"));
2796    }
2797
2798    #[test]
2799    fn scalar_rejects_non_finite_and_degenerate_ranges() {
2800        assert_eq!(
2801            HudScalar::new(f32::NAN, 0.0, 1.0),
2802            Err(HudValueError::NonFinite {
2803                field: HudScalarField::Value
2804            })
2805        );
2806        assert_eq!(
2807            HudScalar::new(0.0, f32::NEG_INFINITY, 1.0),
2808            Err(HudValueError::NonFinite {
2809                field: HudScalarField::Min
2810            })
2811        );
2812        assert_eq!(
2813            HudScalar::new(0.0, 0.0, f32::INFINITY),
2814            Err(HudValueError::NonFinite {
2815                field: HudScalarField::Max
2816            })
2817        );
2818        assert_eq!(
2819            HudScalar::new(0.0, 1.0, 1.0),
2820            Err(HudValueError::InvalidRange { min: 1.0, max: 1.0 })
2821        );
2822
2823        let error = serde_json::from_str::<HudScalar>(r#"{"value":0.0,"min":1.0,"max":1.0}"#)
2824            .expect_err("deserialization must preserve the scalar invariant");
2825        assert!(error.to_string().contains("nonzero span"));
2826    }
2827
2828    #[test]
2829    fn scalar_normalizes_reversed_bounds_and_clamps_ratio() {
2830        let scalar = HudScalar::new(15.0, 10.0, 0.0).expect("range should normalize");
2831        assert_eq!((scalar.min(), scalar.max()), (0.0, 10.0));
2832        assert_eq!(scalar.value(), 15.0);
2833        assert_eq!(scalar.clamped_ratio(), 1.0);
2834
2835        let deserialized =
2836            serde_json::from_str::<HudScalar>(r#"{"value":-5.0,"min":0.0,"max":-10.0}"#)
2837                .expect("valid reversed bounds should normalize during deserialization");
2838        assert_eq!((deserialized.min(), deserialized.max()), (-10.0, 0.0));
2839        assert_eq!(deserialized.clamped_ratio(), 0.5);
2840
2841        let huge = HudScalar::new(0.0, f32::MIN, f32::MAX).expect("finite range is valid");
2842        assert!(huge.clamped_ratio().is_finite());
2843        assert_eq!(huge.clamped_ratio(), 0.5);
2844    }
2845
2846    #[test]
2847    fn presentation_builders_preserve_owned_author_data() {
2848        let text = HudText::new("temperature")
2849            .prefix("T: ")
2850            .suffix(" C")
2851            .precision(1);
2852        assert_eq!(text.value_id().as_str(), "temperature");
2853        assert_eq!(text.prefix_value(), "T: ");
2854        assert_eq!(text.suffix_value(), " C");
2855        assert_eq!(text.precision_value(), Some(1));
2856
2857        let path = String::from("textures/hud/charge.png");
2858        let icon = HudIcon::asset(path);
2859        assert!(
2860            matches!(icon.source(), HudIconSource::Asset(asset) if asset.to_string() == "textures/hud/charge.png")
2861        );
2862
2863        let icon_value = HudValue::icon(String::from("textures/hud/dynamic.png"));
2864        let serialized = serde_json::to_string(&icon_value).expect("icon value should serialize");
2865        assert_eq!(
2866            serde_json::from_str::<HudValue>(&serialized).expect("icon value should deserialize"),
2867            icon_value
2868        );
2869
2870        let segments = HudSegments::new("charges", 8)
2871            .filled_asset(String::from("textures/hud/full.png"))
2872            .empty_asset(String::from("textures/hud/empty.png"));
2873        assert_eq!(segments.capacity(), 8);
2874        assert!(segments.filled_asset_path().is_some());
2875        assert!(segments.empty_asset_path().is_some());
2876    }
2877
2878    #[test]
2879    fn registry_rejects_invalid_definition_kinds_and_bounds() {
2880        let mut registry = HudRegistry::new();
2881        let invalid_fallback =
2882            HudElementDefinition::new("bar", HudPresentation::Bar(HudBar::new("level")))
2883                .fallback(3_u32);
2884        assert!(matches!(
2885            registry.register(invalid_fallback),
2886            Err(HudRegistryError::InvalidDefinition {
2887                reason: HudDefinitionError::InvalidFallbackKind { .. },
2888                ..
2889            })
2890        ));
2891
2892        let excessive = HudElementDefinition::new(
2893            "segments",
2894            HudPresentation::Segments(HudSegments::new("count", MAX_HUD_SEGMENTS + 1)),
2895        );
2896        assert!(matches!(
2897            registry.register(excessive),
2898            Err(HudRegistryError::InvalidDefinition {
2899                reason: HudDefinitionError::InvalidSegmentCapacity { .. },
2900                ..
2901            })
2902        ));
2903
2904        let zero_capacity = HudElementDefinition::new(
2905            "zero_segments",
2906            HudPresentation::Segments(HudSegments::new("count", 0)),
2907        );
2908        assert!(matches!(
2909            registry.register(zero_capacity),
2910            Err(HudRegistryError::InvalidDefinition {
2911                reason: HudDefinitionError::InvalidSegmentCapacity { capacity: 0, .. },
2912                ..
2913            })
2914        ));
2915
2916        let invalid_placement = text_definition("placement", "value")
2917            .placement(HudPlacement::default().offset(f32::NAN, 0.0));
2918        assert!(matches!(
2919            registry.register(invalid_placement),
2920            Err(HudRegistryError::InvalidDefinition {
2921                reason: HudDefinitionError::NonFinitePlacement,
2922                ..
2923            })
2924        ));
2925
2926        for (id, style) in [
2927            (
2928                "negative_size",
2929                HudStyleOverride {
2930                    icon_size: Some([-1.0, 1.0]),
2931                    ..default()
2932                },
2933            ),
2934            (
2935                "infinite_gap",
2936                HudStyleOverride {
2937                    gap: Some(f32::INFINITY),
2938                    ..default()
2939                },
2940            ),
2941            (
2942                "nan_color",
2943                HudStyleOverride {
2944                    text_color: Some([1.0, 1.0, f32::NAN, 1.0]),
2945                    ..default()
2946                },
2947            ),
2948        ] {
2949            assert!(matches!(
2950                registry.register(text_definition(id, "value").style(style)),
2951                Err(HudRegistryError::InvalidDefinition {
2952                    reason: HudDefinitionError::InvalidStyleValue { .. },
2953                    ..
2954                })
2955            ));
2956        }
2957        assert_eq!(registry.revision(), 0);
2958    }
2959
2960    #[test]
2961    fn registry_duplicate_error_precedes_revalidation_and_invalid_replace_is_atomic() {
2962        let mut registry = HudRegistry::new();
2963        registry
2964            .register(text_definition("status", "status_text"))
2965            .expect("initial definition registers");
2966
2967        let invalid_duplicate = HudElementDefinition::new(
2968            "status",
2969            HudPresentation::Segments(HudSegments::new("count", 0)),
2970        );
2971        assert!(matches!(
2972            registry.register(invalid_duplicate.clone()),
2973            Err(HudRegistryError::DuplicateId { .. })
2974        ));
2975        assert_eq!(registry.revision(), 1);
2976
2977        assert!(matches!(
2978            registry.insert_or_replace(invalid_duplicate),
2979            Err(HudRegistryError::InvalidDefinition { .. })
2980        ));
2981        assert!(matches!(
2982            registry.require("status").unwrap().presentation(),
2983            HudPresentation::Text(_)
2984        ));
2985        assert_eq!(registry.revision(), 1);
2986    }
2987
2988    #[test]
2989    fn registry_tracks_only_real_definition_changes() {
2990        let mut registry = HudRegistry::new();
2991        let first = text_definition("status", "status_text");
2992        registry
2993            .register(first.clone())
2994            .expect("definition registers");
2995        assert_eq!(registry.revision(), 1);
2996        assert!(matches!(
2997            registry.register(first.clone()),
2998            Err(HudRegistryError::DuplicateId { .. })
2999        ));
3000        assert_eq!(registry.revision(), 1);
3001
3002        assert_eq!(registry.insert_or_replace(first).unwrap(), None);
3003        assert_eq!(registry.revision(), 1);
3004        let replacement = text_definition("status", "other").order(7);
3005        assert!(registry.insert_or_replace(replacement).unwrap().is_some());
3006        assert_eq!(registry.require("status").unwrap().order_value(), 7);
3007        assert_eq!(registry.revision(), 2);
3008
3009        registry.remove("status").expect("definition exists");
3010        assert_eq!(registry.revision(), 3);
3011        assert!(matches!(
3012            registry.remove("status"),
3013            Err(HudRegistryError::MissingId { .. })
3014        ));
3015        assert_eq!(registry.revision(), 3);
3016    }
3017
3018    #[test]
3019    fn registry_snapshot_is_identity_ordered_and_serializable() {
3020        let mut registry = HudRegistry::new();
3021        registry
3022            .register(text_definition("zeta", "z"))
3023            .expect("zeta registers");
3024        registry
3025            .register(text_definition("alpha", "a"))
3026            .expect("alpha registers");
3027        let snapshot = registry.snapshot();
3028        assert_eq!(snapshot[0].id.as_str(), "alpha");
3029        assert_eq!(snapshot[1].id.as_str(), "zeta");
3030        let serialized =
3031            serde_json::to_string(&snapshot).expect("element snapshots should serialize");
3032
3033        let mut equivalent = HudRegistry::new();
3034        equivalent
3035            .register(text_definition("alpha", "a"))
3036            .expect("alpha registers");
3037        equivalent
3038            .register(text_definition("zeta", "z"))
3039            .expect("zeta registers");
3040        assert_eq!(
3041            serialized,
3042            serde_json::to_string(&equivalent.snapshot()).unwrap()
3043        );
3044    }
3045
3046    #[test]
3047    fn value_set_tracks_real_changes_removal_and_ordered_snapshots() {
3048        let mut values = HudValueSet::new();
3049        assert_eq!(values.insert_or_replace("zeta", 2_u32), None);
3050        assert_eq!(values.revision(), 1);
3051        assert_eq!(values.insert_or_replace("zeta", 2_u32), None);
3052        assert_eq!(values.revision(), 1);
3053        assert_eq!(values.insert_or_replace("alpha", "ready"), None);
3054        assert_eq!(values.revision(), 2);
3055        assert_eq!(values.get("zeta"), Some(&HudValue::Count(2)));
3056
3057        let snapshot = values.snapshot();
3058        assert_eq!(snapshot[0].id.as_str(), "alpha");
3059        assert_eq!(snapshot[1].id.as_str(), "zeta");
3060        let serialized =
3061            serde_json::to_string(&snapshot).expect("value snapshots should serialize");
3062
3063        let mut equivalent = HudValueSet::new();
3064        equivalent.insert_or_replace("alpha", "ready");
3065        equivalent.insert_or_replace("zeta", 2_u32);
3066        assert_eq!(
3067            serialized,
3068            serde_json::to_string(&equivalent.snapshot()).unwrap()
3069        );
3070
3071        assert_eq!(values.remove("missing"), None);
3072        assert_eq!(values.revision(), 2);
3073        assert_eq!(values.remove("zeta"), Some(HudValue::Count(2)));
3074        assert_eq!(values.revision(), 3);
3075    }
3076
3077    #[derive(Resource, Default)]
3078    struct ObservedChanges(Vec<HudValueChanged>);
3079
3080    fn publish_values(
3081        mut values: ResMut<HudValueSet>,
3082        mut changed: MessageWriter<HudValueChanged>,
3083    ) {
3084        assert!(set_hud_value("status", "ready", &mut values, &mut changed));
3085        assert!(!set_hud_value("status", "ready", &mut values, &mut changed));
3086        assert!(set_hud_value("status", "active", &mut values, &mut changed));
3087        assert!(remove_hud_value("status", &mut values, &mut changed));
3088        assert!(!remove_hud_value("status", &mut values, &mut changed));
3089    }
3090
3091    fn record_changes(
3092        mut reader: MessageReader<HudValueChanged>,
3093        mut observed: ResMut<ObservedChanges>,
3094    ) {
3095        observed.0.extend(reader.read().cloned());
3096    }
3097
3098    #[test]
3099    fn publication_helpers_emit_only_real_change_messages() {
3100        let mut app = App::new();
3101        app.add_plugins(MinimalPlugins);
3102        app.init_resource::<HudValueSet>();
3103        app.init_resource::<ObservedChanges>();
3104        app.add_message::<HudValueChanged>();
3105        app.add_systems(Update, (publish_values, record_changes).chain());
3106
3107        app.update();
3108
3109        let observed = app.world().resource::<ObservedChanges>();
3110        assert_eq!(observed.0.len(), 3);
3111        assert_eq!(observed.0[0].previous, None);
3112        assert_eq!(observed.0[0].current, Some(HudValue::Text("ready".into())));
3113        assert_eq!(observed.0[1].previous, Some(HudValue::Text("ready".into())));
3114        assert_eq!(observed.0[2].current, None);
3115    }
3116
3117    #[test]
3118    fn resolution_formats_supported_text_values_without_coercing_kinds() {
3119        let scalar = HudScalar::new(12.345, 0.0, 20.0).unwrap();
3120        let text = HudText::new("value").prefix("<").suffix(">").precision(2);
3121        assert_eq!(
3122            format_text_value(&text, &HudValue::Scalar(scalar)),
3123            "<12.35>"
3124        );
3125        assert_eq!(format_text_value(&text, &HudValue::Count(7)), "<7>");
3126        assert_eq!(format_text_value(&text, &HudValue::Bool(true)), "<true>");
3127        assert_eq!(
3128            format_text_value(&text, &HudValue::Text("ready".into())),
3129            "<ready>"
3130        );
3131        assert_eq!(
3132            resolve_with_value(
3133                &HudPresentation::Text(text),
3134                Some(&HudValue::icon("textures/not-text.png")),
3135                &mut |_| true,
3136            ),
3137            Err(HudDiagnosticKind::InvalidValue {
3138                binding: HudBindingKind::Presentation,
3139                actual: Some(HudValueKind::Icon),
3140            })
3141        );
3142    }
3143
3144    #[test]
3145    fn resolution_handles_all_presentations_and_bounds_numeric_output() {
3146        let mut registry = HudRegistry::new();
3147        for definition in [
3148            text_definition("text", "label"),
3149            HudElementDefinition::new("bar", HudPresentation::Bar(HudBar::new("ratio"))),
3150            HudElementDefinition::new(
3151                "icon",
3152                HudPresentation::Icon(HudIcon::asset("textures/icon.png")),
3153            ),
3154            HudElementDefinition::new(
3155                "segments",
3156                HudPresentation::Segments(HudSegments::new("count", 5)),
3157            ),
3158        ] {
3159            registry.register(definition).unwrap();
3160        }
3161        let mut values = HudValueSet::new();
3162        values.insert_or_replace("label", "ready");
3163        values.insert_or_replace("ratio", HudScalar::new(15.0, 0.0, 10.0).unwrap());
3164        values.insert_or_replace("count", 3_u32);
3165
3166        let mut tracker = HudDiagnosticTracker::default();
3167        let resolved = resolve_hud(
3168            &registry,
3169            &values,
3170            &HudTheme::default(),
3171            |_| true,
3172            &mut tracker,
3173        );
3174        assert_eq!(resolved.diagnostics, Vec::<HudDiagnostic>::new());
3175        assert_eq!(resolved.elements.len(), 4);
3176        assert!(resolved.elements.iter().all(|element| element.visible));
3177        assert!(resolved.elements.iter().any(|element| {
3178            matches!(element.presentation, ResolvedHudPresentation::Text(ref value) if value == "ready")
3179        }));
3180        assert!(resolved.elements.iter().any(|element| {
3181            matches!(element.presentation, ResolvedHudPresentation::Bar { ratio } if ratio == 1.0)
3182        }));
3183        assert!(resolved.elements.iter().any(|element| {
3184            matches!(
3185                element.presentation,
3186                ResolvedHudPresentation::Segments {
3187                    filled: 3,
3188                    capacity: 5,
3189                    ..
3190                }
3191            )
3192        }));
3193        assert!(resolved.elements.iter().any(|element| {
3194            matches!(element.presentation, ResolvedHudPresentation::Icon { path: Some(ref path) } if path.to_string() == "textures/icon.png")
3195        }));
3196    }
3197
3198    #[test]
3199    fn resolution_merges_style_maps_anchors_and_orders_ties_by_id() {
3200        let mut registry = HudRegistry::new();
3201        for id in ["zeta", "alpha"] {
3202            registry
3203                .register(
3204                    text_definition(id, id)
3205                        .order(4)
3206                        .placement(
3207                            HudPlacement::new(HudAnchor::BottomRight)
3208                                .offset(12.0, 8.0)
3209                                .stack_direction(HudStackDirection::Horizontal),
3210                        )
3211                        .style(HudStyleOverride {
3212                            font_size: Some(24.0),
3213                            gap: Some(3.0),
3214                            ..default()
3215                        }),
3216                )
3217                .unwrap();
3218        }
3219        let mut values = HudValueSet::new();
3220        values.insert_or_replace("zeta", "z");
3221        values.insert_or_replace("alpha", "a");
3222
3223        let mut tracker = HudDiagnosticTracker::default();
3224        let resolved = resolve_hud(
3225            &registry,
3226            &values,
3227            &HudTheme::default(),
3228            |_| true,
3229            &mut tracker,
3230        );
3231        assert_eq!(resolved.elements[0].id.as_str(), "alpha");
3232        assert_eq!(resolved.elements[1].id.as_str(), "zeta");
3233        let first = &resolved.elements[0];
3234        assert_eq!(first.layout.horizontal, HudAxisAnchor::End);
3235        assert_eq!(first.layout.vertical, HudAxisAnchor::End);
3236        assert_eq!(first.layout.offset, [12.0, 8.0]);
3237        assert_eq!(first.layout.stack_direction, HudStackDirection::Horizontal);
3238        assert_eq!(first.style.font_size, 24.0);
3239        assert_eq!(first.style.gap, 3.0);
3240        assert_eq!(first.style.bar_size, HudTheme::default().bar_size);
3241    }
3242
3243    #[test]
3244    fn every_anchor_and_style_field_resolves_from_author_configuration() {
3245        let anchors = [
3246            (
3247                HudAnchor::TopLeft,
3248                HudAxisAnchor::Start,
3249                HudAxisAnchor::Start,
3250            ),
3251            (
3252                HudAnchor::TopCenter,
3253                HudAxisAnchor::Center,
3254                HudAxisAnchor::Start,
3255            ),
3256            (
3257                HudAnchor::TopRight,
3258                HudAxisAnchor::End,
3259                HudAxisAnchor::Start,
3260            ),
3261            (
3262                HudAnchor::CenterLeft,
3263                HudAxisAnchor::Start,
3264                HudAxisAnchor::Center,
3265            ),
3266            (
3267                HudAnchor::Center,
3268                HudAxisAnchor::Center,
3269                HudAxisAnchor::Center,
3270            ),
3271            (
3272                HudAnchor::CenterRight,
3273                HudAxisAnchor::End,
3274                HudAxisAnchor::Center,
3275            ),
3276            (
3277                HudAnchor::BottomLeft,
3278                HudAxisAnchor::Start,
3279                HudAxisAnchor::End,
3280            ),
3281            (
3282                HudAnchor::BottomCenter,
3283                HudAxisAnchor::Center,
3284                HudAxisAnchor::End,
3285            ),
3286            (
3287                HudAnchor::BottomRight,
3288                HudAxisAnchor::End,
3289                HudAxisAnchor::End,
3290            ),
3291        ];
3292        let theme = HudTheme {
3293            font_size: 13.0,
3294            text_color: [0.1, 0.2, 0.3, 0.4],
3295            background_color: [0.2, 0.3, 0.4, 0.5],
3296            foreground_color: [0.3, 0.4, 0.5, 0.6],
3297            padding: [1.0, 2.0, 3.0, 4.0],
3298            gap: 5.0,
3299            bar_size: [101.0, 11.0],
3300            icon_size: [21.0, 22.0],
3301            segment_size: [8.0, 9.0],
3302            z_index: 41,
3303        };
3304        let overrides = HudStyleOverride {
3305            font_size: Some(23.0),
3306            text_color: Some([0.9, 0.8, 0.7, 0.6]),
3307            background_color: Some([0.8, 0.7, 0.6, 0.5]),
3308            foreground_color: Some([0.7, 0.6, 0.5, 0.4]),
3309            padding: Some([9.0, 8.0, 7.0, 6.0]),
3310            gap: Some(4.0),
3311            bar_size: Some([202.0, 22.0]),
3312            icon_size: Some([42.0, 44.0]),
3313            segment_size: Some([16.0, 18.0]),
3314            z_index: Some(82),
3315        };
3316
3317        for (index, (anchor, horizontal, vertical)) in anchors.into_iter().enumerate() {
3318            let definition = text_definition(&format!("anchor-{index}"), "value")
3319                .placement(
3320                    HudPlacement::new(anchor)
3321                        .offset(index as f32, -(index as f32))
3322                        .stack_direction(HudStackDirection::Horizontal),
3323                )
3324                .order(index as i32)
3325                .style(overrides.clone());
3326            let layout = resolve_layout(&definition);
3327            assert_eq!(layout.anchor, anchor);
3328            assert_eq!(layout.horizontal, horizontal);
3329            assert_eq!(layout.vertical, vertical);
3330            assert_eq!(layout.offset, [index as f32, -(index as f32)]);
3331            assert_eq!(layout.stack_direction, HudStackDirection::Horizontal);
3332            assert_eq!(layout.order, index as i32);
3333
3334            let style = resolve_style(&theme, definition.style_override()).unwrap();
3335            assert_eq!(style.font_size, 23.0);
3336            assert_eq!(style.text_color, [0.9, 0.8, 0.7, 0.6]);
3337            assert_eq!(style.background_color, [0.8, 0.7, 0.6, 0.5]);
3338            assert_eq!(style.foreground_color, [0.7, 0.6, 0.5, 0.4]);
3339            assert_eq!(style.padding, [9.0, 8.0, 7.0, 6.0]);
3340            assert_eq!(style.gap, 4.0);
3341            assert_eq!(style.bar_size, [202.0, 22.0]);
3342            assert_eq!(style.icon_size, [42.0, 44.0]);
3343            assert_eq!(style.segment_size, [16.0, 18.0]);
3344            assert_eq!(style.z_index, 82);
3345        }
3346
3347        let defaults = resolve_style(&theme, &HudStyleOverride::default()).unwrap();
3348        assert_eq!(defaults.font_size, theme.font_size);
3349        assert_eq!(defaults.text_color, theme.text_color);
3350        assert_eq!(defaults.background_color, theme.background_color);
3351        assert_eq!(defaults.foreground_color, theme.foreground_color);
3352        assert_eq!(defaults.padding, theme.padding);
3353        assert_eq!(defaults.gap, theme.gap);
3354        assert_eq!(defaults.bar_size, theme.bar_size);
3355        assert_eq!(defaults.icon_size, theme.icon_size);
3356        assert_eq!(defaults.segment_size, theme.segment_size);
3357        assert_eq!(defaults.z_index, theme.z_index);
3358    }
3359
3360    #[test]
3361    fn missing_and_mismatched_values_use_only_compatible_fallbacks() {
3362        let fallback =
3363            HudElementDefinition::new("fallback", HudPresentation::Bar(HudBar::new("missing")))
3364                .fallback(HudScalar::new(1.0, 0.0, 4.0).unwrap());
3365        let hidden =
3366            HudElementDefinition::new("hidden", HudPresentation::Bar(HudBar::new("wrong")));
3367        let mut registry = HudRegistry::new();
3368        registry.register(fallback).unwrap();
3369        registry.register(hidden).unwrap();
3370        let mut values = HudValueSet::new();
3371        values.insert_or_replace("wrong", "not a scalar");
3372
3373        let mut tracker = HudDiagnosticTracker::default();
3374        let resolved = resolve_hud(
3375            &registry,
3376            &values,
3377            &HudTheme::default(),
3378            |_| true,
3379            &mut tracker,
3380        );
3381        let fallback = resolved
3382            .elements
3383            .iter()
3384            .find(|element| element.id.as_str() == "fallback")
3385            .unwrap();
3386        assert!(fallback.visible);
3387        assert!(fallback.used_fallback);
3388        assert!(matches!(
3389            fallback.presentation,
3390            ResolvedHudPresentation::Bar { ratio } if ratio == 0.25
3391        ));
3392        let hidden = resolved
3393            .elements
3394            .iter()
3395            .find(|element| element.id.as_str() == "hidden")
3396            .unwrap();
3397        assert!(!hidden.visible);
3398        assert!(!hidden.used_fallback);
3399        assert_eq!(resolved.diagnostics.len(), 2);
3400        assert!(
3401            resolved.diagnostics.iter().any(|diagnostic| matches!(
3402                diagnostic.kind,
3403                HudDiagnosticKind::MissingValue { .. }
3404            ))
3405        );
3406        assert!(resolved.diagnostics.iter().any(|diagnostic| matches!(
3407            diagnostic.kind,
3408            HudDiagnosticKind::MismatchedValue { .. }
3409        )));
3410    }
3411
3412    #[test]
3413    fn excessive_segments_are_never_clamped_and_may_use_a_bounded_fallback() {
3414        let definition = HudElementDefinition::new(
3415            "charges",
3416            HudPresentation::Segments(HudSegments::new("count", 4)),
3417        )
3418        .fallback(2_u32);
3419        let mut registry = HudRegistry::new();
3420        registry.register(definition).unwrap();
3421        let mut values = HudValueSet::new();
3422        values.insert_or_replace("count", 99_u32);
3423
3424        let mut tracker = HudDiagnosticTracker::default();
3425        let resolved = resolve_hud(
3426            &registry,
3427            &values,
3428            &HudTheme::default(),
3429            |_| true,
3430            &mut tracker,
3431        );
3432        assert!(resolved.elements[0].visible);
3433        assert!(resolved.elements[0].used_fallback);
3434        assert!(matches!(
3435            resolved.elements[0].presentation,
3436            ResolvedHudPresentation::Segments {
3437                filled: 2,
3438                capacity: 4,
3439                ..
3440            }
3441        ));
3442        assert!(matches!(
3443            resolved.diagnostics[0].kind,
3444            HudDiagnosticKind::ExcessiveSegments {
3445                count: 99,
3446                capacity: 4
3447            }
3448        ));
3449    }
3450
3451    #[test]
3452    fn visibility_and_asset_failures_resolve_to_hidden_or_available_fallback_state() {
3453        let conditional = text_definition("conditional", "label").visible_when("show");
3454        let icon =
3455            HudElementDefinition::new("icon", HudPresentation::Icon(HudIcon::bound("icon_path")))
3456                .fallback(HudValue::icon("textures/fallback.png"));
3457        let mut registry = HudRegistry::new();
3458        registry.register(conditional).unwrap();
3459        registry.register(icon).unwrap();
3460        let mut values = HudValueSet::new();
3461        values.insert_or_replace("label", "ready");
3462        values.insert_or_replace("show", false);
3463        values.insert_or_replace("icon_path", HudValue::icon("textures/missing.png"));
3464
3465        let mut tracker = HudDiagnosticTracker::default();
3466        let resolved = resolve_hud(
3467            &registry,
3468            &values,
3469            &HudTheme::default(),
3470            |path| path.to_string() == "textures/fallback.png",
3471            &mut tracker,
3472        );
3473        let conditional = resolved
3474            .elements
3475            .iter()
3476            .find(|element| element.id.as_str() == "conditional")
3477            .unwrap();
3478        assert!(!conditional.visible);
3479        let icon = resolved
3480            .elements
3481            .iter()
3482            .find(|element| element.id.as_str() == "icon")
3483            .unwrap();
3484        assert!(icon.visible);
3485        assert!(icon.used_fallback);
3486        assert!(matches!(
3487            icon.presentation,
3488            ResolvedHudPresentation::Icon { path: Some(ref path) }
3489                if path.to_string() == "textures/fallback.png"
3490        ));
3491        assert_eq!(resolved.diagnostics.len(), 1);
3492        assert!(matches!(
3493            resolved.diagnostics[0].kind,
3494            HudDiagnosticKind::AssetUnavailable { .. }
3495        ));
3496
3497        let unavailable_fallback = resolve_hud(
3498            &registry,
3499            &values,
3500            &HudTheme::default(),
3501            |_| false,
3502            &mut tracker,
3503        );
3504        let icon = unavailable_fallback
3505            .elements
3506            .iter()
3507            .find(|element| element.id.as_str() == "icon")
3508            .unwrap();
3509        assert!(!icon.visible);
3510        assert!(!icon.used_fallback);
3511        assert!(matches!(
3512            unavailable_fallback.diagnostics[0].kind,
3513            HudDiagnosticKind::AssetUnavailable { ref path }
3514                if path.to_string() == "textures/fallback.png"
3515        ));
3516    }
3517
3518    #[test]
3519    fn invalid_definition_and_theme_inputs_hide_without_panicking() {
3520        let invalid_definition = HudElementDefinition::new(
3521            "invalid",
3522            HudPresentation::Segments(HudSegments::new("count", 0)),
3523        );
3524        let values = HudValueSet::new();
3525        let (resolved, failure) = resolve_hud_element(
3526            &invalid_definition,
3527            &values,
3528            &HudTheme::default(),
3529            &mut |_| true,
3530        );
3531        assert!(!resolved.visible);
3532        assert!(matches!(
3533            failure,
3534            Some(HudDiagnosticKind::InvalidDefinition { .. })
3535        ));
3536
3537        let invalid_placement = text_definition("invalid-placement", "label")
3538            .placement(HudPlacement::new(HudAnchor::BottomRight).offset(f32::NAN, f32::INFINITY));
3539        let (resolved, failure) = resolve_hud_element(
3540            &invalid_placement,
3541            &values,
3542            &HudTheme::default(),
3543            &mut |_| true,
3544        );
3545        assert!(!resolved.visible);
3546        assert_eq!(resolved.layout.offset, HudPlacement::default().offset);
3547        assert!(resolved.layout.offset.into_iter().all(f32::is_finite));
3548        assert!(matches!(
3549            failure,
3550            Some(HudDiagnosticKind::InvalidDefinition {
3551                reason: HudDefinitionError::NonFinitePlacement
3552            })
3553        ));
3554
3555        let invalid_override = text_definition("invalid-style", "label").style(HudStyleOverride {
3556            gap: Some(-1.0),
3557            ..default()
3558        });
3559        let (resolved, failure) = resolve_hud_element(
3560            &invalid_override,
3561            &values,
3562            &HudTheme::default(),
3563            &mut |_| true,
3564        );
3565        assert!(!resolved.visible);
3566        assert_eq!(resolved.style, safe_default_style());
3567        assert!(matches!(
3568            failure,
3569            Some(HudDiagnosticKind::InvalidDefinition {
3570                reason: HudDefinitionError::InvalidStyleValue { field: "gap" }
3571            })
3572        ));
3573
3574        let definition = text_definition("theme", "label");
3575        let mut values = HudValueSet::new();
3576        values.insert_or_replace("label", "ready");
3577        let invalid_theme = HudTheme {
3578            font_size: f32::NAN,
3579            ..default()
3580        };
3581        let (resolved, failure) =
3582            resolve_hud_element(&definition, &values, &invalid_theme, &mut |_| true);
3583        assert!(!resolved.visible);
3584        assert_eq!(
3585            failure,
3586            Some(HudDiagnosticKind::InvalidStyle { field: "font_size" })
3587        );
3588        assert!(resolved.style.font_size.is_finite());
3589    }
3590
3591    #[test]
3592    fn diagnostics_emit_only_on_failure_transitions_and_reset_after_recovery() {
3593        let mut registry = HudRegistry::new();
3594        registry
3595            .register(text_definition("status", "label"))
3596            .unwrap();
3597        let mut values = HudValueSet::new();
3598        let mut tracker = HudDiagnosticTracker::default();
3599
3600        let first = resolve_hud(
3601            &registry,
3602            &values,
3603            &HudTheme::default(),
3604            |_| true,
3605            &mut tracker,
3606        );
3607        let unchanged = resolve_hud(
3608            &registry,
3609            &values,
3610            &HudTheme::default(),
3611            |_| true,
3612            &mut tracker,
3613        );
3614        assert_eq!(first.diagnostics.len(), 1);
3615        assert!(unchanged.diagnostics.is_empty());
3616
3617        values.insert_or_replace("label", "ready");
3618        let recovered = resolve_hud(
3619            &registry,
3620            &values,
3621            &HudTheme::default(),
3622            |_| true,
3623            &mut tracker,
3624        );
3625        assert!(recovered.diagnostics.is_empty());
3626        assert!(recovered.elements[0].visible);
3627
3628        values.remove("label");
3629        let failed_again = resolve_hud(
3630            &registry,
3631            &values,
3632            &HudTheme::default(),
3633            |_| true,
3634            &mut tracker,
3635        );
3636        assert_eq!(failed_again.diagnostics.len(), 1);
3637    }
3638
3639    #[test]
3640    fn public_ecs_types_implement_their_required_bevy_traits() {
3641        fn assert_resource<T: Resource>() {}
3642        fn assert_message<T: Message>() {}
3643
3644        assert_resource::<HudRegistry>();
3645        assert_resource::<HudValueSet>();
3646        assert_resource::<HudTheme>();
3647        assert_message::<HudValueChanged>();
3648        assert_message::<HudDiagnostic>();
3649    }
3650
3651    pub(super) fn root_for(app: &mut App, id: &str) -> Entity {
3652        let mut query = app.world_mut().query::<(Entity, &HudElementRoot)>();
3653        let matches: Vec<_> = query
3654            .iter(app.world())
3655            .filter_map(|(entity, root)| (root.0.as_str() == id).then_some(entity))
3656            .collect();
3657        assert_eq!(matches.len(), 1, "expected exactly one root for {id}");
3658        matches[0]
3659    }
3660
3661    pub(super) fn children_for(app: &mut App, id: &str) -> Vec<(HudChildKind, Entity)> {
3662        let mut query = app.world_mut().query::<(Entity, &HudChildIdentity)>();
3663        let mut matches: Vec<_> = query
3664            .iter(app.world())
3665            .filter_map(|(entity, child)| {
3666                (child.element.as_str() == id).then_some((child.kind, entity))
3667            })
3668            .collect();
3669        matches.sort_by_key(|(kind, entity)| (format!("{kind:?}"), entity.to_bits()));
3670        matches
3671    }
3672
3673    #[test]
3674    fn empty_standalone_plugin_starts_headlessly_and_keeps_structure_stable() {
3675        let mut app = App::new();
3676        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
3677        let mut diagnostics = app
3678            .world()
3679            .resource::<Messages<HudDiagnostic>>()
3680            .get_cursor_current();
3681
3682        app.update();
3683
3684        assert!(app.world().resource::<HudRegistry>().is_empty());
3685        assert_eq!(app.world().resource::<HudRegistry>().revision(), 0);
3686        assert!(app.world().resource::<HudValueSet>().is_empty());
3687        assert_eq!(app.world().resource::<HudValueSet>().revision(), 0);
3688        assert!(app.world().resource::<HudAssetCache>().handles.is_empty());
3689        assert_eq!(
3690            diagnostics
3691                .read(app.world().resource::<Messages<HudDiagnostic>>())
3692                .count(),
3693            0
3694        );
3695
3696        let canvas = {
3697            let mut query = app.world_mut().query_filtered::<Entity, With<HudCanvas>>();
3698            let canvases: Vec<_> = query.iter(app.world()).collect();
3699            assert_eq!(canvases.len(), 1);
3700            canvases[0]
3701        };
3702        let anchors = {
3703            let mut query = app.world_mut().query::<(Entity, &HudAnchorRoot)>();
3704            let mut anchors: Vec<_> = query
3705                .iter(app.world())
3706                .map(|(entity, anchor)| (anchor.0, entity))
3707                .collect();
3708            anchors.sort_by_key(|(key, _)| *key);
3709            assert_eq!(anchors.len(), 18);
3710            anchors
3711        };
3712        let mut roots = app.world_mut().query::<&HudElementRoot>();
3713        assert_eq!(roots.iter(app.world()).count(), 0);
3714        let mut children = app.world_mut().query::<&HudChildIdentity>();
3715        assert_eq!(children.iter(app.world()).count(), 0);
3716
3717        app.update();
3718
3719        let mut canvas_query = app.world_mut().query_filtered::<Entity, With<HudCanvas>>();
3720        assert_eq!(canvas_query.iter(app.world()).collect::<Vec<_>>(), [canvas]);
3721        let mut anchor_query = app.world_mut().query::<(Entity, &HudAnchorRoot)>();
3722        let mut unchanged_anchors: Vec<_> = anchor_query
3723            .iter(app.world())
3724            .map(|(entity, anchor)| (anchor.0, entity))
3725            .collect();
3726        unchanged_anchors.sort_by_key(|(key, _)| *key);
3727        assert_eq!(unchanged_anchors, anchors);
3728    }
3729
3730    #[test]
3731    fn hud_and_existing_ui_plugin_coexist_without_replacing_overlays() {
3732        use crate::world::{LoadingProgress, WorldLoadingState};
3733
3734        let mut app = App::new();
3735        app.add_plugins(MinimalPlugins);
3736        app.init_resource::<WorldLoadingState>();
3737        app.add_message::<LoadingProgress>();
3738        #[cfg(feature = "items")]
3739        {
3740            use crate::items::hotbar::{HotbarSelectionChanged, HotbarState};
3741
3742            app.init_resource::<HotbarState>();
3743            app.add_message::<HotbarSelectionChanged>();
3744        }
3745        app.add_plugins((crate::ui::UiPlugin, VoxelHudPlugin));
3746        app.world_mut()
3747            .resource_mut::<HudRegistry>()
3748            .register(text_definition("coexisting", "coexisting-value"))
3749            .unwrap();
3750        app.world_mut()
3751            .resource_mut::<HudValueSet>()
3752            .insert_or_replace("coexisting-value", "ready");
3753
3754        app.update();
3755
3756        let hud_root = root_for(&mut app, "coexisting");
3757        assert!(app.world().get::<HudElementRoot>(hud_root).is_some());
3758        let mut crosshair = app
3759            .world_mut()
3760            .query_filtered::<Entity, With<crate::ui::CrosshairNode>>();
3761        assert_eq!(crosshair.iter(app.world()).count(), 5);
3762        let mut loading = app
3763            .world_mut()
3764            .query_filtered::<Entity, With<crate::ui::LoadingOverlay>>();
3765        assert_eq!(loading.iter(app.world()).count(), 1);
3766
3767        app.update();
3768
3769        assert_eq!(root_for(&mut app, "coexisting"), hud_root);
3770        assert_eq!(crosshair.iter(app.world()).count(), 5);
3771        assert_eq!(loading.iter(app.world()).count(), 1);
3772    }
3773
3774    #[test]
3775    fn retained_renderer_preserves_roots_and_reconciles_only_changed_children() {
3776        let mut app = App::new();
3777        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
3778        app.world_mut()
3779            .resource_mut::<HudRegistry>()
3780            .register(text_definition("status", "status_value"))
3781            .unwrap();
3782        app.world_mut()
3783            .resource_mut::<HudValueSet>()
3784            .insert_or_replace("status_value", "ready");
3785
3786        app.update();
3787        let root = root_for(&mut app, "status");
3788        let text_child = children_for(&mut app, "status")
3789            .into_iter()
3790            .find_map(|(kind, entity)| (kind == HudChildKind::Text).then_some(entity))
3791            .unwrap();
3792        assert_eq!(app.world().get::<Text>(text_child).unwrap().0, "ready");
3793
3794        app.world_mut()
3795            .resource_mut::<HudValueSet>()
3796            .insert_or_replace("status_value", "updated");
3797        app.update();
3798        assert_eq!(root_for(&mut app, "status"), root);
3799        assert_eq!(app.world().get::<Text>(text_child).unwrap().0, "updated");
3800
3801        app.world_mut()
3802            .resource_mut::<HudRegistry>()
3803            .insert_or_replace(text_definition("status", "status_value").order(5).style(
3804                HudStyleOverride {
3805                    font_size: Some(24.0),
3806                    ..default()
3807                },
3808            ))
3809            .unwrap();
3810        app.update();
3811        assert_eq!(root_for(&mut app, "status"), root);
3812        assert_eq!(
3813            children_for(&mut app, "status"),
3814            vec![(HudChildKind::Text, text_child)]
3815        );
3816
3817        app.world_mut()
3818            .resource_mut::<HudRegistry>()
3819            .insert_or_replace(HudElementDefinition::new(
3820                "status",
3821                HudPresentation::Segments(HudSegments::new("charges", 3)),
3822            ))
3823            .unwrap();
3824        app.world_mut()
3825            .resource_mut::<HudValueSet>()
3826            .insert_or_replace("charges", 2_u32);
3827        app.update();
3828        assert_eq!(root_for(&mut app, "status"), root);
3829        assert!(app.world().get_entity(text_child).is_err());
3830        let first_segments = children_for(&mut app, "status");
3831        assert_eq!(first_segments.len(), 3);
3832
3833        app.world_mut()
3834            .resource_mut::<HudRegistry>()
3835            .insert_or_replace(HudElementDefinition::new(
3836                "status",
3837                HudPresentation::Segments(HudSegments::new("charges", 5)),
3838            ))
3839            .unwrap();
3840        app.update();
3841        assert_eq!(root_for(&mut app, "status"), root);
3842        let resized = children_for(&mut app, "status");
3843        assert_eq!(resized.len(), 5);
3844        for (kind, entity) in first_segments {
3845            assert!(resized.contains(&(kind, entity)));
3846        }
3847
3848        app.world_mut()
3849            .resource_mut::<HudRegistry>()
3850            .remove("status")
3851            .unwrap();
3852        app.update();
3853        let mut query = app.world_mut().query::<&HudElementRoot>();
3854        assert_eq!(query.iter(app.world()).count(), 0);
3855        assert!(app.world().get_entity(root).is_err());
3856    }
3857
3858    #[test]
3859    fn bar_render_transition_mutates_fill_without_rebuilding_tree() {
3860        let mut app = App::new();
3861        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
3862        app.world_mut()
3863            .resource_mut::<HudRegistry>()
3864            .register(HudElementDefinition::new(
3865                "energy",
3866                HudPresentation::Bar(HudBar::new("energy-value")),
3867            ))
3868            .unwrap();
3869        app.world_mut()
3870            .resource_mut::<HudValueSet>()
3871            .insert_or_replace("energy-value", HudScalar::new(25.0, 0.0, 100.0).unwrap());
3872        app.update();
3873
3874        let root = root_for(&mut app, "energy");
3875        let fill = children_for(&mut app, "energy")
3876            .into_iter()
3877            .find_map(|(kind, entity)| (kind == HudChildKind::BarFill).then_some(entity))
3878            .unwrap();
3879        assert_eq!(app.world().get::<Node>(fill).unwrap().width, Val::Px(55.0));
3880
3881        app.world_mut()
3882            .resource_mut::<HudValueSet>()
3883            .insert_or_replace("energy-value", HudScalar::new(75.0, 0.0, 100.0).unwrap());
3884        app.update();
3885
3886        assert_eq!(root_for(&mut app, "energy"), root);
3887        assert!(children_for(&mut app, "energy").contains(&(HudChildKind::BarFill, fill)));
3888        assert_eq!(app.world().get::<Node>(fill).unwrap().width, Val::Px(165.0));
3889    }
3890
3891    #[test]
3892    fn reconciliation_orders_ties_and_reparents_without_replacing_roots() {
3893        let mut app = App::new();
3894        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
3895        for id in ["zeta", "alpha"] {
3896            app.world_mut()
3897                .resource_mut::<HudRegistry>()
3898                .register(
3899                    text_definition(id, id)
3900                        .order(7)
3901                        .placement(HudPlacement::new(HudAnchor::BottomRight)),
3902                )
3903                .unwrap();
3904            app.world_mut()
3905                .resource_mut::<HudValueSet>()
3906                .insert_or_replace(id, id);
3907        }
3908        app.update();
3909
3910        let alpha = root_for(&mut app, "alpha");
3911        let zeta = root_for(&mut app, "zeta");
3912        let mut anchors = app
3913            .world_mut()
3914            .query::<(Entity, &HudAnchorRoot, &Children)>();
3915        let bottom_right = anchors
3916            .iter(app.world())
3917            .find(|(_, anchor, _)| {
3918                anchor.0
3919                    == HudAnchorKey {
3920                        anchor: HudAnchor::BottomRight,
3921                        direction: HudStackDirection::Vertical,
3922                    }
3923            })
3924            .unwrap();
3925        assert_eq!(bottom_right.2.as_ref(), &[alpha, zeta]);
3926
3927        app.world_mut()
3928            .resource_mut::<HudRegistry>()
3929            .insert_or_replace(
3930                text_definition("zeta", "zeta").order(7).placement(
3931                    HudPlacement::new(HudAnchor::TopLeft)
3932                        .offset(12.0, 8.0)
3933                        .stack_direction(HudStackDirection::Horizontal),
3934                ),
3935            )
3936            .unwrap();
3937        app.update();
3938        assert_eq!(root_for(&mut app, "zeta"), zeta);
3939        let zeta_parent = app.world().get::<ChildOf>(zeta).unwrap().parent();
3940        let anchor = app.world().get::<HudAnchorRoot>(zeta_parent).unwrap();
3941        assert_eq!(anchor.0.anchor, HudAnchor::TopLeft);
3942        assert_eq!(anchor.0.direction, HudStackDirection::Horizontal);
3943        let node = app.world().get::<Node>(zeta).unwrap();
3944        assert_eq!(node.margin.left, Val::Px(12.0));
3945        assert_eq!(node.margin.top, Val::Px(8.0));
3946    }
3947
3948    #[derive(Resource, Default)]
3949    struct PublishOnce(bool);
3950
3951    fn register_startup_hud(mut registry: ResMut<HudRegistry>) {
3952        registry
3953            .register(text_definition("same-frame", "same-frame-value"))
3954            .unwrap();
3955    }
3956
3957    fn publish_same_frame(
3958        mut once: ResMut<PublishOnce>,
3959        mut values: ResMut<HudValueSet>,
3960        mut changed: MessageWriter<HudValueChanged>,
3961    ) {
3962        if !once.0 {
3963            set_hud_value("same-frame-value", "visible now", &mut values, &mut changed);
3964            once.0 = true;
3965        }
3966    }
3967
3968    #[test]
3969    fn publish_set_updates_startup_definition_in_the_same_app_update() {
3970        let mut app = App::new();
3971        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
3972        app.init_resource::<PublishOnce>();
3973        app.add_systems(Startup, register_startup_hud);
3974        app.add_systems(Update, publish_same_frame.in_set(HudSystemSet::Publish));
3975
3976        app.update();
3977
3978        let child = children_for(&mut app, "same-frame")
3979            .into_iter()
3980            .find_map(|(kind, entity)| (kind == HudChildKind::Text).then_some(entity))
3981            .unwrap();
3982        assert_eq!(app.world().get::<Text>(child).unwrap().0, "visible now");
3983        let root = root_for(&mut app, "same-frame");
3984        assert_eq!(
3985            *app.world().get::<Visibility>(root).unwrap(),
3986            Visibility::Inherited
3987        );
3988    }
3989
3990    #[test]
3991    fn unchanged_and_unrelated_values_do_not_mutate_retained_text() {
3992        #[derive(Resource, Default)]
3993        struct ChangedTexts(Vec<Vec<String>>);
3994
3995        fn record_changed_texts(
3996            changed: Query<&HudChildIdentity, Changed<Text>>,
3997            mut observed: ResMut<ChangedTexts>,
3998        ) {
3999            let mut ids: Vec<_> = changed
4000                .iter()
4001                .map(|identity| identity.element.as_str().to_owned())
4002                .collect();
4003            ids.sort();
4004            observed.0.push(ids);
4005        }
4006
4007        let mut app = App::new();
4008        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
4009        app.init_resource::<ChangedTexts>();
4010        app.add_systems(Update, record_changed_texts.after(HudSystemSet::Render));
4011        for id in ["alpha", "beta"] {
4012            app.world_mut()
4013                .resource_mut::<HudRegistry>()
4014                .register(text_definition(id, id))
4015                .unwrap();
4016            app.world_mut()
4017                .resource_mut::<HudValueSet>()
4018                .insert_or_replace(id, id);
4019        }
4020        app.update();
4021
4022        app.world_mut()
4023            .resource_mut::<HudValueSet>()
4024            .insert_or_replace("alpha", "changed");
4025        app.update();
4026        assert_eq!(
4027            app.world().resource::<ChangedTexts>().0.last().unwrap(),
4028            &["alpha"]
4029        );
4030
4031        app.update();
4032        assert!(
4033            app.world()
4034                .resource::<ChangedTexts>()
4035                .0
4036                .last()
4037                .unwrap()
4038                .is_empty()
4039        );
4040    }
4041
4042    #[test]
4043    fn missing_asset_server_hides_images_without_starting_asset_io() {
4044        let mut app = App::new();
4045        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
4046        app.world_mut()
4047            .resource_mut::<HudRegistry>()
4048            .register(HudElementDefinition::new(
4049                "icon",
4050                HudPresentation::Icon(HudIcon::asset("textures/icon.png")),
4051            ))
4052            .unwrap();
4053        let mut cursor = app
4054            .world()
4055            .resource::<Messages<HudDiagnostic>>()
4056            .get_cursor_current();
4057
4058        app.update();
4059
4060        let root = root_for(&mut app, "icon");
4061        assert_eq!(
4062            *app.world().get::<Visibility>(root).unwrap(),
4063            Visibility::Hidden
4064        );
4065        assert!(app.world().resource::<HudAssetCache>().handles.is_empty());
4066        let diagnostics: Vec<_> = cursor
4067            .read(app.world().resource::<Messages<HudDiagnostic>>())
4068            .cloned()
4069            .collect();
4070        assert_eq!(diagnostics.len(), 1);
4071        assert!(matches!(
4072            diagnostics[0].kind,
4073            HudDiagnosticKind::AssetUnavailable { .. }
4074        ));
4075
4076        app.update();
4077        assert_eq!(
4078            cursor
4079                .read(app.world().resource::<Messages<HudDiagnostic>>())
4080                .count(),
4081            0
4082        );
4083    }
4084
4085    #[test]
4086    fn ecs_diagnostics_deduplicate_and_reemit_after_recovery() {
4087        let mut app = App::new();
4088        app.add_plugins((MinimalPlugins, VoxelHudPlugin));
4089        app.world_mut()
4090            .resource_mut::<HudRegistry>()
4091            .register(text_definition("status", "status-value"))
4092            .unwrap();
4093        let mut diagnostics = app
4094            .world()
4095            .resource::<Messages<HudDiagnostic>>()
4096            .get_cursor_current();
4097
4098        app.update();
4099        let first: Vec<_> = diagnostics
4100            .read(app.world().resource::<Messages<HudDiagnostic>>())
4101            .cloned()
4102            .collect();
4103        assert_eq!(first.len(), 1);
4104        assert!(matches!(
4105            first[0].kind,
4106            HudDiagnosticKind::MissingValue {
4107                binding: HudBindingKind::Presentation,
4108                ..
4109            }
4110        ));
4111
4112        app.update();
4113        assert_eq!(
4114            diagnostics
4115                .read(app.world().resource::<Messages<HudDiagnostic>>())
4116                .count(),
4117            0
4118        );
4119
4120        app.world_mut()
4121            .resource_mut::<HudValueSet>()
4122            .insert_or_replace("status-value", "ready");
4123        app.update();
4124        assert_eq!(
4125            diagnostics
4126                .read(app.world().resource::<Messages<HudDiagnostic>>())
4127                .count(),
4128            0
4129        );
4130        let root = root_for(&mut app, "status");
4131        assert_eq!(
4132            *app.world().get::<Visibility>(root).unwrap(),
4133            Visibility::Inherited
4134        );
4135
4136        app.world_mut()
4137            .resource_mut::<HudValueSet>()
4138            .remove("status-value");
4139        app.update();
4140        assert_eq!(
4141            diagnostics
4142                .read(app.world().resource::<Messages<HudDiagnostic>>())
4143                .count(),
4144            1
4145        );
4146    }
4147}
4148
4149#[cfg(test)]
4150mod asset_runtime_tests {
4151    use super::tests::{children_for, root_for, text_definition};
4152    use super::*;
4153    use bevy::asset::io::{
4154        AssetSourceBuilder, Reader,
4155        memory::{Dir, MemoryAssetReader},
4156    };
4157    use bevy::asset::{AssetApp, AssetLoader, AssetPlugin, LoadContext, RenderAssetUsages};
4158    use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
4159    use std::{
4160        path::Path,
4161        sync::{Arc, Mutex},
4162        task::{Poll, Waker},
4163        time::{Duration, Instant},
4164    };
4165
4166    #[derive(Default)]
4167    struct Gate {
4168        open: bool,
4169        waker: Option<Waker>,
4170    }
4171
4172    #[derive(TypePath)]
4173    struct TestImageLoader {
4174        gate: Arc<Mutex<Gate>>,
4175        loads: Arc<Mutex<Vec<String>>>,
4176    }
4177
4178    // A genuine async AssetLoader returning Image assets, with an explicit latch
4179    // instead of timing-dependent sleeps to hold the pending state.
4180    impl AssetLoader for TestImageLoader {
4181        type Asset = Image;
4182        type Settings = ();
4183        type Error = std::io::Error;
4184
4185        async fn load(
4186            &self,
4187            reader: &mut dyn Reader,
4188            _: &(),
4189            context: &mut LoadContext<'_>,
4190        ) -> Result<Image, Self::Error> {
4191            let path = context.path().path().to_string_lossy().into_owned();
4192            self.loads.lock().unwrap().push(path.clone());
4193            if path == "slow.hudimage" {
4194                std::future::poll_fn(|cx| {
4195                    let mut gate = self.gate.lock().unwrap();
4196                    if gate.open {
4197                        Poll::Ready(())
4198                    } else {
4199                        gate.waker = Some(cx.waker().clone());
4200                        Poll::Pending
4201                    }
4202                })
4203                .await;
4204            }
4205            let mut bytes = Vec::new();
4206            reader.read_to_end(&mut bytes).await?;
4207            if bytes.len() != 4 {
4208                return Err(std::io::Error::new(
4209                    std::io::ErrorKind::InvalidData,
4210                    "expected one RGBA pixel",
4211                ));
4212            }
4213            Ok(Image::new_fill(
4214                Extent3d {
4215                    width: 1,
4216                    height: 1,
4217                    depth_or_array_layers: 1,
4218                },
4219                TextureDimension::D2,
4220                &bytes,
4221                TextureFormat::Rgba8UnormSrgb,
4222                RenderAssetUsages::default(),
4223            ))
4224        }
4225        fn extensions(&self) -> &[&str] {
4226            &["hudimage"]
4227        }
4228    }
4229
4230    #[derive(Resource, Default)]
4231    struct ImageWrites(Vec<Entity>);
4232
4233    fn record_image_writes(
4234        mut writes: ResMut<ImageWrites>,
4235        images: Query<Entity, Changed<ImageNode>>,
4236    ) {
4237        writes.0 = images.iter().collect();
4238    }
4239
4240    struct Fixture {
4241        app: App,
4242        dir: Dir,
4243        gate: Arc<Mutex<Gate>>,
4244        loads: Arc<Mutex<Vec<String>>>,
4245    }
4246
4247    impl Fixture {
4248        fn new() -> Self {
4249            let dir = Dir::default();
4250            let reader_dir = dir.clone();
4251            let gate = Arc::new(Mutex::new(Gate::default()));
4252            let loads = Arc::new(Mutex::new(Vec::new()));
4253            let mut app = App::new();
4254            app.add_plugins(MinimalPlugins)
4255                .register_asset_source(
4256                    "hud-test",
4257                    AssetSourceBuilder::new(move || {
4258                        Box::new(MemoryAssetReader {
4259                            root: reader_dir.clone(),
4260                        })
4261                    }),
4262                )
4263                .add_plugins(AssetPlugin::default())
4264                .init_asset::<Image>()
4265                .register_asset_loader(TestImageLoader {
4266                    gate: gate.clone(),
4267                    loads: loads.clone(),
4268                })
4269                .register_asset_loader(bevy::image::ImageLoader::new(
4270                    bevy::image::CompressedImageFormats::NONE,
4271                ))
4272                .add_plugins(VoxelHudPlugin)
4273                .init_resource::<ImageWrites>()
4274                .add_systems(Update, record_image_writes.after(HudSystemSet::Render));
4275            Self {
4276                app,
4277                dir,
4278                gate,
4279                loads,
4280            }
4281        }
4282        fn put(&self, path: &str, rgba: [u8; 4]) {
4283            self.dir.insert_asset(Path::new(path), rgba.to_vec());
4284        }
4285        fn release(&self) {
4286            let mut gate = self.gate.lock().unwrap();
4287            gate.open = true;
4288            if let Some(waker) = gate.waker.take() {
4289                waker.wake();
4290            }
4291        }
4292        fn register(&mut self, definition: HudElementDefinition) {
4293            self.app
4294                .world_mut()
4295                .resource_mut::<HudRegistry>()
4296                .register(definition)
4297                .unwrap();
4298        }
4299        fn value(&mut self, id: &str, value: impl Into<HudValue>) {
4300            self.app
4301                .world_mut()
4302                .resource_mut::<HudValueSet>()
4303                .insert_or_replace(id, value);
4304        }
4305        fn handle(&self, name: &str) -> Handle<Image> {
4306            self.app
4307                .world()
4308                .resource::<AssetServer>()
4309                .load(format!("hud-test://{name}"))
4310        }
4311        fn poll(&mut self, label: &str, mut predicate: impl FnMut(&mut App) -> bool) {
4312            let deadline = Instant::now() + Duration::from_secs(5);
4313            loop {
4314                self.app.update();
4315                if predicate(&mut self.app) {
4316                    return;
4317                }
4318                assert!(Instant::now() < deadline, "timed out waiting for {label}");
4319                std::thread::sleep(Duration::from_millis(1));
4320            }
4321        }
4322        fn visible(app: &mut App, id: &str) -> bool {
4323            let root = root_for(app, id);
4324            *app.world().get::<Visibility>(root).unwrap() == Visibility::Inherited
4325        }
4326        fn image(app: &mut App, id: &str) -> Handle<Image> {
4327            let child = children_for(app, id)[0].1;
4328            app.world().get::<ImageNode>(child).unwrap().image.clone()
4329        }
4330    }
4331
4332    #[test]
4333    fn real_asset_failed_icon_recovers_on_same_path_reload_without_publication() {
4334        let mut f = Fixture::new();
4335        f.register(HudElementDefinition::new(
4336            "icon",
4337            HudPresentation::Icon(HudIcon::asset("hud-test://repair.hudimage")),
4338        ));
4339        let handle = f.handle("repair.hudimage");
4340        f.poll("real read failure", |app| {
4341            matches!(
4342                app.world()
4343                    .resource::<AssetServer>()
4344                    .load_state(handle.id()),
4345                LoadState::Failed(_)
4346            )
4347        });
4348        f.app.update();
4349        assert!(!Fixture::visible(&mut f.app, "icon"));
4350        let root = root_for(&mut f.app, "icon");
4351        let children = children_for(&mut f.app, "icon");
4352        let revision = f.app.world().resource::<HudValueSet>().revision();
4353        f.put("repair.hudimage", [20, 200, 80, 255]);
4354        f.app
4355            .world()
4356            .resource::<AssetServer>()
4357            .reload("hud-test://repair.hudimage");
4358        f.poll("same-path Image asset reload", |app| {
4359            matches!(
4360                app.world()
4361                    .resource::<AssetServer>()
4362                    .load_state(handle.id()),
4363                LoadState::Loaded
4364            )
4365        });
4366        f.app.update();
4367        assert!(
4368            f.app
4369                .world()
4370                .resource::<Assets<Image>>()
4371                .contains(handle.id())
4372        );
4373        assert!(
4374            Fixture::visible(&mut f.app, "icon"),
4375            "loaded recovery must invalidate the hidden fingerprint without value changes"
4376        );
4377        assert_eq!(Fixture::image(&mut f.app, "icon"), handle);
4378        assert_eq!(root_for(&mut f.app, "icon"), root);
4379        assert_eq!(children_for(&mut f.app, "icon"), children);
4380        assert_eq!(f.app.world().resource::<HudValueSet>().revision(), revision);
4381        for _ in 0..3 {
4382            f.app.update();
4383        }
4384        f.dir.insert_asset(Path::new("repair.hudimage"), vec![0]);
4385        f.app
4386            .world()
4387            .resource::<AssetServer>()
4388            .reload("hud-test://repair.hudimage");
4389        f.poll("previously loaded asset fails on reload", |app| {
4390            matches!(
4391                app.world()
4392                    .resource::<AssetServer>()
4393                    .load_state(handle.id()),
4394                LoadState::Failed(_)
4395            )
4396        });
4397        f.app.update();
4398        assert!(
4399            !Fixture::visible(&mut f.app, "icon"),
4400            "failed reload must invalidate the visible fingerprint without value changes"
4401        );
4402        f.put("repair.hudimage", [20, 200, 80, 255]);
4403        f.app
4404            .world()
4405            .resource::<AssetServer>()
4406            .reload("hud-test://repair.hudimage");
4407        f.poll("second recovery on unchanged path", |app| {
4408            Fixture::visible(app, "icon")
4409        });
4410        assert_eq!(Fixture::image(&mut f.app, "icon"), handle);
4411        assert_eq!(root_for(&mut f.app, "icon"), root);
4412        assert_eq!(children_for(&mut f.app, "icon"), children);
4413    }
4414
4415    #[test]
4416    fn real_asset_pending_failure_fallback_and_value_recovery_preserve_identity() {
4417        let mut f = Fixture::new();
4418        f.put("slow.hudimage", [255, 40, 10, 255]);
4419        f.put("fallback.hudimage", [10, 40, 255, 255]);
4420        f.dir.insert_asset(Path::new("invalid.hudimage"), vec![0]);
4421        f.register(
4422            HudElementDefinition::new("icon", HudPresentation::Icon(HudIcon::bound("path")))
4423                .fallback(HudValue::icon("hud-test://fallback.hudimage")),
4424        );
4425        f.value("path", HudValue::icon("hud-test://slow.hudimage"));
4426        let slow = f.handle("slow.hudimage");
4427        let fallback = f.handle("fallback.hudimage");
4428        let mut cursor = f
4429            .app
4430            .world()
4431            .resource::<Messages<HudDiagnostic>>()
4432            .get_cursor_current();
4433        let mut observed = Vec::new();
4434        f.poll("loaded fallback while primary is gated", |app| {
4435            observed.extend(
4436                cursor
4437                    .read(app.world().resource::<Messages<HudDiagnostic>>())
4438                    .cloned(),
4439            );
4440            Fixture::visible(app, "icon") && Fixture::image(app, "icon") == fallback
4441        });
4442        assert!(matches!(
4443            f.app
4444                .world()
4445                .resource::<AssetServer>()
4446                .load_state(slow.id()),
4447            LoadState::Loading
4448        ));
4449        assert!(
4450            f.app
4451                .world()
4452                .resource::<Assets<Image>>()
4453                .contains(fallback.id())
4454        );
4455        assert!(observed.iter().any(|d| matches!(&d.kind, HudDiagnosticKind::AssetUnavailable { path } if path.to_string() == "hud-test://slow.hudimage")));
4456        let root = root_for(&mut f.app, "icon");
4457        let children = children_for(&mut f.app, "icon");
4458        assert!(
4459            f.app
4460                .world()
4461                .get::<HudResolvedFingerprint>(root)
4462                .unwrap()
4463                .0
4464                .as_ref()
4465                .unwrap()
4466                .used_fallback
4467        );
4468        f.app.update();
4469        assert_eq!(
4470            cursor
4471                .read(f.app.world().resource::<Messages<HudDiagnostic>>())
4472                .count(),
4473            0
4474        );
4475        f.release();
4476        f.poll("primary replaces fallback", |app| {
4477            Fixture::image(app, "icon") == slow
4478        });
4479        assert!(Fixture::visible(&mut f.app, "icon"));
4480        assert!(
4481            f.app
4482                .world()
4483                .resource::<Assets<Image>>()
4484                .contains(slow.id())
4485        );
4486        assert!(
4487            !f.app
4488                .world()
4489                .get::<HudResolvedFingerprint>(root)
4490                .unwrap()
4491                .0
4492                .as_ref()
4493                .unwrap()
4494                .used_fallback
4495        );
4496        let invalid = f.handle("invalid.hudimage");
4497        f.value("path", HudValue::icon("hud-test://invalid.hudimage"));
4498        f.poll("loader failure and loaded fallback", |app| {
4499            matches!(
4500                app.world()
4501                    .resource::<AssetServer>()
4502                    .load_state(invalid.id()),
4503                LoadState::Failed(_)
4504            ) && Fixture::image(app, "icon") == fallback
4505        });
4506        assert!(Fixture::visible(&mut f.app, "icon"));
4507        // Recover by publication, then fail again: the same diagnostic must reemit.
4508        f.value("path", HudValue::icon("hud-test://slow.hudimage"));
4509        f.app.update();
4510        assert_eq!(Fixture::image(&mut f.app, "icon"), slow);
4511        cursor
4512            .read(f.app.world().resource::<Messages<HudDiagnostic>>())
4513            .for_each(drop);
4514        f.value("path", HudValue::icon("hud-test://invalid.hudimage"));
4515        f.app.update();
4516        let diagnostics: Vec<_> = cursor
4517            .read(f.app.world().resource::<Messages<HudDiagnostic>>())
4518            .collect();
4519        assert_eq!(diagnostics.len(), 1);
4520        assert!(
4521            matches!(&diagnostics[0].kind, HudDiagnosticKind::AssetUnavailable { path } if path.to_string() == "hud-test://invalid.hudimage")
4522        );
4523        f.app.update();
4524        assert_eq!(
4525            cursor
4526                .read(f.app.world().resource::<Messages<HudDiagnostic>>())
4527                .count(),
4528            0
4529        );
4530        assert_eq!(root_for(&mut f.app, "icon"), root);
4531        assert_eq!(children_for(&mut f.app, "icon"), children);
4532    }
4533
4534    #[test]
4535    fn real_assets_render_and_update_all_four_presentations_and_reuse_cached_handles() {
4536        let mut f = Fixture::new();
4537        f.put("full.hudimage", [240, 180, 30, 255]);
4538        f.put("empty.hudimage", [30, 50, 70, 255]);
4539        f.register(text_definition("text", "text"));
4540        f.register(HudElementDefinition::new(
4541            "bar",
4542            HudPresentation::Bar(HudBar::new("ratio")),
4543        ));
4544        f.register(HudElementDefinition::new(
4545            "icon",
4546            HudPresentation::Icon(HudIcon::bound("path")),
4547        ));
4548        f.register(HudElementDefinition::new(
4549            "segments",
4550            HudPresentation::Segments(
4551                HudSegments::new("count", 3)
4552                    .filled_asset("hud-test://full.hudimage")
4553                    .empty_asset("hud-test://empty.hudimage"),
4554            ),
4555        ));
4556        f.value("text", "first");
4557        f.value("ratio", HudScalar::new(1.0, 0.0, 4.0).unwrap());
4558        f.value("path", HudValue::icon("hud-test://full.hudimage"));
4559        f.value("count", 1_u32);
4560        let full = f.handle("full.hudimage");
4561        let empty = f.handle("empty.hudimage");
4562        f.poll("all four visible", |app| {
4563            ["text", "bar", "icon", "segments"]
4564                .into_iter()
4565                .all(|id| Fixture::visible(app, id))
4566        });
4567        let identities: Vec<_> = ["text", "bar", "icon", "segments"]
4568            .into_iter()
4569            .map(|id| (id, root_for(&mut f.app, id), children_for(&mut f.app, id)))
4570            .collect();
4571        assert_eq!(Fixture::image(&mut f.app, "icon"), full);
4572        let check_segments = |app: &mut App, filled: u32| {
4573            for (kind, entity) in children_for(app, "segments") {
4574                let HudChildKind::Segment(index) = kind else {
4575                    panic!("not a segment")
4576                };
4577                assert_eq!(
4578                    app.world().get::<ImageNode>(entity).unwrap().image,
4579                    if index < filled {
4580                        full.clone()
4581                    } else {
4582                        empty.clone()
4583                    }
4584                );
4585                assert_eq!(
4586                    app.world().get::<BackgroundColor>(entity).unwrap().0,
4587                    Color::NONE
4588                );
4589            }
4590        };
4591        check_segments(&mut f.app, 1);
4592        for handle in [&full, &empty] {
4593            assert!(
4594                f.app
4595                    .world()
4596                    .resource::<Assets<Image>>()
4597                    .contains(handle.id())
4598            );
4599        }
4600        assert_eq!(f.app.world().resource::<HudAssetCache>().handles.len(), 2);
4601        f.value("text", "second");
4602        f.value("ratio", HudScalar::new(3.0, 0.0, 4.0).unwrap());
4603        f.value("path", HudValue::icon("hud-test://empty.hudimage"));
4604        f.value("count", 2_u32);
4605        f.app.update();
4606        assert_eq!(Fixture::image(&mut f.app, "icon"), empty);
4607        check_segments(&mut f.app, 2);
4608        let text = children_for(&mut f.app, "text")[0].1;
4609        assert_eq!(f.app.world().get::<Text>(text).unwrap().0, "second");
4610        let fill = children_for(&mut f.app, "bar")
4611            .into_iter()
4612            .find(|(kind, _)| *kind == HudChildKind::BarFill)
4613            .unwrap()
4614            .1;
4615        assert_eq!(
4616            f.app.world().get::<Node>(fill).unwrap().width,
4617            Val::Px(HudTheme::default().bar_size[0] * 0.75)
4618        );
4619        let loads = f.loads.lock().unwrap().clone();
4620        assert_eq!(loads.iter().filter(|p| *p == "full.hudimage").count(), 1);
4621        assert_eq!(loads.iter().filter(|p| *p == "empty.hudimage").count(), 1);
4622        for _ in 0..4 {
4623            f.app.update();
4624        }
4625        for (id, root, children) in &identities {
4626            assert_eq!(root_for(&mut f.app, id), *root);
4627            assert_eq!(children_for(&mut f.app, id), *children);
4628        }
4629        assert_eq!(*f.loads.lock().unwrap(), loads);
4630        assert!(f.app.world().resource::<ImageWrites>().0.is_empty());
4631        // A real unrelated asset emits Added/Loaded events; no HUD image rewrites.
4632        f.put("unrelated.hudimage", [20, 30, 40, 255]);
4633        let unrelated = f.handle("unrelated.hudimage");
4634        f.poll("unrelated image loading", |app| {
4635            app.world()
4636                .resource::<Assets<Image>>()
4637                .contains(unrelated.id())
4638        });
4639        f.app.update();
4640        assert!(f.app.world().resource::<ImageWrites>().0.is_empty());
4641
4642        // Removing the only full-texture user prunes it; shared empty stays cached.
4643        f.app
4644            .world_mut()
4645            .resource_mut::<HudRegistry>()
4646            .remove("segments")
4647            .unwrap();
4648        f.app.update();
4649        let cache = f.app.world().resource::<HudAssetCache>();
4650        assert_eq!(cache.handles.len(), 1);
4651        assert_eq!(
4652            cache.handle(&AssetPath::from("hud-test://empty.hudimage")),
4653            Some(empty)
4654        );
4655        f.app
4656            .world_mut()
4657            .resource_mut::<HudRegistry>()
4658            .remove("icon")
4659            .unwrap();
4660        f.app.update();
4661        assert!(f.app.world().resource::<HudAssetCache>().handles.is_empty());
4662    }
4663
4664    #[test]
4665    fn real_png_loader_and_gated_icon_show_expected_image_nodes_without_gpu() {
4666        let mut f = Fixture::new();
4667        // Valid one-pixel RGBA PNG: exercised by Bevy's stock ImageLoader, not
4668        // our controlled loader and not Assets::add or a resolver predicate.
4669        let png: &[u8] = &[
4670            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1,
4671            8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 120, 156, 99, 120, 150,
4672            34, 247, 31, 0, 6, 4, 2, 104, 229, 197, 141, 181, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66,
4673            96, 130,
4674        ];
4675        f.dir.insert_asset(Path::new("actual.png"), png.to_vec());
4676        f.put("slow.hudimage", [120, 220, 50, 255]);
4677        f.register(HudElementDefinition::new(
4678            "png",
4679            HudPresentation::Icon(HudIcon::asset("hud-test://actual.png")),
4680        ));
4681        f.register(HudElementDefinition::new(
4682            "pending",
4683            HudPresentation::Icon(HudIcon::asset("hud-test://slow.hudimage")),
4684        ));
4685        let png_handle = f.handle("actual.png");
4686        let slow = f.handle("slow.hudimage");
4687        f.app.update();
4688        let root = root_for(&mut f.app, "pending");
4689        let children = children_for(&mut f.app, "pending");
4690        assert!(!Fixture::visible(&mut f.app, "pending"));
4691        assert_eq!(
4692            Fixture::image(&mut f.app, "pending"),
4693            ImageNode::default().image
4694        );
4695        f.poll("stock PNG decode", |app| Fixture::visible(app, "png"));
4696        assert_eq!(Fixture::image(&mut f.app, "png"), png_handle);
4697        let image = f
4698            .app
4699            .world()
4700            .resource::<Assets<Image>>()
4701            .get(&png_handle)
4702            .unwrap();
4703        assert_eq!(image.width(), 1);
4704        assert_eq!(image.height(), 1);
4705        assert_eq!(image.data.as_deref(), Some(&[230, 100, 30, 255][..]));
4706        f.release();
4707        f.poll("gated icon becomes visible", |app| {
4708            Fixture::visible(app, "pending")
4709        });
4710        assert_eq!(Fixture::image(&mut f.app, "pending"), slow);
4711        assert_eq!(root_for(&mut f.app, "pending"), root);
4712        assert_eq!(children_for(&mut f.app, "pending"), children);
4713        // No stale handles or tree rebuilding on an unchanged loaded frame.
4714        let png_children = children_for(&mut f.app, "png");
4715        f.app.update();
4716        assert_eq!(children_for(&mut f.app, "png"), png_children);
4717        assert_eq!(Fixture::image(&mut f.app, "png"), png_handle);
4718    }
4719}