mgui-runtime 0.1.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
use mgui_core::paint::{BlendMode, TextureMode};
use mgui_core::Rect;
use mgui_core::{effect_flags, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand, PaintList, RRectDef, Size};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use wgpu::util::DeviceExt;

/// 阶段 B1:rect 批处理 — batch header(per-layer 共享)
/// 屏幕逻辑尺寸 + instance 数量;**16-align**:`vec2` 后接 `u32` + `vec2 pad` 凑齐 16 字节。
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct RectBatchUniform {
    screen_size: [f32; 2], // 0..8
    count: u32,            // 8..12
    _pad: [f32; 1],        // 12..16 (整体 16-align)
}

/// 阶段 B1:rect 批处理 — 每实例数据
/// size = 5 × vec4 = 80 字节(WGSL 16-align 兼容)。
///
/// - 普通 Rect:from = to = color,params[1] = 0
/// - BoxShadow:params[2] = blur_radius
/// - LinearGradient:grad = (start.xy, end.xy),params[1] = 1
/// - RadialGradient:grad = (center.xy, radius, 0),params[1] = 2
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct RectInstance {
    rect: [f32; 4],
    from: [f32; 4],
    to: [f32; 4],
    grad: [f32; 4],
    /// [corner_radius, kind, blur_radius, pad]
    params: [f32; 4],
}

/// 阶段 B2:text 批处理 — batch header
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TextBatchUniform {
    screen_size: [f32; 2], // 0..8
    count: u32,            // 8..12
    _pad: [f32; 1],        // 12..16 (整体 16-align)
}

/// 阶段 B2:text 批处理 — 每实例数据
/// size = 16(rect vec4) + 16(color vec4) + 16(uv vec4) + 16(mode vec4) = 64 字节
/// 16-align OK。
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TextInstance {
    rect: [f32; 4],  // 0..16
    color: [f32; 4], // 16..32
    uv: [f32; 4],    // 32..48
    /// 纹理采样模式(vec4.x):0.0 = Mask(alpha 在纹理 R 通道,glyph/SVG tint),
    /// 1.0 = Color(straight RGBA 全彩纹理,SVG 全彩 / PNG 图片)
    mode: f32, // 48..52
    _pad: [f32; 3],  // 52..64
}

// 阶段 B2:被 TextInstance + TextBatchUniform 替代(批处理)
// 旧 TextUniform 已删除(deprecated by B2,见 commit log)

/// 阶段 4-B + 4-D:blit uniform(全屏 blit 用,带 layer offset/size)
///
/// 阶段 5:扩展为携带 effect 字段:
/// - effect_flags: bit field(HAS_TRANSFORM / HAS_OPACITY / HAS_CLIP)
/// - opacity / rotation / scale / translate_x / translate_y / clip_radius
///
/// **WGSL 对齐**: u32 4 字节,f32 4 字节;WGSL 会按 16-align 整体 struct。
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct BlitUniform {
    offset: [f32; 2], // 0..8    layer 在父 layer 内的 logical 位置
    size: [f32; 2],   // 8..16   layer 的 logical size
    screen: [f32; 2], // 16..24  surface logical 尺寸
    // ========== 阶段 5:effect 字段 ==========
    effect_flags: u32, // 24..28  bit field
    opacity: f32,      // 28..32
    rotation: f32,     // 32..36
    scale_x: f32,      // 36..40  HAS_TRANSFORM:x 轴缩放
    translate_x: f32,  // 40..44
    translate_y: f32,  // 44..48
    clip_radius: f32,  // 48..52
    scale_y: f32,      // 52..56  HAS_TRANSFORM:y 轴缩放(布局为 16-align 的填充位)
    // bugfix(Transform 旋转被裁):quad 覆盖区域。无旋转时 = offset/size;
    // HAS_TRANSFORM 时 = 旋转+缩放后的 AABB(中心不变,尺寸按 |cos|/|sin| 扩大),
    // 否则旋转超出原矩形的部分会被 quad 光栅化裁掉。
    quad_offset: [f32; 2], // 56..64
    quad_size: [f32; 2],   // 64..72
    phys_screen: [f32; 2], // 72..80 surface 物理像素尺寸
    // ========== 嵌套 layer 合成:局部坐标 → surface 的完整仿射 ==========
    /// [a, b, c, d]:x' = a*x + b*y + tx;y' = c*x + d*y + ty
    affine: [f32; 4], // 80..96
    affine_translate: [f32; 2], // 96..104
    _affine_pad: [f32; 2],      // 104..112(16-align)
    /// 两层裁剪(祖先 + 自己的内两层),surface 逻辑坐标 AABB
    clip_rect0: [f32; 4], // 112..128
    clip_rect1: [f32; 4],       // 128..144
    /// [radius0, radius1, count, unused]
    clip_params: [f32; 4], // 144..160
}
// struct size = 160 bytes (16-aligned)

