Skip to main content

crcbl_ui/debug/
reflected.rs

1//! A reflected value as a debug panel section: one `label: value` row per leaf.
2//!
3//! This is how a selected entity's data reaches the panel. A system lends its
4//! row as `&dyn Reflect` — `crcbl_ecs::SystemTrait::debug_fields` — and
5//! [`ReflectedSection`] walks it with the same [`Reflect::fields`] labels the
6//! property inspector (`Ui::inspector`) draws, so a component reads the same in
7//! the F3 panel as in the editor. It is **read-only**: the panel is rows of
8//! text, and the inspector's widgets edit a `&mut dyn Reflect` the panel is
9//! never handed.
10//!
11//! # Which rows a value becomes
12//!
13//! * A leaf is one row: a float to [`REFLECTED_DECIMALS`] places, everything
14//!   else as [`Value`]'s `Display` spells it.
15//! * A struct's fields are rows labelled by their path from the section —
16//!   `half extents.x` — with each segment the field's
17//!   [`label`](crcbl_reflect::Field::label).
18//! * An enum is a row naming its active variant, then that variant's fields.
19//! * A list of leaves is **one** row, its elements comma-separated: a position
20//!   reads `1.000, 2.000, 3.000` rather than three rows labelled `0`, `1`, `2`.
21//!   A list of composites is a row group per element, labelled by index.
22//!
23//! A value that is itself a leaf — a `System<f32>`'s row — is labelled with its
24//! [`type_name`](Reflect::type_name), as it has no field name to carry.
25
26use core::fmt;
27
28use crcbl_reflect::{Kind, Reflect, Value};
29
30use super::{DebugModule, DebugSection};
31
32/// How many decimal places a float in a [`ReflectedSection`] shows.
33///
34/// A reflected float arrives widened to `f64`, so an `f32` field printed in
35/// full is seventeen digits of rounding noise — `0.30000001192092896` for a
36/// field set to `0.3`. Three places are millimetres in a metre-scale world,
37/// which is what a developer reading a live value can use.
38pub const REFLECTED_DECIMALS: usize = 3;
39
40/// What an enum's variant row is labelled with when the enum is the whole
41/// value, and so has no field name of its own.
42const VARIANT_LABEL: &str = "variant";
43
44/// Separates the segments of a nested row's label.
45const PATH_SEPARATOR: char = '.';
46
47/// A [`DebugModule`] for any [`Reflect`] value: a section titled `title` with
48/// one row per leaf, labelled by its path of field labels.
49///
50/// An enum adds a row naming its active variant; a list of leaves is one
51/// comma-separated row; a float shows [`REFLECTED_DECIMALS`] places; a value
52/// that is itself a leaf is labelled with its type's name. Read-only: the
53/// panel is never handed the `&mut dyn Reflect` an edit would need.
54#[derive(Clone, Copy)]
55pub struct ReflectedSection<'a> {
56    /// The section's heading — a system's name, for a selected entity.
57    pub title: &'a str,
58    /// The value its rows describe.
59    pub value: &'a dyn Reflect,
60}
61
62impl fmt::Debug for ReflectedSection<'_> {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.debug_struct("ReflectedSection")
65            .field("title", &self.title)
66            .field("type", &self.value.type_name())
67            .finish()
68    }
69}
70
71impl DebugModule for ReflectedSection<'_> {
72    fn debug_section(&self, out: &mut DebugSection) {
73        out.set_title(self.title);
74        let mut label = String::new();
75        rows(out, &mut label, self.value);
76    }
77}
78
79/// Writes `value`'s rows into `out`, each labelled `label` plus its own path.
80///
81/// `label` is the path so far and is left as it was found; an empty one means
82/// `value` is the section's whole value.
83fn rows(out: &mut DebugSection, label: &mut String, value: &dyn Reflect) {
84    match value.kind() {
85        Kind::Leaf(_) => {
86            let shown = if label.is_empty() {
87                value.type_name()
88            } else {
89                label.as_str()
90            };
91            out.row(shown, format_args!("{}", Leaf(value)));
92        }
93        Kind::Struct => fields(out, label, value),
94        Kind::Enum => {
95            let shown = if label.is_empty() {
96                VARIANT_LABEL
97            } else {
98                label.as_str()
99            };
100            out.row_str(shown, value.variant().unwrap_or_default());
101            fields(out, label, value);
102        }
103        Kind::List { len } => {
104            let elements = (0..len).filter_map(|index| value.field(index));
105            if elements
106                .clone()
107                .all(|element| matches!(element.kind(), Kind::Leaf(_)))
108            {
109                let shown = if label.is_empty() {
110                    value.type_name()
111                } else {
112                    label.as_str()
113                };
114                out.row(shown, format_args!("{}", Joined(value, len)));
115            } else {
116                for (index, element) in elements.enumerate() {
117                    nested(out, label, format_args!("{index}"), element);
118                }
119            }
120        }
121    }
122}
123
124/// The rows of a struct's fields, or of an enum's active variant's.
125fn fields(out: &mut DebugSection, label: &mut String, value: &dyn Reflect) {
126    for (index, field) in value.fields().iter().enumerate() {
127        if let Some(child) = value.field(index) {
128            nested(out, label, format_args!("{}", field.label), child);
129        }
130    }
131}
132
133/// [`rows`] for `child`, with `segment` appended to `label` for the call and
134/// taken off again after it.
135fn nested(
136    out: &mut DebugSection,
137    label: &mut String,
138    segment: fmt::Arguments<'_>,
139    child: &dyn Reflect,
140) {
141    let kept = label.len();
142    if kept > 0 {
143        label.push(PATH_SEPARATOR);
144    }
145    // Writing into a `String` cannot fail; the `Result` is `fmt`'s shape.
146    let _ = fmt::Write::write_fmt(label, segment);
147    rows(out, label, child);
148    label.truncate(kept);
149}
150
151/// A leaf's value as a row prints it; see [`REFLECTED_DECIMALS`].
152struct Leaf<'a>(&'a dyn Reflect);
153
154impl fmt::Display for Leaf<'_> {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        match self.0.get() {
157            Some(Value::Float(value)) => write!(f, "{value:.REFLECTED_DECIMALS$}"),
158            Some(value) => write!(f, "{value}"),
159            // A `Kind::Leaf` with no value breaks `Reflect`'s own contract;
160            // the row says so rather than printing a value it does not have.
161            None => write!(f, "<{} has no value>", self.0.type_name()),
162        }
163    }
164}
165
166/// A list of leaves, comma-separated, as one row's value.
167struct Joined<'a>(&'a dyn Reflect, usize);
168
169impl fmt::Display for Joined<'_> {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        let Self(list, len) = *self;
172        for (index, element) in (0..len).filter_map(|index| list.field(index)).enumerate() {
173            if index > 0 {
174                f.write_str(", ")?;
175            }
176            write!(f, "{}", Leaf(element))?;
177        }
178        Ok(())
179    }
180}
181
182// ---------------------------------------------------------------------------
183// Tests
184// ---------------------------------------------------------------------------
185
186#[cfg(test)]
187mod tests {
188    use glam::Vec2;
189
190    use super::*;
191    use crate::debug::DebugOverlay;
192    use crate::draw_list::{DrawCommand, DrawList};
193    use crate::text::FontAtlas;
194
195    #[derive(Reflect)]
196    enum Mode {
197        Idle,
198        Chasing { speed: f32 },
199    }
200
201    #[derive(Reflect)]
202    struct Offset {
203        x: f64,
204    }
205
206    /// Every shape [`rows`] distinguishes: a renamed leaf, a list of leaves, a
207    /// nested struct, an enum and a list of composites.
208    #[derive(Reflect)]
209    struct Guard {
210        #[reflect(name = "Hit points")]
211        hit_points: i32,
212        position: [f32; 3],
213        offset: Offset,
214        mode: Mode,
215        waypoints: [Offset; 2],
216        awake: bool,
217    }
218
219    fn guard() -> Guard {
220        Guard {
221            hit_points: 12,
222            position: [1.0, 0.3, -2.5],
223            offset: Offset { x: 0.125 },
224            mode: Mode::Chasing { speed: 4.5 },
225            waypoints: [Offset { x: 1.0 }, Offset { x: 2.0 }],
226            awake: true,
227        }
228    }
229
230    /// The `(label, value)` rows `value` becomes under `title`.
231    fn rows_of(title: &str, value: &dyn Reflect) -> Vec<(String, String)> {
232        let mut section = DebugSection::default();
233        ReflectedSection { title, value }.debug_section(&mut section);
234        assert_eq!(section.title(), title);
235        section
236            .rows()
237            .iter()
238            .map(|row| (row.label.clone(), row.value.clone()))
239            .collect()
240    }
241
242    fn pairs(expected: &[(&str, &str)]) -> Vec<(String, String)> {
243        expected
244            .iter()
245            .map(|&(label, value)| (label.to_owned(), value.to_owned()))
246            .collect()
247    }
248
249    #[test]
250    fn a_struct_becomes_a_row_per_leaf_labelled_by_its_path() {
251        assert_eq!(
252            rows_of("guards", &guard()),
253            pairs(&[
254                ("Hit points", "12"),
255                ("position", "1.000, 0.300, -2.500"),
256                ("offset.x", "0.125"),
257                ("mode", "Chasing"),
258                ("mode.speed", "4.500"),
259                ("waypoints.0.x", "1.000"),
260                ("waypoints.1.x", "2.000"),
261                ("awake", "true"),
262            ]),
263        );
264    }
265
266    #[test]
267    fn a_value_with_no_field_name_is_labelled_by_its_type() {
268        assert_eq!(rows_of("speed", &2.0f32), pairs(&[("f32", "2.000")]));
269        assert_eq!(
270            rows_of("tint", &[0.5f32, 0.25, 1.0]),
271            pairs(&[("[f32; 3]", "0.500, 0.250, 1.000")]),
272        );
273        assert_eq!(rows_of("mode", &Mode::Idle), pairs(&[("variant", "Idle")]));
274    }
275
276    /// The section reaches the panel's draw list like any other module's: the
277    /// title, then each label beside its value.
278    #[test]
279    fn a_reflected_section_is_drawn_in_the_panel() {
280        let atlas = FontAtlas::built_in();
281        let mut overlay = DebugOverlay::with_visible(true);
282        overlay.begin_frame();
283        overlay.add(&ReflectedSection {
284            title: "guards",
285            value: &guard(),
286        });
287
288        let mut dl = DrawList::new();
289        overlay.render(&mut dl, Vec2::new(1280.0, 720.0), &atlas);
290        let drawn: Vec<String> = dl
291            .commands()
292            .iter()
293            .filter_map(|command| match command {
294                DrawCommand::Text { text, .. } => Some(text.clone()),
295                _ => None,
296            })
297            .collect();
298        let at = drawn
299            .iter()
300            .position(|text| text == "guards")
301            .unwrap_or_else(|| panic!("the section's title: {drawn:?}"));
302        assert_eq!(
303            drawn[at + 1..at + 5],
304            ["Hit points", "12", "position", "1.000, 0.300, -2.500"],
305            "each label is followed by its value: {drawn:?}",
306        );
307    }
308}