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    Image,
17    Layout,
18    DeviceLost,
19    WindowRecreate,
20    Visibility,
21}
22
23impl CacheInvalidationReason {
24    pub const ALL: [Self; 8] = [
25        Self::Theme,
26        Self::Dpr,
27        Self::Atlas,
28        Self::Image,
29        Self::Layout,
30        Self::DeviceLost,
31        Self::WindowRecreate,
32        Self::Visibility,
33    ];
34
35    pub fn name(self) -> &'static str {
36        match self {
37            Self::Theme => "theme",
38            Self::Dpr => "dpr",
39            Self::Atlas => "atlas",
40            Self::Image => "image",
41            Self::Layout => "layout",
42            Self::DeviceLost => "device_lost",
43            Self::WindowRecreate => "window_recreate",
44            Self::Visibility => "visibility",
45        }
46    }
47}
48
49/// 单帧 cache 统计。所有字段在采集关闭时恒 0。
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
51pub struct CacheStats {
52    /// 本帧命中持久 resolve texture 且无需重画的 layer 数
53    pub layer_hits: u32,
54    /// 本帧未命中(新建 / 尺寸重建 / dirty 重画)的 layer 数
55    pub layer_misses: u32,
56    /// resolve texture 因尺寸变化重建的次数
57    pub texture_recreates: u32,
58    /// 各归因的本帧失效次数,顺序同 [`CacheInvalidationReason::ALL`]
59    pub invalidations: [u32; 8],
60    /// 本帧估算的 GPU 常驻字节数(layer + atlas + 图片 + scratch)
61    pub vram_bytes: u64,
62    /// 会话内显存高水位
63    pub vram_high_watermark_bytes: u64,
64    /// 本帧从最近一次失效记录到本帧完成提交的恢复耗时(ns)
65    pub recovery_ns: u64,
66    /// 本帧计算 layer 内容 key 的 CPU 耗时(ns)。关闭增量 key 时恒 0。
67    pub key_ns: u64,
68    /// 本帧「被标脏但内容 key 未变、因此跳过重画」的 layer 数。
69    pub content_skips: u32,
70}
71
72impl CacheStats {
73    pub fn invalidation(&self, reason: CacheInvalidationReason) -> u32 {
74        self.invalidations[reason as usize]
75    }
76
77    /// UI / trace 用的紧凑摘要;未发生的归因不会输出。
78    pub fn invalidation_summary(&self) -> String {
79        let parts: Vec<&'static str> =
80            CacheInvalidationReason::ALL.into_iter().filter(|r| self.invalidation(*r) > 0).map(|r| r.name()).collect();
81        if parts.is_empty() {
82            "none".to_string()
83        } else {
84            parts.join(",")
85        }
86    }
87
88    /// 采集侧累加一次失效归因(由 renderer 的宿主入口调用)。
89    pub fn note_invalidation(&mut self, reason: CacheInvalidationReason) {
90        self.invalidations[reason as usize] = self.invalidations[reason as usize].saturating_add(1);
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn invalidation_reasons_are_stable_and_named() {
100        let names: Vec<&str> = CacheInvalidationReason::ALL.iter().map(|r| r.name()).collect();
101        assert_eq!(
102            names,
103            vec!["theme", "dpr", "atlas", "image", "layout", "device_lost", "window_recreate", "visibility"]
104        );
105        assert_eq!(CacheInvalidationReason::default(), CacheInvalidationReason::Theme);
106    }
107
108    #[test]
109    fn invalidation_summary_omits_zero_reasons() {
110        let mut stats = CacheStats::default();
111        assert_eq!(stats.invalidation_summary(), "none");
112        stats.note_invalidation(CacheInvalidationReason::Atlas);
113        stats.note_invalidation(CacheInvalidationReason::Layout);
114        assert_eq!(stats.invalidation(CacheInvalidationReason::Atlas), 1);
115        assert_eq!(stats.invalidation_summary(), "atlas,layout");
116    }
117}