/// 阶段 4-B:每个 layer 的 GPU cache(MSAA texture + resolve texture)
struct LayerGpuCache {
    /// resolve target texture(单采样;blit 采样 + 背景模糊 snapshot 复制源)
    resolve_texture: wgpu::Texture,
    /// resolve target view(sample_count=1,blit 采样这里)
    resolve_view: wgpu::TextureView,
    /// 创建时的物理尺寸;resize 时重建
    cached_size: (u32, u32),
}

/// 可跨窗口复用的 Renderer GPU 资源(pipeline / bind group layout / blit sampler /
/// glyph atlas / 图片纹理缓存)。
///
/// layer 缓存与 batch buffer 仍由各窗口 Renderer 独立持有(LayerId 只在单树内唯一)。
#[derive(Clone)]
pub struct RendererShared {
    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
    rect_pipelines: [wgpu::RenderPipeline; 4],
    rect_bgl: wgpu::BindGroupLayout,
    text_pipeline: wgpu::RenderPipeline,
    text_bgl: wgpu::BindGroupLayout,
    /// 纹理 mask(destination-in)
    text_pipeline_mask: wgpu::RenderPipeline,
    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
    tri_pipeline: wgpu::RenderPipeline,
    tri_bgl: wgpu::BindGroupLayout,
    /// ClipPath stencil mask 写入(推入 +1 / 弹出 -1,front/back 同步)
    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
    text_pipeline_stencil_test: wgpu::RenderPipeline,
    tri_pipeline_stencil_test: wgpu::RenderPipeline,
    blit_pipeline: wgpu::RenderPipeline,
    blit_bgl: wgpu::BindGroupLayout,
    blit_sampler: wgpu::Sampler,
    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
    backdrop_pipeline: wgpu::RenderPipeline,
    backdrop_bgl: wgpu::BindGroupLayout,
    format: wgpu::TextureFormat,
    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
    image_cache: Rc<RefCell<ImageTextureCache>>,
}

/// 跨窗口共享的图片纹理缓存。
#[derive(Default)]
pub(crate) struct ImageTextureCache {
    textures: HashMap<u32, ImageTextureEntry>,
    clock: u64,
    /// 多窗口共享模式下由 host 统一管理预算,暂不做单帧 eviction。
    evict_enabled: bool,
}

impl RendererShared {
    pub fn format(&self) -> wgpu::TextureFormat {
        self.format
    }

    /// 多窗口 host 在一个渲染周期后调用:保护所有窗口最近一帧使用的纹理,
    /// 超预算时淘汰其余最旧纹理。
    pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
        self.image_cache.borrow_mut().evict_to_budget(protected);
    }
}

