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)]
63pub enum FrameDamage {
64 #[default]
67 Untracked,
68 Skipped,
71 Full,
74 Part(WindowRects),
76}
77
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
81pub struct WindowRects {
82 rects: [[u32; 4]; crate::frame::MAX_DAMAGE_RECTS],
83 len: usize,
84}
85
86impl WindowRects {
87 pub fn rects(&self) -> &[[u32; 4]] {
89 &self.rects[..self.len]
90 }
91
92 pub fn contains(&self, x: u32, y: u32) -> bool {
94 self.rects().iter().any(|&[left, top, width, height]| {
95 x >= left && y >= top && x < left + width && y < top + height
96 })
97 }
98
99 pub fn pixels(&self) -> u64 {
101 self.rects()
102 .iter()
103 .map(|&[_, _, width, height]| u64::from(width) * u64::from(height))
104 .sum()
105 }
106
107 pub(crate) fn push(&mut self, rect: [u32; 4]) {
110 if let Some(slot) = self.rects.get_mut(self.len) {
111 *slot = rect;
112 self.len += 1;
113 }
114 }
115}
116
117#[derive(Clone, Copy, Debug, Default, PartialEq)]
120pub struct FrameStatsSnapshot {
121 pub submits: u32,
123 pub encoder_count: u32,
125 pub submit_count: u32,
127 pub pass_count: u32,
129 pub pass_pixels: u64,
132 pub copy_count: u32,
134 pub copy_pixels: u64,
136 pub offscreen_acquires: u32,
138 pub offscreen_news: u32,
140 pub offscreen_total_bytes: u64,
142 pub transient_texture_bytes: u64,
144 pub retained_texture_bytes: u64,
146 pub upload_bytes: u64,
148 pub upload_writes: u32,
151 pub isolated_layer_renders: u32,
153 pub isolated_layer_pixels: u64,
155 pub layer_cache_hits: u32,
157 pub capture_fixup_passes: u32,
159 pub layer_cache_misses: u32,
161 pub layer_cache_hit_pixels: u64,
163 pub layer_cache_miss_pixels: u64,
165 pub layer_cache_hits_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
167 pub layer_cache_misses_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
169 pub layer_cache_miss_pixels_by_kind: [u64; LAYER_RASTER_CACHE_KIND_COUNT],
171 pub shadow_shape_cache_hits: u32,
173 pub shadow_shape_cache_misses: u32,
175 pub shadow_shape_cache_hit_pixels: u64,
177 pub shadow_shape_cache_miss_pixels: u64,
179 pub shadow_text_blur_fallbacks: u32,
182 pub blur_passes: u32,
184 pub stages: u32,
187 pub backdrop_admissions: u32,
190 pub prefix_admissions: u32,
192 pub substrates: u32,
195 pub composite_passes: u32,
199 pub effect_applies: u32,
202 pub shader_pixels: u64,
205 pub blur_pixels: u64,
209 pub shape_fill_pixels: u64,
213 pub shape_fill_pixels_by_class: [u64; ShapeFill::CLASSES],
216 pub shape_vertices: u64,
220 pub shape_passes: u32,
222 pub shape_pipeline_fallback_draws: u32,
225 pub instant_draws: u32,
228 pub shape_specialized_draws: u32,
230 pub shape_interior_draws: u32,
232 pub depth_passes: u32,
234 pub pipelines_created: u64,
238 pub shader_pipeline_fallback_draws: u32,
241 pub shader_specialized_draws: u32,
243 pub placeholder_draws: u32,
246 pub image_passes: u32,
248 pub text_passes: u32,
250 pub draw_calls: u32,
257 pub damage: FrameDamage,
260 pub repainted_pixels: u64,
263 pub text_image_cache_hits: u32,
265 pub text_image_cache_misses: u32,
267 pub text_image_cache_hit_pixels: u64,
269 pub text_image_cache_miss_pixels: u64,
271 pub text_image_raster_bytes: u64,
273 pub text_glyph_atlas_hits: u32,
275 pub text_glyph_atlas_misses: u32,
277 pub text_glyph_atlas_miss_pixels: u64,
279 pub text_glyph_runs_collected: u32,
282 pub offscreen_pool_size: u32,
284 pub offscreen_pool_bytes: u64,
286 pub text_pool_size: u32,
288 pub layer_cache_size: u32,
290 pub layer_cache_bytes: u64,
292 pub image_cache_size: u32,
294 pub top_isolated_layers: [Option<IsolatedLayerStat>; TOP_ISOLATED_LAYER_LIMIT],
297 pub top_isolated_layer_count: usize,
299}
300
301impl FrameStatsSnapshot {
302 fn shape_fill_by_class_text(&self) -> String {
303 let mut text = String::new();
304 for (label, pixels) in ShapeFill::LABELS
305 .iter()
306 .zip(self.shape_fill_pixels_by_class)
307 {
308 if pixels > 0 {
309 use std::fmt::Write;
310 let _ = write!(text, " {label}={:.2}MP", pixels as f64 / 1_000_000.0);
311 }
312 }
313 text
314 }
315
316 pub(crate) fn with_command_stats_added(mut self, stats: FrameCommandStats) -> Self {
317 self.submits = self.submits.saturating_add(stats.submit_count);
318 self.encoder_count = self.encoder_count.saturating_add(stats.encoder_count);
319 self.submit_count = self.submit_count.saturating_add(stats.submit_count);
320 self.pass_count = self.pass_count.saturating_add(stats.pass_count);
321 self.pass_pixels = self.pass_pixels.saturating_add(stats.pass_pixels);
322 self.copy_count = self.copy_count.saturating_add(stats.copy_count);
323 self.copy_pixels = self.copy_pixels.saturating_add(stats.copy_pixels);
324 self.transient_texture_bytes = self
325 .transient_texture_bytes
326 .saturating_add(stats.transient_texture_bytes);
327 self.retained_texture_bytes = self
328 .retained_texture_bytes
329 .max(stats.retained_texture_bytes);
330 self.upload_bytes = self.upload_bytes.saturating_add(stats.upload_bytes);
331 self.upload_writes = self.upload_writes.saturating_add(stats.upload_writes);
332 self.offscreen_acquires = self
333 .offscreen_acquires
334 .saturating_add(stats.transient_acquires);
335 self.offscreen_news = self.offscreen_news.saturating_add(stats.transient_news);
336 self
337 }
338
339 fn top_isolated_display(&self) -> String {
342 match &self.top_isolated_layers[0] {
343 Some(top) => format!(
344 "{}x{}@({:.0},{:.0})",
345 top.width, top.height, top.logical_rect.x, top.logical_rect.y
346 ),
347 None => "-".to_string(),
348 }
349 }
350
351 pub fn top_isolated_layers(self) -> impl Iterator<Item = IsolatedLayerStat> {
353 self.top_isolated_layers
354 .into_iter()
355 .flatten()
356 .take(self.top_isolated_layer_count)
357 }
358
359 fn layer_cache_hit_rate(self) -> f64 {
360 let total = self.layer_cache_hits + self.layer_cache_misses;
361 if total > 0 {
362 (self.layer_cache_hits as f64 / total as f64) * 100.0
363 } else {
364 0.0
365 }
366 }
367
368 fn miss_pixels_by_kind_display(&self) -> String {
369 by_kind_display(&self.layer_cache_miss_pixels_by_kind, |pixels| {
370 format!("{:.2}MP", pixels as f64 / 1_000_000.0)
371 })
372 }
373
374 fn hits_by_kind_display(&self) -> String {
375 by_kind_display(&self.layer_cache_hits_by_kind, |hits| hits.to_string())
376 }
377
378 fn print(self, frame_count: u64) {
379 let mb = self.offscreen_total_bytes as f64 / (1024.0 * 1024.0);
380 let upload_mb = self.upload_bytes as f64 / (1024.0 * 1024.0);
381 let retained_mb = self.retained_texture_bytes as f64 / (1024.0 * 1024.0);
382 let pool_mb = self.offscreen_pool_bytes as f64 / (1024.0 * 1024.0);
383 let layer_cache_hit_mpx = self.layer_cache_hit_pixels as f64 / 1_000_000.0;
384 let layer_cache_miss_mpx = self.layer_cache_miss_pixels as f64 / 1_000_000.0;
385 let shadow_cache_hit_mpx = self.shadow_shape_cache_hit_pixels as f64 / 1_000_000.0;
386 let shadow_cache_miss_mpx = self.shadow_shape_cache_miss_pixels as f64 / 1_000_000.0;
387 let layer_cache_mb = self.layer_cache_bytes as f64 / (1024.0 * 1024.0);
388 let isolated_layer_mpx = self.isolated_layer_pixels as f64 / 1_000_000.0;
389 stats_line!(
390 "[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 | \
391 uploads={:.2}MB writes={} | \
392 isolated_layers={} area={:.2}MP top={} | \
393 layer_cache: hit={} miss={} {:.1}% hit_px={:.2}MP miss_px={:.2}MP size={}({:.1}MB) hit_by_kind={} miss_px_by_kind={} | \
394 shadow_cache: shape_hit={} shape_miss={} hit_px={:.2}MP miss_px={:.2}MP text_blur_fallback={} | \
395 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={} | \
396 text_img_cache: hit={} miss={} hit_px={:.2}MP miss_px={:.2}MP raster={:.2}MB | \
397 text_glyph_atlas: hit={} miss={} miss_px={:.2}MP runs_collected={} | \
398 caches: text_pool={} img={}",
399 frame_count,
400 self.encoder_count,
401 self.submit_count,
402 self.pass_count,
403 self.pass_pixels as f64 / 1_000_000.0,
404 self.copy_count,
405 self.copy_pixels as f64 / 1_000_000.0,
406 self.offscreen_acquires,
407 self.offscreen_news,
408 mb,
409 self.offscreen_pool_size,
410 pool_mb,
411 retained_mb,
412 upload_mb,
413 self.upload_writes,
414 self.isolated_layer_renders,
415 isolated_layer_mpx,
416 self.top_isolated_display(),
417 self.layer_cache_hits,
418 self.layer_cache_misses,
419 self.layer_cache_hit_rate(),
420 layer_cache_hit_mpx,
421 layer_cache_miss_mpx,
422 self.layer_cache_size,
423 layer_cache_mb,
424 self.hits_by_kind_display(),
425 self.miss_pixels_by_kind_display(),
426 self.shadow_shape_cache_hits,
427 self.shadow_shape_cache_misses,
428 shadow_cache_hit_mpx,
429 shadow_cache_miss_mpx,
430 self.shadow_text_blur_fallbacks,
431 self.stages,
432 self.backdrop_admissions,
433 self.blur_passes,
434 self.substrates,
435 self.composite_passes,
436 self.effect_applies,
437 self.shader_pixels as f64 / 1_000_000.0,
438 self.blur_pixels as f64 / 1_000_000.0,
439 self.shape_passes,
440 self.shape_fill_pixels as f64 / 1_000_000.0,
441 self.shape_fill_by_class_text(),
442 self.shape_vertices,
443 self.shape_interior_draws,
444 self.depth_passes,
445 self.image_passes,
446 self.text_passes,
447 self.draw_calls,
448 self.text_image_cache_hits,
449 self.text_image_cache_misses,
450 self.text_image_cache_hit_pixels as f64 / 1_000_000.0,
451 self.text_image_cache_miss_pixels as f64 / 1_000_000.0,
452 self.text_image_raster_bytes as f64 / (1024.0 * 1024.0),
453 self.text_glyph_atlas_hits,
454 self.text_glyph_atlas_misses,
455 self.text_glyph_atlas_miss_pixels as f64 / 1_000_000.0,
456 self.text_glyph_runs_collected,
457 self.text_pool_size,
458 self.image_cache_size,
459 );
460 for (index, layer) in self.top_isolated_layers().enumerate() {
461 stats_line!(
462 " [isolated #{index}] node={:?} rect=({:.1},{:.1},{:.1},{:.1}) target={}x{}",
463 layer.node_id,
464 layer.logical_rect.x,
465 layer.logical_rect.y,
466 layer.logical_rect.width,
467 layer.logical_rect.height,
468 layer.width,
469 layer.height,
470 );
471 }
472 }
473}
474
475pub(crate) fn gpu_stats_enabled() -> bool {
476 cranpose_core::DIAGNOSTICS.gpu_stats.flag()
477}
478
479pub(crate) fn print_gpu_memory_report(device: &wgpu::Device, frame_count: u64) {
480 let Some(report) = device.generate_allocator_report() else {
481 return;
482 };
483
484 const MB: f64 = 1024.0 * 1024.0;
485 let mut blocks = String::new();
486 for block in &report.blocks {
487 if !blocks.is_empty() {
488 blocks.push('+');
489 }
490 blocks.push_str(&format!("{:.1}", block.size as f64 / MB));
491 }
492
493 stats_line!(
494 "[GPU-MEM f#{}] reserved={:.1}MB allocated={:.1}MB blocks={}[{}MB] allocations={} | largest={:.6?}",
495 frame_count,
496 report.total_reserved_bytes as f64 / MB,
497 report.total_allocated_bytes as f64 / MB,
498 report.blocks.len(),
499 blocks,
500 report.allocations.len(),
501 report,
502 );
503}
504
505fn shadow_cache_diagnostics_enabled() -> bool {
506 cranpose_core::DIAGNOSTICS.gpu_shadow_cache_diag.flag()
507}
508
509fn by_kind_display<T: Copy + Default + PartialEq>(
510 by_kind: &[T; LAYER_RASTER_CACHE_KIND_COUNT],
511 format: impl Fn(T) -> String,
512) -> String {
513 LAYER_RASTER_CACHE_KIND_LABELS
514 .iter()
515 .zip(by_kind)
516 .filter(|(_, value)| **value != T::default())
517 .map(|(label, value)| format!("{label}={}", format(*value)))
518 .collect::<Vec<_>>()
519 .join(",")
520}
521
522#[cfg(test)]
523#[path = "tests/gpu_stats_tests.rs"]
524mod tests;