mgui-runtime 0.2.0

mgui 运行时:AppRunner、GPU/软件渲染后端、窗口/无障碍/异步任务集成
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! Renderer 构建与 GPU 资源创建(new / pipeline / atlas / layer cache)。
//! 从 renderer.rs 拆出;struct 定义在父模块,后代模块可访问其私有字段。

use super::composition::LayerComposition;
use super::*;
use mgui_core::paint::BlendMode;

const STENCIL_FMT: wgpu::TextureFormat = wgpu::TextureFormat::Stencil8;

/// 所有 layer resolve texture 的总字节预算(256 MiB,与图片纹理预算一致)。
pub const LAYER_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;

/// 单层目标纹理尺寸。
pub(crate) type LayerTextureSize = (LayerId, (u32, u32));
/// `(每层尺寸, 实际缩放系数)`。
pub(crate) type LayerTextureTargets = (Vec<LayerTextureSize>, f32);

/// 单个 layer 的目标纹理尺寸(logical → 物理,再钳制设备上限)。
fn layer_tex_size(logical: Option<Size>, dpr: f32, screen: (f32, f32), max_dim: u32) -> (u32, u32) {
    let (w, h) = match logical {
        Some(s) => (s.width, s.height),
        None => screen,
    };
    // NaN/负数 → 0,无穷大 → u32::MAX;两者都由 max/min 收敛到合法范围。
    let w = (w * dpr).ceil() as u32;
    let h = (h * dpr).ceil() as u32;
    (w.max(1).min(max_dim), h.max(1).min(max_dim))
}

fn layer_tex_total_bytes(sizes: &[LayerTextureSize]) -> u64 {
    sizes.iter().map(|&(_, (w, h))| w as u64 * h as u64 * 4).sum()
}

/// 计算本帧所有 layer 的目标纹理尺寸(P1-4 资源预算)。
///
/// - 每层按 `logical_size * dpr`(None → 视口)向上取整,并钳制到
///   `max_dim`(防异常 content_size 触发纹理创建失败);
/// - 若总字节超过 `budget`,统一按面积比例降采样到预算内。图层绘制仍按
///   逻辑尺寸归一化、blit 时再拉伸回逻辑尺寸,因此几何/命中不变,只降低
///   极端场景下的分辨率。
///
/// 返回 `(每层尺寸, 实际缩放系数)`;正常情况缩放系数为 1.0。
pub(crate) fn layer_texture_targets(
    layer_paints: &[LayerPaint],
    dpr: f32,
    screen_size: (f32, f32),
    max_dim: u32,
    budget: u64,
) -> LayerTextureTargets {
    let dpr = if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 };
    let max_dim = max_dim.max(1);
    let compute = |scale: f32| -> Vec<LayerTextureSize> {
        layer_paints
            .iter()
            .map(|lp| (lp.layer_id, layer_tex_size(lp.logical_size, dpr * scale, screen_size, max_dim)))
            .collect()
    };

    let mut scale = 1.0f32;
    let mut sizes = compute(scale);
    let mut total = layer_tex_total_bytes(&sizes);
    if total > budget {
        // ceil()/1px 下限会让首次缩放后略超预算;迭代收紧几次直到收敛。
        for _ in 0..8 {
            if total <= budget {
                break;
            }
            let factor = ((budget as f64) / (total as f64)).sqrt().clamp(0.05, 0.99);
            let next = (scale as f64 * factor) as f32;
            if next >= scale || next <= 0.01 {
                break;
            }
            scale = next;
            sizes = compute(scale);
            total = layer_tex_total_bytes(&sizes);
        }
        // 量化到 1/8 步长:overlay 开合导致层数小幅变化时不至于让
        // 所有 layer texture 反复重建。向下取整只会更省(仍然 ≤ 预算)。
        let quantized = (scale * 8.0).floor() / 8.0;
        if quantized > 0.0 && quantized < scale {
            scale = quantized;
            sizes = compute(scale);
        }
    }
    (sizes, scale)
}