impl ImageTextureCache {
    fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
        let budget = IMAGE_TEXTURE_BUDGET_BYTES;
        let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
        if total <= budget {
            return;
        }
        let mut candidates: Vec<(u32, u64, u64)> = self
            .textures
            .iter()
            .filter(|(id, _)| !protected.contains(id))
            .map(|(&id, e)| (id, e.last_used, e.bytes))
            .collect();
        candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
        for (id, _, bytes) in candidates {
            if total <= budget {
                break;
            }
            self.textures.remove(&id);
            total = total.saturating_sub(bytes);
        }
        if total > budget {
            log::warn!(
                target: "mgui_startup",
                "shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
                total / (1024 * 1024),
                budget / (1024 * 1024)
            );
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RenderStats {
    /// 本帧实际重画的 layer 数
    pub layers_painted: u32,
    /// 实际提交的 scissor 段数
    pub segments: u32,
    /// paint pass + stencil mask + layer blit 的 draw 总数
    pub draw_calls: u32,
    /// 跨 layer 复用 scratch 的总字节(MSAA + stencil + snapshot)
    pub scratch_bytes: u64,
    /// 持久 layer resolve texture 的总字节
    pub layer_texture_bytes: u64,
}

pub struct Renderer {
    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
    rect_pipelines: [wgpu::RenderPipeline; 4],
    rect_bgl: wgpu::BindGroupLayout,
    text_pipeline: wgpu::RenderPipeline,
    text_bgl: wgpu::BindGroupLayout,
    /// 纹理 mask(destination-in)
    text_pipeline_mask: wgpu::RenderPipeline,
    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
    /// Stage T1: triangle pipeline(PathBuilder.fill → earcut → vertex/index buffer)
    tri_pipeline: wgpu::RenderPipeline,
    tri_bgl: wgpu::BindGroupLayout,
    /// **ClipPath GPU stencil** — 4 个测试变体 + 2 个 mask 写入变体:
    /// 1. `tri_pipeline_stencil_inc/dec`:只写 stencil,color=NONE(推入 +1 / 弹出 -1)
    /// 2. `rect/text/tri_pipeline_stencil_test`:stencil Equal(当前嵌套深度)
    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
    text_pipeline_stencil_test: wgpu::RenderPipeline,
    tri_pipeline_stencil_test: wgpu::RenderPipeline,
    /// 缓存的 GPU glyph atlas(多窗口共享同一 texture/view/sampler)
    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
    /// 阶段 4-B:layer → GPU texture cache(每 layer 一张全屏 texture)
    layer_cache: HashMap<LayerId, LayerGpuCache>,
    /// P2:frame 内活跃 layer id 复用集合(避免每帧分配 HashSet)
    active_layer_ids: std::collections::HashSet<LayerId>,
    /// P2:frame 内 layer 逻辑尺寸复用表(composition 用)
    frame_layer_sizes: HashMap<LayerId, Size>,
    /// P2:跨帧复用的 composition scratch(by_id/memo/visiting 容器)
    composition_scratch: mgui_core::CompositionScratch,
    /// 阶段 4-B:blit pipeline(把 layer texture 画到 surface)
    blit_pipeline: wgpu::RenderPipeline,
    blit_bgl: wgpu::BindGroupLayout,
    blit_sampler: wgpu::Sampler,
    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
    backdrop_pipeline: wgpu::RenderPipeline,
    backdrop_bgl: wgpu::BindGroupLayout,
    /// 阶段 2-E:surface 格式(layer texture 与 pipeline render target 保持一致)
    format: wgpu::TextureFormat,
    /// 阶段 B4:GPU 端 timestamp profiler(None = 设备不支持 TIMESTAMP_QUERY)
    pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
    /// 阶段 B1.5:**per-layer** batch buffer pool
    ///
    /// **关键**:每个 layer 独立 buffer — **不能所有 layer 共享一个 pool buffer**!
    /// wgpu 的 `queue.write_buffer` 是 staged + 下次 submit 时执行;
    /// 同一 submit 内多个 layer 依次 write_buffer 同一 buffer → 后写覆盖先写,
    /// 所有 layer 的 draw 都用最后一个 layer 的数据 → UI 错乱(元素放大/错位)。
    /// 阶段 6(图片):value 同 LayerBatchPool;key = (LayerId, texture_id) —
    /// text 用 texture_id 0,每张图片一个独立 key(纹理不同 buffer 必须隔离)
    batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
    /// 阶段 6(图片):图片纹理缓存(多窗口共享;按 ImageWidget 的 texture_id 索引)
    image_cache: Rc<RefCell<ImageTextureCache>>,
    /// P2-1.5:跨 layer 复用的临时纹理(按物理尺寸 key;view 持有 texture 引用)
    msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
    stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
    snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
    /// P2-1.5:上一帧的绘制统计(draw calls / scratch / layer texture)
    last_stats: RenderStats,
}

/// 单张图片纹理的 GPU 缓存条目
pub(crate) struct ImageTextureEntry {
    /// 仅用于保持 GPU 纹理存活(view 是否持有引用不应依赖)
    pub _texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub sampler: wgpu::Sampler,
    /// 最近一次被 PaintList 声明使用的时钟
    pub last_used: u64,
    /// 纹理字节数(width * height * 4),用于预算淘汰
    pub bytes: u64,
}

/// 图片纹理预算(256 MiB)
pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;

/// 单窗口所有 layer resolve texture 的总预算(256 MiB)。
pub use setup::LAYER_TEXTURE_BUDGET_BYTES;

pub use crate::backend_info::ImageTextureStats;

impl Renderer {
    /// P2-1.5:上一帧绘制统计(draw calls / segment / scratch 内存)
    pub fn last_stats(&self) -> RenderStats {
        self.last_stats
    }

    /// 当前图片纹理数量/字节数与预算
    pub fn image_texture_stats(&self) -> ImageTextureStats {
        let cache = self.image_cache.borrow();
        ImageTextureStats {
            count: cache.textures.len(),
            bytes: cache.textures.values().map(|e| e.bytes).sum(),
            budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
        }
    }
}

/// 阶段 B1.5:单 layer 的 batch buffer pool(9 个 buffer — 含 tri + stencil mask)
struct LayerBatchPool {
    rect_header: Option<wgpu::Buffer>,
    rect_instances: Option<wgpu::Buffer>,
    text_header: Option<wgpu::Buffer>,
    text_instances: Option<wgpu::Buffer>,
    /// Stage T1:tri buffers(vertex + index + uniform)
    tri_vertex: Option<wgpu::Buffer>,
    tri_index: Option<wgpu::Buffer>,
    tri_uniform: Option<wgpu::Buffer>,
    /// **T0-1.5:ClipPath stencil** — PushClipPath path triangles 的 vertex/index buffer
    /// 每帧 write_buffer 覆盖内容;grow-only 容量够就复用
    stencil_vertex: Option<wgpu::Buffer>,
    stencil_index: Option<wgpu::Buffer>,
}

/// GPU atlas 资源 + 缓存的 size
pub(crate) struct AtlasGpu {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    sampler: wgpu::Sampler,
    /// 创建时的 atlas 尺寸;尺寸变化时重建
    cached_size: (u32, u32),
}

pub(crate) struct RectBatch {
    bg: wgpu::BindGroup,
}

/// Stage T1:triangle pipeline — 每 layer 一个批次(所有 PathBuilder.fill 合并画)
pub(crate) struct TriBatch {
    bg: wgpu::BindGroup,
}

/// Stage T1:triangle uniform(跟 RectBatchUniform 同样的 16 bytes pattern)
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct TriUniform {
    screen_size: [f32; 2],
    _pad0: u32,
    _pad1: u32,
}

/// P2-1.4b:背景模糊 uniform(64 bytes)
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct BackdropUniform {
    screen: [f32; 2],
    _pad: [f32; 2],
    rect: [f32; 4],
    /// [corner_radius, blur_radius, 0, 0]
    params: [f32; 4],
    /// tint rgb + mix alpha
    tint: [f32; 4],
}

/// 阶段 B2:text 批处理结果(pub(crate):ImageBatchDraw::batch 字段引用)
pub(crate) struct TextBatch {
    bg: wgpu::BindGroup,
    count: u32,
}

// ============================================================
// 阶段 B2+B3:clip 分段收集 + GPU scissor 裁剪
// ============================================================

/// PushClipPath 的 earcut 三角形(扁平 vertices + indices)
#[derive(Debug, Clone, Default)]
pub(crate) struct StencilDraw {
    /// [x, y, r, g, b, a, ...]
    pub vertices: Vec<f32>,
    pub indices: Vec<u32>,
}

/// 进入/退出一个 ClipPath 时对 stencil 覆盖计数的操作。
///
/// 推入时 +1、弹出时 -1;内容段用 `Equal(level)` 测试,
/// 因此嵌套 clip 的交集会自动生效(只有每个 mask 都覆盖到的像素计数 = depth)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StencilAction {
    /// `StencilDraw` 下标
    pub draw: u32,
    /// 操作时的嵌套深度(从 1 开始)
    pub level: u32,
    pub increment: bool,
}

/// 合并后的 ClipPath mask GPU 资源;`ranges[draw]` = (first_index, index_count)
pub(crate) struct StencilGpu {
    pub vertex: wgpu::Buffer,
    pub index: wgpu::Buffer,
    pub ranges: Vec<(u32, u32)>,
    pub bg: wgpu::BindGroup,
}

/// 背景模糊命令参数(圆角遮罩 + 13-tap blur + tint)
#[derive(Debug, Clone, Copy)]
pub(crate) struct BackdropBlurSpec {
    pub rect: Rect,
    pub radius: f32,
    pub blur_radius: f32,
    pub tint: [f32; 4],
}

/// 段内的一次绘制操作(按 PaintList 命令顺序记录,保留跨类型 z-order)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DrawOp {
    /// rect instance 半开区间 [start, end) + 混合模式
    Rect(u32, u32, BlendMode),
    /// text instance 半开区间 [start, end)
    Text(u32, u32),
    /// 图片组下标
    Image(u32),
    /// 纹理 alpha mask(destination-in),引用图片组下标
    Mask(u32),
    /// 背景模糊(引用 BackdropBlurSpec 下标)
    BackdropBlur(u32),
    /// tri index 半开区间 [start, end)(index 进合并后的 tri index buffer)
    Tri(u32, u32),
}

