Skip to main content

mgui_core/
cache_stats.rs

1//! GPU layer cache 可观测契约(0.6 M3 / DT-06)。
2//!
3//! 这一层只定义**口径与数值容器**,不依赖 wgpu:renderer 填数,DevTools 读数,
4//! trace 记录原因与恢复时间。采集开关在 [`crate::frame::cache_stats_collecting()`]:
5//! 编译期 `profiling` 或运行期 DevTools 面板可见时才收集,其余时候字段恒 0,
6//! 工具读到 0 必须按「未量到」处理,不能当成「无失效」。
7
8/// 一次 layer cache 失效的归因。renderer 能直接判定 layout / visibility;
9/// 其余由宿主在主题、DPR、atlas、图片、设备丢失、窗口重建时显式调用 `note`。
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum CacheInvalidationReason {
12    #[default]
13    Theme,
14    Dpr,
15    Atlas,
16    Font,
17    Image,
18    Layout,
19    DeviceLost,
20    WindowRecreate,
21    Visibility,
22}
23
24impl CacheInvalidationReason {
25    pub const ALL: [Self; 9] = [
26        Self::Theme,
27        Self::Dpr,
28        Self::Atlas,
29        Self::Font,
30        Self::Image,
31        Self::Layout,
32        Self::DeviceLost,
33        Self::WindowRecreate,
34        Self::Visibility,
35    ];
36
37    pub fn name(self) -> &'static str {
38        match self {
39            Self::Theme => "theme",
40            Self::Dpr => "dpr",
41            Self::Atlas => "atlas",
42            Self::Font => "font",
43            Self::Image => "image",
44            Self::Layout => "layout",
45            Self::DeviceLost => "device_lost",
46            Self::WindowRecreate => "window_recreate",
47            Self::Visibility => "visibility",
48        }
49    }
50}
51
52/// 单帧 cache 统计。所有字段在采集关闭时恒 0。
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
54pub struct CacheStats {
55    /// 本帧命中持久 resolve texture 且无需重画的 layer 数
56    pub layer_hits: u32,
57    /// 本帧未命中(新建 / 尺寸重建 / dirty 重画)的 layer 数
58    pub layer_misses: u32,
59    /// resolve texture 因尺寸变化重建的次数
60    pub texture_recreates: u32,
61    /// 各归因的本帧失效次数,顺序同 [`CacheInvalidationReason::ALL`]
62    pub invalidations: [u32; 9],
63    /// 本帧估算的 GPU 常驻字节数(layer + atlas + 图片 + scratch)
64    pub vram_bytes: u64,
65    /// 会话内显存高水位
66    pub vram_high_watermark_bytes: u64,
67    /// 本帧从最近一次失效记录到本帧完成提交的恢复耗时(ns)
68    pub recovery_ns: u64,
69    /// 本帧计算 layer 内容 key 的 CPU 耗时(ns)。关闭增量 key 时恒 0。
70    pub key_ns: u64,
71    /// 本帧「被标脏但内容 key 未变、因此跳过重画」的 layer 数。
72    pub content_skips: u32,
73}
74
75impl CacheStats {
76    pub fn invalidation(&self, reason: CacheInvalidationReason) -> u32 {
77        self.invalidations[reason as usize]
78    }
79
80    /// UI / trace 用的紧凑摘要;未发生的归因不会输出。
81    pub fn invalidation_summary(&self) -> String {
82        let parts: Vec<&'static str> =
83            CacheInvalidationReason::ALL.into_iter().filter(|r| self.invalidation(*r) > 0).map(|r| r.name()).collect();
84        if parts.is_empty() {
85            "none".to_string()
86        } else {
87            parts.join(",")
88        }
89    }
90
91    /// 采集侧累加一次失效归因(由 renderer 的宿主入口调用)。
92    pub fn note_invalidation(&mut self, reason: CacheInvalidationReason) {
93        self.invalidations[reason as usize] = self.invalidations[reason as usize].saturating_add(1);
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn invalidation_reasons_are_stable_and_named() {
103        let names: Vec<&str> = CacheInvalidationReason::ALL.iter().map(|r| r.name()).collect();
104        assert_eq!(
105            names,
106            vec!["theme", "dpr", "atlas", "font", "image", "layout", "device_lost", "window_recreate", "visibility"]
107        );
108        assert_eq!(CacheInvalidationReason::default(), CacheInvalidationReason::Theme);
109    }
110
111    #[test]
112    fn invalidation_summary_omits_zero_reasons() {
113        let mut stats = CacheStats::default();
114        assert_eq!(stats.invalidation_summary(), "none");
115        stats.note_invalidation(CacheInvalidationReason::Atlas);
116        stats.note_invalidation(CacheInvalidationReason::Layout);
117        assert_eq!(stats.invalidation(CacheInvalidationReason::Atlas), 1);
118        assert_eq!(stats.invalidation_summary(), "atlas,layout");
119    }
120}