/// 固定功能可实现的混合模式子集(矩形族)。
fn blend_state_for(mode: BlendMode) -> wgpu::BlendState {
    use wgpu::{BlendComponent, BlendFactor, BlendOperation, BlendState};
    let comp = |src_factor, dst_factor| BlendComponent { src_factor, dst_factor, operation: BlendOperation::Add };
    match mode {
        BlendMode::Normal => BlendState::ALPHA_BLENDING,
        BlendMode::Multiply => BlendState {
            color: comp(BlendFactor::Dst, BlendFactor::Zero),
            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
        },
        BlendMode::Screen => BlendState {
            color: comp(BlendFactor::One, BlendFactor::OneMinusSrc),
            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
        },
        BlendMode::Add => BlendState {
            color: comp(BlendFactor::One, BlendFactor::One),
            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
        },
    }
}

/// ClipPath/ClipRRect 内容测试:stencil == reference,不写 stencil。
fn stencil_equal_state() -> wgpu::DepthStencilState {
    let face = wgpu::StencilFaceState {
        compare: wgpu::CompareFunction::Equal,
        fail_op: wgpu::StencilOperation::Keep,
        depth_fail_op: wgpu::StencilOperation::Keep,
        pass_op: wgpu::StencilOperation::Keep,
    };
    wgpu::DepthStencilState {
        format: STENCIL_FMT,
        depth_write_enabled: None,
        depth_compare: None,
        stencil: wgpu::StencilState { front: face, back: face, read_mask: 0xFF, write_mask: 0 },
        bias: wgpu::DepthBiasState::default(),
    }
}

impl Renderer {
    /// 克隆可跨窗口复用的 pipeline / layout / sampler 句柄。
    pub fn shared_resources(&self) -> RendererShared {
        // 多窗口共享缓存:预算 eviction 暂交给 host(避免误淘汰其他窗口在用的纹理)。
        self.image_cache.borrow_mut().evict_enabled = false;
        RendererShared {
            atlas_cache: Rc::clone(&self.atlas_cache),
            image_cache: Rc::clone(&self.image_cache),
            rect_pipelines: self.rect_pipelines.clone(),
            rect_bgl: self.rect_bgl.clone(),
            text_pipeline: self.text_pipeline.clone(),
            text_bgl: self.text_bgl.clone(),
            text_pipeline_mask: self.text_pipeline_mask.clone(),
            text_pipeline_mask_stencil_test: self.text_pipeline_mask_stencil_test.clone(),
            tri_pipeline: self.tri_pipeline.clone(),
            tri_bgl: self.tri_bgl.clone(),
            tri_pipeline_stencil_inc: self.tri_pipeline_stencil_inc.clone(),
            tri_pipeline_stencil_dec: self.tri_pipeline_stencil_dec.clone(),
            rect_pipelines_stencil_test: self.rect_pipelines_stencil_test.clone(),
            text_pipeline_stencil_test: self.text_pipeline_stencil_test.clone(),
            tri_pipeline_stencil_test: self.tri_pipeline_stencil_test.clone(),
            blit_pipeline: self.blit_pipeline.clone(),
            blit_bgl: self.blit_bgl.clone(),
            blit_sampler: self.blit_sampler.clone(),
            backdrop_pipeline: self.backdrop_pipeline.clone(),
            backdrop_bgl: self.backdrop_bgl.clone(),
            format: self.format,
        }
    }

    /// 复用另一个窗口的 pipeline/layout/sampler,只初始化本窗口缓存。
    pub fn new_with_shared(device: &wgpu::Device, shared: &RendererShared) -> Self {
        Self {
            rect_pipelines: shared.rect_pipelines.clone(),
            rect_bgl: shared.rect_bgl.clone(),
            text_pipeline: shared.text_pipeline.clone(),
            text_bgl: shared.text_bgl.clone(),
            text_pipeline_mask: shared.text_pipeline_mask.clone(),
            text_pipeline_mask_stencil_test: shared.text_pipeline_mask_stencil_test.clone(),
            tri_pipeline: shared.tri_pipeline.clone(),
            tri_bgl: shared.tri_bgl.clone(),
            tri_pipeline_stencil_inc: shared.tri_pipeline_stencil_inc.clone(),
            tri_pipeline_stencil_dec: shared.tri_pipeline_stencil_dec.clone(),
            rect_pipelines_stencil_test: shared.rect_pipelines_stencil_test.clone(),
            text_pipeline_stencil_test: shared.text_pipeline_stencil_test.clone(),
            tri_pipeline_stencil_test: shared.tri_pipeline_stencil_test.clone(),
            atlas_cache: Rc::clone(&shared.atlas_cache),
            layer_cache: HashMap::new(),
            active_layer_ids: std::collections::HashSet::new(),
            frame_layer_sizes: HashMap::new(),
            composition_scratch: mgui_core::CompositionScratch::default(),
            blit_pipeline: shared.blit_pipeline.clone(),
            blit_bgl: shared.blit_bgl.clone(),
            blit_sampler: shared.blit_sampler.clone(),
            backdrop_pipeline: shared.backdrop_pipeline.clone(),
            backdrop_bgl: shared.backdrop_bgl.clone(),
            format: shared.format,
            gpu_profiler: crate::gpu_profiler::GpuProfiler::new(device),
            batch_pools: HashMap::new(),
            image_cache: Rc::clone(&shared.image_cache),
            msaa_scratch: HashMap::new(),
            stencil_scratch: HashMap::new(),
            snapshot_scratch: HashMap::new(),
            last_stats: RenderStats::default(),
        }
    }

    pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
        // ============ **Pass1:4x MSAA** ============
        // 矢量图边缘毛边根因:所有 Pass1 pipeline 之前 count=1(零 MSAA),
        // 三角形硬边缘只有 0/1 覆盖度 → 锯齿。4x MSAA 让 GPU 算亚像素 coverage,
        // 边缘有 partial coverage → 抗锯齿。
        // 注意:blit_pipeline(Pass2)必须保持 count=1,因为它画到 surface(单采样)。
        let pass1_msaa = wgpu::MultisampleState { count: 4, mask: !0, alpha_to_coverage_enabled: false };
        // text_pipeline MSAA 也 count=4(wgpu 要求 pipeline.sample_count == render pass attachment.sample_count)
        // text glyph rect 已 snap 到物理像素(snap 函数在 collect_instances_segmented),
        // glyph 边缘正好在像素边界 → 4 个子样全 0 或全 1 → coverage 不生效 → glyph 自带 alpha AA 正常
        let text_msaa = pass1_msaa;

        // ============ 纯色矩形 pipeline ============
        let rect_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rect-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/rect.wgsl").into()),
        });

        let rect_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("rect-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    // binding 0:batch header(screen_size + count)uniform
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    // 阶段 B1:binding 1:rect instance 数组 storage buffer
                    binding: 1,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("rect-pipeline-layout"),
            bind_group_layouts: &[Some(&rect_bgl)],
            immediate_size: 0,
        });

        // 矩形族 pipeline:Normal / Multiply / Screen / Add 各一个
        // (stencil 版本在下方用同一个 closure 创建)
        const RECT_BLEND_MODES: [BlendMode; 4] =
            [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Add];
        let make_rect_pipeline =
            |label: &'static str, blend: wgpu::BlendState, depth_stencil: Option<wgpu::DepthStencilState>| {
                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                    label: Some(label),
                    layout: Some(&rect_pipeline_layout),
                    vertex: wgpu::VertexState {
                        module: &rect_shader,
                        entry_point: Some("vs_main"),
                        compilation_options: Default::default(),
                        buffers: &[],
                    },
                    primitive: wgpu::PrimitiveState {
                        topology: wgpu::PrimitiveTopology::TriangleList,
                        ..Default::default()
                    },
                    depth_stencil,
                    multisample: pass1_msaa,
                    fragment: Some(wgpu::FragmentState {
                        module: &rect_shader,
                        entry_point: Some("fs_main"),
                        compilation_options: Default::default(),
                        targets: &[Some(wgpu::ColorTargetState {
                            format,
                            blend: Some(blend),
                            write_mask: wgpu::ColorWrites::ALL,
                        })],
                    }),
                    multiview_mask: None,
                    cache: None,
                })
            };
        let rect_pipelines: [wgpu::RenderPipeline; 4] =
            std::array::from_fn(|i| make_rect_pipeline("rect-pipeline", blend_state_for(RECT_BLEND_MODES[i]), None));

        // ============ 文字 pipeline(纹理) ============
        let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("text-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/text.wgsl").into()),
        });

        let text_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("text-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    // 阶段 B2:binding 0 = batch header uniform
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    // 阶段 B2:binding 1 = text instance storage buffer
                    binding: 1,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    // binding 2 = atlas texture(同 layer 所有 text 共享)
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    // 阶段 B2:binding 3 = atlas sampler(共享)
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("text-pipeline-layout"),
            bind_group_layouts: &[Some(&text_bgl)],
            immediate_size: 0,
        });

        // **P2-1.3 纹理 mask** — 只缩放目的地 alpha,保留 RGB。
        // layer texture 走 blit 的 straight-alpha 约定:若 RGB 也乘 src.a,
        // blit 再乘一次 alpha 会双重变暗(BUG:50% mask 变成 25%)。
        let mask_blend = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::Zero,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::Zero,
                dst_factor: wgpu::BlendFactor::SrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
        };

        let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("text-pipeline"),
            layout: Some(&text_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &text_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            // text glyph atlas 自带 alpha AA,MSAA 会额外糊一层
            multisample: text_msaa,
            fragment: Some(wgpu::FragmentState {
                module: &text_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        // 纹理 mask:同一 text shader,alpha 模式 + destination-in
        let text_pipeline_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("text-pipeline-mask"),
            layout: Some(&text_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &text_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            multisample: text_msaa,
            fragment: Some(wgpu::FragmentState {
                module: &text_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(mask_blend),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        // ============ Stage T1:triangle pipeline ============
        let tri_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("tri-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/tri.wgsl").into()),
        });

        let tri_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("tri-bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });

        let tri_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("tri-pipeline-layout"),
            bind_group_layouts: &[Some(&tri_bgl)],
            immediate_size: 0,
        });

        let tri_vb_layouts = [Some(wgpu::VertexBufferLayout {
            array_stride: 24,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &[
                wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x2 },
                wgpu::VertexAttribute { offset: 8, shader_location: 1, format: wgpu::VertexFormat::Float32x4 },
            ],
        })];

        let tri_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("tri-pipeline"),
            layout: Some(&tri_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &tri_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &tri_vb_layouts,
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            multisample: pass1_msaa,
            fragment: Some(wgpu::FragmentState {
                module: &tri_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        // ============ **ClipPath GPU stencil** — pipeline variants ============
        // 嵌套 mask:推入时 IncrementWrap、弹出时 DecrementWrap(双面同 op,
        // 与三角形绕序无关);内容段用 Equal(depth) 测试 → 所有 clip 的交集。
        let keep_op = wgpu::StencilOperation::Keep;

        // ---- tri_pipeline_stencil_inc/dec:只写 stencil,color=NONE ----
        let stencil_write_pipeline = |label: &'static str, op: wgpu::StencilOperation| {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&tri_pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &tri_shader,
                    entry_point: Some("vs_main"),
                    compilation_options: Default::default(),
                    buffers: &tri_vb_layouts,
                },
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: STENCIL_FMT,
                    depth_write_enabled: None,
                    depth_compare: None,
                    stencil: wgpu::StencilState {
                        front: wgpu::StencilFaceState {
                            compare: wgpu::CompareFunction::Always,
                            fail_op: keep_op,
                            depth_fail_op: keep_op,
                            pass_op: op,
                        },
                        back: wgpu::StencilFaceState {
                            compare: wgpu::CompareFunction::Always,
                            fail_op: keep_op,
                            depth_fail_op: keep_op,
                            pass_op: op,
                        },
                        read_mask: 0xFF,
                        write_mask: 0xFF,
                    },
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: pass1_msaa,
                fragment: Some(wgpu::FragmentState {
                    module: &tri_shader,
                    entry_point: Some("fs_main"),
                    compilation_options: Default::default(),
                    targets: &[Some(wgpu::ColorTargetState {
                        format,
                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                        write_mask: wgpu::ColorWrites::empty(), // 关键:只写 stencil,不写 color
                    })],
                }),
                multiview_mask: None,
                cache: None,
            })
        };
        let tri_pipeline_stencil_inc =
            stencil_write_pipeline("tri-pipeline-stencil-inc", wgpu::StencilOperation::IncrementWrap);
        let tri_pipeline_stencil_dec =
            stencil_write_pipeline("tri-pipeline-stencil-dec", wgpu::StencilOperation::DecrementWrap);

        // ---- rect_pipelines_stencil_test:stencil Equal(depth) × 4 种混合模式 ----
        let rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4] = std::array::from_fn(|i| {
            make_rect_pipeline(
                "rect-pipeline-stencil-test",
                blend_state_for(RECT_BLEND_MODES[i]),
                Some(stencil_equal_state()),
            )
        });

        // ---- text_pipeline_stencil_test ----
        let text_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("text-pipeline-stencil-test"),
            layout: Some(&text_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &text_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: STENCIL_FMT,
                depth_write_enabled: None,
                depth_compare: None,
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Equal,
                        fail_op: keep_op,
                        depth_fail_op: keep_op,
                        pass_op: keep_op,
                    },
                    back: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Equal,
                        fail_op: keep_op,
                        depth_fail_op: keep_op,
                        pass_op: keep_op,
                    },
                    read_mask: 0xFF,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: text_msaa,
            fragment: Some(wgpu::FragmentState {
                module: &text_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        // ---- text_pipeline_mask_stencil_test:mask 在 ClipPath/ClipRRect 内也精确裁剪 ----
        let text_pipeline_mask_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("text-pipeline-mask-stencil-test"),
            layout: Some(&text_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &text_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: STENCIL_FMT,
                depth_write_enabled: None,
                depth_compare: None,
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Equal,
                        fail_op: keep_op,
                        depth_fail_op: keep_op,
                        pass_op: keep_op,
                    },
                    back: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Equal,
                        fail_op: keep_op,
                        depth_fail_op: keep_op,
                        pass_op: keep_op,
                    },
                    read_mask: 0xFF,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: text_msaa,
            fragment: Some(wgpu::FragmentState {
                module: &text_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(mask_blend),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        // ---- tri_pipeline_stencil_test ----
        let tri_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("tri-pipeline-stencil-test"),
            layout: Some(&tri_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &tri_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &tri_vb_layouts,
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: STENCIL_FMT,
                depth_write_enabled: None,
                depth_compare: None,
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Equal,
                        fail_op: keep_op,
                        depth_fail_op: keep_op,
                        pass_op: keep_op,
                    },
                    back: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Equal,
                        fail_op: keep_op,
                        depth_fail_op: keep_op,
                        pass_op: keep_op,
                    },
                    read_mask: 0xFF,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: pass1_msaa,
            fragment: Some(wgpu::FragmentState {
                module: &tri_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        // ============ 阶段 4-B:blit pipeline(全屏 sample layer texture) ============
        let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("blit-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/blit.wgsl").into()),
        });
        let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("blit-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let blit_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("blit-pipeline-layout"),
            bind_group_layouts: &[Some(&blit_bgl)],
            immediate_size: 0,
        });
        let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("blit-pipeline"),
            layout: Some(&blit_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &blit_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            // blit 画到 surface(单采样),必须 count=1
            multisample: wgpu::MultisampleState::default(),
            fragment: Some(wgpu::FragmentState {
                module: &blit_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });
        // ============ P2-1.4b:背景模糊 pipeline ============
        let backdrop_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("backdrop-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/backdrop.wgsl").into()),
        });
        let backdrop_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("backdrop-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let backdrop_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("backdrop-pipeline-layout"),
            bind_group_layouts: &[Some(&backdrop_bgl)],
            immediate_size: 0,
        });
        let backdrop_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("backdrop-pipeline"),
            layout: Some(&backdrop_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &backdrop_shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            // 背景模糊层始终带 stencil attachment,保证 clip 生效
            depth_stencil: Some(stencil_equal_state()),
            multisample: pass1_msaa,
            fragment: Some(wgpu::FragmentState {
                module: &backdrop_shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        Self {
            rect_pipelines,
            rect_bgl,
            text_pipeline,
            text_bgl,
            text_pipeline_mask,
            text_pipeline_mask_stencil_test,
            tri_pipeline,
            tri_bgl,
            tri_pipeline_stencil_inc,
            tri_pipeline_stencil_dec,
            rect_pipelines_stencil_test,
            text_pipeline_stencil_test,
            tri_pipeline_stencil_test,
            atlas_cache: Rc::new(RefCell::new(None)),
            layer_cache: HashMap::new(),
            blit_pipeline,
            blit_bgl,
            blit_sampler,
            backdrop_pipeline,
            backdrop_bgl,
            // 阶段 2-E 修复:记录 surface 格式 — layer texture 必须用同一格式,
            // 否则 rect/text pipeline(render target = surface 格式)画进
            // layer texture 时 wgpu validation error
            format,
            // P2:frame 级复用容器
            active_layer_ids: std::collections::HashSet::new(),
            frame_layer_sizes: HashMap::new(),
            composition_scratch: mgui_core::CompositionScratch::default(),
            // 阶段 B4:GPU timestamp profiler(可选,无 TIMESTAMP_QUERY 时 None)
            gpu_profiler: crate::gpu_profiler::GpuProfiler::new(device),
            // 阶段 B1.5:per-layer buffer pool
            batch_pools: HashMap::new(),
            image_cache: Rc::new(RefCell::new(ImageTextureCache { evict_enabled: true, ..Default::default() })),
            msaa_scratch: HashMap::new(),
            stencil_scratch: HashMap::new(),
            snapshot_scratch: HashMap::new(),
            last_stats: RenderStats::default(),
        }
    }

    /// 确保 GPU atlas 资源是最新的
    ///
    /// - size 变化 → 重建 texture/view/sampler
    /// - dirty    → `write_texture` 上传新像素
    /// - 其他     → 复用 cache
    pub(crate) fn ensure_atlas(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) -> (wgpu::TextureView, wgpu::Sampler) {
        let snap = crate::text::atlas_snapshot();
        let mut atlas_cache = self.atlas_cache.borrow_mut();

        let need_recreate = match atlas_cache.as_ref() {
            None => true,
            Some(c) => c.cached_size != (snap.width, snap.height),
        };

        if need_recreate {
            log::info!("atlas: rebuild texture (size {}x{}, dirty={})", snap.width, snap.height, snap.dirty);
            // 第一次或尺寸变化 → 重建(texture 初值为 0,只需上传 dirty 行)
            let (dy0, dy1) = snap.dirty_y;
            let rows = dy1.saturating_sub(dy0);
            let pixels = snap.pixels.as_deref().filter(|p| !p.is_empty()).unwrap_or(&[]);
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("glyph-atlas"),
                size: wgpu::Extent3d { width: snap.width, height: snap.height, depth_or_array_layers: 1 },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::R8Unorm,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            });
            if rows > 0 && !pixels.is_empty() {
                queue.write_texture(
                    wgpu::TexelCopyTextureInfo {
                        texture: &texture,
                        mip_level: 0,
                        origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
                        aspect: wgpu::TextureAspect::All,
                    },
                    pixels,
                    wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(snap.width),
                        rows_per_image: Some(rows),
                    },
                    wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
                );
            }
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
                address_mode_u: wgpu::AddressMode::ClampToEdge,
                address_mode_v: wgpu::AddressMode::ClampToEdge,
                address_mode_w: wgpu::AddressMode::ClampToEdge,
                mag_filter: wgpu::FilterMode::Linear,
                min_filter: wgpu::FilterMode::Linear,
                mipmap_filter: wgpu::MipmapFilterMode::Nearest,
                ..Default::default()
            });
            *atlas_cache = Some(AtlasGpu { texture, view, sampler, cached_size: (snap.width, snap.height) });
        } else if snap.dirty {
            let (dy0, dy1) = snap.dirty_y;
            let rows = dy1.saturating_sub(dy0);
            log::info!("atlas: upload {} KB (rows {}..{})", (snap.width * rows) as usize / 1024, dy0, dy1);
            // 尺寸未变但有新 glyph → 只上传本次写入的行区间(整行宽度满足对齐)
            if rows > 0 {
                if let (Some(cache), Some(pixels)) = (atlas_cache.as_ref(), snap.pixels.as_deref()) {
                    queue.write_texture(
                        wgpu::TexelCopyTextureInfo {
                            texture: &cache.texture,
                            mip_level: 0,
                            origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
                            aspect: wgpu::TextureAspect::All,
                        },
                        pixels,
                        wgpu::TexelCopyBufferLayout {
                            offset: 0,
                            bytes_per_row: Some(snap.width),
                            rows_per_image: Some(rows),
                        },
                        wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
                    );
                }
            }
        }

        // 同步 CPU 端 dirty 状态(避免下次又走上传分支)
        if snap.dirty {
            crate::text::atlas_clear_dirty();
        }

        let atlas = atlas_cache.as_ref().expect("atlas cache populated");
        (atlas.view.clone(), atlas.sampler.clone())
    }

    /// 渲染一帧(阶段 4-B + 4-D:layer GPU cache + 嵌套层隔离 + DPR + offset/size blit)。
    ///
    /// 流程:
    /// 1. **Pass 1**(为每个 dirty layer 独立一个 render pass):
    ///    把 layer 的 `paint_list` 画到 layer 自己的 GPU texture(按 `logical_size` 物理像素大小)
    /// 2. **Pass 2**(一次 render pass 到 surface):
    ///    按 z_order 升序 blit 每个 layer 的 texture 到 surface 的 (offset.x, offset.y) 位置
    ///    (逻辑坐标),alpha 混合叠加
    ///
    /// 干净 layer 在 Pass 1 被跳过(其 GPU cache 保持上次的画);在 Pass 2 被 blit
    /// 到 surface(blit 操作很便宜,几乎免费)。**真正的局部重画完成**。
    ///
    /// 阶段 4-D(候选 2):layer offset/size
    /// - 每个 layer texture 大小 = logical_size * dpr(None 时 fallback 全屏)
    /// - blit 时按 layer.offset 把 texture 画到 surface 的 logical 位置
    /// - 高分屏(2.0/3.0 dpr)下小 layer 用小 texture,大幅节省 fillrate
    ///
    /// 阶段 4-D(候选 3):DPR 支持
    /// - `screen_size`:logical 尺寸(pixel),用于 rect/text 顶点坐标(归一化)
    /// - `physical_size`:物理像素尺寸,用于 layer texture 大小 + surface viewport
    ///   比例=physical/logical,典型 1.0/1.5/2.0/3.0
    ///
    /// 阶段 4-B + 4-D:确保所有 layer 都有 GPU cache(按需创建/重建)
    ///
    /// 阶段 4-D 新行为:
    /// - 每个 layer texture 大小 = `logical_size * dpr`(None 时 fallback 全屏)
    /// - size 变化(重新 layout 后)时重建 texture
    /// - 同一 layer 多次 paint 复用同一 texture(只要 size 没变)
    ///
    /// P1-4:总字节预算。所有活跃 layer 的目标尺寸先按 `dpr` 计算,若总和超过
    /// [`LAYER_TEXTURE_BUDGET_BYTES`],统一按面积比例降采样(几何不变,只降低
    /// 分辨率);极端多 layer/4K/高 DPI 下不会无限占用显存。
    pub(crate) fn ensure_all_layer_caches(
        &mut self,
        device: &wgpu::Device,
        layer_paints: &[LayerPaint],
        dpr: f32,
        screen_size: (f32, f32),
    ) {
        let max_dim = device.limits().max_texture_dimension_2d.max(1);
        let (targets, scale) =
            layer_texture_targets(layer_paints, dpr, screen_size, max_dim, LAYER_TEXTURE_BUDGET_BYTES);
        if scale < 0.999 {
            log::debug!(
                target: "mgui_profile",
                "layer texture budget exceeded: rendering {} layers at {:.0}% resolution",
                targets.len(),
                scale * 100.0
            );
        }

        for (layer_id, tex_size) in targets {
            // P2-1.5:每层只保留持久的 resolve texture;MSAA/stencil/snapshot
            // 改为跨 layer 复用的 scratch(见 msaa_scratch_view / stencil_scratch_view)。
            let need_create = match self.layer_cache.get(&layer_id) {
                None => true,
                Some(c) => c.cached_size != tex_size,
            };
            if need_create {
                let resolve_tex = device.create_texture(&wgpu::TextureDescriptor {
                    label: Some("layer-resolve"),
                    size: wgpu::Extent3d { width: tex_size.0, height: tex_size.1, depth_or_array_layers: 1 },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: self.format,
                    // resolve texture 既可做 resolve_target(RENDER_ATTACHMENT)又可被 blit 采样
                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                        | wgpu::TextureUsages::TEXTURE_BINDING
                        | wgpu::TextureUsages::COPY_SRC,
                    view_formats: &[],
                });
                let resolve_view = resolve_tex.create_view(&wgpu::TextureViewDescriptor::default());
                self.layer_cache.insert(
                    layer_id,
                    LayerGpuCache { resolve_texture: resolve_tex, resolve_view, cached_size: tex_size },
                );
            }
        }
    }

    /// P2-1.5:按尺寸复用 MSAA scratch(sample_count=4)。
    pub(super) fn msaa_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
        if let Some(v) = self.msaa_scratch.get(&size) {
            return v.clone();
        }
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("scratch-msaa"),
            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
            mip_level_count: 1,
            sample_count: 4,
            dimension: wgpu::TextureDimension::D2,
            format: self.format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        self.msaa_scratch.insert(size, view.clone());
        view
    }

    /// P2-1.5:按尺寸复用 stencil scratch(MSAA sample_count=4)。
    pub(super) fn stencil_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
        if let Some(v) = self.stencil_scratch.get(&size) {
            return v.clone();
        }
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("scratch-stencil"),
            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
            mip_level_count: 1,
            sample_count: 4,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Stencil8,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        self.stencil_scratch.insert(size, view.clone());
        view
    }

    /// P2-1.5:按尺寸复用背景模糊 snapshot(单采样)。
    pub(super) fn snapshot_scratch(
        &mut self,
        device: &wgpu::Device,
        size: (u32, u32),
    ) -> (wgpu::Texture, wgpu::TextureView) {
        if let Some((tex, view)) = self.snapshot_scratch.get(&size) {
            return (tex.clone(), view.clone());
        }
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("scratch-snapshot"),
            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: self.format,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        self.snapshot_scratch.insert(size, (tex.clone(), view.clone()));
        (tex, view)
    }

    // ================================================================
    // 阶段 5 入口已上移到 render() 里调用 build_blit_uniform
    // ================================================================
}