/// 阶段 B3:一个 scissor 段 — 相邻 clip 边界(PushClip/PopClip)之间的绘制区间
///
/// Pass 1 里每段一次 `set_scissor_rect`,再按 `ops` 顺序逐条 draw —— 这样
/// rect/text/图片/三角形都保持 PaintList 的原始绘制顺序,而不是被类型分组
/// 重排(旧实现固定 rect→image→text→tri,后画的 rect 会盖不住先画的文字)。
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ClipSegment {
    /// scissor 矩形物理像素 [x, y, w, h];`None` = 本段无裁剪(整个 target)
    pub scissor: Option<[u32; 4]>,
    /// 本段实际 draw 的顺序列表
    pub ops: Vec<DrawOp>,
    /// 段内 rect/text/图片组的总范围(测试/诊断兼容字段)
    pub rect_range: (u32, u32),
    pub text_range: (u32, u32),
    pub image_range: (u32, u32),
    /// 本段生效的 ClipPath 嵌套深度(0 = 无 path 裁剪,>0 时用 stencil Equal(level))
    pub stencil_level: u32,
    /// 本段绘制前要执行的 stencil mask 操作(推入/弹出,按顺序)
    pub stencil_actions: Vec<StencilAction>,
}

/// 阶段 6(图片):一个 texture_id 的连续图片组(paint 命令顺序里相邻的同图
/// TexturedRect 合为一组 — 同一 ImageWidget 只产 1 条命令,组数 = 层内图片数)
pub(crate) struct ImageGroup {
    pub texture_id: u32,
    pub instances: Vec<TextInstance>,
}

