1use cranpose_core::NodeId;
2use cranpose_render_common::raster_cache::{
3 LAYER_RASTER_CACHE_KIND_COUNT, LAYER_RASTER_CACHE_KIND_LABELS,
4};
5use cranpose_ui_graphics::Rect;
6
7use crate::{frame_graph::FrameCommandStats, run_geometry::ShapeFill};
8
9macro_rules! stats_line {
12 ($($arg:tt)*) => {{
13 #[cfg(target_os = "android")]
14 log::info!($($arg)*);
15 #[cfg(not(target_os = "android"))]
16 eprintln!($($arg)*);
17 }};
18}
19
20mod frame_stats;
21pub(crate) use frame_stats::FrameStats;
22
23const TOP_ISOLATED_LAYER_LIMIT: usize = 8;
24
25#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct IsolatedLayerStat {
28 pub node_id: Option<NodeId>,
30 pub logical_rect: Rect,
32 pub width: u32,
34 pub height: u32,
36}
37
38impl IsolatedLayerStat {
39 fn pixel_area(self) -> u64 {
40 (self.width as u64) * (self.height as u64)
41 }
42}
43
44impl Default for IsolatedLayerStat {
45 fn default() -> Self {
46 Self {
47 node_id: None,
48 logical_rect: Rect {
49 x: 0.0,
50 y: 0.0,
51 width: 0.0,
52 height: 0.0,
53 },
54 width: 0,
55 height: 0,
56 }
57 }
58}
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63#[expect(
64 clippy::large_enum_variant,
65 reason = "a frame's statistics keep its damage inline; a box would allocate every frame"
66)]
67pub enum FrameDamage {
68 #[default]
71 Untracked,
72 Skipped,
75 Full,
78 Part(WindowRects),
80}
81
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub struct WindowRects {
86 rects: [[u32; 4]; crate::frame::MAX_DAMAGE_RECTS],
87 len: usize,
88}
89
90impl WindowRects {
91 pub fn rects(&self) -> &[[u32; 4]] {
93 &self.rects[..self.len]
94 }
95
96 pub fn contains(&self, x: u32, y: u32) -> bool {
98 self.rects().iter().any(|&[left, top, width, height]| {
99 x >= left && y >= top && x < left + width && y < top + height
100 })
101 }
102
103 pub fn pixels(&self) -> u64 {
105 self.rects()
106 .iter()
107 .map(|&[_, _, width, height]| u64::from(width) * u64::from(height))
108 .sum()
109 }
110
111 pub(crate) fn push(&mut self, rect: [u32; 4]) {
114 if let Some(slot) = self.rects.get_mut(self.len) {
115 *slot = rect;
116 self.len += 1;
117 }
118 }
119}
120
121#[derive(Clone, Copy, Debug, Default, PartialEq)]
124pub struct FrameStatsSnapshot {
125 pub submits: u32,
127 pub encoder_count: u32,
129 pub submit_count: u32,
131 pub pass_count: u32,
133 pub pass_pixels: u64,
136 pub copy_count: u32,
138 pub copy_pixels: u64,
140 pub offscreen_acquires: u32,
142 pub offscreen_news: u32,
144 pub offscreen_total_bytes: u64,
146 pub transient_texture_bytes: u64,
148 pub retained_texture_bytes: u64,
150 pub upload_bytes: u64,
152 pub upload_writes: u32,
155 pub isolated_layer_renders: u32,
157 pub isolated_layer_pixels: u64,
159 pub layer_cache_hits: u32,
161 pub capture_fixup_passes: u32,
163 pub layer_cache_misses: u32,
165 pub layer_cache_hit_pixels: u64,
167 pub layer_cache_miss_pixels: u64,
169 pub layer_cache_hits_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
171 pub layer_cache_misses_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
173 pub layer_cache_miss_pixels_by_kind: [u64; LAYER_RASTER_CACHE_KIND_COUNT],
175 pub shadow_shape_cache_hits: u32,
177 pub shadow_shape_cache_misses: u32,
179 pub shadow_shape_cache_hit_pixels: u64,
181 pub shadow_shape_cache_miss_pixels: u64,
183 pub shadow_text_blur_fallbacks: u32,
186 pub blur_passes: u32,
188 pub stages: u32,
191 pub backdrop_admissions: u32,
194 pub prefix_admissions: u32,
196 pub substrates: u32,
199 pub composite_passes: u32,
203 pub effect_applies: u32,
206 pub shader_pixels: u64,
209 pub blur_pixels: u64,
213 pub shape_fill_pixels: u64,
217 pub shape_fill_pixels_by_class: [u64; ShapeFill::CLASSES],
220 pub shape_vertices: u64,
224 pub shape_passes: u32,
226 pub shape_pipeline_fallback_draws: u32,
229 pub instant_draws: u32,
232 pub shape_specialized_draws: u32,
234 pub shape_interior_draws: u32,
236 pub depth_passes: u32,
238 pub pipelines_created: u64,
242 pub shader_pipeline_fallback_draws: u32,
245 pub shader_specialized_draws: u32,
247 pub placeholder_draws: u32,
250 pub image_passes: u32,
252 pub text_passes: u32,
254 pub draw_calls: u32,
261 pub damage: FrameDamage,
264 pub repainted_pixels: u64,
267 pub kept_stand_in_pixels: u64,
271 pub text_image_cache_hits: u32,
273 pub text_image_cache_misses: u32,
275 pub text_image_cache_hit_pixels: u64,
277 pub text_image_cache_miss_pixels: u64,
279 pub text_image_raster_bytes: u64,
281 pub text_glyph_atlas_hits: u32,
283 pub text_glyph_atlas_misses: u32,
285 pub text_glyph_atlas_miss_pixels: u64,
287 pub text_glyph_runs_collected: u32,
290 pub offscreen_pool_size: u32,
292 pub offscreen_pool_bytes: u64,
294 pub text_pool_size: u32,
296 pub layer_cache_size: u32,
298 pub layer_cache_bytes: u64,
300 pub image_cache_size: u32,
302 pub top_isolated_layers: [Option<IsolatedLayerStat>; TOP_ISOLATED_LAYER_LIMIT],
305 pub top_isolated_layer_count: usize,
307}
308
309impl FrameStatsSnapshot {
310 fn shape_fill_by_class_text(&self) -> String {
311 let mut text = String::new();
312 for (label, pixels) in ShapeFill::LABELS
313 .iter()
314 .zip(self.shape_fill_pixels_by_class)
315 {
316 if pixels > 0 {
317 use std::fmt::Write;
318 let _ = write!(text, " {label}={:.2}MP", pixels as f64 / 1_000_000.0);
319 }
320 }
321 text
322 }
323
324 pub(crate) fn with_command_stats_added(mut self, stats: FrameCommandStats) -> Self {
325 self.submits = self.submits.saturating_add(stats.submit_count);
326 self.encoder_count = self.encoder_count.saturating_add(stats.encoder_count);
327 self.submit_count = self.submit_count.saturating_add(stats.submit_count);
328 self.pass_count = self.pass_count.saturating_add(stats.pass_count);
329 self.pass_pixels = self.pass_pixels.saturating_add(stats.pass_pixels);
330 self.copy_count = self.copy_count.saturating_add(stats.copy_count);
331 self.copy_pixels = self.copy_pixels.saturating_add(stats.copy_pixels);
332 self.transient_texture_bytes = self
333 .transient_texture_bytes
334 .saturating_add(stats.transient_texture_bytes);
335 self.retained_texture_bytes = self
336 .retained_texture_bytes
337 .max(stats.retained_texture_bytes);
338 self.upload_bytes = self.upload_bytes.saturating_add(stats.upload_bytes);
339 self.upload_writes = self.upload_writes.saturating_add(stats.upload_writes);
340 self.offscreen_acquires = self
341 .offscreen_acquires
342 .saturating_add(stats.transient_acquires);
343 self.offscreen_news = self.offscreen_news.saturating_add(stats.transient_news);
344 self
345 }
346
347 fn top_isolated_display(&self) -> String {
350 match &self.top_isolated_layers[0] {
351 Some(top) => format!(
352 "{}x{}@({:.0},{:.0})",
353 top.width, top.height, top.logical_rect.x, top.logical_rect.y
354 ),
355 None => "-".to_string(),
356 }
357 }
358
359 pub fn top_isolated_layers(self) -> impl Iterator<Item = IsolatedLayerStat> {
361 self.top_isolated_layers
362 .into_iter()
363 .flatten()
364 .take(self.top_isolated_layer_count)
365 }
366
367 fn layer_cache_hit_rate(self) -> f64 {
368 let total = self.layer_cache_hits + self.layer_cache_misses;
369 if total > 0 {
370 (self.layer_cache_hits as f64 / total as f64) * 100.0
371 } else {
372 0.0
373 }
374 }
375
376 fn miss_pixels_by_kind_display(&self) -> String {
377 by_kind_display(&self.layer_cache_miss_pixels_by_kind, |pixels| {
378 format!("{:.2}MP", pixels as f64 / 1_000_000.0)
379 })
380 }
381
382 fn hits_by_kind_display(&self) -> String {
383 by_kind_display(&self.layer_cache_hits_by_kind, |hits| hits.to_string())
384 }
385
386 fn print(self, frame_count: u64) {
387 let mb = self.offscreen_total_bytes as f64 / (1024.0 * 1024.0);
388 let upload_mb = self.upload_bytes as f64 / (1024.0 * 1024.0);
389 let retained_mb = self.retained_texture_bytes as f64 / (1024.0 * 1024.0);
390 let pool_mb = self.offscreen_pool_bytes as f64 / (1024.0 * 1024.0);
391 let layer_cache_hit_mpx = self.layer_cache_hit_pixels as f64 / 1_000_000.0;
392 let layer_cache_miss_mpx = self.layer_cache_miss_pixels as f64 / 1_000_000.0;
393 let shadow_cache_hit_mpx = self.shadow_shape_cache_hit_pixels as f64 / 1_000_000.0;
394 let shadow_cache_miss_mpx = self.shadow_shape_cache_miss_pixels as f64 / 1_000_000.0;
395 let layer_cache_mb = self.layer_cache_bytes as f64 / (1024.0 * 1024.0);
396 let isolated_layer_mpx = self.isolated_layer_pixels as f64 / 1_000_000.0;
397 stats_line!(
398 "[GPU f#{}] encoders={} submits={} passes={} pass_px={:.2}MP copies={} copy_px={:.2}MP | offscreen: acq={} new={} {:.1}MB pool={}({:.1}MB) retained={:.1}MB | \
399 uploads={:.2}MB writes={} | \
400 isolated_layers={} area={:.2}MP top={} | \
401 layer_cache: hit={} miss={} {:.1}% hit_px={:.2}MP miss_px={:.2}MP size={}({:.1}MB) hit_by_kind={} miss_px_by_kind={} | \
402 shadow_cache: shape_hit={} shape_miss={} hit_px={:.2}MP miss_px={:.2}MP text_blur_fallback={} | \
403 stages={} admit={} blur={} substrate={} composite={} effect={} shader_px={:.2}MP blur_px={:.2}MP | shape={} shape_fill_px={:.2}MP{} shape_verts={} interiors={} depth_passes={} image={} text={} draws={} | \
404 text_img_cache: hit={} miss={} hit_px={:.2}MP miss_px={:.2}MP raster={:.2}MB | \
405 text_glyph_atlas: hit={} miss={} miss_px={:.2}MP runs_collected={} | \
406 caches: text_pool={} img={}",
407 frame_count,
408 self.encoder_count,
409 self.submit_count,
410 self.pass_count,
411 self.pass_pixels as f64 / 1_000_000.0,
412 self.copy_count,
413 self.copy_pixels as f64 / 1_000_000.0,
414 self.offscreen_acquires,
415 self.offscreen_news,
416 mb,
417 self.offscreen_pool_size,
418 pool_mb,
419 retained_mb,
420 upload_mb,
421 self.upload_writes,
422 self.isolated_layer_renders,
423 isolated_layer_mpx,
424 self.top_isolated_display(),
425 self.layer_cache_hits,
426 self.layer_cache_misses,
427 self.layer_cache_hit_rate(),
428 layer_cache_hit_mpx,
429 layer_cache_miss_mpx,
430 self.layer_cache_size,
431 layer_cache_mb,
432 self.hits_by_kind_display(),
433 self.miss_pixels_by_kind_display(),
434 self.shadow_shape_cache_hits,
435 self.shadow_shape_cache_misses,
436 shadow_cache_hit_mpx,
437 shadow_cache_miss_mpx,
438 self.shadow_text_blur_fallbacks,
439 self.stages,
440 self.backdrop_admissions,
441 self.blur_passes,
442 self.substrates,
443 self.composite_passes,
444 self.effect_applies,
445 self.shader_pixels as f64 / 1_000_000.0,
446 self.blur_pixels as f64 / 1_000_000.0,
447 self.shape_passes,
448 self.shape_fill_pixels as f64 / 1_000_000.0,
449 self.shape_fill_by_class_text(),
450 self.shape_vertices,
451 self.shape_interior_draws,
452 self.depth_passes,
453 self.image_passes,
454 self.text_passes,
455 self.draw_calls,
456 self.text_image_cache_hits,
457 self.text_image_cache_misses,
458 self.text_image_cache_hit_pixels as f64 / 1_000_000.0,
459 self.text_image_cache_miss_pixels as f64 / 1_000_000.0,
460 self.text_image_raster_bytes as f64 / (1024.0 * 1024.0),
461 self.text_glyph_atlas_hits,
462 self.text_glyph_atlas_misses,
463 self.text_glyph_atlas_miss_pixels as f64 / 1_000_000.0,
464 self.text_glyph_runs_collected,
465 self.text_pool_size,
466 self.image_cache_size,
467 );
468 for (index, layer) in self.top_isolated_layers().enumerate() {
469 stats_line!(
470 " [isolated #{index}] node={:?} rect=({:.1},{:.1},{:.1},{:.1}) target={}x{}",
471 layer.node_id,
472 layer.logical_rect.x,
473 layer.logical_rect.y,
474 layer.logical_rect.width,
475 layer.logical_rect.height,
476 layer.width,
477 layer.height,
478 );
479 }
480 }
481}
482
483pub(crate) fn gpu_stats_enabled() -> bool {
484 cranpose_core::DIAGNOSTICS.gpu_stats.flag()
485}
486
487pub(crate) fn print_gpu_memory_report(device: &wgpu::Device, frame_count: u64) {
488 let Some(report) = device.generate_allocator_report() else {
489 return;
490 };
491
492 const MB: f64 = 1024.0 * 1024.0;
493 let mut blocks = String::new();
494 for block in &report.blocks {
495 if !blocks.is_empty() {
496 blocks.push('+');
497 }
498 blocks.push_str(&format!("{:.1}", block.size as f64 / MB));
499 }
500
501 stats_line!(
502 "[GPU-MEM f#{}] reserved={:.1}MB allocated={:.1}MB blocks={}[{}MB] allocations={} | largest={:.6?}",
503 frame_count,
504 report.total_reserved_bytes as f64 / MB,
505 report.total_allocated_bytes as f64 / MB,
506 report.blocks.len(),
507 blocks,
508 report.allocations.len(),
509 report,
510 );
511}
512
513fn shadow_cache_diagnostics_enabled() -> bool {
514 cranpose_core::DIAGNOSTICS.gpu_shadow_cache_diag.flag()
515}
516
517fn by_kind_display<T: Copy + Default + PartialEq>(
518 by_kind: &[T; LAYER_RASTER_CACHE_KIND_COUNT],
519 format: impl Fn(T) -> String,
520) -> String {
521 LAYER_RASTER_CACHE_KIND_LABELS
522 .iter()
523 .zip(by_kind)
524 .filter(|(_, value)| **value != T::default())
525 .map(|(label, value)| format!("{label}={}", format(*value)))
526 .collect::<Vec<_>>()
527 .join(",")
528}
529
530#[cfg(test)]
531#[path = "tests/gpu_stats_tests.rs"]
532mod tests;