Skip to main content

mgui_runtime/renderer/
setup.rs

1//! Renderer 构建与 GPU 资源创建(new / pipeline / atlas / layer cache)。
2//! 从 renderer.rs 拆出;struct 定义在父模块,后代模块可访问其私有字段。
3
4use super::composition::LayerComposition;
5use super::*;
6use mgui_core::paint::BlendMode;
7use std::collections::hash_map::DefaultHasher;
8use std::collections::HashSet;
9use std::hash::{Hash, Hasher};
10
11const STENCIL_FMT: wgpu::TextureFormat = wgpu::TextureFormat::Stencil8;
12
13/// PaintList 实际引用到的非 atlas texture id(去重、升序)。
14/// atlas id 0 的失效由 `mgui_core::element::resource_epoch()` 单独覆盖。
15fn referenced_texture_ids(paint_list: &PaintList) -> Vec<u32> {
16    let mut ids = Vec::new();
17    for command in &paint_list.commands {
18        let id = match command {
19            PaintCommand::TexturedRect { texture_id, .. } | PaintCommand::MaskRect { texture_id, .. } => *texture_id,
20            _ => continue,
21        };
22        if id != 0 && !ids.contains(&id) {
23            ids.push(id);
24        }
25    }
26    ids.sort_unstable();
27    ids
28}
29
30/// 所有 layer resolve texture 的总字节预算(256 MiB,与图片纹理预算一致)。
31pub const LAYER_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
32
33/// 单层目标纹理尺寸。
34pub(crate) type LayerTextureSize = (LayerId, (u32, u32));
35/// `(每层尺寸, 实际缩放系数)`。
36pub(crate) type LayerTextureTargets = (Vec<LayerTextureSize>, f32);
37
38/// 单个 layer 的目标纹理尺寸(logical → 物理,再钳制设备上限)。
39fn layer_tex_size(logical: Option<Size>, dpr: f32, screen: (f32, f32), max_dim: u32) -> (u32, u32) {
40    let (w, h) = match logical {
41        Some(s) => (s.width, s.height),
42        None => screen,
43    };
44    // NaN/负数 → 0,无穷大 → u32::MAX;两者都由 max/min 收敛到合法范围。
45    let w = (w * dpr).ceil() as u32;
46    let h = (h * dpr).ceil() as u32;
47    (w.max(1).min(max_dim), h.max(1).min(max_dim))
48}
49
50fn layer_tex_total_bytes(sizes: &[LayerTextureSize]) -> u64 {
51    sizes.iter().map(|&(_, (w, h))| w as u64 * h as u64 * 4).sum()
52}
53
54/// 计算本帧所有 layer 的目标纹理尺寸(P1-4 资源预算)。
55///
56/// - 每层按 `logical_size * dpr`(None → 视口)向上取整,并钳制到
57///   `max_dim`(防异常 content_size 触发纹理创建失败);
58/// - 若总字节超过 `budget`,统一按面积比例降采样到预算内。图层绘制仍按
59///   逻辑尺寸归一化、blit 时再拉伸回逻辑尺寸,因此几何/命中不变,只降低
60///   极端场景下的分辨率。
61///
62/// 返回 `(每层尺寸, 实际缩放系数)`;正常情况缩放系数为 1.0。
63pub(crate) fn layer_texture_targets(
64    layer_paints: &[LayerPaint],
65    dpr: f32,
66    screen_size: (f32, f32),
67    max_dim: u32,
68    budget: u64,
69) -> LayerTextureTargets {
70    let dpr = if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 };
71    let max_dim = max_dim.max(1);
72    let compute = |scale: f32| -> Vec<LayerTextureSize> {
73        layer_paints
74            .iter()
75            .map(|lp| (lp.layer_id, layer_tex_size(lp.logical_size, dpr * scale, screen_size, max_dim)))
76            .collect()
77    };
78
79    let mut scale = 1.0f32;
80    let mut sizes = compute(scale);
81    let mut total = layer_tex_total_bytes(&sizes);
82    if total > budget {
83        // ceil()/1px 下限会让首次缩放后略超预算;迭代收紧几次直到收敛。
84        for _ in 0..8 {
85            if total <= budget {
86                break;
87            }
88            let factor = ((budget as f64) / (total as f64)).sqrt().clamp(0.05, 0.99);
89            let next = (scale as f64 * factor) as f32;
90            if next >= scale || next <= 0.01 {
91                break;
92            }
93            scale = next;
94            sizes = compute(scale);
95            total = layer_tex_total_bytes(&sizes);
96        }
97        // 量化到 1/8 步长:overlay 开合导致层数小幅变化时不至于让
98        // 所有 layer texture 反复重建。向下取整只会更省(仍然 ≤ 预算)。
99        let quantized = (scale * 8.0).floor() / 8.0;
100        if quantized > 0.0 && quantized < scale {
101            scale = quantized;
102            sizes = compute(scale);
103        }
104    }
105    (sizes, scale)
106}
107
108/// 固定功能可实现的混合模式子集(矩形族)。
109fn blend_state_for(mode: BlendMode) -> wgpu::BlendState {
110    use wgpu::{BlendComponent, BlendFactor, BlendOperation, BlendState};
111    let comp = |src_factor, dst_factor| BlendComponent { src_factor, dst_factor, operation: BlendOperation::Add };
112    match mode {
113        BlendMode::Normal => BlendState::ALPHA_BLENDING,
114        BlendMode::Multiply => BlendState {
115            color: comp(BlendFactor::Dst, BlendFactor::Zero),
116            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
117        },
118        BlendMode::Screen => BlendState {
119            color: comp(BlendFactor::One, BlendFactor::OneMinusSrc),
120            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
121        },
122        BlendMode::Add => BlendState {
123            color: comp(BlendFactor::One, BlendFactor::One),
124            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
125        },
126    }
127}
128
129/// ClipPath/ClipRRect 内容测试:stencil == reference,不写 stencil。
130fn stencil_equal_state() -> wgpu::DepthStencilState {
131    let face = wgpu::StencilFaceState {
132        compare: wgpu::CompareFunction::Equal,
133        fail_op: wgpu::StencilOperation::Keep,
134        depth_fail_op: wgpu::StencilOperation::Keep,
135        pass_op: wgpu::StencilOperation::Keep,
136    };
137    wgpu::DepthStencilState {
138        format: STENCIL_FMT,
139        depth_write_enabled: None,
140        depth_compare: None,
141        stencil: wgpu::StencilState { front: face, back: face, read_mask: 0xFF, write_mask: 0 },
142        bias: wgpu::DepthBiasState::default(),
143    }
144}
145
146impl Renderer {
147    /// 克隆可跨窗口复用的 pipeline / layout / sampler 句柄。
148    pub fn shared_resources(&self) -> RendererShared {
149        // 多窗口共享缓存:预算 eviction 暂交给 host(避免误淘汰其他窗口在用的纹理)。
150        self.image_cache.borrow_mut().evict_enabled = false;
151        RendererShared {
152            atlas_cache: Rc::clone(&self.atlas_cache),
153            image_cache: Rc::clone(&self.image_cache),
154            rect_pipelines: self.rect_pipelines.clone(),
155            rect_bgl: self.rect_bgl.clone(),
156            text_pipeline: self.text_pipeline.clone(),
157            text_bgl: self.text_bgl.clone(),
158            text_pipeline_mask: self.text_pipeline_mask.clone(),
159            text_pipeline_mask_stencil_test: self.text_pipeline_mask_stencil_test.clone(),
160            tri_pipeline: self.tri_pipeline.clone(),
161            tri_bgl: self.tri_bgl.clone(),
162            tri_pipeline_stencil_inc: self.tri_pipeline_stencil_inc.clone(),
163            tri_pipeline_stencil_dec: self.tri_pipeline_stencil_dec.clone(),
164            rect_pipelines_stencil_test: self.rect_pipelines_stencil_test.clone(),
165            text_pipeline_stencil_test: self.text_pipeline_stencil_test.clone(),
166            tri_pipeline_stencil_test: self.tri_pipeline_stencil_test.clone(),
167            blit_pipeline: self.blit_pipeline.clone(),
168            blit_bgl: self.blit_bgl.clone(),
169            blit_sampler: self.blit_sampler.clone(),
170            backdrop_pipeline: self.backdrop_pipeline.clone(),
171            backdrop_bgl: self.backdrop_bgl.clone(),
172            format: self.format,
173        }
174    }
175
176    /// 复用另一个窗口的 pipeline/layout/sampler,只初始化本窗口缓存。
177    pub fn new_with_shared(device: &wgpu::Device, shared: &RendererShared) -> Self {
178        Self {
179            rect_pipelines: shared.rect_pipelines.clone(),
180            rect_bgl: shared.rect_bgl.clone(),
181            text_pipeline: shared.text_pipeline.clone(),
182            text_bgl: shared.text_bgl.clone(),
183            text_pipeline_mask: shared.text_pipeline_mask.clone(),
184            text_pipeline_mask_stencil_test: shared.text_pipeline_mask_stencil_test.clone(),
185            tri_pipeline: shared.tri_pipeline.clone(),
186            tri_bgl: shared.tri_bgl.clone(),
187            tri_pipeline_stencil_inc: shared.tri_pipeline_stencil_inc.clone(),
188            tri_pipeline_stencil_dec: shared.tri_pipeline_stencil_dec.clone(),
189            rect_pipelines_stencil_test: shared.rect_pipelines_stencil_test.clone(),
190            text_pipeline_stencil_test: shared.text_pipeline_stencil_test.clone(),
191            tri_pipeline_stencil_test: shared.tri_pipeline_stencil_test.clone(),
192            atlas_cache: Rc::clone(&shared.atlas_cache),
193            layer_cache: HashMap::new(),
194            active_layer_ids: std::collections::HashSet::new(),
195            frame_layer_sizes: HashMap::new(),
196            composition_scratch: mgui_core::CompositionScratch::default(),
197            blit_pipeline: shared.blit_pipeline.clone(),
198            blit_bgl: shared.blit_bgl.clone(),
199            blit_sampler: shared.blit_sampler.clone(),
200            backdrop_pipeline: shared.backdrop_pipeline.clone(),
201            backdrop_bgl: shared.backdrop_bgl.clone(),
202            format: shared.format,
203            gpu_profiler: crate::gpu_profiler::mount(device),
204            batch_pools: HashMap::new(),
205            image_cache: Rc::clone(&shared.image_cache),
206            msaa_scratch: HashMap::new(),
207            stencil_scratch: HashMap::new(),
208            snapshot_scratch: HashMap::new(),
209            last_stats: RenderStats::default(),
210            pending_invalidations: [0; 8],
211            pending_invalidation_start: None,
212            cache_high_watermark_bytes: 0,
213            pending_upload: None,
214        }
215    }
216
217    pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
218        // ============ **Pass1:4x MSAA** ============
219        // 矢量图边缘毛边根因:所有 Pass1 pipeline 之前 count=1(零 MSAA),
220        // 三角形硬边缘只有 0/1 覆盖度 → 锯齿。4x MSAA 让 GPU 算亚像素 coverage,
221        // 边缘有 partial coverage → 抗锯齿。
222        // 注意:blit_pipeline(Pass2)必须保持 count=1,因为它画到 surface(单采样)。
223        let pass1_msaa = wgpu::MultisampleState { count: 4, mask: !0, alpha_to_coverage_enabled: false };
224        // text_pipeline MSAA 也 count=4(wgpu 要求 pipeline.sample_count == render pass attachment.sample_count)
225        // text glyph rect 已 snap 到物理像素(snap 函数在 collect_instances_segmented),
226        // glyph 边缘正好在像素边界 → 4 个子样全 0 或全 1 → coverage 不生效 → glyph 自带 alpha AA 正常
227        let text_msaa = pass1_msaa;
228
229        // ============ 纯色矩形 pipeline ============
230        let rect_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
231            label: Some("rect-shader"),
232            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/rect.wgsl").into()),
233        });
234
235        let rect_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
236            label: Some("rect-bgl"),
237            entries: &[
238                wgpu::BindGroupLayoutEntry {
239                    // binding 0:batch header(screen_size + count)uniform
240                    binding: 0,
241                    visibility: wgpu::ShaderStages::VERTEX,
242                    ty: wgpu::BindingType::Buffer {
243                        ty: wgpu::BufferBindingType::Uniform,
244                        has_dynamic_offset: false,
245                        min_binding_size: None,
246                    },
247                    count: None,
248                },
249                wgpu::BindGroupLayoutEntry {
250                    // 阶段 B1:binding 1:rect instance 数组 storage buffer
251                    binding: 1,
252                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
253                    ty: wgpu::BindingType::Buffer {
254                        ty: wgpu::BufferBindingType::Storage { read_only: true },
255                        has_dynamic_offset: false,
256                        min_binding_size: None,
257                    },
258                    count: None,
259                },
260            ],
261        });
262
263        let rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
264            label: Some("rect-pipeline-layout"),
265            bind_group_layouts: &[Some(&rect_bgl)],
266            immediate_size: 0,
267        });
268
269        // 矩形族 pipeline:Normal / Multiply / Screen / Add 各一个
270        // (stencil 版本在下方用同一个 closure 创建)
271        const RECT_BLEND_MODES: [BlendMode; 4] =
272            [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Add];
273        let make_rect_pipeline =
274            |label: &'static str, blend: wgpu::BlendState, depth_stencil: Option<wgpu::DepthStencilState>| {
275                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
276                    label: Some(label),
277                    layout: Some(&rect_pipeline_layout),
278                    vertex: wgpu::VertexState {
279                        module: &rect_shader,
280                        entry_point: Some("vs_main"),
281                        compilation_options: Default::default(),
282                        buffers: &[],
283                    },
284                    primitive: wgpu::PrimitiveState {
285                        topology: wgpu::PrimitiveTopology::TriangleList,
286                        ..Default::default()
287                    },
288                    depth_stencil,
289                    multisample: pass1_msaa,
290                    fragment: Some(wgpu::FragmentState {
291                        module: &rect_shader,
292                        entry_point: Some("fs_main"),
293                        compilation_options: Default::default(),
294                        targets: &[Some(wgpu::ColorTargetState {
295                            format,
296                            blend: Some(blend),
297                            write_mask: wgpu::ColorWrites::ALL,
298                        })],
299                    }),
300                    multiview_mask: None,
301                    cache: None,
302                })
303            };
304        let rect_pipelines: [wgpu::RenderPipeline; 4] =
305            std::array::from_fn(|i| make_rect_pipeline("rect-pipeline", blend_state_for(RECT_BLEND_MODES[i]), None));
306
307        // ============ 文字 pipeline(纹理) ============
308        let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
309            label: Some("text-shader"),
310            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/text.wgsl").into()),
311        });
312
313        let text_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
314            label: Some("text-bgl"),
315            entries: &[
316                wgpu::BindGroupLayoutEntry {
317                    // 阶段 B2:binding 0 = batch header uniform
318                    binding: 0,
319                    visibility: wgpu::ShaderStages::VERTEX,
320                    ty: wgpu::BindingType::Buffer {
321                        ty: wgpu::BufferBindingType::Uniform,
322                        has_dynamic_offset: false,
323                        min_binding_size: None,
324                    },
325                    count: None,
326                },
327                wgpu::BindGroupLayoutEntry {
328                    // 阶段 B2:binding 1 = text instance storage buffer
329                    binding: 1,
330                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
331                    ty: wgpu::BindingType::Buffer {
332                        ty: wgpu::BufferBindingType::Storage { read_only: true },
333                        has_dynamic_offset: false,
334                        min_binding_size: None,
335                    },
336                    count: None,
337                },
338                wgpu::BindGroupLayoutEntry {
339                    // binding 2 = atlas texture(同 layer 所有 text 共享)
340                    binding: 2,
341                    visibility: wgpu::ShaderStages::FRAGMENT,
342                    ty: wgpu::BindingType::Texture {
343                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
344                        view_dimension: wgpu::TextureViewDimension::D2,
345                        multisampled: false,
346                    },
347                    count: None,
348                },
349                wgpu::BindGroupLayoutEntry {
350                    // 阶段 B2:binding 3 = atlas sampler(共享)
351                    binding: 3,
352                    visibility: wgpu::ShaderStages::FRAGMENT,
353                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
354                    count: None,
355                },
356            ],
357        });
358
359        let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
360            label: Some("text-pipeline-layout"),
361            bind_group_layouts: &[Some(&text_bgl)],
362            immediate_size: 0,
363        });
364
365        // **P2-1.3 纹理 mask** — 只缩放目的地 alpha,保留 RGB。
366        // layer texture 走 blit 的 straight-alpha 约定:若 RGB 也乘 src.a,
367        // blit 再乘一次 alpha 会双重变暗(BUG:50% mask 变成 25%)。
368        let mask_blend = wgpu::BlendState {
369            color: wgpu::BlendComponent {
370                src_factor: wgpu::BlendFactor::Zero,
371                dst_factor: wgpu::BlendFactor::One,
372                operation: wgpu::BlendOperation::Add,
373            },
374            alpha: wgpu::BlendComponent {
375                src_factor: wgpu::BlendFactor::Zero,
376                dst_factor: wgpu::BlendFactor::SrcAlpha,
377                operation: wgpu::BlendOperation::Add,
378            },
379        };
380
381        let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
382            label: Some("text-pipeline"),
383            layout: Some(&text_pipeline_layout),
384            vertex: wgpu::VertexState {
385                module: &text_shader,
386                entry_point: Some("vs_main"),
387                compilation_options: Default::default(),
388                buffers: &[],
389            },
390            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
391            depth_stencil: None,
392            // text glyph atlas 自带 alpha AA,MSAA 会额外糊一层
393            multisample: text_msaa,
394            fragment: Some(wgpu::FragmentState {
395                module: &text_shader,
396                entry_point: Some("fs_main"),
397                compilation_options: Default::default(),
398                targets: &[Some(wgpu::ColorTargetState {
399                    format,
400                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
401                    write_mask: wgpu::ColorWrites::ALL,
402                })],
403            }),
404            multiview_mask: None,
405            cache: None,
406        });
407
408        // 纹理 mask:同一 text shader,alpha 模式 + destination-in
409        let text_pipeline_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
410            label: Some("text-pipeline-mask"),
411            layout: Some(&text_pipeline_layout),
412            vertex: wgpu::VertexState {
413                module: &text_shader,
414                entry_point: Some("vs_main"),
415                compilation_options: Default::default(),
416                buffers: &[],
417            },
418            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
419            depth_stencil: None,
420            multisample: text_msaa,
421            fragment: Some(wgpu::FragmentState {
422                module: &text_shader,
423                entry_point: Some("fs_main"),
424                compilation_options: Default::default(),
425                targets: &[Some(wgpu::ColorTargetState {
426                    format,
427                    blend: Some(mask_blend),
428                    write_mask: wgpu::ColorWrites::ALL,
429                })],
430            }),
431            multiview_mask: None,
432            cache: None,
433        });
434
435        // ============ Stage T1:triangle pipeline ============
436        let tri_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
437            label: Some("tri-shader"),
438            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/tri.wgsl").into()),
439        });
440
441        let tri_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
442            label: Some("tri-bgl"),
443            entries: &[wgpu::BindGroupLayoutEntry {
444                binding: 0,
445                visibility: wgpu::ShaderStages::VERTEX,
446                ty: wgpu::BindingType::Buffer {
447                    ty: wgpu::BufferBindingType::Uniform,
448                    has_dynamic_offset: false,
449                    min_binding_size: None,
450                },
451                count: None,
452            }],
453        });
454
455        let tri_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
456            label: Some("tri-pipeline-layout"),
457            bind_group_layouts: &[Some(&tri_bgl)],
458            immediate_size: 0,
459        });
460
461        let tri_vb_layouts = [Some(wgpu::VertexBufferLayout {
462            array_stride: 24,
463            step_mode: wgpu::VertexStepMode::Vertex,
464            attributes: &[
465                wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x2 },
466                wgpu::VertexAttribute { offset: 8, shader_location: 1, format: wgpu::VertexFormat::Float32x4 },
467            ],
468        })];
469
470        let tri_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
471            label: Some("tri-pipeline"),
472            layout: Some(&tri_pipeline_layout),
473            vertex: wgpu::VertexState {
474                module: &tri_shader,
475                entry_point: Some("vs_main"),
476                compilation_options: Default::default(),
477                buffers: &tri_vb_layouts,
478            },
479            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
480            depth_stencil: None,
481            multisample: pass1_msaa,
482            fragment: Some(wgpu::FragmentState {
483                module: &tri_shader,
484                entry_point: Some("fs_main"),
485                compilation_options: Default::default(),
486                targets: &[Some(wgpu::ColorTargetState {
487                    format,
488                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
489                    write_mask: wgpu::ColorWrites::ALL,
490                })],
491            }),
492            multiview_mask: None,
493            cache: None,
494        });
495
496        // ============ **ClipPath GPU stencil** — pipeline variants ============
497        // 嵌套 mask:推入时 IncrementWrap、弹出时 DecrementWrap(双面同 op,
498        // 与三角形绕序无关);内容段用 Equal(depth) 测试 → 所有 clip 的交集。
499        let keep_op = wgpu::StencilOperation::Keep;
500
501        // ---- tri_pipeline_stencil_inc/dec:只写 stencil,color=NONE ----
502        let stencil_write_pipeline = |label: &'static str, op: wgpu::StencilOperation| {
503            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
504                label: Some(label),
505                layout: Some(&tri_pipeline_layout),
506                vertex: wgpu::VertexState {
507                    module: &tri_shader,
508                    entry_point: Some("vs_main"),
509                    compilation_options: Default::default(),
510                    buffers: &tri_vb_layouts,
511                },
512                primitive: wgpu::PrimitiveState {
513                    topology: wgpu::PrimitiveTopology::TriangleList,
514                    ..Default::default()
515                },
516                depth_stencil: Some(wgpu::DepthStencilState {
517                    format: STENCIL_FMT,
518                    depth_write_enabled: None,
519                    depth_compare: None,
520                    stencil: wgpu::StencilState {
521                        front: wgpu::StencilFaceState {
522                            compare: wgpu::CompareFunction::Always,
523                            fail_op: keep_op,
524                            depth_fail_op: keep_op,
525                            pass_op: op,
526                        },
527                        back: wgpu::StencilFaceState {
528                            compare: wgpu::CompareFunction::Always,
529                            fail_op: keep_op,
530                            depth_fail_op: keep_op,
531                            pass_op: op,
532                        },
533                        read_mask: 0xFF,
534                        write_mask: 0xFF,
535                    },
536                    bias: wgpu::DepthBiasState::default(),
537                }),
538                multisample: pass1_msaa,
539                fragment: Some(wgpu::FragmentState {
540                    module: &tri_shader,
541                    entry_point: Some("fs_main"),
542                    compilation_options: Default::default(),
543                    targets: &[Some(wgpu::ColorTargetState {
544                        format,
545                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
546                        write_mask: wgpu::ColorWrites::empty(), // 关键:只写 stencil,不写 color
547                    })],
548                }),
549                multiview_mask: None,
550                cache: None,
551            })
552        };
553        let tri_pipeline_stencil_inc =
554            stencil_write_pipeline("tri-pipeline-stencil-inc", wgpu::StencilOperation::IncrementWrap);
555        let tri_pipeline_stencil_dec =
556            stencil_write_pipeline("tri-pipeline-stencil-dec", wgpu::StencilOperation::DecrementWrap);
557
558        // ---- rect_pipelines_stencil_test:stencil Equal(depth) × 4 种混合模式 ----
559        let rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4] = std::array::from_fn(|i| {
560            make_rect_pipeline(
561                "rect-pipeline-stencil-test",
562                blend_state_for(RECT_BLEND_MODES[i]),
563                Some(stencil_equal_state()),
564            )
565        });
566
567        // ---- text_pipeline_stencil_test ----
568        let text_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
569            label: Some("text-pipeline-stencil-test"),
570            layout: Some(&text_pipeline_layout),
571            vertex: wgpu::VertexState {
572                module: &text_shader,
573                entry_point: Some("vs_main"),
574                compilation_options: Default::default(),
575                buffers: &[],
576            },
577            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
578            depth_stencil: Some(wgpu::DepthStencilState {
579                format: STENCIL_FMT,
580                depth_write_enabled: None,
581                depth_compare: None,
582                stencil: wgpu::StencilState {
583                    front: wgpu::StencilFaceState {
584                        compare: wgpu::CompareFunction::Equal,
585                        fail_op: keep_op,
586                        depth_fail_op: keep_op,
587                        pass_op: keep_op,
588                    },
589                    back: wgpu::StencilFaceState {
590                        compare: wgpu::CompareFunction::Equal,
591                        fail_op: keep_op,
592                        depth_fail_op: keep_op,
593                        pass_op: keep_op,
594                    },
595                    read_mask: 0xFF,
596                    write_mask: 0,
597                },
598                bias: wgpu::DepthBiasState::default(),
599            }),
600            multisample: text_msaa,
601            fragment: Some(wgpu::FragmentState {
602                module: &text_shader,
603                entry_point: Some("fs_main"),
604                compilation_options: Default::default(),
605                targets: &[Some(wgpu::ColorTargetState {
606                    format,
607                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
608                    write_mask: wgpu::ColorWrites::ALL,
609                })],
610            }),
611            multiview_mask: None,
612            cache: None,
613        });
614
615        // ---- text_pipeline_mask_stencil_test:mask 在 ClipPath/ClipRRect 内也精确裁剪 ----
616        let text_pipeline_mask_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
617            label: Some("text-pipeline-mask-stencil-test"),
618            layout: Some(&text_pipeline_layout),
619            vertex: wgpu::VertexState {
620                module: &text_shader,
621                entry_point: Some("vs_main"),
622                compilation_options: Default::default(),
623                buffers: &[],
624            },
625            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
626            depth_stencil: Some(wgpu::DepthStencilState {
627                format: STENCIL_FMT,
628                depth_write_enabled: None,
629                depth_compare: None,
630                stencil: wgpu::StencilState {
631                    front: wgpu::StencilFaceState {
632                        compare: wgpu::CompareFunction::Equal,
633                        fail_op: keep_op,
634                        depth_fail_op: keep_op,
635                        pass_op: keep_op,
636                    },
637                    back: wgpu::StencilFaceState {
638                        compare: wgpu::CompareFunction::Equal,
639                        fail_op: keep_op,
640                        depth_fail_op: keep_op,
641                        pass_op: keep_op,
642                    },
643                    read_mask: 0xFF,
644                    write_mask: 0,
645                },
646                bias: wgpu::DepthBiasState::default(),
647            }),
648            multisample: text_msaa,
649            fragment: Some(wgpu::FragmentState {
650                module: &text_shader,
651                entry_point: Some("fs_main"),
652                compilation_options: Default::default(),
653                targets: &[Some(wgpu::ColorTargetState {
654                    format,
655                    blend: Some(mask_blend),
656                    write_mask: wgpu::ColorWrites::ALL,
657                })],
658            }),
659            multiview_mask: None,
660            cache: None,
661        });
662
663        // ---- tri_pipeline_stencil_test ----
664        let tri_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
665            label: Some("tri-pipeline-stencil-test"),
666            layout: Some(&tri_pipeline_layout),
667            vertex: wgpu::VertexState {
668                module: &tri_shader,
669                entry_point: Some("vs_main"),
670                compilation_options: Default::default(),
671                buffers: &tri_vb_layouts,
672            },
673            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
674            depth_stencil: Some(wgpu::DepthStencilState {
675                format: STENCIL_FMT,
676                depth_write_enabled: None,
677                depth_compare: None,
678                stencil: wgpu::StencilState {
679                    front: wgpu::StencilFaceState {
680                        compare: wgpu::CompareFunction::Equal,
681                        fail_op: keep_op,
682                        depth_fail_op: keep_op,
683                        pass_op: keep_op,
684                    },
685                    back: wgpu::StencilFaceState {
686                        compare: wgpu::CompareFunction::Equal,
687                        fail_op: keep_op,
688                        depth_fail_op: keep_op,
689                        pass_op: keep_op,
690                    },
691                    read_mask: 0xFF,
692                    write_mask: 0,
693                },
694                bias: wgpu::DepthBiasState::default(),
695            }),
696            multisample: pass1_msaa,
697            fragment: Some(wgpu::FragmentState {
698                module: &tri_shader,
699                entry_point: Some("fs_main"),
700                compilation_options: Default::default(),
701                targets: &[Some(wgpu::ColorTargetState {
702                    format,
703                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
704                    write_mask: wgpu::ColorWrites::ALL,
705                })],
706            }),
707            multiview_mask: None,
708            cache: None,
709        });
710
711        // ============ 阶段 4-B:blit pipeline(全屏 sample layer texture) ============
712        let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
713            label: Some("blit-shader"),
714            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/blit.wgsl").into()),
715        });
716        let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
717            label: Some("blit-bgl"),
718            entries: &[
719                wgpu::BindGroupLayoutEntry {
720                    binding: 0,
721                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
722                    ty: wgpu::BindingType::Buffer {
723                        ty: wgpu::BufferBindingType::Uniform,
724                        has_dynamic_offset: false,
725                        min_binding_size: None,
726                    },
727                    count: None,
728                },
729                wgpu::BindGroupLayoutEntry {
730                    binding: 1,
731                    visibility: wgpu::ShaderStages::FRAGMENT,
732                    ty: wgpu::BindingType::Texture {
733                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
734                        view_dimension: wgpu::TextureViewDimension::D2,
735                        multisampled: false,
736                    },
737                    count: None,
738                },
739                wgpu::BindGroupLayoutEntry {
740                    binding: 2,
741                    visibility: wgpu::ShaderStages::FRAGMENT,
742                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
743                    count: None,
744                },
745            ],
746        });
747        let blit_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
748            label: Some("blit-pipeline-layout"),
749            bind_group_layouts: &[Some(&blit_bgl)],
750            immediate_size: 0,
751        });
752        let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
753            label: Some("blit-pipeline"),
754            layout: Some(&blit_pipeline_layout),
755            vertex: wgpu::VertexState {
756                module: &blit_shader,
757                entry_point: Some("vs_main"),
758                compilation_options: Default::default(),
759                buffers: &[],
760            },
761            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
762            depth_stencil: None,
763            // blit 画到 surface(单采样),必须 count=1
764            multisample: wgpu::MultisampleState::default(),
765            fragment: Some(wgpu::FragmentState {
766                module: &blit_shader,
767                entry_point: Some("fs_main"),
768                compilation_options: Default::default(),
769                targets: &[Some(wgpu::ColorTargetState {
770                    format,
771                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
772                    write_mask: wgpu::ColorWrites::ALL,
773                })],
774            }),
775            multiview_mask: None,
776            cache: None,
777        });
778        // ============ P2-1.4b:背景模糊 pipeline ============
779        let backdrop_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
780            label: Some("backdrop-shader"),
781            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/backdrop.wgsl").into()),
782        });
783        let backdrop_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
784            label: Some("backdrop-bgl"),
785            entries: &[
786                wgpu::BindGroupLayoutEntry {
787                    binding: 0,
788                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
789                    ty: wgpu::BindingType::Buffer {
790                        ty: wgpu::BufferBindingType::Uniform,
791                        has_dynamic_offset: false,
792                        min_binding_size: None,
793                    },
794                    count: None,
795                },
796                wgpu::BindGroupLayoutEntry {
797                    binding: 1,
798                    visibility: wgpu::ShaderStages::FRAGMENT,
799                    ty: wgpu::BindingType::Texture {
800                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
801                        view_dimension: wgpu::TextureViewDimension::D2,
802                        multisampled: false,
803                    },
804                    count: None,
805                },
806                wgpu::BindGroupLayoutEntry {
807                    binding: 2,
808                    visibility: wgpu::ShaderStages::FRAGMENT,
809                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
810                    count: None,
811                },
812            ],
813        });
814        let backdrop_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
815            label: Some("backdrop-pipeline-layout"),
816            bind_group_layouts: &[Some(&backdrop_bgl)],
817            immediate_size: 0,
818        });
819        let backdrop_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
820            label: Some("backdrop-pipeline"),
821            layout: Some(&backdrop_pipeline_layout),
822            vertex: wgpu::VertexState {
823                module: &backdrop_shader,
824                entry_point: Some("vs_main"),
825                compilation_options: Default::default(),
826                buffers: &[],
827            },
828            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
829            // 背景模糊层始终带 stencil attachment,保证 clip 生效
830            depth_stencil: Some(stencil_equal_state()),
831            multisample: pass1_msaa,
832            fragment: Some(wgpu::FragmentState {
833                module: &backdrop_shader,
834                entry_point: Some("fs_main"),
835                compilation_options: Default::default(),
836                targets: &[Some(wgpu::ColorTargetState {
837                    format,
838                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
839                    write_mask: wgpu::ColorWrites::ALL,
840                })],
841            }),
842            multiview_mask: None,
843            cache: None,
844        });
845
846        let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
847            address_mode_u: wgpu::AddressMode::ClampToEdge,
848            address_mode_v: wgpu::AddressMode::ClampToEdge,
849            address_mode_w: wgpu::AddressMode::ClampToEdge,
850            mag_filter: wgpu::FilterMode::Linear,
851            min_filter: wgpu::FilterMode::Linear,
852            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
853            ..Default::default()
854        });
855
856        Self {
857            rect_pipelines,
858            rect_bgl,
859            text_pipeline,
860            text_bgl,
861            text_pipeline_mask,
862            text_pipeline_mask_stencil_test,
863            tri_pipeline,
864            tri_bgl,
865            tri_pipeline_stencil_inc,
866            tri_pipeline_stencil_dec,
867            rect_pipelines_stencil_test,
868            text_pipeline_stencil_test,
869            tri_pipeline_stencil_test,
870            atlas_cache: Rc::new(RefCell::new(None)),
871            layer_cache: HashMap::new(),
872            blit_pipeline,
873            blit_bgl,
874            blit_sampler,
875            backdrop_pipeline,
876            backdrop_bgl,
877            // 阶段 2-E 修复:记录 surface 格式 — layer texture 必须用同一格式,
878            // 否则 rect/text pipeline(render target = surface 格式)画进
879            // layer texture 时 wgpu validation error
880            format,
881            // P2:frame 级复用容器
882            active_layer_ids: std::collections::HashSet::new(),
883            frame_layer_sizes: HashMap::new(),
884            composition_scratch: mgui_core::CompositionScratch::default(),
885            // 阶段 B4:GPU timestamp profiler。默认 None —— 只有开了 `profiling` feature
886            // 的构建才会去探测设备能力(DT-04;能力探测不是关闭策略,feature 才是)
887            gpu_profiler: crate::gpu_profiler::mount(device),
888            // 阶段 B1.5:per-layer buffer pool
889            batch_pools: HashMap::new(),
890            image_cache: Rc::new(RefCell::new(ImageTextureCache { evict_enabled: true, ..Default::default() })),
891            msaa_scratch: HashMap::new(),
892            stencil_scratch: HashMap::new(),
893            snapshot_scratch: HashMap::new(),
894            last_stats: RenderStats::default(),
895            pending_invalidations: [0; 8],
896            pending_invalidation_start: None,
897            cache_high_watermark_bytes: 0,
898            pending_upload: None,
899        }
900    }
901
902    /// 确保 GPU atlas 资源是最新的
903    ///
904    /// - size 变化 → 重建 texture/view/sampler
905    /// - dirty    → `write_texture` 上传新像素
906    /// - 其他     → 复用 cache
907    pub(crate) fn ensure_atlas(
908        &mut self,
909        device: &wgpu::Device,
910        queue: &wgpu::Queue,
911    ) -> (wgpu::TextureView, wgpu::Sampler) {
912        let snap = crate::text::atlas_snapshot();
913        let mut atlas_cache = self.atlas_cache.borrow_mut();
914
915        let need_recreate = match atlas_cache.as_ref() {
916            None => true,
917            Some(c) => c.cached_size != (snap.width, snap.height),
918        };
919
920        if need_recreate {
921            log::info!("atlas: rebuild texture (size {}x{}, dirty={})", snap.width, snap.height, snap.dirty);
922            // 第一次或尺寸变化 → 重建(texture 初值为 0,只需上传 dirty 行)
923            let (dy0, dy1) = snap.dirty_y;
924            let rows = dy1.saturating_sub(dy0);
925            let pixels = snap.pixels.as_deref().filter(|p| !p.is_empty()).unwrap_or(&[]);
926            let texture = device.create_texture(&wgpu::TextureDescriptor {
927                label: Some("glyph-atlas"),
928                size: wgpu::Extent3d { width: snap.width, height: snap.height, depth_or_array_layers: 1 },
929                mip_level_count: 1,
930                sample_count: 1,
931                dimension: wgpu::TextureDimension::D2,
932                format: wgpu::TextureFormat::R8Unorm,
933                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
934                view_formats: &[],
935            });
936            if rows > 0 && !pixels.is_empty() {
937                queue.write_texture(
938                    wgpu::TexelCopyTextureInfo {
939                        texture: &texture,
940                        mip_level: 0,
941                        origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
942                        aspect: wgpu::TextureAspect::All,
943                    },
944                    pixels,
945                    wgpu::TexelCopyBufferLayout {
946                        offset: 0,
947                        bytes_per_row: Some(snap.width),
948                        rows_per_image: Some(rows),
949                    },
950                    wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
951                );
952            }
953            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
954            let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
955                address_mode_u: wgpu::AddressMode::ClampToEdge,
956                address_mode_v: wgpu::AddressMode::ClampToEdge,
957                address_mode_w: wgpu::AddressMode::ClampToEdge,
958                mag_filter: wgpu::FilterMode::Linear,
959                min_filter: wgpu::FilterMode::Linear,
960                mipmap_filter: wgpu::MipmapFilterMode::Nearest,
961                ..Default::default()
962            });
963            *atlas_cache = Some(AtlasGpu { texture, view, sampler, cached_size: (snap.width, snap.height) });
964        } else if snap.dirty {
965            let (dy0, dy1) = snap.dirty_y;
966            let rows = dy1.saturating_sub(dy0);
967            log::info!("atlas: upload {} KB (rows {}..{})", (snap.width * rows) as usize / 1024, dy0, dy1);
968            // 尺寸未变但有新 glyph → 只上传本次写入的行区间(整行宽度满足对齐)
969            if rows > 0 {
970                if let (Some(cache), Some(pixels)) = (atlas_cache.as_ref(), snap.pixels.as_deref()) {
971                    queue.write_texture(
972                        wgpu::TexelCopyTextureInfo {
973                            texture: &cache.texture,
974                            mip_level: 0,
975                            origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
976                            aspect: wgpu::TextureAspect::All,
977                        },
978                        pixels,
979                        wgpu::TexelCopyBufferLayout {
980                            offset: 0,
981                            bytes_per_row: Some(snap.width),
982                            rows_per_image: Some(rows),
983                        },
984                        wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
985                    );
986                }
987            }
988        }
989
990        // 同步 CPU 端 dirty 状态(避免下次又走上传分支)
991        if snap.dirty {
992            crate::text::atlas_clear_dirty();
993        }
994
995        let atlas = atlas_cache.as_ref().expect("atlas cache populated");
996        (atlas.view.clone(), atlas.sampler.clone())
997    }
998
999    /// 渲染一帧(阶段 4-B + 4-D:layer GPU cache + 嵌套层隔离 + DPR + offset/size blit)。
1000    ///
1001    /// 流程:
1002    /// 1. **Pass 1**(为每个 dirty layer 独立一个 render pass):
1003    ///    把 layer 的 `paint_list` 画到 layer 自己的 GPU texture(按 `logical_size` 物理像素大小)
1004    /// 2. **Pass 2**(一次 render pass 到 surface):
1005    ///    按 z_order 升序 blit 每个 layer 的 texture 到 surface 的 (offset.x, offset.y) 位置
1006    ///    (逻辑坐标),alpha 混合叠加
1007    ///
1008    /// 干净 layer 在 Pass 1 被跳过(其 GPU cache 保持上次的画);在 Pass 2 被 blit
1009    /// 到 surface(blit 操作很便宜,几乎免费)。**真正的局部重画完成**。
1010    ///
1011    /// 阶段 4-D(候选 2):layer offset/size
1012    /// - 每个 layer texture 大小 = logical_size * dpr(None 时 fallback 全屏)
1013    /// - blit 时按 layer.offset 把 texture 画到 surface 的 logical 位置
1014    /// - 高分屏(2.0/3.0 dpr)下小 layer 用小 texture,大幅节省 fillrate
1015    ///
1016    /// 阶段 4-D(候选 3):DPR 支持
1017    /// - `screen_size`:logical 尺寸(pixel),用于 rect/text 顶点坐标(归一化)
1018    /// - `physical_size`:物理像素尺寸,用于 layer texture 大小 + surface viewport
1019    ///   比例=physical/logical,典型 1.0/1.5/2.0/3.0
1020    ///
1021    /// 阶段 4-B + 4-D:确保所有 layer 都有 GPU cache(按需创建/重建)
1022    ///
1023    /// 阶段 4-D 新行为:
1024    /// - 每个 layer texture 大小 = `logical_size * dpr`(None 时 fallback 全屏)
1025    /// - size 变化(重新 layout 后)时重建 texture
1026    /// - 同一 layer 多次 paint 复用同一 texture(只要 size 没变)
1027    ///
1028    /// P1-4:总字节预算。所有活跃 layer 的目标尺寸先按 `dpr` 计算,若总和超过
1029    /// [`LAYER_TEXTURE_BUDGET_BYTES`],统一按面积比例降采样(几何不变,只降低
1030    /// 分辨率);极端多 layer/4K/高 DPI 下不会无限占用显存。
1031    pub(crate) fn ensure_all_layer_caches(
1032        &mut self,
1033        device: &wgpu::Device,
1034        layer_paints: &[LayerPaint],
1035        dpr: f32,
1036        screen_size: (f32, f32),
1037    ) -> (u32, u32, HashMap<LayerId, u64>, HashSet<LayerId>, u64) {
1038        let max_dim = device.limits().max_texture_dimension_2d.max(1);
1039        let (targets, scale) =
1040            layer_texture_targets(layer_paints, dpr, screen_size, max_dim, LAYER_TEXTURE_BUDGET_BYTES);
1041        if scale < 0.999 {
1042            log::debug!(
1043                target: "mgui_profile",
1044                "layer texture budget exceeded: rendering {} layers at {:.0}% resolution",
1045                targets.len(),
1046                scale * 100.0
1047            );
1048        }
1049
1050        let collecting = mgui_core::frame::cache_stats_collecting();
1051        let incremental = super::incremental_layer_cache_enabled();
1052        let key_start = collecting.then(std::time::Instant::now);
1053        let mut content_keys = HashMap::new();
1054        let mut recreated = HashSet::new();
1055
1056        // 先快照本帧引用的图片代数,避免持有 image_cache 的 Ref 跨越 &mut self 调用。
1057        let image_generations: HashMap<u32, u64> = if incremental {
1058            let mut ids = HashSet::new();
1059            for lp in layer_paints {
1060                ids.extend(referenced_texture_ids(&lp.paint_list));
1061            }
1062            let cache = self.image_cache.borrow();
1063            ids.into_iter().map(|id| (id, cache.generation(id))).collect()
1064        } else {
1065            HashMap::new()
1066        };
1067        let resource_epoch = if incremental { mgui_core::element::resource_epoch() } else { 0 };
1068
1069        let mut created = 0u32;
1070        let mut resized = 0u32;
1071        for (lp, (layer_id, tex_size)) in layer_paints.iter().zip(targets) {
1072            let content_key = if incremental {
1073                let mut hasher = DefaultHasher::new();
1074                lp.paint_list.content_digest().hash(&mut hasher);
1075                tex_size.0.hash(&mut hasher);
1076                tex_size.1.hash(&mut hasher);
1077                resource_epoch.hash(&mut hasher);
1078                for id in referenced_texture_ids(&lp.paint_list) {
1079                    id.hash(&mut hasher);
1080                    image_generations.get(&id).copied().unwrap_or(0).hash(&mut hasher);
1081                }
1082                hasher.finish()
1083            } else {
1084                0
1085            };
1086            content_keys.insert(layer_id, content_key);
1087
1088            // P2-1.5:每层只保留持久的 resolve texture;MSAA/stencil/snapshot
1089            // 改为跨 layer 复用的 scratch(见 msaa_scratch_view / stencil_scratch_view)。
1090            let existed = self.layer_cache.contains_key(&layer_id);
1091            let need_create = match self.layer_cache.get(&layer_id) {
1092                None => true,
1093                Some(c) => c.cached_size != tex_size,
1094            };
1095            if need_create {
1096                // DT-06:尺寸变化归 layout;新条目来自 layer 可见性/重建,归 visibility。
1097                if existed {
1098                    resized += 1;
1099                    self.note_cache_invalidation(CacheInvalidationReason::Layout);
1100                } else {
1101                    created += 1;
1102                    self.note_cache_invalidation(CacheInvalidationReason::Visibility);
1103                }
1104                let resolve_tex = device.create_texture(&wgpu::TextureDescriptor {
1105                    label: Some("layer-resolve"),
1106                    size: wgpu::Extent3d { width: tex_size.0, height: tex_size.1, depth_or_array_layers: 1 },
1107                    mip_level_count: 1,
1108                    sample_count: 1,
1109                    dimension: wgpu::TextureDimension::D2,
1110                    format: self.format,
1111                    // resolve texture 既可做 resolve_target(RENDER_ATTACHMENT)又可被 blit 采样
1112                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT
1113                        | wgpu::TextureUsages::TEXTURE_BINDING
1114                        | wgpu::TextureUsages::COPY_SRC,
1115                    view_formats: &[],
1116                });
1117                let resolve_view = resolve_tex.create_view(&wgpu::TextureViewDescriptor::default());
1118                self.layer_cache.insert(
1119                    layer_id,
1120                    LayerGpuCache { resolve_texture: resolve_tex, resolve_view, cached_size: tex_size, content_key: 0 },
1121                );
1122                recreated.insert(layer_id);
1123            }
1124        }
1125        let key_ns = key_start.map(|start| start.elapsed().as_nanos() as u64).unwrap_or(0);
1126        (created, resized, content_keys, recreated, key_ns)
1127    }
1128
1129    /// P2-1.5:按尺寸复用 MSAA scratch(sample_count=4)。
1130    pub(super) fn msaa_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1131        if let Some(v) = self.msaa_scratch.get(&size) {
1132            return v.clone();
1133        }
1134        let tex = device.create_texture(&wgpu::TextureDescriptor {
1135            label: Some("scratch-msaa"),
1136            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1137            mip_level_count: 1,
1138            sample_count: 4,
1139            dimension: wgpu::TextureDimension::D2,
1140            format: self.format,
1141            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1142            view_formats: &[],
1143        });
1144        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1145        self.msaa_scratch.insert(size, view.clone());
1146        view
1147    }
1148
1149    /// P2-1.5:按尺寸复用 stencil scratch(MSAA sample_count=4)。
1150    pub(super) fn stencil_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1151        if let Some(v) = self.stencil_scratch.get(&size) {
1152            return v.clone();
1153        }
1154        let tex = device.create_texture(&wgpu::TextureDescriptor {
1155            label: Some("scratch-stencil"),
1156            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1157            mip_level_count: 1,
1158            sample_count: 4,
1159            dimension: wgpu::TextureDimension::D2,
1160            format: wgpu::TextureFormat::Stencil8,
1161            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1162            view_formats: &[],
1163        });
1164        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1165        self.stencil_scratch.insert(size, view.clone());
1166        view
1167    }
1168
1169    /// P2-1.5:按尺寸复用背景模糊 snapshot(单采样)。
1170    pub(super) fn snapshot_scratch(
1171        &mut self,
1172        device: &wgpu::Device,
1173        size: (u32, u32),
1174    ) -> (wgpu::Texture, wgpu::TextureView) {
1175        if let Some((tex, view)) = self.snapshot_scratch.get(&size) {
1176            return (tex.clone(), view.clone());
1177        }
1178        let tex = device.create_texture(&wgpu::TextureDescriptor {
1179            label: Some("scratch-snapshot"),
1180            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1181            mip_level_count: 1,
1182            sample_count: 1,
1183            dimension: wgpu::TextureDimension::D2,
1184            format: self.format,
1185            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1186            view_formats: &[],
1187        });
1188        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1189        self.snapshot_scratch.insert(size, (tex.clone(), view.clone()));
1190        (tex, view)
1191    }
1192
1193    // ================================================================
1194    // 阶段 5 入口已上移到 render() 里调用 build_blit_uniform
1195    // ================================================================
1196}
1197
1198// 重新打开 impl Renderer 包含后续 build_paint_bind_groups
1199// (build_blit_uniform 是 free function,定义在下面 impl 之外)
1200
1201/// 阶段 5:从 LayerPaint 的 effect 字段生成 BlitUniform(单层,无父级继承)。
1202/// 渲染主路径使用 `build_blit_uniform_composed`;此函数仅供单测。
1203#[cfg(test)]
1204pub(crate) fn build_blit_uniform(lp: &LayerPaint, layer_logical_size: &Size, screen_size: (f32, f32)) -> BlitUniform {
1205    let comp = LayerComposition::single(lp, *layer_logical_size);
1206    build_blit_uniform_composed(lp, &comp, layer_logical_size, screen_size)
1207}
1208
1209/// 用已解析的合成参数构造 blit uniform。
1210///
1211/// 兼容字段(rotation/scale/clip_radius/quad_*)保留给测试与调试;
1212/// shader 实际使用 `affine` / `affine_translate` / `clip_rect*`。
1213pub(crate) fn build_blit_uniform_composed(
1214    lp: &LayerPaint,
1215    comp: &LayerComposition,
1216    layer_logical_size: &Size,
1217    screen_size: (f32, f32),
1218) -> BlitUniform {
1219    let mut flags: u32 = 0;
1220    let mut rotation = 0.0_f32;
1221    let mut scale_x = 1.0_f32;
1222    let mut scale_y = 1.0_f32;
1223    let mut translate_x = 0.0_f32;
1224    let mut translate_y = 0.0_f32;
1225    let mut clip_radius = 0.0_f32;
1226
1227    match lp.effect {
1228        LayerEffect::None => {}
1229        LayerEffect::Transform(t) => {
1230            if !t.is_identity() {
1231                flags |= effect_flags::HAS_TRANSFORM;
1232            }
1233            rotation = t.rotation;
1234            scale_x = t.scale_x;
1235            scale_y = t.scale_y;
1236            translate_x = t.translate.x;
1237            translate_y = t.translate.y;
1238        }
1239        LayerEffect::Opacity(_) => {}
1240        LayerEffect::ClipRRect(RRectDef { radius }) => {
1241            clip_radius = radius;
1242        }
1243    }
1244    if comp.opacity < 1.0 {
1245        flags |= effect_flags::HAS_OPACITY;
1246    }
1247    if !comp.clips.is_empty() {
1248        flags |= effect_flags::HAS_CLIP;
1249    }
1250
1251    let w = layer_logical_size.width;
1252    let h = layer_logical_size.height;
1253    let mut clip_rect0 = [0.0; 4];
1254    let mut clip_rect1 = [0.0; 4];
1255    let mut clip_params = [0.0; 4];
1256    if let Some(c) = comp.clips.first() {
1257        clip_rect0 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1258        clip_params[0] = c.radius;
1259    }
1260    if let Some(c) = comp.clips.get(1) {
1261        clip_rect1 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1262        clip_params[1] = c.radius;
1263    }
1264    clip_params[2] = comp.clips.len().min(2) as f32;
1265
1266    BlitUniform {
1267        offset: [lp.offset.x, lp.offset.y],
1268        size: [w, h],
1269        screen: [screen_size.0, screen_size.1],
1270        effect_flags: flags,
1271        opacity: comp.opacity,
1272        rotation,
1273        scale_x,
1274        translate_x,
1275        translate_y,
1276        clip_radius,
1277        scale_y,
1278        quad_offset: [lp.offset.x, lp.offset.y],
1279        quad_size: [w, h],
1280        // phys_screen 由调用点按 dpr 填(build_blit_uniform 不感知设备)
1281        phys_screen: [0.0, 0.0],
1282        affine: [comp.affine.a, comp.affine.b, comp.affine.c, comp.affine.d],
1283        affine_translate: [comp.affine.tx, comp.affine.ty],
1284        _affine_pad: [0.0; 2],
1285        clip_rect0,
1286        clip_rect1,
1287        clip_params,
1288    }
1289}