/// 阶段 6(图片):一个图片组的可绘制批次(bind group 已绑定该组纹理)。
///
/// 在 `Vec<Option<ImageBatchDraw>>` 里**下标 = ImageGroup 下标**:
/// 未注册纹理的组是 `None` 占位,这样段的 `image_range`(组下标区间)
/// 不因跳过而错位。
pub(crate) struct ImageBatchDraw {
    pub(crate) batch: TextBatch,
}

/// 矩形求交(负宽高 clamp 为 0 — 退化矩形与任何东西都不相交)
fn intersect_rect(a: Rect, b: Rect) -> Rect {
    let x1 = a.x.max(b.x);
    let y1 = a.y.max(b.y);
    let x2 = (a.x + a.width).min(b.x + b.width);
    let y2 = (a.y + a.height).min(b.y + b.height);
    Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
}

/// 计算 path triangles 的 bounding box(用于 PushClipPath → scissor 近似)
fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
    if vertices.is_empty() {
        return Rect::new(0.0, 0.0, 0.0, 0.0);
    }
    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for v in vertices {
        min_x = min_x.min(v.x);
        min_y = min_y.min(v.y);
        max_x = max_x.max(v.x);
        max_y = max_y.max(v.y);
    }
    Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
}

/// instance 矩形是否与当前 clip 相交(CPU 粗剔除;精确裁剪交给 GPU scissor)
fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
    match clip {
        None => true,
        // 退化 clip(宽或高 = 0)与任何东西都不相交
        Some(c) => {
            c.width > 0.0
                && c.height > 0.0
                && r.x < c.x + c.width
                && r.x + r.width > c.x
                && r.y < c.y + c.height
                && r.y + r.height > c.y
        }
    }
}