// 重新打开 impl Renderer 包含后续 build_paint_bind_groups
// (build_blit_uniform 是 free function,定义在下面 impl 之外)

/// 阶段 5:从 LayerPaint 的 effect 字段生成 BlitUniform(单层,无父级继承)。
/// 渲染主路径使用 `build_blit_uniform_composed`;此函数仅供单测。
#[cfg(test)]
pub(crate) fn build_blit_uniform(lp: &LayerPaint, layer_logical_size: &Size, screen_size: (f32, f32)) -> BlitUniform {
    let comp = LayerComposition::single(lp, *layer_logical_size);
    build_blit_uniform_composed(lp, &comp, layer_logical_size, screen_size)
}

/// 用已解析的合成参数构造 blit uniform。
///
/// 兼容字段(rotation/scale/clip_radius/quad_*)保留给测试与调试;
/// shader 实际使用 `affine` / `affine_translate` / `clip_rect*`。
pub(crate) fn build_blit_uniform_composed(
    lp: &LayerPaint,
    comp: &LayerComposition,
    layer_logical_size: &Size,
    screen_size: (f32, f32),
) -> BlitUniform {
    let mut flags: u32 = 0;
    let mut rotation = 0.0_f32;
    let mut scale_x = 1.0_f32;
    let mut scale_y = 1.0_f32;
    let mut translate_x = 0.0_f32;
    let mut translate_y = 0.0_f32;
    let mut clip_radius = 0.0_f32;

    match lp.effect {
        LayerEffect::None => {}
        LayerEffect::Transform(t) => {
            if !t.is_identity() {
                flags |= effect_flags::HAS_TRANSFORM;
            }
            rotation = t.rotation;
            scale_x = t.scale_x;
            scale_y = t.scale_y;
            translate_x = t.translate.x;
            translate_y = t.translate.y;
        }
        LayerEffect::Opacity(_) => {}
        LayerEffect::ClipRRect(RRectDef { radius }) => {
            clip_radius = radius;
        }
    }
    if comp.opacity < 1.0 {
        flags |= effect_flags::HAS_OPACITY;
    }
    if !comp.clips.is_empty() {
        flags |= effect_flags::HAS_CLIP;
    }

    let w = layer_logical_size.width;
    let h = layer_logical_size.height;
    let mut clip_rect0 = [0.0; 4];
    let mut clip_rect1 = [0.0; 4];
    let mut clip_params = [0.0; 4];
    if let Some(c) = comp.clips.first() {
        clip_rect0 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
        clip_params[0] = c.radius;
    }
    if let Some(c) = comp.clips.get(1) {
        clip_rect1 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
        clip_params[1] = c.radius;
    }
    clip_params[2] = comp.clips.len().min(2) as f32;

    BlitUniform {
        offset: [lp.offset.x, lp.offset.y],
        size: [w, h],
        screen: [screen_size.0, screen_size.1],
        effect_flags: flags,
        opacity: comp.opacity,
        rotation,
        scale_x,
        translate_x,
        translate_y,
        clip_radius,
        scale_y,
        quad_offset: [lp.offset.x, lp.offset.y],
        quad_size: [w, h],
        // phys_screen 由调用点按 dpr 填(build_blit_uniform 不感知设备)
        phys_screen: [0.0, 0.0],
        affine: [comp.affine.a, comp.affine.b, comp.affine.c, comp.affine.d],
        affine_translate: [comp.affine.tx, comp.affine.ty],
        _affine_pad: [0.0; 2],
        clip_rect0,
        clip_rect1,
        clip_params,
    }
}