Skip to main content

cranpose_render_wgpu/
gpu_stats.rs

1use std::cell::{Cell, RefCell};
2
3use cranpose_core::NodeId;
4use cranpose_render_common::raster_cache::{
5    LAYER_RASTER_CACHE_KIND_COUNT, LAYER_RASTER_CACHE_KIND_LABELS, LayerRasterCacheKey,
6};
7use cranpose_ui_graphics::Rect;
8
9use crate::{debug_toggles::DebugToggle, frame_graph::FrameCommandStats, run_geometry::ShapeFill};
10
11/// A diagnostics line: logcat on Android, where nothing reads stderr, and
12/// stderr elsewhere.
13macro_rules! stats_line {
14    ($($arg:tt)*) => {{
15        #[cfg(target_os = "android")]
16        log::info!($($arg)*);
17        #[cfg(not(target_os = "android"))]
18        eprintln!($($arg)*);
19    }};
20}
21
22const TOP_ISOLATED_LAYER_LIMIT: usize = 8;
23
24/// A layer the renderer drew into an offscreen texture of its own.
25#[derive(Clone, Copy, Debug, PartialEq)]
26pub struct IsolatedLayerStat {
27    /// The node of the layer, or `None` when no node owns it.
28    pub node_id: Option<NodeId>,
29    /// The layer's bounds in logical pixels.
30    pub logical_rect: Rect,
31    /// Width of the layer's offscreen texture in device pixels.
32    pub width: u32,
33    /// Height of the layer's offscreen texture in device pixels.
34    pub height: u32,
35}
36
37impl IsolatedLayerStat {
38    fn pixel_area(self) -> u64 {
39        (self.width as u64) * (self.height as u64)
40    }
41}
42
43impl Default for IsolatedLayerStat {
44    fn default() -> Self {
45        Self {
46            node_id: None,
47            logical_rect: Rect {
48                x: 0.0,
49                y: 0.0,
50                width: 0.0,
51                height: 0.0,
52            },
53            width: 0,
54            height: 0,
55        }
56    }
57}
58
59/// The counters of one drawn frame, from `WgpuRenderer::last_frame_stats`. Pixel counts are in
60/// device pixels.
61#[derive(Clone, Copy, Debug, Default, PartialEq)]
62pub struct FrameStatsSnapshot {
63    /// Submissions to the GPU queue during the frame.
64    pub submits: u32,
65    /// Command encoders the frame recorded.
66    pub encoder_count: u32,
67    /// Submissions to the GPU queue, as counted from the recorded commands; equals `submits`.
68    pub submit_count: u32,
69    /// Render passes the frame recorded.
70    pub pass_count: u32,
71    /// Sum of every render pass's first color target area: the tile traffic a
72    /// tiling GPU pays whatever the passes draw.
73    pub pass_pixels: u64,
74    /// Texture regions copied outside any pass, and their texels.
75    pub copy_count: u32,
76    /// Texels of those copies.
77    pub copy_pixels: u64,
78    /// Offscreen textures the frame took from the pool or created.
79    pub offscreen_acquires: u32,
80    /// Of the acquired offscreen textures, those created because the pool held none that fit.
81    pub offscreen_news: u32,
82    /// Bytes of every offscreen texture the frame acquired, new or reused.
83    pub offscreen_total_bytes: u64,
84    /// Bytes of the textures the frame used for one frame only.
85    pub transient_texture_bytes: u64,
86    /// Bytes of the textures kept between frames: the offscreen pool and the layer cache.
87    pub retained_texture_bytes: u64,
88    /// Bytes the frame uploaded to the GPU.
89    pub upload_bytes: u64,
90    /// Buffer writes the frame staged: uploads that reach the GPU as one
91    /// write each, however many draws they carry.
92    pub upload_writes: u32,
93    /// Layers the frame drew into an offscreen texture of their own.
94    pub isolated_layer_renders: u32,
95    /// Pixels of the offscreen textures of those layers.
96    pub isolated_layer_pixels: u64,
97    /// Layers drawn from the layer cache instead of drawn again.
98    pub layer_cache_hits: u32,
99    /// Capture passes that replayed ops not yet on the page.
100    pub capture_fixup_passes: u32,
101    /// Layers drawn anew and stored in the layer cache, because it held no match.
102    pub layer_cache_misses: u32,
103    /// Pixels of the layers drawn from the layer cache.
104    pub layer_cache_hit_pixels: u64,
105    /// Pixels of the layers drawn anew and stored in the layer cache.
106    pub layer_cache_miss_pixels: u64,
107    /// Hits per key kind, indexed by `LayerRasterCacheKey::kind_slot`.
108    pub layer_cache_hits_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
109    /// Stores per key kind, indexed by `LayerRasterCacheKey::kind_slot`.
110    pub layer_cache_misses_by_kind: [u32; LAYER_RASTER_CACHE_KIND_COUNT],
111    /// Stored pixels per key kind, indexed by `LayerRasterCacheKey::kind_slot`.
112    pub layer_cache_miss_pixels_by_kind: [u64; LAYER_RASTER_CACHE_KIND_COUNT],
113    /// Shadows drawn from a cached blurred texture.
114    pub shadow_shape_cache_hits: u32,
115    /// Shadows blurred anew because the shadow cache held no match.
116    pub shadow_shape_cache_misses: u32,
117    /// Pixels composited from the cached shadow textures.
118    pub shadow_shape_cache_hit_pixels: u64,
119    /// Pixels of the shadow textures blurred anew.
120    pub shadow_shape_cache_miss_pixels: u64,
121    /// Shadows whose source holds more than shapes, such as text, that found no cached texture and
122    /// were blurred anew.
123    pub shadow_text_blur_fallbacks: u32,
124    /// Blur passes the frame encoded, each downsample, horizontal and vertical pass counting one.
125    pub blur_passes: u32,
126    /// Backdrop stages resolved: every stage flushes the page and captures
127    /// once, so the layer pass count is one more than this.
128    pub stages: u32,
129    /// Backdrops whose stage texture the layer cache pinned this frame, so
130    /// later frames replay their composites from it.
131    pub backdrop_admissions: u32,
132    /// Opaque page prefixes copied into the layer cache this frame.
133    pub prefix_admissions: u32,
134    /// Captures averaged into a quarter-size substrate for a shader's wide
135    /// taps.
136    pub substrates: u32,
137    /// Passes that draw at least one resolved composite: a final pass holding
138    /// twelve glass tails counts once, a composite resolved into its own
139    /// texture counts its own pass.
140    pub composite_passes: u32,
141    /// Render effects, such as offsets and runtime shaders, the frame applied to an offscreen
142    /// source.
143    pub effect_applies: u32,
144    /// Pixels shaded by runtime shader composites: what every glass surface
145    /// costs a tiling GPU per frame, each capture that re-shades one included.
146    pub shader_pixels: u64,
147    /// Pixels the runtime shader draws rasterize once each draw is split into its interior and rim
148    /// regions.
149    pub glass_rasterized_pixels: u64,
150    /// Pixels the blur passes write: every downsample, horizontal and
151    /// vertical pass of a backdrop's blur and of its substrates, within
152    /// the scissor the pass was given.
153    pub blur_pixels: u64,
154    /// Pixels the shape draws rasterize: a band drawn as a mesh counts its
155    /// mesh, everything else its quad. Fill rate is what a scene of rings
156    /// costs a tiling GPU, however few draws it takes.
157    pub shape_fill_pixels: u64,
158    /// `shape_fill_pixels` split by shape kind and brush, in the order of
159    /// `ShapeFill::LABELS`: which records a fill-bound frame pays for.
160    pub shape_fill_pixels_by_class: [u64; ShapeFill::CLASSES],
161    /// Vertices the shape draws run through the vertex stage: six per quad,
162    /// six per band segment. A tiling GPU stores every vertex's varyings
163    /// before it shades a pixel, so this bounds a frame as fill does.
164    pub shape_vertices: u64,
165    /// Batches of shape draws the frame recorded.
166    pub shape_passes: u32,
167    /// Shape draws that took a stand-in while their pipeline compiled: a
168    /// general pipeline, or triangles the CPU laid out.
169    pub shape_pipeline_fallback_draws: u32,
170    /// Shape draws using a completed specialized pipeline.
171    pub shape_specialized_draws: u32,
172    /// Shape draws laying opaque interiors down in a pass's depth pre-pass.
173    pub shape_interior_draws: u32,
174    /// Render passes that took a depth buffer for their opaque interiors.
175    pub depth_passes: u32,
176    /// Pipelines this process has built, counted since it started rather than
177    /// over the frame. A count that grows while a person is interacting names
178    /// a backend shader compile they waited through.
179    pub pipelines_created: u64,
180    /// Runtime shader draws using a shader's general pipeline while the
181    /// specialization they asked for compiles in the background.
182    pub shader_pipeline_fallback_draws: u32,
183    /// Runtime shader draws using a completed specialized pipeline.
184    pub shader_specialized_draws: u32,
185    /// Effects drawn as their placeholder, or left out, because no pipeline
186    /// they need had compiled yet.
187    pub placeholder_draws: u32,
188    /// Batches of image draws the frame recorded.
189    pub image_passes: u32,
190    /// Batches of text draws the frame recorded.
191    pub text_passes: u32,
192    /// Shape, image, glyph and composite draws recorded this frame. The
193    /// `*_passes` counters above count *batches* or passes, so a single image
194    /// batch reports `image_passes=1` however many images it draws; this
195    /// counts what the driver actually sees. Blur and effect quads are not
196    /// included: they are one draw each and already counted by `blur_passes`
197    /// and `effect_applies`.
198    pub draw_calls: u32,
199    /// Texts drawn from the cache of rasterized text images.
200    pub text_image_cache_hits: u32,
201    /// Texts rasterized into an image because the cache held none.
202    pub text_image_cache_misses: u32,
203    /// Pixels of the text images taken from the cache.
204    pub text_image_cache_hit_pixels: u64,
205    /// Pixels of the text images rasterized.
206    pub text_image_cache_miss_pixels: u64,
207    /// Bytes of the text images rasterized, four per pixel.
208    pub text_image_raster_bytes: u64,
209    /// Glyphs found in the glyph atlas.
210    pub text_glyph_atlas_hits: u32,
211    /// Glyphs rasterized and added to the glyph atlas.
212    pub text_glyph_atlas_misses: u32,
213    /// Pixels of the glyphs added to the glyph atlas.
214    pub text_glyph_atlas_miss_pixels: u64,
215    /// Texts whose glyph runs the frame laid out again: a text drawn as it
216    /// was before takes its run from the cache.
217    pub text_glyph_runs_collected: u32,
218    /// Textures held for reuse at the end of the frame, with the composition target.
219    pub offscreen_pool_size: u32,
220    /// Bytes of the textures counted by `offscreen_pool_size`.
221    pub offscreen_pool_bytes: u64,
222    /// Rasterized text images in the text image cache at the end of the frame.
223    pub text_pool_size: u32,
224    /// Layers in the layer cache at the end of the frame.
225    pub layer_cache_size: u32,
226    /// Bytes of the layer cache's textures at the end of the frame.
227    pub layer_cache_bytes: u64,
228    /// Image textures cached at the end of the frame.
229    pub image_cache_size: u32,
230    /// The largest isolated layers of the frame by pixel area, largest first, in the first
231    /// `top_isolated_layer_count` entries; the rest are `None`.
232    pub top_isolated_layers: [Option<IsolatedLayerStat>; TOP_ISOLATED_LAYER_LIMIT],
233    /// How many entries of `top_isolated_layers` are filled, at most eight.
234    pub top_isolated_layer_count: usize,
235}
236
237impl FrameStatsSnapshot {
238    fn shape_fill_by_class_text(&self) -> String {
239        let mut text = String::new();
240        for (label, pixels) in ShapeFill::LABELS
241            .iter()
242            .zip(self.shape_fill_pixels_by_class)
243        {
244            if pixels > 0 {
245                use std::fmt::Write;
246                let _ = write!(text, " {label}={:.2}MP", pixels as f64 / 1_000_000.0);
247            }
248        }
249        text
250    }
251
252    pub(crate) fn with_command_stats_added(mut self, stats: FrameCommandStats) -> Self {
253        self.submits = self.submits.saturating_add(stats.submit_count);
254        self.encoder_count = self.encoder_count.saturating_add(stats.encoder_count);
255        self.submit_count = self.submit_count.saturating_add(stats.submit_count);
256        self.pass_count = self.pass_count.saturating_add(stats.pass_count);
257        self.pass_pixels = self.pass_pixels.saturating_add(stats.pass_pixels);
258        self.copy_count = self.copy_count.saturating_add(stats.copy_count);
259        self.copy_pixels = self.copy_pixels.saturating_add(stats.copy_pixels);
260        self.transient_texture_bytes = self
261            .transient_texture_bytes
262            .saturating_add(stats.transient_texture_bytes);
263        self.retained_texture_bytes = self
264            .retained_texture_bytes
265            .max(stats.retained_texture_bytes);
266        self.upload_bytes = self.upload_bytes.saturating_add(stats.upload_bytes);
267        self.upload_writes = self.upload_writes.saturating_add(stats.upload_writes);
268        self.offscreen_acquires = self
269            .offscreen_acquires
270            .saturating_add(stats.transient_acquires);
271        self.offscreen_news = self.offscreen_news.saturating_add(stats.transient_news);
272        self
273    }
274
275    /// The largest isolated surface of the frame as `WxH@(x,y)` in device
276    /// pixels and logical origin, or `-`.
277    fn top_isolated_display(&self) -> String {
278        match &self.top_isolated_layers[0] {
279            Some(top) => format!(
280                "{}x{}@({:.0},{:.0})",
281                top.width, top.height, top.logical_rect.x, top.logical_rect.y
282            ),
283            None => "-".to_string(),
284        }
285    }
286
287    /// The largest isolated layers of the frame by pixel area, largest first.
288    pub fn top_isolated_layers(self) -> impl Iterator<Item = IsolatedLayerStat> {
289        self.top_isolated_layers
290            .into_iter()
291            .flatten()
292            .take(self.top_isolated_layer_count)
293    }
294
295    fn layer_cache_hit_rate(self) -> f64 {
296        let total = self.layer_cache_hits + self.layer_cache_misses;
297        if total > 0 {
298            (self.layer_cache_hits as f64 / total as f64) * 100.0
299        } else {
300            0.0
301        }
302    }
303
304    fn miss_pixels_by_kind_display(&self) -> String {
305        by_kind_display(&self.layer_cache_miss_pixels_by_kind, |pixels| {
306            format!("{:.2}MP", pixels as f64 / 1_000_000.0)
307        })
308    }
309
310    fn hits_by_kind_display(&self) -> String {
311        by_kind_display(&self.layer_cache_hits_by_kind, |hits| hits.to_string())
312    }
313
314    fn print(self, frame_count: u64) {
315        let mb = self.offscreen_total_bytes as f64 / (1024.0 * 1024.0);
316        let upload_mb = self.upload_bytes as f64 / (1024.0 * 1024.0);
317        let retained_mb = self.retained_texture_bytes as f64 / (1024.0 * 1024.0);
318        let pool_mb = self.offscreen_pool_bytes as f64 / (1024.0 * 1024.0);
319        let layer_cache_hit_mpx = self.layer_cache_hit_pixels as f64 / 1_000_000.0;
320        let layer_cache_miss_mpx = self.layer_cache_miss_pixels as f64 / 1_000_000.0;
321        let shadow_cache_hit_mpx = self.shadow_shape_cache_hit_pixels as f64 / 1_000_000.0;
322        let shadow_cache_miss_mpx = self.shadow_shape_cache_miss_pixels as f64 / 1_000_000.0;
323        let layer_cache_mb = self.layer_cache_bytes as f64 / (1024.0 * 1024.0);
324        let isolated_layer_mpx = self.isolated_layer_pixels as f64 / 1_000_000.0;
325        stats_line!(
326            "[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 | \
327             uploads={:.2}MB writes={} | \
328             isolated_layers={} area={:.2}MP top={} | \
329             layer_cache: hit={} miss={} {:.1}% hit_px={:.2}MP miss_px={:.2}MP size={}({:.1}MB) hit_by_kind={} miss_px_by_kind={} | \
330             shadow_cache: shape_hit={} shape_miss={} hit_px={:.2}MP miss_px={:.2}MP text_blur_fallback={} | \
331             stages={} admit={} blur={} substrate={} composite={} effect={} shader_px={:.2}MP glass_raster_px={:.2}MP blur_px={:.2}MP | shape={} shape_fill_px={:.2}MP{} shape_verts={} interiors={} depth_passes={} image={} text={} draws={} | \
332             text_img_cache: hit={} miss={} hit_px={:.2}MP miss_px={:.2}MP raster={:.2}MB | \
333             text_glyph_atlas: hit={} miss={} miss_px={:.2}MP runs_collected={} | \
334             caches: text_pool={} img={}",
335            frame_count,
336            self.encoder_count,
337            self.submit_count,
338            self.pass_count,
339            self.pass_pixels as f64 / 1_000_000.0,
340            self.copy_count,
341            self.copy_pixels as f64 / 1_000_000.0,
342            self.offscreen_acquires,
343            self.offscreen_news,
344            mb,
345            self.offscreen_pool_size,
346            pool_mb,
347            retained_mb,
348            upload_mb,
349            self.upload_writes,
350            self.isolated_layer_renders,
351            isolated_layer_mpx,
352            self.top_isolated_display(),
353            self.layer_cache_hits,
354            self.layer_cache_misses,
355            self.layer_cache_hit_rate(),
356            layer_cache_hit_mpx,
357            layer_cache_miss_mpx,
358            self.layer_cache_size,
359            layer_cache_mb,
360            self.hits_by_kind_display(),
361            self.miss_pixels_by_kind_display(),
362            self.shadow_shape_cache_hits,
363            self.shadow_shape_cache_misses,
364            shadow_cache_hit_mpx,
365            shadow_cache_miss_mpx,
366            self.shadow_text_blur_fallbacks,
367            self.stages,
368            self.backdrop_admissions,
369            self.blur_passes,
370            self.substrates,
371            self.composite_passes,
372            self.effect_applies,
373            self.shader_pixels as f64 / 1_000_000.0,
374            self.glass_rasterized_pixels as f64 / 1_000_000.0,
375            self.blur_pixels as f64 / 1_000_000.0,
376            self.shape_passes,
377            self.shape_fill_pixels as f64 / 1_000_000.0,
378            self.shape_fill_by_class_text(),
379            self.shape_vertices,
380            self.shape_interior_draws,
381            self.depth_passes,
382            self.image_passes,
383            self.text_passes,
384            self.draw_calls,
385            self.text_image_cache_hits,
386            self.text_image_cache_misses,
387            self.text_image_cache_hit_pixels as f64 / 1_000_000.0,
388            self.text_image_cache_miss_pixels as f64 / 1_000_000.0,
389            self.text_image_raster_bytes as f64 / (1024.0 * 1024.0),
390            self.text_glyph_atlas_hits,
391            self.text_glyph_atlas_misses,
392            self.text_glyph_atlas_miss_pixels as f64 / 1_000_000.0,
393            self.text_glyph_runs_collected,
394            self.text_pool_size,
395            self.image_cache_size,
396        );
397        for (index, layer) in self.top_isolated_layers().enumerate() {
398            stats_line!(
399                "  [isolated #{index}] node={:?} rect=({:.1},{:.1},{:.1},{:.1}) target={}x{}",
400                layer.node_id,
401                layer.logical_rect.x,
402                layer.logical_rect.y,
403                layer.logical_rect.width,
404                layer.logical_rect.height,
405                layer.width,
406                layer.height,
407            );
408        }
409    }
410}
411
412#[derive(Default)]
413pub(crate) struct FrameStats {
414    pub submits: Cell<u32>,
415    pub command_encoder_count: Cell<u32>,
416    pub command_submit_count: Cell<u32>,
417    pub command_pass_count: Cell<u32>,
418    pub command_pass_pixels: Cell<u64>,
419    pub command_copy_count: Cell<u32>,
420    pub command_copy_pixels: Cell<u64>,
421    pub command_transient_texture_bytes: Cell<u64>,
422    pub command_upload_bytes: Cell<u64>,
423    pub offscreen_acquires: Cell<u32>,
424    pub offscreen_news: Cell<u32>,
425    pub offscreen_total_bytes: Cell<u64>,
426    pub upload_writes: Cell<u32>,
427    pub isolated_layer_renders: Cell<u32>,
428    pub isolated_layer_pixels: Cell<u64>,
429    pub layer_cache_hits: Cell<u32>,
430    pub capture_fixup_passes: Cell<u32>,
431    pub layer_cache_misses: Cell<u32>,
432    pub layer_cache_hit_pixels: Cell<u64>,
433    pub layer_cache_miss_pixels: Cell<u64>,
434    pub layer_cache_hits_by_kind: [Cell<u32>; LAYER_RASTER_CACHE_KIND_COUNT],
435    pub layer_cache_misses_by_kind: [Cell<u32>; LAYER_RASTER_CACHE_KIND_COUNT],
436    pub layer_cache_miss_pixels_by_kind: [Cell<u64>; LAYER_RASTER_CACHE_KIND_COUNT],
437    pub shadow_shape_cache_hits: Cell<u32>,
438    pub shadow_shape_cache_misses: Cell<u32>,
439    pub shadow_shape_cache_hit_pixels: Cell<u64>,
440    pub shadow_shape_cache_miss_pixels: Cell<u64>,
441    pub shadow_text_blur_fallbacks: Cell<u32>,
442    pub blur_passes: Cell<u32>,
443    pub stages: Cell<u32>,
444    pub backdrop_admissions: Cell<u32>,
445    pub prefix_admissions: Cell<u32>,
446    pub substrates: Cell<u32>,
447    pub composite_passes: Cell<u32>,
448    pub effect_applies: Cell<u32>,
449    pub shader_pixels: Cell<u64>,
450    pub glass_rasterized_pixels: Cell<u64>,
451    pub blur_pixels: Cell<u64>,
452    pub shape_fill_pixels: Cell<u64>,
453    pub shape_fill_pixels_by_class: Cell<[u64; ShapeFill::CLASSES]>,
454    pub shape_vertices: Cell<u64>,
455    pub shape_passes: Cell<u32>,
456    pub shape_pipeline_fallback_draws: Cell<u32>,
457    pub shape_specialized_draws: Cell<u32>,
458    pub shape_interior_draws: Cell<u32>,
459    pub depth_passes: Cell<u32>,
460    pub shader_pipeline_fallback_draws: Cell<u32>,
461    pub shader_specialized_draws: Cell<u32>,
462    pub placeholder_draws: Cell<u32>,
463    pub image_passes: Cell<u32>,
464    pub text_passes: Cell<u32>,
465    pub draw_calls: Cell<u32>,
466    pub text_image_cache_hits: Cell<u32>,
467    pub text_image_cache_misses: Cell<u32>,
468    pub text_image_cache_hit_pixels: Cell<u64>,
469    pub text_image_cache_miss_pixels: Cell<u64>,
470    pub text_image_raster_bytes: Cell<u64>,
471    pub text_glyph_atlas_hits: Cell<u32>,
472    pub text_glyph_atlas_misses: Cell<u32>,
473    pub text_glyph_atlas_miss_pixels: Cell<u64>,
474    pub text_glyph_runs_collected: Cell<u32>,
475    pub offscreen_pool_size: Cell<u32>,
476    pub offscreen_pool_bytes: Cell<u64>,
477    pub text_pool_size: Cell<u32>,
478    pub layer_cache_size: Cell<u32>,
479    pub layer_cache_bytes: Cell<u64>,
480    pub image_cache_size: Cell<u32>,
481    top_isolated_layers: RefCell<[Option<IsolatedLayerStat>; TOP_ISOLATED_LAYER_LIMIT]>,
482    top_isolated_layer_count: Cell<usize>,
483    shadow_shape_cache_miss_log_count: Cell<u32>,
484}
485
486impl FrameStats {
487    pub fn record_capture_fixup_pass(&self) {
488        self.capture_fixup_passes
489            .set(self.capture_fixup_passes.get().saturating_add(1));
490    }
491
492    pub fn record_stages(&self, count: u32) {
493        self.stages.set(self.stages.get().saturating_add(count));
494    }
495
496    pub fn record_backdrop_admission(&self) {
497        self.backdrop_admissions
498            .set(self.backdrop_admissions.get().saturating_add(1));
499    }
500
501    pub fn record_prefix_admission(&self) {
502        self.prefix_admissions
503            .set(self.prefix_admissions.get().saturating_add(1));
504    }
505
506    pub fn record_command_stats(&self, stats: FrameCommandStats) {
507        self.submits
508            .set(self.submits.get().saturating_add(stats.submit_count));
509        self.command_encoder_count.set(
510            self.command_encoder_count
511                .get()
512                .saturating_add(stats.encoder_count),
513        );
514        self.command_submit_count.set(
515            self.command_submit_count
516                .get()
517                .saturating_add(stats.submit_count),
518        );
519        self.command_pass_count.set(
520            self.command_pass_count
521                .get()
522                .saturating_add(stats.pass_count),
523        );
524        self.command_pass_pixels.set(
525            self.command_pass_pixels
526                .get()
527                .saturating_add(stats.pass_pixels),
528        );
529        self.command_copy_count.set(
530            self.command_copy_count
531                .get()
532                .saturating_add(stats.copy_count),
533        );
534        self.command_copy_pixels.set(
535            self.command_copy_pixels
536                .get()
537                .saturating_add(stats.copy_pixels),
538        );
539        self.command_transient_texture_bytes.set(
540            self.command_transient_texture_bytes
541                .get()
542                .saturating_add(stats.transient_texture_bytes),
543        );
544        self.command_upload_bytes.set(
545            self.command_upload_bytes
546                .get()
547                .saturating_add(stats.upload_bytes),
548        );
549        self.upload_writes
550            .set(self.upload_writes.get().saturating_add(stats.upload_writes));
551        self.offscreen_acquires.set(
552            self.offscreen_acquires
553                .get()
554                .saturating_add(stats.transient_acquires),
555        );
556        self.offscreen_news.set(
557            self.offscreen_news
558                .get()
559                .saturating_add(stats.transient_news),
560        );
561    }
562
563    pub fn record_offscreen_acquire(
564        &self,
565        width: u32,
566        height: u32,
567        format: wgpu::TextureFormat,
568        is_new: bool,
569    ) {
570        self.offscreen_acquires
571            .set(self.offscreen_acquires.get() + 1);
572        if is_new {
573            self.offscreen_news.set(self.offscreen_news.get() + 1);
574        }
575        self.offscreen_total_bytes.set(
576            self.offscreen_total_bytes.get()
577                + (width as u64)
578                    * (height as u64)
579                    * crate::frame_graph::texture_format_bytes_per_pixel(format),
580        );
581    }
582
583    pub fn record_isolated_layer_render(
584        &self,
585        width: u32,
586        height: u32,
587        node_id: Option<NodeId>,
588        logical_rect: Rect,
589    ) {
590        self.isolated_layer_renders
591            .set(self.isolated_layer_renders.get().saturating_add(1));
592        self.isolated_layer_pixels.set(
593            self.isolated_layer_pixels
594                .get()
595                .saturating_add((width as u64) * (height as u64)),
596        );
597        self.record_top_isolated_layer(IsolatedLayerStat {
598            node_id,
599            logical_rect,
600            width,
601            height,
602        });
603    }
604
605    pub fn record_layer_cache_hit(&self, key: &LayerRasterCacheKey, width: u32, height: u32) {
606        let by_kind = &self.layer_cache_hits_by_kind[key.kind_slot()];
607        by_kind.set(by_kind.get().saturating_add(1));
608        self.layer_cache_hits
609            .set(self.layer_cache_hits.get().saturating_add(1));
610        self.layer_cache_hit_pixels.set(
611            self.layer_cache_hit_pixels
612                .get()
613                .saturating_add((width as u64) * (height as u64)),
614        );
615    }
616
617    pub fn record_layer_cache_miss(&self, key: &LayerRasterCacheKey, width: u32, height: u32) {
618        let slot = key.kind_slot();
619        let by_kind = &self.layer_cache_misses_by_kind[slot];
620        by_kind.set(by_kind.get().saturating_add(1));
621        let pixels_by_kind = &self.layer_cache_miss_pixels_by_kind[slot];
622        pixels_by_kind.set(
623            pixels_by_kind
624                .get()
625                .saturating_add((width as u64) * (height as u64)),
626        );
627        self.layer_cache_misses
628            .set(self.layer_cache_misses.get().saturating_add(1));
629        self.layer_cache_miss_pixels.set(
630            self.layer_cache_miss_pixels
631                .get()
632                .saturating_add((width as u64) * (height as u64)),
633        );
634    }
635
636    pub fn record_shadow_shape_cache_hit(&self, composited_pixels: u64) {
637        self.shadow_shape_cache_hits
638            .set(self.shadow_shape_cache_hits.get().saturating_add(1));
639        self.shadow_shape_cache_hit_pixels.set(
640            self.shadow_shape_cache_hit_pixels
641                .get()
642                .saturating_add(composited_pixels),
643        );
644    }
645
646    pub fn record_shadow_shape_cache_miss(&self, width: u32, height: u32) {
647        self.shadow_shape_cache_misses
648            .set(self.shadow_shape_cache_misses.get().saturating_add(1));
649        self.shadow_shape_cache_miss_pixels.set(
650            self.shadow_shape_cache_miss_pixels
651                .get()
652                .saturating_add((width as u64) * (height as u64)),
653        );
654    }
655
656    #[expect(clippy::too_many_arguments)]
657    pub fn maybe_print_shadow_shape_cache_miss(
658        &self,
659        width: u32,
660        height: u32,
661        content_hash: u64,
662        blur_radius: f32,
663        viewport_offset: [f32; 2],
664        shape_count: usize,
665        clip: Option<Rect>,
666    ) {
667        if !shadow_cache_diagnostics_enabled() {
668            return;
669        }
670
671        let count = self.shadow_shape_cache_miss_log_count.get();
672        if count >= 16 {
673            return;
674        }
675        self.shadow_shape_cache_miss_log_count.set(count + 1);
676
677        let clip_text = clip.map_or_else(
678            || "none".to_string(),
679            |clip| {
680                format!(
681                    "({:.1},{:.1},{:.1},{:.1})",
682                    clip.x, clip.y, clip.width, clip.height
683                )
684            },
685        );
686        stats_line!(
687            "[shadow-cache-miss #{count}] size={}x{} content_hash={content_hash} blur={:.2} viewport_offset=({:.1},{:.1}) shapes={} clip={}",
688            width,
689            height,
690            blur_radius,
691            viewport_offset[0],
692            viewport_offset[1],
693            shape_count,
694            clip_text,
695        );
696    }
697
698    pub fn record_shadow_text_blur_fallback(&self) {
699        self.shadow_text_blur_fallbacks
700            .set(self.shadow_text_blur_fallbacks.get().saturating_add(1));
701    }
702
703    pub fn add_shape_fill(&self, fill: ShapeFill) {
704        self.shape_fill_pixels.set(
705            self.shape_fill_pixels
706                .get()
707                .saturating_add(fill.total().round() as u64),
708        );
709        let mut by_class = self.shape_fill_pixels_by_class.get();
710        for (total, pixels) in by_class.iter_mut().zip(fill.pixels) {
711            *total = total.saturating_add(pixels.round() as u64);
712        }
713        self.shape_fill_pixels_by_class.set(by_class);
714        self.shape_vertices
715            .set(self.shape_vertices.get().saturating_add(fill.vertices));
716    }
717
718    pub fn bump_shapes(&self) {
719        self.shape_passes.set(self.shape_passes.get() + 1);
720    }
721
722    pub fn bump_images(&self) {
723        self.image_passes.set(self.image_passes.get() + 1);
724    }
725
726    pub fn add_draw_calls(&self, count: u32) {
727        self.draw_calls
728            .set(self.draw_calls.get().saturating_add(count));
729    }
730
731    pub fn bump_text(&self) {
732        self.text_passes.set(self.text_passes.get() + 1);
733    }
734
735    pub fn record_text_image_cache_hit(&self, width: u32, height: u32) {
736        self.text_image_cache_hits
737            .set(self.text_image_cache_hits.get().saturating_add(1));
738        self.text_image_cache_hit_pixels.set(
739            self.text_image_cache_hit_pixels
740                .get()
741                .saturating_add((width as u64) * (height as u64)),
742        );
743    }
744
745    pub fn record_text_image_cache_miss(&self, width: u32, height: u32) {
746        let pixels = (width as u64) * (height as u64);
747        self.text_image_cache_misses
748            .set(self.text_image_cache_misses.get().saturating_add(1));
749        self.text_image_cache_miss_pixels.set(
750            self.text_image_cache_miss_pixels
751                .get()
752                .saturating_add(pixels),
753        );
754        self.text_image_raster_bytes.set(
755            self.text_image_raster_bytes
756                .get()
757                .saturating_add(pixels * 4),
758        );
759    }
760
761    pub fn record_text_glyph_atlas_hits(&self, count: u32) {
762        self.text_glyph_atlas_hits
763            .set(self.text_glyph_atlas_hits.get().saturating_add(count));
764    }
765
766    pub fn record_text_glyph_run_collected(&self) {
767        self.text_glyph_runs_collected
768            .set(self.text_glyph_runs_collected.get().saturating_add(1));
769    }
770
771    pub fn record_text_glyph_atlas_miss(&self, width: u32, height: u32) {
772        self.text_glyph_atlas_misses
773            .set(self.text_glyph_atlas_misses.get().saturating_add(1));
774        self.text_glyph_atlas_miss_pixels.set(
775            self.text_glyph_atlas_miss_pixels
776                .get()
777                .saturating_add((width as u64) * (height as u64)),
778        );
779    }
780
781    pub fn snapshot(&self) -> FrameStatsSnapshot {
782        let retained_texture_bytes = self
783            .offscreen_pool_bytes
784            .get()
785            .saturating_add(self.layer_cache_bytes.get());
786        FrameStatsSnapshot {
787            submits: self.submits.get(),
788            encoder_count: self.command_encoder_count.get(),
789            submit_count: self.command_submit_count.get(),
790            pass_count: self.command_pass_count.get(),
791            pass_pixels: self.command_pass_pixels.get(),
792            copy_count: self.command_copy_count.get(),
793            copy_pixels: self.command_copy_pixels.get(),
794            offscreen_acquires: self.offscreen_acquires.get(),
795            offscreen_news: self.offscreen_news.get(),
796            offscreen_total_bytes: self.offscreen_total_bytes.get(),
797            transient_texture_bytes: self
798                .offscreen_total_bytes
799                .get()
800                .saturating_add(self.command_transient_texture_bytes.get()),
801            retained_texture_bytes,
802            upload_bytes: self.command_upload_bytes.get(),
803            upload_writes: self.upload_writes.get(),
804            isolated_layer_renders: self.isolated_layer_renders.get(),
805            isolated_layer_pixels: self.isolated_layer_pixels.get(),
806            layer_cache_hits: self.layer_cache_hits.get(),
807            capture_fixup_passes: self.capture_fixup_passes.get(),
808            layer_cache_misses: self.layer_cache_misses.get(),
809            layer_cache_hit_pixels: self.layer_cache_hit_pixels.get(),
810            layer_cache_miss_pixels: self.layer_cache_miss_pixels.get(),
811            layer_cache_hits_by_kind: self.layer_cache_hits_by_kind.each_ref().map(Cell::get),
812            layer_cache_misses_by_kind: self.layer_cache_misses_by_kind.each_ref().map(Cell::get),
813            layer_cache_miss_pixels_by_kind: self
814                .layer_cache_miss_pixels_by_kind
815                .each_ref()
816                .map(Cell::get),
817            shadow_shape_cache_hits: self.shadow_shape_cache_hits.get(),
818            shadow_shape_cache_misses: self.shadow_shape_cache_misses.get(),
819            shadow_shape_cache_hit_pixels: self.shadow_shape_cache_hit_pixels.get(),
820            shadow_shape_cache_miss_pixels: self.shadow_shape_cache_miss_pixels.get(),
821            shadow_text_blur_fallbacks: self.shadow_text_blur_fallbacks.get(),
822            blur_passes: self.blur_passes.get(),
823            stages: self.stages.get(),
824            backdrop_admissions: self.backdrop_admissions.get(),
825            prefix_admissions: self.prefix_admissions.get(),
826            substrates: self.substrates.get(),
827            composite_passes: self.composite_passes.get(),
828            effect_applies: self.effect_applies.get(),
829            shader_pixels: self.shader_pixels.get(),
830            glass_rasterized_pixels: self.glass_rasterized_pixels.get(),
831            blur_pixels: self.blur_pixels.get(),
832            shape_fill_pixels: self.shape_fill_pixels.get(),
833            shape_fill_pixels_by_class: self.shape_fill_pixels_by_class.get(),
834            shape_vertices: self.shape_vertices.get(),
835            shape_passes: self.shape_passes.get(),
836            shape_pipeline_fallback_draws: self.shape_pipeline_fallback_draws.get(),
837            shape_specialized_draws: self.shape_specialized_draws.get(),
838            shape_interior_draws: self.shape_interior_draws.get(),
839            depth_passes: self.depth_passes.get(),
840            pipelines_created: crate::render::pipelines_created(),
841            shader_pipeline_fallback_draws: self.shader_pipeline_fallback_draws.get(),
842            shader_specialized_draws: self.shader_specialized_draws.get(),
843            placeholder_draws: self.placeholder_draws.get(),
844            image_passes: self.image_passes.get(),
845            text_passes: self.text_passes.get(),
846            draw_calls: self.draw_calls.get(),
847            text_image_cache_hits: self.text_image_cache_hits.get(),
848            text_image_cache_misses: self.text_image_cache_misses.get(),
849            text_image_cache_hit_pixels: self.text_image_cache_hit_pixels.get(),
850            text_image_cache_miss_pixels: self.text_image_cache_miss_pixels.get(),
851            text_image_raster_bytes: self.text_image_raster_bytes.get(),
852            text_glyph_atlas_hits: self.text_glyph_atlas_hits.get(),
853            text_glyph_atlas_misses: self.text_glyph_atlas_misses.get(),
854            text_glyph_atlas_miss_pixels: self.text_glyph_atlas_miss_pixels.get(),
855            text_glyph_runs_collected: self.text_glyph_runs_collected.get(),
856            offscreen_pool_size: self.offscreen_pool_size.get(),
857            offscreen_pool_bytes: self.offscreen_pool_bytes.get(),
858            text_pool_size: self.text_pool_size.get(),
859            layer_cache_size: self.layer_cache_size.get(),
860            layer_cache_bytes: self.layer_cache_bytes.get(),
861            image_cache_size: self.image_cache_size.get(),
862            top_isolated_layers: *self.top_isolated_layers.borrow(),
863            top_isolated_layer_count: self.top_isolated_layer_count.get(),
864        }
865    }
866
867    pub fn reset(&self) {
868        self.submits.set(0);
869        self.command_encoder_count.set(0);
870        self.command_submit_count.set(0);
871        self.command_pass_count.set(0);
872        self.command_pass_pixels.set(0);
873        self.command_copy_count.set(0);
874        self.command_copy_pixels.set(0);
875        self.command_transient_texture_bytes.set(0);
876        self.command_upload_bytes.set(0);
877        self.upload_writes.set(0);
878        self.offscreen_acquires.set(0);
879        self.offscreen_news.set(0);
880        self.offscreen_total_bytes.set(0);
881        self.isolated_layer_renders.set(0);
882        self.isolated_layer_pixels.set(0);
883        self.layer_cache_hits.set(0);
884        self.capture_fixup_passes.set(0);
885        self.layer_cache_misses.set(0);
886        self.layer_cache_hit_pixels.set(0);
887        self.layer_cache_miss_pixels.set(0);
888        for slot in 0..LAYER_RASTER_CACHE_KIND_COUNT {
889            self.layer_cache_hits_by_kind[slot].set(0);
890            self.layer_cache_misses_by_kind[slot].set(0);
891            self.layer_cache_miss_pixels_by_kind[slot].set(0);
892        }
893        self.shadow_shape_cache_hits.set(0);
894        self.shadow_shape_cache_misses.set(0);
895        self.shadow_shape_cache_hit_pixels.set(0);
896        self.shadow_shape_cache_miss_pixels.set(0);
897        self.shadow_text_blur_fallbacks.set(0);
898        self.blur_passes.set(0);
899        self.stages.set(0);
900        self.backdrop_admissions.set(0);
901        self.prefix_admissions.set(0);
902        self.substrates.set(0);
903        self.composite_passes.set(0);
904        self.effect_applies.set(0);
905        self.shader_pixels.set(0);
906        self.glass_rasterized_pixels.set(0);
907        self.blur_pixels.set(0);
908        self.shape_fill_pixels.set(0);
909        self.shape_fill_pixels_by_class.set([0; ShapeFill::CLASSES]);
910        self.shape_vertices.set(0);
911        self.shape_passes.set(0);
912        self.shape_pipeline_fallback_draws.set(0);
913        self.shape_specialized_draws.set(0);
914        self.shape_interior_draws.set(0);
915        self.depth_passes.set(0);
916        self.shader_pipeline_fallback_draws.set(0);
917        self.shader_specialized_draws.set(0);
918        self.placeholder_draws.set(0);
919        self.image_passes.set(0);
920        self.text_passes.set(0);
921        self.draw_calls.set(0);
922        self.text_image_cache_hits.set(0);
923        self.text_image_cache_misses.set(0);
924        self.text_image_cache_hit_pixels.set(0);
925        self.text_image_cache_miss_pixels.set(0);
926        self.text_image_raster_bytes.set(0);
927        self.text_glyph_atlas_hits.set(0);
928        self.text_glyph_atlas_misses.set(0);
929        self.text_glyph_atlas_miss_pixels.set(0);
930        self.text_glyph_runs_collected.set(0);
931        *self.top_isolated_layers.borrow_mut() = [None; TOP_ISOLATED_LAYER_LIMIT];
932        self.top_isolated_layer_count.set(0);
933        self.shadow_shape_cache_miss_log_count.set(0);
934    }
935
936    pub fn maybe_print_snapshot(
937        &self,
938        snapshot: FrameStatsSnapshot,
939        frame_count: &mut u64,
940        enabled: bool,
941    ) {
942        if !enabled {
943            return;
944        }
945        *frame_count += 1;
946        if (*frame_count).is_multiple_of(60) {
947            snapshot.print(*frame_count);
948        }
949    }
950
951    fn record_top_isolated_layer(&self, layer: IsolatedLayerStat) {
952        let mut top_layers = self.top_isolated_layers.borrow_mut();
953        let len = self.top_isolated_layer_count.get();
954        let insert_at = top_layers[..len]
955            .iter()
956            .enumerate()
957            .find_map(|(index, existing)| {
958                existing
959                    .filter(|existing| layer.pixel_area() > existing.pixel_area())
960                    .map(|_| index)
961            })
962            .unwrap_or(len);
963
964        if insert_at >= TOP_ISOLATED_LAYER_LIMIT {
965            return;
966        }
967
968        let new_len = if len < TOP_ISOLATED_LAYER_LIMIT {
969            len + 1
970        } else {
971            TOP_ISOLATED_LAYER_LIMIT
972        };
973
974        let mut index = new_len.saturating_sub(1);
975        while index > insert_at {
976            top_layers[index] = top_layers[index - 1];
977            index -= 1;
978        }
979        top_layers[insert_at] = Some(layer);
980        self.top_isolated_layer_count.set(new_len);
981    }
982}
983
984static GPU_STATS: DebugToggle = DebugToggle::new("CRANPOSE_GPU_STATS");
985
986pub(crate) fn gpu_stats_enabled() -> bool {
987    GPU_STATS.flag()
988}
989
990pub(crate) fn print_gpu_memory_report(device: &wgpu::Device, frame_count: u64) {
991    let Some(report) = device.generate_allocator_report() else {
992        return;
993    };
994
995    const MB: f64 = 1024.0 * 1024.0;
996    let mut blocks = String::new();
997    for block in &report.blocks {
998        if !blocks.is_empty() {
999            blocks.push('+');
1000        }
1001        blocks.push_str(&format!("{:.1}", block.size as f64 / MB));
1002    }
1003
1004    stats_line!(
1005        "[GPU-MEM f#{}] reserved={:.1}MB allocated={:.1}MB blocks={}[{}MB] allocations={} | largest={:.6?}",
1006        frame_count,
1007        report.total_reserved_bytes as f64 / MB,
1008        report.total_allocated_bytes as f64 / MB,
1009        report.blocks.len(),
1010        blocks,
1011        report.allocations.len(),
1012        report,
1013    );
1014}
1015
1016static SHADOW_CACHE_DIAG: DebugToggle = DebugToggle::new("CRANPOSE_GPU_SHADOW_CACHE_DIAG");
1017
1018fn shadow_cache_diagnostics_enabled() -> bool {
1019    SHADOW_CACHE_DIAG.flag()
1020}
1021
1022fn by_kind_display<T: Copy + Default + PartialEq>(
1023    by_kind: &[T; LAYER_RASTER_CACHE_KIND_COUNT],
1024    format: impl Fn(T) -> String,
1025) -> String {
1026    LAYER_RASTER_CACHE_KIND_LABELS
1027        .iter()
1028        .zip(by_kind)
1029        .filter(|(_, value)| **value != T::default())
1030        .map(|(label, value)| format!("{label}={}", format(*value)))
1031        .collect::<Vec<_>>()
1032        .join(",")
1033}
1034
1035#[cfg(test)]
1036#[path = "tests/gpu_stats_tests.rs"]
1037mod tests;