/// 圆角矩形三角扇(凸多边形,中心 + 周边点即可精确覆盖)。
///
/// 用于 `PushClipRRect` 的 stencil mask;每角 8 段二次近似圆,
/// 顶点格式与 `StencilDraw` 一致([x,y,r,g,b,a])。
fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
    if rect.width <= 0.0 || rect.height <= 0.0 {
        return (Vec::new(), Vec::new());
    }
    let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
    let r = radius.max(0.0).min(w.min(h) * 0.5);

    let mut pts: Vec<(f32, f32)> = Vec::new();
    if r <= 0.0 {
        pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
    } else {
        const SEG: u32 = 8;
        // 顺时针(屏幕 y 向下):右上 → 右下 → 左下 → 左上
        let arcs = [
            (x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
            (x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
            (x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
            (x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
        ];
        for &(cx, cy, a0, a1) in &arcs {
            for i in 0..=SEG {
                let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
                pts.push((cx + r * a.cos(), cy + r * a.sin()));
            }
        }
        // 最后一角回到起点(首尾重复),去掉
        if pts.len() > 1 && pts.first() == pts.last() {
            pts.pop();
        }
    }
    pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);

    let n = pts.len();
    if n < 3 {
        return (Vec::new(), Vec::new());
    }
    let mut verts = Vec::with_capacity((n + 1) * 6);
    for &(px, py) in &pts {
        verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
    }
    verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
    let center = n as u32;
    let mut indices = Vec::with_capacity(n * 3);
    for i in 0..n as u32 {
        indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
    }
    (verts, indices)
}

/// clip 逻辑坐标 → scissor 物理像素 [x, y, w, h](floor/ceil 取整,clamp 到 texture 尺寸)
fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
    let d = dpr.max(0.0);
    let (tw, th) = (tex.0 as f32, tex.1 as f32);
    // 近边也必须 clamp 到 target 尺寸,否则完全落在 target 右侧/下方的 clip
    // 会产出 x/y 越界的 scissor → wgpu validation error。
    let x0 = (r.x * d).floor().clamp(0.0, tw);
    let y0 = (r.y * d).floor().clamp(0.0, th);
    let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
    let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
    let x = x0 as u32;
    let y = y0 as u32;
    let w = (x1 as u32).saturating_sub(x);
    let h = (y1 as u32).saturating_sub(y);
    [x, y, w, h]
}

/// 阶段 B2+B3:一次遍历 paint_list → rect/text instances + scissor 分段
///
/// - `PushClip`/`PopClip` 是段边界;`PushClip` 与外层 clip 求交(嵌套 clip)
/// - instance 与当前 clip 相交才收集(CPU 粗剔除),溢出边缘交给 GPU scissor
/// - 空段(无 instance)不产出 — 不浪费 draw call
///
/// Stage T1:Triangles — 合并所有 PaintCommand::Triangles(vertices,indices)
/// 进一个 Vec<f32>(vertex flat) + Vec<u32>(index merged + offset by base vertex count)
/// **不分 clip 分段**(简化:path fill 的三角形通常不需要 clip 分段;
/// 未来需要时加 tri_range 进 ClipSegment)
///
/// **ClipPath stencil** — 最后一个返回值:
/// 所有 PushClipPath 的 earcut 三角形(供 renderer 在段间写 stencil mask);
/// 每个 `ClipSegment.stencil_actions` 用下标引用它。
type CollectedInstances = (
    Vec<RectInstance>,
    Vec<TextInstance>,
    Vec<ImageGroup>,
    Vec<ClipSegment>,
    // Stage T1:triangle data(所有 PaintCommand::Triangles 合并)
    Vec<f32>, // vertex flat data: [x,y,r,g,b,a, x,y,r,g,b,a, ...]
    Vec<u32>, // merged index data(offset per command)
    // ClipPath mask triangles(按 PushClipPath 顺序)
    Vec<StencilDraw>,
    // 背景模糊参数
    Vec<BackdropBlurSpec>,
);

pub(crate) fn collect_instances_segmented(
    paint_list: &PaintList,
    dpr: f32,
    tex_size: (u32, u32),
) -> CollectedInstances {
    let mut rects: Vec<RectInstance> = Vec::new();
    let mut texts: Vec<TextInstance> = Vec::new();
    let mut image_groups: Vec<ImageGroup> = Vec::new();
    let mut segments: Vec<ClipSegment> = Vec::new();
    // Stage T1:triangles
    let mut tri_vertices: Vec<f32> = Vec::new(); // 扁平化后的顶点
    let mut tri_indices: Vec<u32> = Vec::new(); // 合并后的 index(加偏移)
    let mut tri_base_vertex: u32 = 0; // 当前 command 的顶点在全局数组里的 base offset
                                      // **ClipPath stencil** — 每个 PushClipPath 的 mask 三角形 + 待执行的 +1/-1 操作
    let mut stencil_draws: Vec<StencilDraw> = Vec::new();
    let mut pending_stencil: Vec<StencilAction> = Vec::new();
    let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
    let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
    let mut clip_depth: u32 = 0;
    // 混合模式栈:作用于后续矩形族命令,不产生段边界
    let mut blend_stack: Vec<BlendMode> = Vec::new();
    let mut cur_blend = BlendMode::Normal;
    // clip 栈:每层保存"压入前的外层 clip" + 是否为 stencil mask 裁剪
    let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
    let mut cur_clip: Option<Rect> = None;
    let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
    // 段内绘制顺序(rect/text/image/tri 交错,保留 painter's order)
    let mut ops: Vec<DrawOp> = Vec::new();

    // 关闭当前段(有绘制操作才记录;重置段起点)
    macro_rules! close_segment {
        () => {
            let r_end = rects.len() as u32;
            let t_end = texts.len() as u32;
            let i_end = image_groups.len() as u32;
            if !ops.is_empty() {
                segments.push(ClipSegment {
                    scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
                    ops: ops.clone(),
                    rect_range: (seg_r, r_end),
                    text_range: (seg_t, t_end),
                    image_range: (seg_i, i_end),
                    stencil_level: clip_depth,
                    // 边界上的 mask 操作属于"下一段内容";空段不消费它们,
                    // 留到下一个有绘制的段(净效果仍然正确)。
                    stencil_actions: std::mem::take(&mut pending_stencil),
                });
                ops.clear();
            }
            seg_r = r_end;
            seg_t = t_end;
            seg_i = i_end;
        };
    }

    fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
        match op {
            DrawOp::Rect(s, e, mode) => {
                if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
                    if *last_end == s && *last_mode == mode {
                        *last_end = e;
                        return;
                    }
                }
            }
            DrawOp::Text(s, e) => {
                if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
                    if *last_end == s {
                        *last_end = e;
                        return;
                    }
                }
            }
            DrawOp::Tri(s, e) => {
                if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
                    if *last_end == s {
                        *last_end = e;
                        return;
                    }
                }
            }
            DrawOp::Image(_) => {}
            DrawOp::Mask(_) => {}
            DrawOp::BackdropBlur(_) => {}
        }
        ops.push(op);
    }

    // ClipPath / ClipRRect 共用:压入一层 stencil mask + bbox scissor
    macro_rules! push_mask_clip {
        ($flat:expr, $idxs:expr, $bbox:expr) => {{
            clip_depth += 1;
            let flat_verts: Vec<f32> = $flat;
            let idxs: &[u32] = $idxs;
            let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
                let idx = stencil_draws.len() as u32;
                stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
                pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
                Some(idx)
            } else {
                None
            };
            path_draw_stack.push(draw_index);

            let bbox: Rect = $bbox;
            stack.push((cur_clip, true));
            cur_clip = Some(match cur_clip {
                Some(outer) => intersect_rect(outer, bbox),
                None => bbox,
            });
        }};
    }

    // 弹出 mask clip:深度的 -1 操作 + 恢复外层 scissor
    macro_rules! pop_mask_clip {
        () => {{
            if let Some(Some(draw)) = path_draw_stack.pop() {
                // 弹出时 -1,恢复外层的覆盖计数(兄弟 clip 不会互相污染)
                pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
            }
            clip_depth = clip_depth.saturating_sub(1);
        }};
    }

    for cmd in &paint_list.commands {
        match cmd {
            PaintCommand::PushBlendMode(mode) => {
                blend_stack.push(cur_blend);
                cur_blend = *mode;
            }
            PaintCommand::PopBlendMode => {
                cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
            }
            PaintCommand::PushClip(r) => {
                close_segment!();
                stack.push((cur_clip, false));
                cur_clip = Some(match cur_clip {
                    Some(outer) => intersect_rect(outer, *r),
                    None => *r,
                });
            }
            PaintCommand::PushClipRRect { rect, radius } => {
                close_segment!();
                let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
                push_mask_clip!(flat_verts, &idxs, *rect);
            }
            PaintCommand::PopClip => {
                close_segment!();
                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
                if is_mask {
                    pop_mask_clip!();
                }
                cur_clip = prev;
            }
            // PushClipPath — 路径裁剪(scissor 用 bbox 粗裁,GPU stencil 精确 mask)
            PaintCommand::PushClipPath { vertices, indices } => {
                close_segment!();
                let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
                for v in vertices {
                    flat_verts.push(v.x);
                    flat_verts.push(v.y);
                    flat_verts.push(v.color.r);
                    flat_verts.push(v.color.g);
                    flat_verts.push(v.color.b);
                    flat_verts.push(v.color.a);
                }
                push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
            }
            PaintCommand::PopClipPath => {
                close_segment!();
                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
                if is_mask {
                    pop_mask_clip!();
                }
                cur_clip = prev;
            }
            PaintCommand::Rect { rect, color, radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let start = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [color.r, color.g, color.b, color.a],
                        to: [color.r, color.g, color.b, color.a],
                        grad: [0.0; 4],
                        params: [*radius, 0.0, 0.0, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
                }
            }
            // **T0-2:BoxShadow** — 走同一条 Rect pipeline,shader 根据 blur_radius 做 SDF blur
            PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let start = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [color.r, color.g, color.b, color.a],
                        to: [color.r, color.g, color.b, color.a],
                        grad: [0.0; 4],
                        params: [*radius, 0.0, *blur_radius, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
                }
            }
            // **P2-1.4:InsetShadow** — 同一 rect pipeline,shader kind=3 做内侧 SDF 衰减
            PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [color.r, color.g, color.b, color.a],
                        to: [color.r, color.g, color.b, color.a],
                        grad: [0.0; 4],
                        params: [*radius, 3.0, *blur_radius, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
                }
            }
            PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [from.r, from.g, from.b, from.a],
                        to: [to.r, to.g, to.b, to.a],
                        grad: [start.x, start.y, end.x, end.y],
                        params: [*corner_radius, 1.0, 0.0, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
                }
            }
            PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [from.r, from.g, from.b, from.a],
                        to: [to.r, to.g, to.b, to.a],
                        grad: [center.x, center.y, *radial_radius, 0.0],
                        params: [*corner_radius, 2.0, 0.0, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
                }
            }
            // **P2-1.4b:背景模糊** — 在命令处切 pass,模糊此前已绘制内容
            PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = backdrop_blurs.len() as u32;
                    backdrop_blurs.push(BackdropBlurSpec {
                        rect: *rect,
                        radius: *radius,
                        blur_radius: *blur_radius,
                        tint: [tint.r, tint.g, tint.b, tint.a],
                    });
                    ops.push(DrawOp::BackdropBlur(idx));
                }
            }
            // **P2-1.3:纹理 mask** — destination-in,只保留纹理 alpha 覆盖的区域
            PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
                if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
                    let gi = image_groups.len() as u32;
                    image_groups.push(ImageGroup {
                        texture_id: *texture_id,
                        instances: vec![TextInstance {
                            rect: [rect.x, rect.y, rect.width, rect.height],
                            // mode 2.0 = Alpha:alpha 取纹理 A 通道 × color.a
                            color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
                            uv: *uv,
                            mode: 2.0,
                            _pad: [0.0; 3],
                        }],
                    });
                    ops.push(DrawOp::Mask(gi));
                }
            }
            PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
                if rect_intersects_clip(rect, cur_clip) {
                    // **像素对齐**:text glyph atlas 按物理分辨率栅格化(每个 glyph 一个 texel=一个物理像素),
                    // rect 在逻辑坐标上做 round(x*dpr)/dpr → 确保 UV 采样 1:1 对齐 atlas texel → 文字锐
                    let snap = |v: f32| (v * dpr).round() / dpr;
                    let inst = TextInstance {
                        rect: [
                            snap(rect.x),
                            snap(rect.y),
                            snap(rect.x + rect.width) - snap(rect.x),
                            snap(rect.y + rect.height) - snap(rect.y),
                        ],
                        color: [color.r, color.g, color.b, color.a],
                        uv: *uv,
                        mode: match mode {
                            TextureMode::Mask => 0.0,
                            TextureMode::Color => 1.0,
                        },
                        _pad: [0.0; 3],
                    };
                    if *texture_id == 0 {
                        let start = texts.len() as u32;
                        texts.push(inst);
                        push_range_op(&mut ops, DrawOp::Text(start, start + 1));
                    } else {
                        // 阶段 6(图片):texture_id != 0 = ImageWidget 的全图 quad。
                        // 只有「紧邻的上一笔也是同纹理图片」才合并成组 —— 中间插入
                        // rect/text 后必须新开一组,否则绘制顺序无法恢复。
                        let reuse_group = ops
                            .last()
                            .and_then(|op| match op {
                                DrawOp::Image(gi) => Some(*gi),
                                _ => None,
                            })
                            .filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
                        if let Some(gi) = reuse_group {
                            image_groups[gi as usize].instances.push(inst);
                        } else {
                            let gi = image_groups.len() as u32;
                            image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
                            ops.push(DrawOp::Image(gi));
                        }
                    }
                }
            }
            // Stage T1:Triangles — 合并所有 path fill 的 earcut 输出
            // 每个 command 的 indices 加 base offset(避免不同 PathBuilder 的 triangles 互相引用)
            PaintCommand::Triangles { vertices, indices } => {
                let idx_start = tri_indices.len() as u32;
                // vertices 扁平化为 [x, y, r, g, b, a]
                for v in vertices {
                    tri_vertices.push(v.x);
                    tri_vertices.push(v.y);
                    tri_vertices.push(v.color.r);
                    tri_vertices.push(v.color.g);
                    tri_vertices.push(v.color.b);
                    tri_vertices.push(v.color.a);
                }
                // indices 加 base(让每个 command 的顶点全局唯一)
                for &idx in indices {
                    tri_indices.push(tri_base_vertex + idx);
                }
                tri_base_vertex += vertices.len() as u32;
                if !vertices.is_empty() && !indices.is_empty() {
                    push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
                }
            }
            // Stage T2:PaintCommand::Text — core 层 Widget 要画文字的高层命令
            // 让 paint_text_line 展开成 TexturedRect → 逐个收集
            PaintCommand::Text { text, range, font_size, color, position, max_width } => {
                let mut temp_list = PaintList::new();
                crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
                // 展开后的 TexturedRect 逐个收集
                let snap = |v: f32| (v * dpr).round() / dpr;
                let start = texts.len() as u32;
                for cmd in temp_list.commands {
                    if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
                        if rect_intersects_clip(&rect, cur_clip) {
                            texts.push(TextInstance {
                                rect: [
                                    snap(rect.x),
                                    snap(rect.y),
                                    snap(rect.x + rect.width) - snap(rect.x),
                                    snap(rect.y + rect.height) - snap(rect.y),
                                ],
                                color: [color.r, color.g, color.b, color.a],
                                uv,
                                // glyph atlas 永远走 mask 采样
                                mode: 0.0,
                                _pad: [0.0; 3],
                            });
                        }
                    }
                }
                if texts.len() as u32 > start {
                    push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
                }
            }
        }
    }
    // 尾段
    close_segment!();
    let _ = (seg_r, seg_t, seg_i); // 尾段关闭后不再读 — 显式消费消除 unused_assignments

    // P2-1.5:合并相邻且 scissor/stencil 状态相同的段。
    // 常见于 PopClip 后立刻 PushClip 同一矩形(虚拟列表/滚动容器),
    // 合并后减少 set_scissor / pipeline 状态切换;跨 mask 操作的段不合并。
    let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
    for seg in segments.drain(..) {
        let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
            prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
        });
        if can_merge {
            let prev = merged.last_mut().expect("checked non-empty");
            for op in &seg.ops {
                push_range_op(&mut prev.ops, *op);
            }
            prev.rect_range.1 = seg.rect_range.1;
            prev.text_range.1 = seg.text_range.1;
            prev.image_range.1 = seg.image_range.1;
        } else {
            merged.push(seg);
        }
    }

    (rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
}

/// 阶段 B1:helper — 构造 rect batch bind group(0 rect → None)
///
/// 阶段 B1.5:**per-layer buffer pool** — header(16B 固定)永驻,instances(grow-only)
/// 容量够就复用,只 `queue.write_buffer` 覆盖。稳态 0 alloc/帧/layer。
///
/// **关键教训**:**不能所有 layer 共享一个 pool buffer** — wgpu 的
// `queue.write_buffer` 是 staged + 下次 submit 执行;同一 submit 内多个 layer
// 依次 write_buffer 同一 buffer → 后写覆盖先写 → 所有 layer 的 draw 都用
// 最后一个 layer 的数据 → UI 元素放大/错乱。
// =================================================================
// 子模块
// =================================================================
mod batches;
mod composition;
mod render;
mod setup;
#[cfg(test)]
mod tests;