1use core::fmt;
67use core::fmt::Write as _;
68use core::time::Duration;
69use std::cell::RefCell;
70use std::collections::VecDeque;
71
72use glam::Vec2;
73
74use crate::budget::BudgetStats;
75use crate::draw_list::DrawList;
76use crate::hud::Anchor;
77use crate::style::{Declaration, Sides};
78use crate::text::{FontAtlas, LINE_HEIGHT};
79use crate::tree::{Align, AvailableSpace, Length, LengthAuto, NodeKey, Ui};
80use crate::widget::{NATURAL_FONT_SIZE, PointerInput};
81
82mod reflected;
83
84pub use reflected::{REFLECTED_DECIMALS, ReflectedSection};
85
86#[derive(Debug, Clone, Default, PartialEq, Eq)]
92pub struct DebugRow {
93 pub label: String,
95 pub value: String,
97}
98
99#[derive(Debug, Clone, Default, PartialEq)]
102pub struct DebugGraph {
103 pub label: String,
105 pub bars: Vec<f32>,
107}
108
109#[derive(Debug, Clone, Default)]
117pub struct DebugSection {
118 title: String,
119 rows: Vec<DebugRow>,
120 used: usize,
122 graphs: Vec<DebugGraph>,
123 graphs_used: usize,
125}
126
127impl DebugSection {
128 #[must_use]
130 pub fn new(title: impl AsRef<str>) -> Self {
131 let mut section = Self::default();
132 section.set_title(title.as_ref());
133 section
134 }
135
136 pub fn set_title(&mut self, title: &str) {
138 self.title.clear();
139 self.title.push_str(title);
140 }
141
142 #[must_use]
144 pub fn title(&self) -> &str {
145 &self.title
146 }
147
148 pub fn row(&mut self, label: &str, value: fmt::Arguments<'_>) {
155 if self.used == self.rows.len() {
156 self.rows.push(DebugRow::default());
157 }
158 let row = &mut self.rows[self.used];
159 row.label.clear();
160 row.label.push_str(label);
161 row.value.clear();
162 let _ = row.value.write_fmt(value);
164 self.used += 1;
165 }
166
167 pub fn row_str(&mut self, label: &str, value: &str) {
169 self.row(label, format_args!("{value}"));
170 }
171
172 #[must_use]
174 pub fn rows(&self) -> &[DebugRow] {
175 &self.rows[..self.used]
176 }
177
178 pub fn graph(&mut self, label: &str, samples: impl IntoIterator<Item = f32>, scale: f32) {
185 if self.graphs_used == self.graphs.len() {
186 self.graphs.push(DebugGraph::default());
187 }
188 let graph = &mut self.graphs[self.graphs_used];
189 graph.label.clear();
190 graph.label.push_str(label);
191 graph.bars.clear();
192 graph.bars.extend(samples.into_iter().map(|sample| {
193 if scale > 0.0 {
194 (sample / scale).clamp(0.0, 1.0)
195 } else {
196 0.0
197 }
198 }));
199 self.graphs_used += 1;
200 }
201
202 #[must_use]
204 pub fn graphs(&self) -> &[DebugGraph] {
205 &self.graphs[..self.graphs_used]
206 }
207
208 #[must_use]
210 pub const fn is_empty(&self) -> bool {
211 self.used == 0 && self.graphs_used == 0
212 }
213
214 pub fn clear(&mut self) {
216 self.title.clear();
217 self.used = 0;
218 self.graphs_used = 0;
219 }
220}
221
222pub trait DebugModule {
228 fn debug_section(&self, out: &mut DebugSection);
230}
231
232pub const DEFAULT_FRAME_WINDOW: usize = 120;
242
243#[derive(Debug, Clone)]
258pub struct FrameStats {
259 window: usize,
260 samples: VecDeque<Duration>,
261 total: Duration,
264}
265
266impl Default for FrameStats {
267 fn default() -> Self {
268 Self::new()
269 }
270}
271
272impl FrameStats {
273 #[must_use]
275 pub fn new() -> Self {
276 Self::with_window(DEFAULT_FRAME_WINDOW)
277 }
278
279 #[must_use]
281 pub fn with_window(window: usize) -> Self {
282 let window = window.max(1);
283 Self {
284 window,
285 samples: VecDeque::with_capacity(window),
286 total: Duration::ZERO,
287 }
288 }
289
290 pub fn record(&mut self, dt: Duration) {
300 if dt.is_zero() {
301 return;
302 }
303 if self.samples.len() == self.window
304 && let Some(oldest) = self.samples.pop_front()
305 {
306 self.total -= oldest;
307 }
308 self.samples.push_back(dt);
309 self.total += dt;
310 }
311
312 #[must_use]
314 pub fn len(&self) -> usize {
315 self.samples.len()
316 }
317
318 #[must_use]
320 pub fn is_empty(&self) -> bool {
321 self.samples.is_empty()
322 }
323
324 #[must_use]
326 pub const fn window(&self) -> usize {
327 self.window
328 }
329
330 #[must_use]
332 pub const fn total(&self) -> Duration {
333 self.total
334 }
335
336 #[must_use]
338 pub fn mean(&self) -> Duration {
339 let count = u32::try_from(self.samples.len()).unwrap_or(u32::MAX);
340 if count == 0 {
341 Duration::ZERO
342 } else {
343 self.total / count
344 }
345 }
346
347 #[must_use]
352 pub fn fps(&self) -> f64 {
353 let seconds = self.total.as_secs_f64();
354 if self.samples.is_empty() || seconds <= 0.0 {
355 0.0
356 } else {
357 self.samples.len() as f64 / seconds
358 }
359 }
360
361 #[must_use]
363 pub fn last(&self) -> Option<Duration> {
364 self.samples.back().copied()
365 }
366
367 #[must_use]
369 pub fn best(&self) -> Option<Duration> {
370 self.samples.iter().min().copied()
371 }
372
373 #[must_use]
375 pub fn worst(&self) -> Option<Duration> {
376 self.samples.iter().max().copied()
377 }
378
379 pub fn clear(&mut self) {
381 self.samples.clear();
382 self.total = Duration::ZERO;
383 }
384}
385
386fn millis(duration: Duration) -> f64 {
388 duration.as_secs_f64() * 1_000.0
389}
390
391impl DebugModule for FrameStats {
392 fn debug_section(&self, out: &mut DebugSection) {
393 out.set_title("frame");
394 out.row("fps", format_args!("{:.1}", self.fps()));
395 out.row("avg", format_args!("{:.2} ms", millis(self.mean())));
396 out.row(
397 "last",
398 format_args!("{:.2} ms", millis(self.last().unwrap_or_default())),
399 );
400 out.row(
401 "best",
402 format_args!("{:.2} ms", millis(self.best().unwrap_or_default())),
403 );
404 out.row(
405 "worst",
406 format_args!("{:.2} ms", millis(self.worst().unwrap_or_default())),
407 );
408 out.row("window", format_args!("{}/{}", self.len(), self.window()));
409 }
410}
411
412#[derive(Debug, Clone, Copy, PartialEq)]
421pub struct DebugStyle {
422 pub bg: [f32; 4],
424 pub title: [f32; 4],
426 pub label: [f32; 4],
428 pub value: [f32; 4],
430 pub graph: [f32; 4],
432 pub font_size: f32,
434 pub padding: f32,
436 pub column_gap: f32,
438 pub section_gap: f32,
440}
441
442impl Default for DebugStyle {
443 fn default() -> Self {
444 Self {
445 bg: [0.04, 0.04, 0.07, 0.82],
446 title: [0.45, 0.85, 1.0, 1.0],
447 label: [0.72, 0.72, 0.78, 1.0],
448 value: [1.0, 1.0, 1.0, 1.0],
449 graph: [0.45, 0.85, 1.0, 0.9],
450 font_size: NATURAL_FONT_SIZE,
451 padding: 6.0,
452 column_gap: 10.0,
453 section_gap: 6.0,
454 }
455 }
456}
457
458#[derive(Debug, Clone)]
463pub struct DebugPanel {
464 visible: bool,
465 pub anchor: Anchor,
468 pub offset: Vec2,
470 pub style: DebugStyle,
472 sections: Vec<DebugSection>,
473 used: usize,
476}
477
478impl Default for DebugPanel {
479 fn default() -> Self {
480 Self::new()
481 }
482}
483
484impl DebugPanel {
485 #[must_use]
487 pub fn new() -> Self {
488 Self {
489 visible: false,
490 anchor: Anchor::TopRight,
491 offset: Vec2::splat(8.0),
492 style: DebugStyle::default(),
493 sections: Vec::new(),
494 used: 0,
495 }
496 }
497
498 #[must_use]
500 pub const fn is_visible(&self) -> bool {
501 self.visible
502 }
503
504 pub const fn set_visible(&mut self, visible: bool) {
509 self.visible = visible;
510 if !visible {
511 self.used = 0;
512 }
513 }
514
515 pub const fn toggle(&mut self) {
517 self.set_visible(!self.visible);
518 }
519
520 pub const fn begin_frame(&mut self) {
522 self.used = 0;
523 }
524
525 pub fn add(&mut self, module: &dyn DebugModule) {
530 if !self.visible {
531 return;
532 }
533 if self.used == self.sections.len() {
534 self.sections.push(DebugSection::default());
535 }
536 let section = &mut self.sections[self.used];
537 section.clear();
538 module.debug_section(section);
539 self.used += 1;
540 }
541
542 #[must_use]
544 pub fn sections(&self) -> &[DebugSection] {
545 &self.sections[..self.used]
546 }
547
548 #[must_use]
551 pub fn size(&self, atlas: &FontAtlas) -> Vec2 {
552 self.laid_out(atlas, |ui, panel| {
553 let (min, max) = ui.rect(panel).expect("laid out this frame");
554 max - min
555 })
556 .unwrap_or(Vec2::ZERO)
557 }
558
559 pub fn render(&self, dl: &mut DrawList, screen_size: Vec2, atlas: &FontAtlas) {
565 self.laid_out(atlas, |ui, panel| {
566 let (min, max) = ui.rect(panel).expect("laid out this frame");
567 let origin = self.anchor.position(screen_size, self.offset, max - min);
573 ui.layout(origin, AvailableSpace::MAX_CONTENT, atlas);
574 ui.emit(dl);
575 });
576 }
577
578 fn laid_out<R>(
593 &self,
594 atlas: &FontAtlas,
595 read: impl FnOnce(&mut Ui, NodeKey) -> R,
596 ) -> Option<R> {
597 if self.sections().is_empty() {
598 return None;
599 }
600 DEBUG_TREE.with(|tree| {
601 let mut ui = tree.borrow_mut();
602 ui.begin_frame(PointerInput::hovering(OFF_SCREEN));
603 let panel = self.build(&mut ui, atlas);
604 ui.layout(Vec2::ZERO, AvailableSpace::MAX_CONTENT, atlas);
605 Some(read(&mut ui, panel))
606 })
607 }
608
609 fn build(&self, ui: &mut Ui, atlas: &FontAtlas) -> NodeKey {
617 use Declaration as D;
618 let style = &self.style;
619 let scale = style.font_size / NATURAL_FONT_SIZE;
620 let mut label_width = 0.0f32;
621 for section in self.sections() {
622 let rows = section.rows().iter().map(|row| &row.label);
623 let graphs = section.graphs().iter().map(|graph| &graph.label);
624 for label in rows.chain(graphs) {
625 label_width = label_width.max(atlas.text_width(label, scale));
626 }
627 }
628
629 let panel = [
630 D::Padding(Sides::All, Length::Px(style.padding)),
631 D::RowGap(Length::Px(style.section_gap)),
632 D::Background(style.bg),
633 D::FontSize(style.font_size),
634 ];
635 let title = [D::Color(style.title)];
636 let label = [
637 D::Color(style.label),
638 D::MinWidth(LengthAuto::Px(label_width + style.column_gap)),
639 ];
640 let value = [D::Color(style.value)];
641 let graph_height = GRAPH_HEIGHT * scale;
642 let graph = [
643 D::Height(LengthAuto::Px(graph_height)),
644 D::AlignItems(Some(Align::FlexEnd)),
645 ];
646
647 ui.block("debug-panel", &panel, |ui| {
648 for (index, section) in self.sections().iter().enumerate() {
649 ui.block_keyed(index, ".debug-section", &[], |ui| {
650 ui.span(".debug-title", section.title(), &title);
651 for (row_index, row) in section.rows().iter().enumerate() {
652 ui.block_keyed(row_index, ".debug-row", &[], |ui| {
653 ui.span(".debug-label", row.label.as_str(), &label);
654 ui.span(".debug-value", row.value.as_str(), &value);
655 });
656 }
657 for (graph_index, plotted) in section.graphs().iter().enumerate() {
658 let key = (section.rows().len(), graph_index);
659 ui.block_keyed(key, ".debug-row", &[], |ui| {
660 ui.span(".debug-label", plotted.label.as_str(), &label);
661 ui.block(".debug-graph", &graph, |ui| {
662 for (bar_index, bar) in plotted.bars.iter().enumerate() {
663 let height = (bar * graph_height).max(MIN_BAR_HEIGHT);
664 let bar = [
665 D::Width(LengthAuto::Px(GRAPH_BAR_WIDTH * scale)),
666 D::Height(LengthAuto::Px(height)),
667 D::Background(style.graph),
668 ];
669 ui.block_keyed(bar_index, ".debug-bar", &bar, |_| {});
670 }
671 });
672 });
673 }
674 });
675 }
676 })
677 .key
678 }
679}
680
681thread_local! {
682 static DEBUG_TREE: RefCell<Ui> = RefCell::new(Ui::new());
685}
686
687const OFF_SCREEN: Vec2 = Vec2::splat(-1.0);
690
691pub const GRAPH_HEIGHT: f32 = LINE_HEIGHT;
694
695pub const GRAPH_BAR_WIDTH: f32 = 2.0;
698
699pub const MIN_BAR_HEIGHT: f32 = 1.0;
702
703#[derive(Debug, Clone, Default)]
717pub struct DebugOverlay {
718 pub panel: DebugPanel,
721 pub frame: FrameStats,
723 pub budget: BudgetStats,
730}
731
732impl DebugOverlay {
733 #[must_use]
735 pub fn new() -> Self {
736 Self::default()
737 }
738
739 #[must_use]
744 pub fn with_visible(visible: bool) -> Self {
745 let mut overlay = Self::new();
746 overlay.panel.set_visible(visible);
747 overlay
748 }
749
750 #[must_use]
752 pub const fn is_visible(&self) -> bool {
753 self.panel.is_visible()
754 }
755
756 pub const fn set_visible(&mut self, visible: bool) {
758 self.panel.set_visible(visible);
759 }
760
761 pub const fn toggle(&mut self) {
763 self.panel.toggle();
764 }
765
766 pub fn record(&mut self, dt: Duration) {
768 self.frame.record(dt);
769 }
770
771 pub fn begin_frame(&mut self) {
782 self.panel.begin_frame();
783 self.panel.add(&self.frame);
784 if self.budget.has_samples() {
785 self.panel.add(&self.budget);
786 }
787 }
788
789 pub fn add(&mut self, module: &dyn DebugModule) {
791 self.panel.add(module);
792 }
793
794 pub fn render(&self, dl: &mut DrawList, screen_size: Vec2, atlas: &FontAtlas) {
796 self.panel.render(dl, screen_size, atlas);
797 }
798}
799
800#[cfg(test)]
805mod tests {
806 use super::*;
807 use crate::draw_list::DrawCommand;
808
809 fn ms(millis: u64) -> Duration {
810 Duration::from_millis(millis)
811 }
812
813 fn screen() -> Vec2 {
814 Vec2::new(1280.0, 720.0)
815 }
816
817 fn texts(dl: &DrawList) -> Vec<String> {
819 dl.commands()
820 .iter()
821 .filter_map(|command| match command {
822 DrawCommand::Text { text, .. } => Some(text.clone()),
823 _ => None,
824 })
825 .collect()
826 }
827
828 struct Fake {
830 title: &'static str,
831 rows: &'static [(&'static str, &'static str)],
832 }
833
834 impl DebugModule for Fake {
835 fn debug_section(&self, out: &mut DebugSection) {
836 out.set_title(self.title);
837 for (label, value) in self.rows {
838 out.row_str(label, value);
839 }
840 }
841 }
842
843 fn shown() -> DebugPanel {
844 let mut panel = DebugPanel::new();
845 panel.set_visible(true);
846 panel.begin_frame();
847 panel
848 }
849
850 #[test]
855 fn fps_is_frames_over_elapsed_not_the_mean_of_instantaneous_rates() {
856 let mut stats = FrameStats::new();
857 stats.record(ms(10));
858 stats.record(ms(30));
859 assert_eq!(stats.len(), 2);
860 assert_eq!(stats.total(), ms(40));
861 assert_eq!(stats.mean(), ms(20));
862 assert!(
863 (stats.fps() - 50.0).abs() < 1e-9,
864 "expected 50 fps, got {}",
865 stats.fps()
866 );
867 assert_eq!(stats.best(), Some(ms(10)));
868 assert_eq!(stats.worst(), Some(ms(30)));
869 assert_eq!(stats.last(), Some(ms(30)));
870 }
871
872 #[test]
875 fn a_steady_sequence_reports_its_own_rate() {
876 let mut stats = FrameStats::new();
877 let step = Duration::from_nanos(15_625_000); for _ in 0..16 {
879 stats.record(step);
880 }
881 assert_eq!(stats.mean(), step);
882 assert!((stats.fps() - 64.0).abs() < 1e-9, "got {}", stats.fps());
883 assert_eq!(stats.best(), Some(step));
884 assert_eq!(stats.worst(), Some(step));
885 }
886
887 #[test]
892 fn the_first_frames_zero_delta_is_not_a_sample_and_fps_is_not_infinite() {
893 let mut stats = FrameStats::new();
894 stats.record(Duration::ZERO);
895 assert!(stats.is_empty(), "a zero-length interval is not a frame");
896 assert_eq!(stats.fps(), 0.0);
897 assert!(stats.fps().is_finite());
898 assert_eq!(stats.mean(), Duration::ZERO);
899 assert_eq!(stats.last(), None);
900
901 let mut section = DebugSection::default();
903 stats.debug_section(&mut section);
904 for row in section.rows() {
905 assert!(
906 !row.value.contains("inf") && !row.value.contains("NaN"),
907 "{}: {}",
908 row.label,
909 row.value
910 );
911 }
912 }
913
914 #[test]
917 fn a_stall_shows_in_the_worst_frame_and_moves_the_average() {
918 let mut stats = FrameStats::new();
919 for _ in 0..60 {
920 stats.record(ms(16));
921 }
922 let smooth = stats.mean();
923 stats.record(ms(500));
924 assert_eq!(stats.worst(), Some(ms(500)));
925 assert_eq!(stats.best(), Some(ms(16)));
926 assert_eq!(stats.last(), Some(ms(500)));
927 assert_eq!(stats.total(), ms(1460));
929 assert_eq!(stats.mean(), ms(1460) / 61);
930 assert!(
931 stats.mean() > smooth,
932 "the stall must move the average: {smooth:?} → {:?}",
933 stats.mean()
934 );
935 assert!(
936 (stats.fps() - 61.0 / 1.46).abs() < 1e-9,
937 "got {}",
938 stats.fps()
939 );
940 }
941
942 #[test]
945 fn the_window_evicts_and_the_running_total_matches_the_samples() {
946 let mut stats = FrameStats::with_window(4);
947 stats.record(ms(500));
948 for _ in 0..4 {
949 stats.record(ms(10));
950 }
951 assert_eq!(stats.len(), 4, "the window holds four");
952 assert_eq!(stats.total(), ms(40), "the stall has scrolled off");
953 assert_eq!(stats.worst(), Some(ms(10)));
954 assert!((stats.fps() - 100.0).abs() < 1e-9, "got {}", stats.fps());
955 }
956
957 #[test]
959 fn a_zero_window_is_clamped_to_one_frame() {
960 let mut stats = FrameStats::with_window(0);
961 assert_eq!(stats.window(), 1);
962 stats.record(ms(10));
963 stats.record(ms(20));
964 assert_eq!(stats.len(), 1);
965 assert_eq!(stats.total(), ms(20));
966 }
967
968 #[test]
976 fn a_panel_with_only_the_frame_module_draws_the_frame_numbers() {
977 let atlas = FontAtlas::built_in();
978 let mut overlay = DebugOverlay::with_visible(true);
979 overlay.record(ms(20));
980 overlay.record(ms(20));
981 overlay.begin_frame();
982
983 let mut dl = DrawList::new();
984 overlay.render(&mut dl, screen(), &atlas);
985
986 let drawn = texts(&dl);
987 assert_eq!(
988 drawn.first().map(String::as_str),
989 Some("frame"),
990 "the section heading: {drawn:?}"
991 );
992 assert!(drawn.iter().any(|t| t == "fps"), "{drawn:?}");
993 assert!(
994 drawn.iter().any(|t| t == "50.0"),
995 "two 20 ms frames is 50 fps: {drawn:?}"
996 );
997 assert!(
998 drawn.iter().any(|t| t == "20.00 ms"),
999 "the mean must be drawn: {drawn:?}"
1000 );
1001 assert!(
1002 dl.commands()
1003 .iter()
1004 .any(|c| matches!(c, DrawCommand::Rect { .. })),
1005 "the panel draws its own background"
1006 );
1007 assert_eq!(overlay.panel.sections().len(), 1, "no network module");
1008 }
1009
1010 #[test]
1018 fn the_budget_section_appears_once_it_has_a_sample_and_carries_its_numbers() {
1019 use crate::budget::MIN_PERCENTILE_SAMPLES;
1020
1021 let atlas = FontAtlas::built_in();
1022 let mut overlay = DebugOverlay::with_visible(true);
1023 overlay.record(ms(16));
1024
1025 overlay.begin_frame();
1027 assert_eq!(
1028 overlay
1029 .panel
1030 .sections()
1031 .iter()
1032 .map(DebugSection::title)
1033 .collect::<Vec<_>>(),
1034 ["frame"],
1035 "a run with no trace and no GPU timers has no budget to report"
1036 );
1037
1038 for frame in 0..MIN_PERCENTILE_SAMPLES as u64 {
1039 overlay.budget.record_cpu(ms(4));
1040 overlay.budget.record_gpu(frame, ms(11));
1041 }
1042 overlay.begin_frame();
1043 let mut dl = DrawList::new();
1044 overlay.render(&mut dl, screen(), &atlas);
1045
1046 let drawn = texts(&dl);
1047 let start = drawn
1048 .iter()
1049 .position(|text| text == "budget")
1050 .unwrap_or_else(|| panic!("no budget section: {drawn:?}"));
1051 assert_eq!(
1052 &drawn[start..],
1053 [
1054 "budget",
1055 "cpu p50/p95",
1056 "4.00 / 4.00 ms",
1057 "gpu elapsed p50/p95",
1058 "11.00 / 11.00 ms",
1059 "bound",
1060 "gpu",
1061 "gpu frame",
1062 "19",
1063 ],
1064 );
1065 }
1066
1067 #[test]
1070 fn two_modules_render_both_sections_in_the_order_added() {
1071 let atlas = FontAtlas::built_in();
1072 let first = Fake {
1073 title: "alpha",
1074 rows: &[("a1", "one"), ("a2", "two")],
1075 };
1076 let second = Fake {
1077 title: "beta",
1078 rows: &[("b1", "three")],
1079 };
1080
1081 let mut panel = shown();
1082 panel.add(&first);
1083 panel.add(&second);
1084
1085 assert_eq!(
1086 panel
1087 .sections()
1088 .iter()
1089 .map(DebugSection::title)
1090 .collect::<Vec<_>>(),
1091 ["alpha", "beta"],
1092 );
1093
1094 let mut dl = DrawList::new();
1095 panel.render(&mut dl, screen(), &atlas);
1096 assert_eq!(
1097 texts(&dl),
1098 ["alpha", "a1", "one", "a2", "two", "beta", "b1", "three"],
1099 "titles and rows, in order",
1100 );
1101
1102 let mut swapped = shown();
1104 swapped.add(&second);
1105 swapped.add(&first);
1106 let mut other = DrawList::new();
1107 swapped.render(&mut other, screen(), &atlas);
1108 assert_eq!(
1109 texts(&other),
1110 ["beta", "b1", "three", "alpha", "a1", "one", "a2", "two"],
1111 );
1112 }
1113
1114 #[test]
1117 fn a_frame_with_fewer_modules_does_not_render_the_previous_frames() {
1118 let atlas = FontAtlas::built_in();
1119 let first = Fake {
1120 title: "alpha",
1121 rows: &[("a1", "one")],
1122 };
1123 let second = Fake {
1124 title: "beta",
1125 rows: &[("b1", "two")],
1126 };
1127
1128 let mut panel = shown();
1129 panel.add(&first);
1130 panel.add(&second);
1131 assert_eq!(panel.sections().len(), 2);
1132
1133 panel.begin_frame();
1134 panel.add(&first);
1135 let mut dl = DrawList::new();
1136 panel.render(&mut dl, screen(), &atlas);
1137 let drawn = texts(&dl);
1138 assert_eq!(panel.sections().len(), 1);
1139 assert!(
1140 !drawn.iter().any(|t| t == "beta"),
1141 "the dropped module is gone: {drawn:?}"
1142 );
1143 }
1144
1145 #[test]
1147 fn a_panel_with_no_sections_at_all_draws_nothing() {
1148 let atlas = FontAtlas::built_in();
1149 let panel = shown();
1150 let mut dl = DrawList::new();
1151 panel.render(&mut dl, screen(), &atlas);
1152 assert!(dl.is_empty(), "{:?}", dl.commands());
1153 assert_eq!(panel.size(&atlas), Vec2::ZERO);
1154 }
1155
1156 #[test]
1162 fn toggling_the_panel_changes_the_draw_list() {
1163 let atlas = FontAtlas::built_in();
1164 let module = Fake {
1165 title: "alpha",
1166 rows: &[("a1", "one")],
1167 };
1168 let mut panel = DebugPanel::new();
1169
1170 let draw = |panel: &mut DebugPanel| {
1171 panel.begin_frame();
1172 panel.add(&module);
1173 let mut dl = DrawList::new();
1174 panel.render(&mut dl, screen(), &atlas);
1175 dl
1176 };
1177
1178 let off = draw(&mut panel);
1180 assert!(off.is_empty(), "hidden: {:?}", off.commands());
1181 assert!(panel.sections().is_empty(), "hidden panels gather nothing");
1182
1183 panel.toggle();
1185 let on = draw(&mut panel);
1186 assert!(texts(&on).iter().any(|t| t == "alpha"), "{:?}", texts(&on));
1187
1188 panel.toggle();
1190 let off_again = draw(&mut panel);
1191 assert!(off_again.is_empty(), "{:?}", off_again.commands());
1192 }
1193
1194 #[test]
1197 fn hiding_forgets_the_sections_it_had() {
1198 let atlas = FontAtlas::built_in();
1199 let mut panel = shown();
1200 panel.add(&Fake {
1201 title: "alpha",
1202 rows: &[("a1", "one")],
1203 });
1204 assert_eq!(panel.sections().len(), 1);
1205
1206 panel.set_visible(false);
1207 panel.set_visible(true);
1208 assert!(panel.sections().is_empty());
1209 let mut dl = DrawList::new();
1210 panel.render(&mut dl, screen(), &atlas);
1211 assert!(dl.is_empty(), "{:?}", dl.commands());
1212 }
1213
1214 #[test]
1219 fn the_panel_follows_the_screen_across_a_resize() {
1220 let atlas = FontAtlas::built_in();
1221 let mut panel = shown();
1222 panel.add(&Fake {
1223 title: "alpha",
1224 rows: &[("a1", "one")],
1225 });
1226 let size = panel.size(&atlas);
1227
1228 let bounds = |screen: Vec2| {
1229 let mut dl = DrawList::new();
1230 panel.render(&mut dl, screen, &atlas);
1231 match dl.commands().first() {
1232 Some(DrawCommand::Rect { min, max, .. }) => (*min, *max),
1233 other => panic!("expected the panel background, got {other:?}"),
1234 }
1235 };
1236
1237 for screen in [Vec2::new(1280.0, 720.0), Vec2::new(640.0, 360.0)] {
1238 let (min, max) = bounds(screen);
1239 assert_eq!(max - min, size, "the panel is the same size either way");
1240 assert_eq!(
1241 max,
1242 Vec2::new(screen.x - panel.offset.x, min.y + size.y),
1243 "the right edge stays {}px in from the right of {screen:?}",
1244 panel.offset.x,
1245 );
1246 assert!(
1247 min.x >= 0.0 && max.x <= screen.x,
1248 "off-screen: {min:?}..{max:?}"
1249 );
1250 }
1251
1252 assert_ne!(
1255 bounds(Vec2::new(1280.0, 720.0)).0,
1256 bounds(Vec2::new(640.0, 360.0)).0
1257 );
1258 }
1259
1260 #[test]
1263 fn a_resize_does_not_reset_the_frame_window() {
1264 let mut overlay = DebugOverlay::with_visible(true);
1265 for _ in 0..10 {
1266 overlay.record(ms(16));
1267 }
1268 overlay.record(ms(120)); assert_eq!(overlay.frame.len(), 11);
1270 assert_eq!(overlay.frame.worst(), Some(ms(120)));
1271 assert_eq!(overlay.frame.best(), Some(ms(16)));
1272 }
1273
1274 #[test]
1276 fn the_value_column_starts_past_the_longest_label() {
1277 let atlas = FontAtlas::built_in();
1278 let mut panel = shown();
1279 panel.add(&Fake {
1280 title: "x",
1281 rows: &[("short", "1"), ("a-much-longer-label", "2")],
1282 });
1283 let mut dl = DrawList::new();
1284 panel.render(&mut dl, screen(), &atlas);
1285
1286 let scale = panel.style.font_size / NATURAL_FONT_SIZE;
1287 let widest = atlas.text_width("a-much-longer-label", scale);
1288 let mut label_x = None;
1289 let mut checked = 0;
1294 for command in dl.commands() {
1295 if let DrawCommand::Text { pos, text, .. } = command {
1296 match text.as_str() {
1297 "short" | "a-much-longer-label" => label_x = Some(pos.x),
1298 "1" | "2" => {
1299 let start = label_x.expect("a label precedes its value");
1300 assert!(
1301 pos.x >= start + widest,
1302 "value at {} overlaps a {widest}px label at {start}",
1303 pos.x,
1304 );
1305 checked += 1;
1306 }
1307 _ => {}
1308 }
1309 }
1310 }
1311 assert_eq!(
1312 checked,
1313 2,
1314 "both rows' values must have been placed and checked, in {:?}",
1315 dl.commands()
1316 );
1317 }
1318
1319 #[test]
1321 fn a_section_reuses_its_row_allocations() {
1322 let mut section = DebugSection::new("frame");
1323 section.row("fps", format_args!("{:.1}", 59.94));
1324 section.row("avg", format_args!("{:.2} ms", 16.68));
1325 assert_eq!(section.rows().len(), 2);
1326 assert_eq!(section.rows()[0].value, "59.9");
1327 assert_eq!(section.rows.len(), 2, "two row slots exist");
1331
1332 section.clear();
1333 assert!(section.is_empty(), "no live rows");
1334 assert_eq!(section.title(), "");
1335 assert_eq!(
1336 section.rows.len(),
1337 2,
1338 "clear keeps the slots — that is the whole point of it",
1339 );
1340
1341 section.row("fps", format_args!("{:.1}", 30.0));
1342 assert_eq!(section.rows().len(), 1, "one live row");
1343 assert_eq!(section.rows()[0].value, "30.0");
1344 assert_eq!(section.rows.len(), 2, "and the second slot is still there");
1345 }
1346
1347 fn arithmetic_render(
1350 panel: &DebugPanel,
1351 dl: &mut DrawList,
1352 screen_size: Vec2,
1353 atlas: &FontAtlas,
1354 ) {
1355 use crate::text::LINE_HEIGHT;
1356
1357 let sections = panel.sections();
1358 if sections.is_empty() {
1359 return;
1360 }
1361 let style = &panel.style;
1362 let scale = style.font_size / NATURAL_FONT_SIZE;
1363 let line_height = LINE_HEIGHT * scale;
1364
1365 let mut label_width = 0.0f32;
1366 let mut value_width = 0.0f32;
1367 let mut title_width = 0.0f32;
1368 let mut lines = 0.0f32;
1369 for section in sections {
1370 title_width = title_width.max(atlas.text_width(section.title(), scale));
1371 lines += 1.0;
1372 for row in section.rows() {
1373 label_width = label_width.max(atlas.text_width(&row.label, scale));
1374 value_width = value_width.max(atlas.text_width(&row.value, scale));
1375 lines += 1.0;
1376 }
1377 }
1378 let value_column = label_width + style.column_gap;
1379 let content_width = title_width.max(value_column + value_width);
1380 let gaps = (sections.len() - 1) as f32 * style.section_gap;
1381 let content_height = lines * line_height + gaps;
1382 let size = Vec2::new(content_width, content_height) + Vec2::splat(style.padding * 2.0);
1383
1384 let origin = panel.anchor.position(screen_size, panel.offset, size);
1385 dl.rect(origin, origin + size, style.bg);
1386 let mut cursor = origin + Vec2::splat(style.padding);
1387 for section in sections {
1388 dl.text(cursor, section.title(), style.title, style.font_size);
1389 cursor.y += line_height;
1390 for row in section.rows() {
1391 dl.text(cursor, row.label.as_str(), style.label, style.font_size);
1392 dl.text(
1393 Vec2::new(cursor.x + value_column, cursor.y),
1394 row.value.as_str(),
1395 style.value,
1396 style.font_size,
1397 );
1398 cursor.y += line_height;
1399 }
1400 cursor.y += style.section_gap;
1401 }
1402 }
1403
1404 fn rendering(dl: &DrawList) -> Vec<String> {
1408 dl.commands()
1409 .iter()
1410 .zip(dl.clips())
1411 .map(|(command, clip)| format!("{command:?} under {clip:?}"))
1412 .collect()
1413 }
1414
1415 #[test]
1426 fn the_tree_draws_the_panel_exactly_where_the_arithmetic_did() {
1427 let atlas = FontAtlas::built_in();
1428 let modules = [
1429 Fake {
1430 title: "frame",
1431 rows: &[("fps", "59.9"), ("avg", "16.68 ms"), ("window", "120/120")],
1432 },
1433 Fake {
1434 title: "budget",
1435 rows: &[("cpu p50/p95", "4.00 / 4.00 ms"), ("bound", "gpu")],
1436 },
1437 Fake {
1438 title: "a-much-longer-section-title",
1439 rows: &[("", ""), ("x", "1")],
1440 },
1441 ];
1442 for anchor in [
1443 Anchor::TopLeft,
1444 Anchor::TopRight,
1445 Anchor::BottomLeft,
1446 Anchor::BottomRight,
1447 Anchor::Center,
1448 ] {
1449 for count in 1..=modules.len() {
1450 let mut panel = shown();
1451 panel.anchor = anchor;
1452 for module in &modules[..count] {
1453 panel.add(module);
1454 }
1455 for screen in [
1456 Vec2::new(960.0, 720.0),
1457 Vec2::new(800.0, 600.0),
1458 Vec2::new(1920.0, 1080.0),
1459 Vec2::new(1440.0, 400.0),
1460 Vec2::new(600.0, 900.0),
1461 ] {
1462 let mut tree = DrawList::new();
1463 panel.render(&mut tree, screen, &atlas);
1464 let mut arithmetic = DrawList::new();
1465 arithmetic_render(&panel, &mut arithmetic, screen, &atlas);
1466 assert_eq!(
1467 rendering(&tree),
1468 rendering(&arithmetic),
1469 "{anchor:?}, {count} sections, {screen:?}",
1470 );
1471 assert!(
1472 !tree.is_empty(),
1473 "the panel drew nothing, so this proves nothing",
1474 );
1475 }
1476 }
1477 }
1478 }
1479
1480 #[test]
1483 fn the_trees_panel_is_the_size_the_arithmetic_measured() {
1484 let atlas = FontAtlas::built_in();
1485 let mut panel = shown();
1486 panel.add(&Fake {
1487 title: "frame",
1488 rows: &[("fps", "59.9"), ("a-much-longer-label", "16.68 ms")],
1489 });
1490 panel.add(&Fake {
1491 title: "budget",
1492 rows: &[("bound", "gpu")],
1493 });
1494
1495 let mut arithmetic = DrawList::new();
1496 arithmetic_render(&panel, &mut arithmetic, Vec2::ZERO, &atlas);
1497 let measured = match arithmetic.commands().first() {
1498 Some(DrawCommand::Rect { min, max, .. }) => *max - *min,
1499 other => panic!("expected the panel background, got {other:?}"),
1500 };
1501 assert_eq!(panel.size(&atlas), measured);
1502 assert_ne!(measured, Vec2::ZERO, "a zero panel proves nothing");
1503 }
1504
1505 struct Plot {
1509 samples: &'static [f32],
1510 scale: f32,
1511 }
1512
1513 impl DebugModule for Plot {
1514 fn debug_section(&self, out: &mut DebugSection) {
1515 out.set_title("net");
1516 out.row_str("rtt", "12.0 ms");
1517 out.graph("rtt graph", self.samples.iter().copied(), self.scale);
1518 }
1519 }
1520
1521 fn bars(dl: &DrawList, colour: [f32; 4]) -> Vec<(Vec2, Vec2)> {
1523 dl.commands()
1524 .iter()
1525 .filter_map(|command| match command {
1526 DrawCommand::Rect { min, max, color } if *color == colour => Some((*min, *max)),
1527 _ => None,
1528 })
1529 .collect()
1530 }
1531
1532 #[test]
1536 fn a_graph_draws_a_bar_per_sample_scaled_to_its_height() {
1537 let atlas = FontAtlas::built_in();
1538 let mut panel = shown();
1539 panel.add(&Plot {
1540 samples: &[0.0, 5.0, 10.0, 40.0],
1541 scale: 20.0,
1542 });
1543 let mut dl = DrawList::new();
1544 panel.render(&mut dl, screen(), &atlas);
1545
1546 let drawn = bars(&dl, panel.style.graph);
1547 let heights: Vec<f32> = drawn.iter().map(|(min, max)| max.y - min.y).collect();
1548 assert_eq!(
1549 heights,
1550 [
1551 MIN_BAR_HEIGHT,
1552 GRAPH_HEIGHT / 4.0,
1553 GRAPH_HEIGHT / 2.0,
1554 GRAPH_HEIGHT
1555 ],
1556 "0 is the baseline tick, 5 and 10 of 20 a quarter and a half, 40 clamped full",
1557 );
1558 for (min, max) in &drawn {
1559 assert_eq!(max.x - min.x, GRAPH_BAR_WIDTH);
1560 assert_eq!(max.y, drawn[0].1.y, "every bar stands on one baseline");
1561 }
1562 for pair in drawn.windows(2) {
1563 assert_eq!(pair[1].0.x, pair[0].1.x, "oldest first, side by side");
1564 }
1565 assert!(
1566 texts(&dl).iter().any(|text| text == "rtt graph"),
1567 "the graph's label is drawn: {:?}",
1568 texts(&dl)
1569 );
1570 }
1571
1572 #[test]
1575 fn a_graph_with_no_scale_draws_its_bars_empty() {
1576 let mut section = DebugSection::new("net");
1577 section.graph("rtt graph", [3.0, f32::MAX], 0.0);
1578 assert_eq!(section.graphs()[0].bars, [0.0, 0.0]);
1579 }
1580
1581 #[test]
1585 fn a_graph_label_counts_toward_the_value_column() {
1586 let atlas = FontAtlas::built_in();
1587 let mut panel = shown();
1588 panel.add(&Plot {
1589 samples: &[1.0],
1590 scale: 1.0,
1591 });
1592 let mut dl = DrawList::new();
1593 panel.render(&mut dl, screen(), &atlas);
1594 let scale = panel.style.font_size / NATURAL_FONT_SIZE;
1595 let widest = atlas.text_width("rtt graph", scale);
1596 let label_x = dl
1597 .commands()
1598 .iter()
1599 .find_map(|command| match command {
1600 DrawCommand::Text { pos, text, .. } if text == "rtt" => Some(pos.x),
1601 _ => None,
1602 })
1603 .expect("the row's label is drawn");
1604 let value_x = dl
1605 .commands()
1606 .iter()
1607 .find_map(|command| match command {
1608 DrawCommand::Text { pos, text, .. } if text == "12.0 ms" => Some(pos.x),
1609 _ => None,
1610 })
1611 .expect("the row's value is drawn");
1612 assert!(
1613 value_x >= label_x + widest,
1614 "the value at {value_x} sits under the {widest}px graph label at {label_x}",
1615 );
1616 let (bar_min, _) = bars(&dl, panel.style.graph)[0];
1617 assert_eq!(bar_min.x, value_x, "the bars start in the value column");
1618 }
1619
1620 #[test]
1623 fn clearing_a_section_drops_its_graphs() {
1624 let mut section = DebugSection::new("net");
1625 section.graph("a", [1.0], 1.0);
1626 assert!(!section.is_empty(), "a graph alone is something to draw");
1627 section.clear();
1628 assert!(section.graphs().is_empty());
1629 assert!(section.is_empty());
1630 section.graph("b", [0.5, 0.25], 1.0);
1631 assert_eq!(
1632 section.graphs(),
1633 [DebugGraph {
1634 label: "b".to_owned(),
1635 bars: vec![0.5, 0.25],
1636 }]
1637 );
1638 }
1639
1640 #[test]
1641 fn the_overlay_starts_hidden_unless_asked() {
1642 assert!(!DebugOverlay::new().is_visible());
1643 assert!(DebugOverlay::with_visible(true).is_visible());
1644 let mut overlay = DebugOverlay::with_visible(true);
1645 overlay.toggle();
1646 assert!(!overlay.is_visible());
1647 overlay.set_visible(true);
1648 assert!(overlay.is_visible());
1649 }
1650
1651 #[test]
1652 fn debug_format_covers_the_public_types() {
1653 let overlay = DebugOverlay::with_visible(true);
1654 let text = format!("{overlay:?}");
1655 assert!(text.contains("panel"), "{text}");
1656 assert!(text.contains("visible"), "{text}");
1657 assert_eq!(
1658 format!("{:?}", DebugRow::default()),
1659 "DebugRow { label: \"\", value: \"\" }"
1660 );
1661 }
1662}