BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-pre / src / debug_overlay.rs

debug_overlay.rs

debug_overlay.rs 14.9 KiB Download Raw
1//! A developer overlay that paints frame-time statistics directly into the
2//! scene, bypassing layout, text, and view invalidation entirely (to avoid
3//! infinitely triggering new frames).
4
5use crate::{
6 BorderStyle, Bounds, ContentMask, Corners, Edges, Hsla, Pixels, Quad, ScaledPixels, Scene,
7 Size, point, rgba, size, transparent_black,
8};
9use std::{collections::VecDeque, time::Duration};
10
11#[allow(missing_docs)]
12#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
13pub enum DebugFrameOverlayMode {
14 #[default]
15 Hidden,
16 Minimal,
17 Full,
18}
19
20impl DebugFrameOverlayMode {
21 /// Returns the next mode in the Hidden → FrameTime → Detailed cycle.
22 pub fn next(self) -> Self {
23 match self {
24 Self::Hidden => Self::Minimal,
25 Self::Minimal => Self::Full,
26 Self::Full => Self::Hidden,
27 }
28 }
29}
30
31/// The number of most recent draw durations retained for percentile statistics.
32const MAX_SAMPLES: usize = 1000;
33
34const GLYPH_WIDTH: usize = 5;
35const GLYPH_HEIGHT: usize = 7;
36/// Glyph advance and line advance, in font cells.
37const CHAR_ADVANCE: f32 = (GLYPH_WIDTH + 1) as f32;
38const LINE_ADVANCE: f32 = (GLYPH_HEIGHT + 2) as f32;
39/// Padding between the panel edge and the text, in font cells.
40const PANEL_PADDING: f32 = 2.0;
41/// Margin between the panel and the window corner, in font cells.
42const PANEL_MARGIN: f32 = 4.0;
43/// Side of one square font cell, in logical pixels.
44const CELL_SIZE: f32 = 2.0;
45
46fn text_color() -> Hsla {
47 rgba(0x33ff33ff).into()
48}
49
50fn panel_color() -> Hsla {
51 rgba(0x000000aa).into()
52}
53
54pub(crate) struct DebugFrameOverlay {
55 mode: DebugFrameOverlayMode,
56 draw_durations: VecDeque<Duration>,
57 total_frame_count: u64,
58}
59
60impl DebugFrameOverlay {
61 pub(crate) fn new() -> Self {
62 Self {
63 mode: DebugFrameOverlayMode::default(),
64 draw_durations: VecDeque::new(),
65 total_frame_count: 0,
66 }
67 }
68
69 pub(crate) fn mode(&self) -> DebugFrameOverlayMode {
70 self.mode
71 }
72
73 pub(crate) fn set_mode(&mut self, mode: DebugFrameOverlayMode) {
74 self.mode = mode;
75 }
76
77 /// Clears the draw-duration samples, restarting the percentile window.
78 /// The total frame count is left untouched.
79 pub(crate) fn reset_stats(&mut self) {
80 self.draw_durations.clear();
81 }
82
83 pub(crate) fn is_enabled(&self) -> bool {
84 self.mode != DebugFrameOverlayMode::Hidden
85 }
86
87 pub(crate) fn record_frame(&mut self, draw_duration: Duration) {
88 self.total_frame_count += 1;
89 if self.draw_durations.len() >= MAX_SAMPLES {
90 self.draw_durations.pop_front();
91 }
92 self.draw_durations.push_back(draw_duration);
93 }
94
95 pub(crate) fn paint(&self, scene: &mut Scene, viewport_size: Size<Pixels>, scale_factor: f32) {
96 if !self.is_enabled() {
97 return;
98 }
99
100 let lines = self.lines();
101 let max_line_chars = lines.iter().map(|line| line.len()).max().unwrap_or(0);
102 // Ensure at least one physical pixel per cell so the text stays legible
103 // at fractional downscale factors.
104 let cell = (CELL_SIZE * scale_factor).max(1.0);
105
106 let panel_width = cell * (max_line_chars as f32 * CHAR_ADVANCE + 2.0 * PANEL_PADDING);
107 let panel_height = cell * (lines.len() as f32 * LINE_ADVANCE + 2.0 * PANEL_PADDING);
108 let viewport = viewport_size.scale(scale_factor);
109 let panel_left = viewport.width.0 - panel_width - cell * PANEL_MARGIN;
110 let panel_top = cell * PANEL_MARGIN;
111
112 let content_mask = ContentMask {
113 bounds: Bounds {
114 origin: point(ScaledPixels(0.), ScaledPixels(0.)),
115 size: viewport,
116 },
117 };
118
119 scene.insert_primitive(solid_quad(
120 scaled_bounds(panel_left, panel_top, panel_width, panel_height),
121 &content_mask,
122 panel_color(),
123 ));
124
125 let text_color = text_color();
126 for (line_index, line) in lines.iter().enumerate() {
127 let line_top = panel_top + cell * (PANEL_PADDING + line_index as f32 * LINE_ADVANCE);
128 for (char_index, character) in line.chars().enumerate() {
129 let Some(rows) = glyph(character) else {
130 continue;
131 };
132 let glyph_left =
133 panel_left + cell * (PANEL_PADDING + char_index as f32 * CHAR_ADVANCE);
134 for (row_index, row) in rows.iter().enumerate() {
135 let row_top = line_top + cell * row_index as f32;
136 // Merge horizontal runs of lit cells into single quads.
137 let mut column = 0;
138 while column < GLYPH_WIDTH {
139 if row & (1 << (GLYPH_WIDTH - 1 - column)) == 0 {
140 column += 1;
141 continue;
142 }
143 let run_start = column;
144 while column < GLYPH_WIDTH && row & (1 << (GLYPH_WIDTH - 1 - column)) != 0 {
145 column += 1;
146 }
147 scene.insert_primitive(solid_quad(
148 scaled_bounds(
149 glyph_left + cell * run_start as f32,
150 row_top,
151 cell * (column - run_start) as f32,
152 cell,
153 ),
154 &content_mask,
155 text_color,
156 ));
157 }
158 }
159 }
160 }
161 }
162
163 fn lines(&self) -> Vec<String> {
164 let current = self.draw_durations.back().copied();
165 match self.mode {
166 DebugFrameOverlayMode::Hidden => Vec::new(),
167 DebugFrameOverlayMode::Minimal => vec![format_ms(current)],
168 DebugFrameOverlayMode::Full => {
169 let mut sorted: Vec<Duration> = self.draw_durations.iter().copied().collect();
170 sorted.sort_unstable();
171 let percentile = |numerator: usize| {
172 (!sorted.is_empty()).then(|| sorted[(sorted.len() - 1) * numerator / 100])
173 };
174 // Past five digits the count would break the column
175 // alignment, so it saturates instead.
176 let frame_count = if self.total_frame_count > 99_999 {
177 "LOTS".to_string()
178 } else {
179 self.total_frame_count.to_string()
180 };
181 // Labels are padded to a uniform width so the fixed-width
182 // durations start in the same column on every line.
183 vec![
184 format!("CUR {}", format_ms(current)),
185 format!("1% {}", format_ms(percentile(99))),
186 format!("10% {}", format_ms(percentile(90))),
187 format!("MAX {}", format_ms(sorted.last().copied())),
188 format!("FRAMES {frame_count:>5}"),
189 ]
190 }
191 }
192 }
193}
194
195/// Formats as `abc.d MS`, right-aligned in room for three integer digits and
196/// one decimal (padded with spaces, not zeroes), so stacked readouts align.
197fn format_ms(duration: Option<Duration>) -> String {
198 match duration {
199 Some(duration) => {
200 let ms = duration.as_secs_f32() * 1000.0;
201 format!("{ms:>5.1} MS")
202 }
203 None => " -- MS".into(),
204 }
205}
206
207fn scaled_bounds(left: f32, top: f32, width: f32, height: f32) -> Bounds<ScaledPixels> {
208 Bounds {
209 origin: point(ScaledPixels(left), ScaledPixels(top)),
210 size: size(ScaledPixels(width), ScaledPixels(height)),
211 }
212}
213
214fn solid_quad(
215 bounds: Bounds<ScaledPixels>,
216 content_mask: &ContentMask<ScaledPixels>,
217 color: Hsla,
218) -> Quad {
219 Quad {
220 order: 0,
221 border_style: BorderStyle::Solid,
222 bounds,
223 content_mask: *content_mask,
224 background: color.into(),
225 border_color: transparent_black(),
226 corner_radii: Corners::default(),
227 border_widths: Edges::default(),
228 }
229}
230
231/// Returns the 5x7 bitmap for the given character, one `u8` of column bits per
232/// row with the most significant of the 5 bits leftmost. Only the characters
233/// used by the overlay's readouts are defined.
234fn glyph(character: char) -> Option<[u8; GLYPH_HEIGHT]> {
235 Some(match character {
236 '0' => [
237 0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
238 ],
239 '1' => [
240 0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
241 ],
242 '2' => [
243 0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
244 ],
245 '3' => [
246 0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
247 ],
248 '4' => [
249 0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
250 ],
251 '5' => [
252 0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
253 ],
254 '6' => [
255 0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
256 ],
257 '7' => [
258 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
259 ],
260 '8' => [
261 0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
262 ],
263 '9' => [
264 0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
265 ],
266 '.' => [
267 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100,
268 ],
269 '-' => [
270 0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000,
271 ],
272 '%' => [
273 0b11001, 0b11001, 0b00010, 0b00100, 0b01000, 0b10011, 0b10011,
274 ],
275 'A' => [
276 0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
277 ],
278 'C' => [
279 0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
280 ],
281 'E' => [
282 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
283 ],
284 'F' => [
285 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
286 ],
287 'L' => [
288 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
289 ],
290 'M' => [
291 0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
292 ],
293 'N' => [
294 0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
295 ],
296 'O' => [
297 0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
298 ],
299 'R' => [
300 0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
301 ],
302 'S' => [
303 0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
304 ],
305 'T' => [
306 0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
307 ],
308 'U' => [
309 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
310 ],
311 'X' => [
312 0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
313 ],
314 _ => return None,
315 })
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 /// Every character the readouts can produce must have a glyph, or it
323 /// would silently render as blank space.
324 #[test]
325 fn all_rendered_characters_have_glyphs() {
326 let mut overlay = DebugFrameOverlay::new();
327 overlay.set_mode(DebugFrameOverlayMode::Full);
328
329 let mut lines = Vec::new();
330 for duration in [
331 Duration::ZERO,
332 Duration::from_micros(1),
333 Duration::from_micros(8_333),
334 Duration::from_millis(123),
335 Duration::from_secs(2),
336 ] {
337 overlay.record_frame(duration);
338 lines.extend(overlay.lines());
339 }
340 // Counts beyond five digits render as "LOTS".
341 overlay.total_frame_count = 100_000;
342 lines.extend(overlay.lines());
343
344 // An enabled overlay with no samples yet renders placeholders.
345 let mut empty = DebugFrameOverlay::new();
346 empty.set_mode(DebugFrameOverlayMode::Full);
347 lines.extend(empty.lines());
348
349 for line in lines {
350 for character in line.chars() {
351 assert!(
352 character == ' ' || glyph(character).is_some(),
353 "no glyph for {character:?} in line {line:?}"
354 );
355 }
356 }
357 }
358
359 #[test]
360 fn percentile_lows_are_reported_as_times() {
361 let mut overlay = DebugFrameOverlay::new();
362 overlay.set_mode(DebugFrameOverlayMode::Full);
363 for milliseconds in 1..=100 {
364 overlay.record_frame(Duration::from_millis(milliseconds));
365 }
366 let lines = overlay.lines();
367 assert_eq!(lines[0], "CUR 100.0 MS");
368 assert_eq!(lines[1], "1% 99.0 MS");
369 assert_eq!(lines[2], "10% 90.0 MS");
370 assert_eq!(lines[3], "MAX 100.0 MS");
371 assert_eq!(lines[4], "FRAMES 100");
372 }
373
374 #[test]
375 fn reset_clears_durations_but_keeps_frame_count() {
376 let mut overlay = DebugFrameOverlay::new();
377 overlay.set_mode(DebugFrameOverlayMode::Full);
378 for _ in 0..10 {
379 overlay.record_frame(Duration::from_millis(10));
380 }
381 overlay.reset_stats();
382 let lines = overlay.lines();
383 assert_eq!(lines[0], "CUR -- MS");
384 assert_eq!(lines[3], "MAX -- MS");
385 assert_eq!(lines[4], "FRAMES 10");
386 overlay.record_frame(Duration::from_millis(20));
387 let lines = overlay.lines();
388 assert_eq!(lines[0], "CUR 20.0 MS");
389 assert_eq!(lines[4], "FRAMES 11");
390 }
391
392 #[test]
393 fn frame_count_accumulates_across_mode_changes() {
394 let mut overlay = DebugFrameOverlay::new();
395 for _ in 0..3 {
396 overlay.record_frame(Duration::from_millis(10));
397 }
398 overlay.set_mode(DebugFrameOverlayMode::Minimal);
399 assert_eq!(overlay.lines(), vec![" 10.0 MS".to_string()]);
400 overlay.set_mode(DebugFrameOverlayMode::Full);
401 overlay.record_frame(Duration::from_millis(10));
402 assert_eq!(overlay.lines()[4], "FRAMES 4");
403 overlay.set_mode(DebugFrameOverlayMode::Hidden);
404 overlay.record_frame(Duration::from_millis(10));
405 overlay.set_mode(DebugFrameOverlayMode::Full);
406 assert_eq!(overlay.lines()[4], "FRAMES 5");
407 }
408
409 #[test]
410 fn frame_count_is_right_aligned_and_saturates() {
411 let mut overlay = DebugFrameOverlay::new();
412 overlay.set_mode(DebugFrameOverlayMode::Full);
413 overlay.record_frame(Duration::from_millis(10));
414 assert_eq!(overlay.lines()[4], "FRAMES 1");
415 overlay.total_frame_count = 99_999;
416 assert_eq!(overlay.lines()[4], "FRAMES 99999");
417 overlay.total_frame_count = 100_000;
418 assert_eq!(overlay.lines()[4], "FRAMES LOTS");
419 }
420
421 #[test]
422 fn toggling_on_shows_previous_frame_immediately() {
423 let mut overlay = DebugFrameOverlay::new();
424 overlay.record_frame(Duration::from_millis(10));
425 overlay.set_mode(DebugFrameOverlayMode::Minimal);
426 assert_eq!(overlay.lines(), vec![" 10.0 MS".to_string()]);
427 }
428}