Skip to main content

mgui_runtime/renderer/
mod.rs

1use mgui_core::paint::{BlendMode, TextureMode};
2use mgui_core::Rect;
3use mgui_core::{effect_flags, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand, PaintList, RRectDef, Size};
4use std::cell::RefCell;
5use std::collections::HashMap;
6use std::rc::Rc;
7
8use wgpu::util::DeviceExt;
9
10/// 阶段 B1:rect 批处理 — batch header(per-layer 共享)
11/// 屏幕逻辑尺寸 + instance 数量;**16-align**:`vec2` 后接 `u32` + `vec2 pad` 凑齐 16 字节。
12#[repr(C)]
13#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
14pub(crate) struct RectBatchUniform {
15    screen_size: [f32; 2], // 0..8
16    count: u32,            // 8..12
17    _pad: [f32; 1],        // 12..16 (整体 16-align)
18}
19
20/// 阶段 B1:rect 批处理 — 每实例数据
21/// size = 5 × vec4 = 80 字节(WGSL 16-align 兼容)。
22///
23/// - 普通 Rect:from = to = color,params[1] = 0
24/// - BoxShadow:params[2] = blur_radius
25/// - LinearGradient:grad = (start.xy, end.xy),params[1] = 1
26/// - RadialGradient:grad = (center.xy, radius, 0),params[1] = 2
27#[repr(C)]
28#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
29pub(crate) struct RectInstance {
30    rect: [f32; 4],
31    from: [f32; 4],
32    to: [f32; 4],
33    grad: [f32; 4],
34    /// [corner_radius, kind, blur_radius, pad]
35    params: [f32; 4],
36}
37
38/// 阶段 B2:text 批处理 — batch header
39#[repr(C)]
40#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
41pub(crate) struct TextBatchUniform {
42    screen_size: [f32; 2], // 0..8
43    count: u32,            // 8..12
44    _pad: [f32; 1],        // 12..16 (整体 16-align)
45}
46
47/// 阶段 B2:text 批处理 — 每实例数据
48/// size = 16(rect vec4) + 16(color vec4) + 16(uv vec4) + 16(mode vec4) = 64 字节
49/// 16-align OK。
50#[repr(C)]
51#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
52pub(crate) struct TextInstance {
53    rect: [f32; 4],  // 0..16
54    color: [f32; 4], // 16..32
55    uv: [f32; 4],    // 32..48
56    /// 纹理采样模式(vec4.x):0.0 = Mask(alpha 在纹理 R 通道,glyph/SVG tint),
57    /// 1.0 = Color(straight RGBA 全彩纹理,SVG 全彩 / PNG 图片)
58    mode: f32, // 48..52
59    _pad: [f32; 3],  // 52..64
60}
61
62// 阶段 B2:被 TextInstance + TextBatchUniform 替代(批处理)
63// 旧 TextUniform 已删除(deprecated by B2,见 commit log)
64
65/// 阶段 4-B + 4-D:blit uniform(全屏 blit 用,带 layer offset/size)
66///
67/// 阶段 5:扩展为携带 effect 字段:
68/// - effect_flags: bit field(HAS_TRANSFORM / HAS_OPACITY / HAS_CLIP)
69/// - opacity / rotation / scale / translate_x / translate_y / clip_radius
70///
71/// **WGSL 对齐**: u32 4 字节,f32 4 字节;WGSL 会按 16-align 整体 struct。
72#[repr(C)]
73#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
74pub(crate) struct BlitUniform {
75    offset: [f32; 2], // 0..8    layer 在父 layer 内的 logical 位置
76    size: [f32; 2],   // 8..16   layer 的 logical size
77    screen: [f32; 2], // 16..24  surface logical 尺寸
78    // ========== 阶段 5:effect 字段 ==========
79    effect_flags: u32, // 24..28  bit field
80    opacity: f32,      // 28..32
81    rotation: f32,     // 32..36
82    scale_x: f32,      // 36..40  HAS_TRANSFORM:x 轴缩放
83    translate_x: f32,  // 40..44
84    translate_y: f32,  // 44..48
85    clip_radius: f32,  // 48..52
86    scale_y: f32,      // 52..56  HAS_TRANSFORM:y 轴缩放(布局为 16-align 的填充位)
87    // bugfix(Transform 旋转被裁):quad 覆盖区域。无旋转时 = offset/size;
88    // HAS_TRANSFORM 时 = 旋转+缩放后的 AABB(中心不变,尺寸按 |cos|/|sin| 扩大),
89    // 否则旋转超出原矩形的部分会被 quad 光栅化裁掉。
90    quad_offset: [f32; 2], // 56..64
91    quad_size: [f32; 2],   // 64..72
92    phys_screen: [f32; 2], // 72..80 surface 物理像素尺寸
93    // ========== 嵌套 layer 合成:局部坐标 → surface 的完整仿射 ==========
94    /// [a, b, c, d]:x' = a*x + b*y + tx;y' = c*x + d*y + ty
95    affine: [f32; 4], // 80..96
96    affine_translate: [f32; 2], // 96..104
97    _affine_pad: [f32; 2],      // 104..112(16-align)
98    /// 两层裁剪(祖先 + 自己的内两层),surface 逻辑坐标 AABB
99    clip_rect0: [f32; 4], // 112..128
100    clip_rect1: [f32; 4],       // 128..144
101    /// [radius0, radius1, count, unused]
102    clip_params: [f32; 4], // 144..160
103}
104// struct size = 160 bytes (16-aligned)
105
106/// 阶段 4-B:每个 layer 的 GPU cache(MSAA texture + resolve texture)
107struct LayerGpuCache {
108    /// resolve target texture(单采样;blit 采样 + 背景模糊 snapshot 复制源)
109    resolve_texture: wgpu::Texture,
110    /// resolve target view(sample_count=1,blit 采样这里)
111    resolve_view: wgpu::TextureView,
112    /// 创建时的物理尺寸;resize 时重建
113    cached_size: (u32, u32),
114}
115
116/// 可跨窗口复用的 Renderer GPU 资源(pipeline / bind group layout / blit sampler /
117/// glyph atlas / 图片纹理缓存)。
118///
119/// layer 缓存与 batch buffer 仍由各窗口 Renderer 独立持有(LayerId 只在单树内唯一)。
120#[derive(Clone)]
121pub struct RendererShared {
122    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
123    rect_pipelines: [wgpu::RenderPipeline; 4],
124    rect_bgl: wgpu::BindGroupLayout,
125    text_pipeline: wgpu::RenderPipeline,
126    text_bgl: wgpu::BindGroupLayout,
127    /// 纹理 mask(destination-in)
128    text_pipeline_mask: wgpu::RenderPipeline,
129    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
130    tri_pipeline: wgpu::RenderPipeline,
131    tri_bgl: wgpu::BindGroupLayout,
132    /// ClipPath stencil mask 写入(推入 +1 / 弹出 -1,front/back 同步)
133    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
134    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
135    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
136    text_pipeline_stencil_test: wgpu::RenderPipeline,
137    tri_pipeline_stencil_test: wgpu::RenderPipeline,
138    blit_pipeline: wgpu::RenderPipeline,
139    blit_bgl: wgpu::BindGroupLayout,
140    blit_sampler: wgpu::Sampler,
141    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
142    backdrop_pipeline: wgpu::RenderPipeline,
143    backdrop_bgl: wgpu::BindGroupLayout,
144    format: wgpu::TextureFormat,
145    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
146    image_cache: Rc<RefCell<ImageTextureCache>>,
147}
148
149/// 跨窗口共享的图片纹理缓存。
150#[derive(Default)]
151pub(crate) struct ImageTextureCache {
152    textures: HashMap<u32, ImageTextureEntry>,
153    clock: u64,
154    /// 多窗口共享模式下由 host 统一管理预算,暂不做单帧 eviction。
155    evict_enabled: bool,
156}
157
158impl RendererShared {
159    pub fn format(&self) -> wgpu::TextureFormat {
160        self.format
161    }
162
163    /// 多窗口 host 在一个渲染周期后调用:保护所有窗口最近一帧使用的纹理,
164    /// 超预算时淘汰其余最旧纹理。
165    pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
166        self.image_cache.borrow_mut().evict_to_budget(protected);
167    }
168}
169
170impl ImageTextureCache {
171    fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
172        let budget = IMAGE_TEXTURE_BUDGET_BYTES;
173        let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
174        if total <= budget {
175            return;
176        }
177        let mut candidates: Vec<(u32, u64, u64)> = self
178            .textures
179            .iter()
180            .filter(|(id, _)| !protected.contains(id))
181            .map(|(&id, e)| (id, e.last_used, e.bytes))
182            .collect();
183        candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
184        for (id, _, bytes) in candidates {
185            if total <= budget {
186                break;
187            }
188            self.textures.remove(&id);
189            total = total.saturating_sub(bytes);
190        }
191        if total > budget {
192            log::warn!(
193                target: "mgui_startup",
194                "shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
195                total / (1024 * 1024),
196                budget / (1024 * 1024)
197            );
198        }
199    }
200}
201
202#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203pub struct RenderStats {
204    /// 本帧实际重画的 layer 数
205    pub layers_painted: u32,
206    /// 实际提交的 scissor 段数
207    pub segments: u32,
208    /// paint pass + stencil mask + layer blit 的 draw 总数
209    pub draw_calls: u32,
210    /// 跨 layer 复用 scratch 的总字节(MSAA + stencil + snapshot)
211    pub scratch_bytes: u64,
212    /// 持久 layer resolve texture 的总字节
213    pub layer_texture_bytes: u64,
214}
215
216pub struct Renderer {
217    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
218    rect_pipelines: [wgpu::RenderPipeline; 4],
219    rect_bgl: wgpu::BindGroupLayout,
220    text_pipeline: wgpu::RenderPipeline,
221    text_bgl: wgpu::BindGroupLayout,
222    /// 纹理 mask(destination-in)
223    text_pipeline_mask: wgpu::RenderPipeline,
224    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
225    /// Stage T1: triangle pipeline(PathBuilder.fill → earcut → vertex/index buffer)
226    tri_pipeline: wgpu::RenderPipeline,
227    tri_bgl: wgpu::BindGroupLayout,
228    /// **ClipPath GPU stencil** — 4 个测试变体 + 2 个 mask 写入变体:
229    /// 1. `tri_pipeline_stencil_inc/dec`:只写 stencil,color=NONE(推入 +1 / 弹出 -1)
230    /// 2. `rect/text/tri_pipeline_stencil_test`:stencil Equal(当前嵌套深度)
231    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
232    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
233    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
234    text_pipeline_stencil_test: wgpu::RenderPipeline,
235    tri_pipeline_stencil_test: wgpu::RenderPipeline,
236    /// 缓存的 GPU glyph atlas(多窗口共享同一 texture/view/sampler)
237    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
238    /// 阶段 4-B:layer → GPU texture cache(每 layer 一张全屏 texture)
239    layer_cache: HashMap<LayerId, LayerGpuCache>,
240    /// P2:frame 内活跃 layer id 复用集合(避免每帧分配 HashSet)
241    active_layer_ids: std::collections::HashSet<LayerId>,
242    /// P2:frame 内 layer 逻辑尺寸复用表(composition 用)
243    frame_layer_sizes: HashMap<LayerId, Size>,
244    /// P2:跨帧复用的 composition scratch(by_id/memo/visiting 容器)
245    composition_scratch: mgui_core::CompositionScratch,
246    /// 阶段 4-B:blit pipeline(把 layer texture 画到 surface)
247    blit_pipeline: wgpu::RenderPipeline,
248    blit_bgl: wgpu::BindGroupLayout,
249    blit_sampler: wgpu::Sampler,
250    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
251    backdrop_pipeline: wgpu::RenderPipeline,
252    backdrop_bgl: wgpu::BindGroupLayout,
253    /// 阶段 2-E:surface 格式(layer texture 与 pipeline render target 保持一致)
254    format: wgpu::TextureFormat,
255    /// 阶段 B4:GPU 端 timestamp profiler(None = 设备不支持 TIMESTAMP_QUERY)
256    pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
257    /// 阶段 B1.5:**per-layer** batch buffer pool
258    ///
259    /// **关键**:每个 layer 独立 buffer — **不能所有 layer 共享一个 pool buffer**!
260    /// wgpu 的 `queue.write_buffer` 是 staged + 下次 submit 时执行;
261    /// 同一 submit 内多个 layer 依次 write_buffer 同一 buffer → 后写覆盖先写,
262    /// 所有 layer 的 draw 都用最后一个 layer 的数据 → UI 错乱(元素放大/错位)。
263    /// 阶段 6(图片):value 同 LayerBatchPool;key = (LayerId, texture_id) —
264    /// text 用 texture_id 0,每张图片一个独立 key(纹理不同 buffer 必须隔离)
265    batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
266    /// 阶段 6(图片):图片纹理缓存(多窗口共享;按 ImageWidget 的 texture_id 索引)
267    image_cache: Rc<RefCell<ImageTextureCache>>,
268    /// P2-1.5:跨 layer 复用的临时纹理(按物理尺寸 key;view 持有 texture 引用)
269    msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
270    stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
271    snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
272    /// P2-1.5:上一帧的绘制统计(draw calls / scratch / layer texture)
273    last_stats: RenderStats,
274}
275
276/// 单张图片纹理的 GPU 缓存条目
277pub(crate) struct ImageTextureEntry {
278    /// 仅用于保持 GPU 纹理存活(view 是否持有引用不应依赖)
279    pub _texture: wgpu::Texture,
280    pub view: wgpu::TextureView,
281    pub sampler: wgpu::Sampler,
282    /// 最近一次被 PaintList 声明使用的时钟
283    pub last_used: u64,
284    /// 纹理字节数(width * height * 4),用于预算淘汰
285    pub bytes: u64,
286}
287
288/// 图片纹理预算(256 MiB)
289pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
290
291/// 单窗口所有 layer resolve texture 的总预算(256 MiB)。
292pub use setup::LAYER_TEXTURE_BUDGET_BYTES;
293
294pub use crate::backend_info::ImageTextureStats;
295
296impl Renderer {
297    /// P2-1.5:上一帧绘制统计(draw calls / segment / scratch 内存)
298    pub fn last_stats(&self) -> RenderStats {
299        self.last_stats
300    }
301
302    /// 当前图片纹理数量/字节数与预算
303    pub fn image_texture_stats(&self) -> ImageTextureStats {
304        let cache = self.image_cache.borrow();
305        ImageTextureStats {
306            count: cache.textures.len(),
307            bytes: cache.textures.values().map(|e| e.bytes).sum(),
308            budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
309        }
310    }
311}
312
313/// 阶段 B1.5:单 layer 的 batch buffer pool(9 个 buffer — 含 tri + stencil mask)
314struct LayerBatchPool {
315    rect_header: Option<wgpu::Buffer>,
316    rect_instances: Option<wgpu::Buffer>,
317    text_header: Option<wgpu::Buffer>,
318    text_instances: Option<wgpu::Buffer>,
319    /// Stage T1:tri buffers(vertex + index + uniform)
320    tri_vertex: Option<wgpu::Buffer>,
321    tri_index: Option<wgpu::Buffer>,
322    tri_uniform: Option<wgpu::Buffer>,
323    /// **T0-1.5:ClipPath stencil** — PushClipPath path triangles 的 vertex/index buffer
324    /// 每帧 write_buffer 覆盖内容;grow-only 容量够就复用
325    stencil_vertex: Option<wgpu::Buffer>,
326    stencil_index: Option<wgpu::Buffer>,
327}
328
329/// GPU atlas 资源 + 缓存的 size
330pub(crate) struct AtlasGpu {
331    texture: wgpu::Texture,
332    view: wgpu::TextureView,
333    sampler: wgpu::Sampler,
334    /// 创建时的 atlas 尺寸;尺寸变化时重建
335    cached_size: (u32, u32),
336}
337
338pub(crate) struct RectBatch {
339    bg: wgpu::BindGroup,
340}
341
342/// Stage T1:triangle pipeline — 每 layer 一个批次(所有 PathBuilder.fill 合并画)
343pub(crate) struct TriBatch {
344    bg: wgpu::BindGroup,
345}
346
347/// Stage T1:triangle uniform(跟 RectBatchUniform 同样的 16 bytes pattern)
348#[repr(C)]
349#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
350struct TriUniform {
351    screen_size: [f32; 2],
352    _pad0: u32,
353    _pad1: u32,
354}
355
356/// P2-1.4b:背景模糊 uniform(64 bytes)
357#[repr(C)]
358#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
359struct BackdropUniform {
360    screen: [f32; 2],
361    _pad: [f32; 2],
362    rect: [f32; 4],
363    /// [corner_radius, blur_radius, 0, 0]
364    params: [f32; 4],
365    /// tint rgb + mix alpha
366    tint: [f32; 4],
367}
368
369/// 阶段 B2:text 批处理结果(pub(crate):ImageBatchDraw::batch 字段引用)
370pub(crate) struct TextBatch {
371    bg: wgpu::BindGroup,
372    count: u32,
373}
374
375// ============================================================
376// 阶段 B2+B3:clip 分段收集 + GPU scissor 裁剪
377// ============================================================
378
379/// PushClipPath 的 earcut 三角形(扁平 vertices + indices)
380#[derive(Debug, Clone, Default)]
381pub(crate) struct StencilDraw {
382    /// [x, y, r, g, b, a, ...]
383    pub vertices: Vec<f32>,
384    pub indices: Vec<u32>,
385}
386
387/// 进入/退出一个 ClipPath 时对 stencil 覆盖计数的操作。
388///
389/// 推入时 +1、弹出时 -1;内容段用 `Equal(level)` 测试,
390/// 因此嵌套 clip 的交集会自动生效(只有每个 mask 都覆盖到的像素计数 = depth)。
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392pub(crate) struct StencilAction {
393    /// `StencilDraw` 下标
394    pub draw: u32,
395    /// 操作时的嵌套深度(从 1 开始)
396    pub level: u32,
397    pub increment: bool,
398}
399
400/// 合并后的 ClipPath mask GPU 资源;`ranges[draw]` = (first_index, index_count)
401pub(crate) struct StencilGpu {
402    pub vertex: wgpu::Buffer,
403    pub index: wgpu::Buffer,
404    pub ranges: Vec<(u32, u32)>,
405    pub bg: wgpu::BindGroup,
406}
407
408/// 背景模糊命令参数(圆角遮罩 + 13-tap blur + tint)
409#[derive(Debug, Clone, Copy)]
410pub(crate) struct BackdropBlurSpec {
411    pub rect: Rect,
412    pub radius: f32,
413    pub blur_radius: f32,
414    pub tint: [f32; 4],
415}
416
417/// 段内的一次绘制操作(按 PaintList 命令顺序记录,保留跨类型 z-order)
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub(crate) enum DrawOp {
420    /// rect instance 半开区间 [start, end) + 混合模式
421    Rect(u32, u32, BlendMode),
422    /// text instance 半开区间 [start, end)
423    Text(u32, u32),
424    /// 图片组下标
425    Image(u32),
426    /// 纹理 alpha mask(destination-in),引用图片组下标
427    Mask(u32),
428    /// 背景模糊(引用 BackdropBlurSpec 下标)
429    BackdropBlur(u32),
430    /// tri index 半开区间 [start, end)(index 进合并后的 tri index buffer)
431    Tri(u32, u32),
432}
433
434/// 阶段 B3:一个 scissor 段 — 相邻 clip 边界(PushClip/PopClip)之间的绘制区间
435///
436/// Pass 1 里每段一次 `set_scissor_rect`,再按 `ops` 顺序逐条 draw —— 这样
437/// rect/text/图片/三角形都保持 PaintList 的原始绘制顺序,而不是被类型分组
438/// 重排(旧实现固定 rect→image→text→tri,后画的 rect 会盖不住先画的文字)。
439#[derive(Debug, Clone, PartialEq)]
440pub(crate) struct ClipSegment {
441    /// scissor 矩形物理像素 [x, y, w, h];`None` = 本段无裁剪(整个 target)
442    pub scissor: Option<[u32; 4]>,
443    /// 本段实际 draw 的顺序列表
444    pub ops: Vec<DrawOp>,
445    /// 段内 rect/text/图片组的总范围(测试/诊断兼容字段)
446    pub rect_range: (u32, u32),
447    pub text_range: (u32, u32),
448    pub image_range: (u32, u32),
449    /// 本段生效的 ClipPath 嵌套深度(0 = 无 path 裁剪,>0 时用 stencil Equal(level))
450    pub stencil_level: u32,
451    /// 本段绘制前要执行的 stencil mask 操作(推入/弹出,按顺序)
452    pub stencil_actions: Vec<StencilAction>,
453}
454
455/// 阶段 6(图片):一个 texture_id 的连续图片组(paint 命令顺序里相邻的同图
456/// TexturedRect 合为一组 — 同一 ImageWidget 只产 1 条命令,组数 = 层内图片数)
457pub(crate) struct ImageGroup {
458    pub texture_id: u32,
459    pub instances: Vec<TextInstance>,
460}
461
462/// 阶段 6(图片):一个图片组的可绘制批次(bind group 已绑定该组纹理)。
463///
464/// 在 `Vec<Option<ImageBatchDraw>>` 里**下标 = ImageGroup 下标**:
465/// 未注册纹理的组是 `None` 占位,这样段的 `image_range`(组下标区间)
466/// 不因跳过而错位。
467pub(crate) struct ImageBatchDraw {
468    pub(crate) batch: TextBatch,
469}
470
471/// 矩形求交(负宽高 clamp 为 0 — 退化矩形与任何东西都不相交)
472fn intersect_rect(a: Rect, b: Rect) -> Rect {
473    let x1 = a.x.max(b.x);
474    let y1 = a.y.max(b.y);
475    let x2 = (a.x + a.width).min(b.x + b.width);
476    let y2 = (a.y + a.height).min(b.y + b.height);
477    Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
478}
479
480/// 计算 path triangles 的 bounding box(用于 PushClipPath → scissor 近似)
481fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
482    if vertices.is_empty() {
483        return Rect::new(0.0, 0.0, 0.0, 0.0);
484    }
485    let mut min_x = f32::INFINITY;
486    let mut min_y = f32::INFINITY;
487    let mut max_x = f32::NEG_INFINITY;
488    let mut max_y = f32::NEG_INFINITY;
489    for v in vertices {
490        min_x = min_x.min(v.x);
491        min_y = min_y.min(v.y);
492        max_x = max_x.max(v.x);
493        max_y = max_y.max(v.y);
494    }
495    Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
496}
497
498/// instance 矩形是否与当前 clip 相交(CPU 粗剔除;精确裁剪交给 GPU scissor)
499fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
500    match clip {
501        None => true,
502        // 退化 clip(宽或高 = 0)与任何东西都不相交
503        Some(c) => {
504            c.width > 0.0
505                && c.height > 0.0
506                && r.x < c.x + c.width
507                && r.x + r.width > c.x
508                && r.y < c.y + c.height
509                && r.y + r.height > c.y
510        }
511    }
512}
513
514/// 圆角矩形三角扇(凸多边形,中心 + 周边点即可精确覆盖)。
515///
516/// 用于 `PushClipRRect` 的 stencil mask;每角 8 段二次近似圆,
517/// 顶点格式与 `StencilDraw` 一致([x,y,r,g,b,a])。
518fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
519    if rect.width <= 0.0 || rect.height <= 0.0 {
520        return (Vec::new(), Vec::new());
521    }
522    let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
523    let r = radius.max(0.0).min(w.min(h) * 0.5);
524
525    let mut pts: Vec<(f32, f32)> = Vec::new();
526    if r <= 0.0 {
527        pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
528    } else {
529        const SEG: u32 = 8;
530        // 顺时针(屏幕 y 向下):右上 → 右下 → 左下 → 左上
531        let arcs = [
532            (x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
533            (x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
534            (x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
535            (x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
536        ];
537        for &(cx, cy, a0, a1) in &arcs {
538            for i in 0..=SEG {
539                let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
540                pts.push((cx + r * a.cos(), cy + r * a.sin()));
541            }
542        }
543        // 最后一角回到起点(首尾重复),去掉
544        if pts.len() > 1 && pts.first() == pts.last() {
545            pts.pop();
546        }
547    }
548    pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);
549
550    let n = pts.len();
551    if n < 3 {
552        return (Vec::new(), Vec::new());
553    }
554    let mut verts = Vec::with_capacity((n + 1) * 6);
555    for &(px, py) in &pts {
556        verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
557    }
558    verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
559    let center = n as u32;
560    let mut indices = Vec::with_capacity(n * 3);
561    for i in 0..n as u32 {
562        indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
563    }
564    (verts, indices)
565}
566
567/// clip 逻辑坐标 → scissor 物理像素 [x, y, w, h](floor/ceil 取整,clamp 到 texture 尺寸)
568fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
569    let d = dpr.max(0.0);
570    let (tw, th) = (tex.0 as f32, tex.1 as f32);
571    // 近边也必须 clamp 到 target 尺寸,否则完全落在 target 右侧/下方的 clip
572    // 会产出 x/y 越界的 scissor → wgpu validation error。
573    let x0 = (r.x * d).floor().clamp(0.0, tw);
574    let y0 = (r.y * d).floor().clamp(0.0, th);
575    let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
576    let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
577    let x = x0 as u32;
578    let y = y0 as u32;
579    let w = (x1 as u32).saturating_sub(x);
580    let h = (y1 as u32).saturating_sub(y);
581    [x, y, w, h]
582}
583
584/// 阶段 B2+B3:一次遍历 paint_list → rect/text instances + scissor 分段
585///
586/// - `PushClip`/`PopClip` 是段边界;`PushClip` 与外层 clip 求交(嵌套 clip)
587/// - instance 与当前 clip 相交才收集(CPU 粗剔除),溢出边缘交给 GPU scissor
588/// - 空段(无 instance)不产出 — 不浪费 draw call
589///
590/// Stage T1:Triangles — 合并所有 PaintCommand::Triangles(vertices,indices)
591/// 进一个 Vec<f32>(vertex flat) + Vec<u32>(index merged + offset by base vertex count)
592/// **不分 clip 分段**(简化:path fill 的三角形通常不需要 clip 分段;
593/// 未来需要时加 tri_range 进 ClipSegment)
594///
595/// **ClipPath stencil** — 最后一个返回值:
596/// 所有 PushClipPath 的 earcut 三角形(供 renderer 在段间写 stencil mask);
597/// 每个 `ClipSegment.stencil_actions` 用下标引用它。
598type CollectedInstances = (
599    Vec<RectInstance>,
600    Vec<TextInstance>,
601    Vec<ImageGroup>,
602    Vec<ClipSegment>,
603    // Stage T1:triangle data(所有 PaintCommand::Triangles 合并)
604    Vec<f32>, // vertex flat data: [x,y,r,g,b,a, x,y,r,g,b,a, ...]
605    Vec<u32>, // merged index data(offset per command)
606    // ClipPath mask triangles(按 PushClipPath 顺序)
607    Vec<StencilDraw>,
608    // 背景模糊参数
609    Vec<BackdropBlurSpec>,
610);
611
612pub(crate) fn collect_instances_segmented(
613    paint_list: &PaintList,
614    dpr: f32,
615    tex_size: (u32, u32),
616) -> CollectedInstances {
617    let mut rects: Vec<RectInstance> = Vec::new();
618    let mut texts: Vec<TextInstance> = Vec::new();
619    let mut image_groups: Vec<ImageGroup> = Vec::new();
620    let mut segments: Vec<ClipSegment> = Vec::new();
621    // Stage T1:triangles
622    let mut tri_vertices: Vec<f32> = Vec::new(); // 扁平化后的顶点
623    let mut tri_indices: Vec<u32> = Vec::new(); // 合并后的 index(加偏移)
624    let mut tri_base_vertex: u32 = 0; // 当前 command 的顶点在全局数组里的 base offset
625                                      // **ClipPath stencil** — 每个 PushClipPath 的 mask 三角形 + 待执行的 +1/-1 操作
626    let mut stencil_draws: Vec<StencilDraw> = Vec::new();
627    let mut pending_stencil: Vec<StencilAction> = Vec::new();
628    let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
629    let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
630    let mut clip_depth: u32 = 0;
631    // 混合模式栈:作用于后续矩形族命令,不产生段边界
632    let mut blend_stack: Vec<BlendMode> = Vec::new();
633    let mut cur_blend = BlendMode::Normal;
634    // clip 栈:每层保存"压入前的外层 clip" + 是否为 stencil mask 裁剪
635    let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
636    let mut cur_clip: Option<Rect> = None;
637    let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
638    // 段内绘制顺序(rect/text/image/tri 交错,保留 painter's order)
639    let mut ops: Vec<DrawOp> = Vec::new();
640
641    // 关闭当前段(有绘制操作才记录;重置段起点)
642    macro_rules! close_segment {
643        () => {
644            let r_end = rects.len() as u32;
645            let t_end = texts.len() as u32;
646            let i_end = image_groups.len() as u32;
647            if !ops.is_empty() {
648                segments.push(ClipSegment {
649                    scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
650                    ops: ops.clone(),
651                    rect_range: (seg_r, r_end),
652                    text_range: (seg_t, t_end),
653                    image_range: (seg_i, i_end),
654                    stencil_level: clip_depth,
655                    // 边界上的 mask 操作属于"下一段内容";空段不消费它们,
656                    // 留到下一个有绘制的段(净效果仍然正确)。
657                    stencil_actions: std::mem::take(&mut pending_stencil),
658                });
659                ops.clear();
660            }
661            seg_r = r_end;
662            seg_t = t_end;
663            seg_i = i_end;
664        };
665    }
666
667    fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
668        match op {
669            DrawOp::Rect(s, e, mode) => {
670                if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
671                    if *last_end == s && *last_mode == mode {
672                        *last_end = e;
673                        return;
674                    }
675                }
676            }
677            DrawOp::Text(s, e) => {
678                if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
679                    if *last_end == s {
680                        *last_end = e;
681                        return;
682                    }
683                }
684            }
685            DrawOp::Tri(s, e) => {
686                if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
687                    if *last_end == s {
688                        *last_end = e;
689                        return;
690                    }
691                }
692            }
693            DrawOp::Image(_) => {}
694            DrawOp::Mask(_) => {}
695            DrawOp::BackdropBlur(_) => {}
696        }
697        ops.push(op);
698    }
699
700    // ClipPath / ClipRRect 共用:压入一层 stencil mask + bbox scissor
701    macro_rules! push_mask_clip {
702        ($flat:expr, $idxs:expr, $bbox:expr) => {{
703            clip_depth += 1;
704            let flat_verts: Vec<f32> = $flat;
705            let idxs: &[u32] = $idxs;
706            let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
707                let idx = stencil_draws.len() as u32;
708                stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
709                pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
710                Some(idx)
711            } else {
712                None
713            };
714            path_draw_stack.push(draw_index);
715
716            let bbox: Rect = $bbox;
717            stack.push((cur_clip, true));
718            cur_clip = Some(match cur_clip {
719                Some(outer) => intersect_rect(outer, bbox),
720                None => bbox,
721            });
722        }};
723    }
724
725    // 弹出 mask clip:深度的 -1 操作 + 恢复外层 scissor
726    macro_rules! pop_mask_clip {
727        () => {{
728            if let Some(Some(draw)) = path_draw_stack.pop() {
729                // 弹出时 -1,恢复外层的覆盖计数(兄弟 clip 不会互相污染)
730                pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
731            }
732            clip_depth = clip_depth.saturating_sub(1);
733        }};
734    }
735
736    for cmd in &paint_list.commands {
737        match cmd {
738            PaintCommand::PushBlendMode(mode) => {
739                blend_stack.push(cur_blend);
740                cur_blend = *mode;
741            }
742            PaintCommand::PopBlendMode => {
743                cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
744            }
745            PaintCommand::PushClip(r) => {
746                close_segment!();
747                stack.push((cur_clip, false));
748                cur_clip = Some(match cur_clip {
749                    Some(outer) => intersect_rect(outer, *r),
750                    None => *r,
751                });
752            }
753            PaintCommand::PushClipRRect { rect, radius } => {
754                close_segment!();
755                let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
756                push_mask_clip!(flat_verts, &idxs, *rect);
757            }
758            PaintCommand::PopClip => {
759                close_segment!();
760                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
761                if is_mask {
762                    pop_mask_clip!();
763                }
764                cur_clip = prev;
765            }
766            // PushClipPath — 路径裁剪(scissor 用 bbox 粗裁,GPU stencil 精确 mask)
767            PaintCommand::PushClipPath { vertices, indices } => {
768                close_segment!();
769                let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
770                for v in vertices {
771                    flat_verts.push(v.x);
772                    flat_verts.push(v.y);
773                    flat_verts.push(v.color.r);
774                    flat_verts.push(v.color.g);
775                    flat_verts.push(v.color.b);
776                    flat_verts.push(v.color.a);
777                }
778                push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
779            }
780            PaintCommand::PopClipPath => {
781                close_segment!();
782                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
783                if is_mask {
784                    pop_mask_clip!();
785                }
786                cur_clip = prev;
787            }
788            PaintCommand::Rect { rect, color, radius } => {
789                if rect_intersects_clip(rect, cur_clip) {
790                    let start = rects.len() as u32;
791                    rects.push(RectInstance {
792                        rect: [rect.x, rect.y, rect.width, rect.height],
793                        from: [color.r, color.g, color.b, color.a],
794                        to: [color.r, color.g, color.b, color.a],
795                        grad: [0.0; 4],
796                        params: [*radius, 0.0, 0.0, 0.0],
797                    });
798                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
799                }
800            }
801            // **T0-2:BoxShadow** — 走同一条 Rect pipeline,shader 根据 blur_radius 做 SDF blur
802            PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
803                if rect_intersects_clip(rect, cur_clip) {
804                    let start = rects.len() as u32;
805                    rects.push(RectInstance {
806                        rect: [rect.x, rect.y, rect.width, rect.height],
807                        from: [color.r, color.g, color.b, color.a],
808                        to: [color.r, color.g, color.b, color.a],
809                        grad: [0.0; 4],
810                        params: [*radius, 0.0, *blur_radius, 0.0],
811                    });
812                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
813                }
814            }
815            // **P2-1.4:InsetShadow** — 同一 rect pipeline,shader kind=3 做内侧 SDF 衰减
816            PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
817                if rect_intersects_clip(rect, cur_clip) {
818                    let idx = rects.len() as u32;
819                    rects.push(RectInstance {
820                        rect: [rect.x, rect.y, rect.width, rect.height],
821                        from: [color.r, color.g, color.b, color.a],
822                        to: [color.r, color.g, color.b, color.a],
823                        grad: [0.0; 4],
824                        params: [*radius, 3.0, *blur_radius, 0.0],
825                    });
826                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
827                }
828            }
829            PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
830                if rect_intersects_clip(rect, cur_clip) {
831                    let idx = rects.len() as u32;
832                    rects.push(RectInstance {
833                        rect: [rect.x, rect.y, rect.width, rect.height],
834                        from: [from.r, from.g, from.b, from.a],
835                        to: [to.r, to.g, to.b, to.a],
836                        grad: [start.x, start.y, end.x, end.y],
837                        params: [*corner_radius, 1.0, 0.0, 0.0],
838                    });
839                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
840                }
841            }
842            PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
843                if rect_intersects_clip(rect, cur_clip) {
844                    let idx = rects.len() as u32;
845                    rects.push(RectInstance {
846                        rect: [rect.x, rect.y, rect.width, rect.height],
847                        from: [from.r, from.g, from.b, from.a],
848                        to: [to.r, to.g, to.b, to.a],
849                        grad: [center.x, center.y, *radial_radius, 0.0],
850                        params: [*corner_radius, 2.0, 0.0, 0.0],
851                    });
852                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
853                }
854            }
855            // **P2-1.4b:背景模糊** — 在命令处切 pass,模糊此前已绘制内容
856            PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
857                if rect_intersects_clip(rect, cur_clip) {
858                    let idx = backdrop_blurs.len() as u32;
859                    backdrop_blurs.push(BackdropBlurSpec {
860                        rect: *rect,
861                        radius: *radius,
862                        blur_radius: *blur_radius,
863                        tint: [tint.r, tint.g, tint.b, tint.a],
864                    });
865                    ops.push(DrawOp::BackdropBlur(idx));
866                }
867            }
868            // **P2-1.3:纹理 mask** — destination-in,只保留纹理 alpha 覆盖的区域
869            PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
870                if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
871                    let gi = image_groups.len() as u32;
872                    image_groups.push(ImageGroup {
873                        texture_id: *texture_id,
874                        instances: vec![TextInstance {
875                            rect: [rect.x, rect.y, rect.width, rect.height],
876                            // mode 2.0 = Alpha:alpha 取纹理 A 通道 × color.a
877                            color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
878                            uv: *uv,
879                            mode: 2.0,
880                            _pad: [0.0; 3],
881                        }],
882                    });
883                    ops.push(DrawOp::Mask(gi));
884                }
885            }
886            PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
887                if rect_intersects_clip(rect, cur_clip) {
888                    // **像素对齐**:text glyph atlas 按物理分辨率栅格化(每个 glyph 一个 texel=一个物理像素),
889                    // rect 在逻辑坐标上做 round(x*dpr)/dpr → 确保 UV 采样 1:1 对齐 atlas texel → 文字锐
890                    let snap = |v: f32| (v * dpr).round() / dpr;
891                    let inst = TextInstance {
892                        rect: [
893                            snap(rect.x),
894                            snap(rect.y),
895                            snap(rect.x + rect.width) - snap(rect.x),
896                            snap(rect.y + rect.height) - snap(rect.y),
897                        ],
898                        color: [color.r, color.g, color.b, color.a],
899                        uv: *uv,
900                        mode: match mode {
901                            TextureMode::Mask => 0.0,
902                            TextureMode::Color => 1.0,
903                        },
904                        _pad: [0.0; 3],
905                    };
906                    if *texture_id == 0 {
907                        let start = texts.len() as u32;
908                        texts.push(inst);
909                        push_range_op(&mut ops, DrawOp::Text(start, start + 1));
910                    } else {
911                        // 阶段 6(图片):texture_id != 0 = ImageWidget 的全图 quad。
912                        // 只有「紧邻的上一笔也是同纹理图片」才合并成组 —— 中间插入
913                        // rect/text 后必须新开一组,否则绘制顺序无法恢复。
914                        let reuse_group = ops
915                            .last()
916                            .and_then(|op| match op {
917                                DrawOp::Image(gi) => Some(*gi),
918                                _ => None,
919                            })
920                            .filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
921                        if let Some(gi) = reuse_group {
922                            image_groups[gi as usize].instances.push(inst);
923                        } else {
924                            let gi = image_groups.len() as u32;
925                            image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
926                            ops.push(DrawOp::Image(gi));
927                        }
928                    }
929                }
930            }
931            // Stage T1:Triangles — 合并所有 path fill 的 earcut 输出
932            // 每个 command 的 indices 加 base offset(避免不同 PathBuilder 的 triangles 互相引用)
933            PaintCommand::Triangles { vertices, indices } => {
934                let idx_start = tri_indices.len() as u32;
935                // vertices 扁平化为 [x, y, r, g, b, a]
936                for v in vertices {
937                    tri_vertices.push(v.x);
938                    tri_vertices.push(v.y);
939                    tri_vertices.push(v.color.r);
940                    tri_vertices.push(v.color.g);
941                    tri_vertices.push(v.color.b);
942                    tri_vertices.push(v.color.a);
943                }
944                // indices 加 base(让每个 command 的顶点全局唯一)
945                for &idx in indices {
946                    tri_indices.push(tri_base_vertex + idx);
947                }
948                tri_base_vertex += vertices.len() as u32;
949                if !vertices.is_empty() && !indices.is_empty() {
950                    push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
951                }
952            }
953            // Stage T2:PaintCommand::Text — core 层 Widget 要画文字的高层命令
954            // 让 paint_text_line 展开成 TexturedRect → 逐个收集
955            PaintCommand::Text { text, range, font_size, color, position, max_width } => {
956                let mut temp_list = PaintList::new();
957                crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
958                // 展开后的 TexturedRect 逐个收集
959                let snap = |v: f32| (v * dpr).round() / dpr;
960                let start = texts.len() as u32;
961                for cmd in temp_list.commands {
962                    if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
963                        if rect_intersects_clip(&rect, cur_clip) {
964                            texts.push(TextInstance {
965                                rect: [
966                                    snap(rect.x),
967                                    snap(rect.y),
968                                    snap(rect.x + rect.width) - snap(rect.x),
969                                    snap(rect.y + rect.height) - snap(rect.y),
970                                ],
971                                color: [color.r, color.g, color.b, color.a],
972                                uv,
973                                // glyph atlas 永远走 mask 采样
974                                mode: 0.0,
975                                _pad: [0.0; 3],
976                            });
977                        }
978                    }
979                }
980                if texts.len() as u32 > start {
981                    push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
982                }
983            }
984        }
985    }
986    // 尾段
987    close_segment!();
988    let _ = (seg_r, seg_t, seg_i); // 尾段关闭后不再读 — 显式消费消除 unused_assignments
989
990    // P2-1.5:合并相邻且 scissor/stencil 状态相同的段。
991    // 常见于 PopClip 后立刻 PushClip 同一矩形(虚拟列表/滚动容器),
992    // 合并后减少 set_scissor / pipeline 状态切换;跨 mask 操作的段不合并。
993    let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
994    for seg in segments.drain(..) {
995        let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
996            prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
997        });
998        if can_merge {
999            let prev = merged.last_mut().expect("checked non-empty");
1000            for op in &seg.ops {
1001                push_range_op(&mut prev.ops, *op);
1002            }
1003            prev.rect_range.1 = seg.rect_range.1;
1004            prev.text_range.1 = seg.text_range.1;
1005            prev.image_range.1 = seg.image_range.1;
1006        } else {
1007            merged.push(seg);
1008        }
1009    }
1010
1011    (rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
1012}
1013
1014/// 阶段 B1:helper — 构造 rect batch bind group(0 rect → None)
1015///
1016/// 阶段 B1.5:**per-layer buffer pool** — header(16B 固定)永驻,instances(grow-only)
1017/// 容量够就复用,只 `queue.write_buffer` 覆盖。稳态 0 alloc/帧/layer。
1018///
1019/// **关键教训**:**不能所有 layer 共享一个 pool buffer** — wgpu 的
1020// `queue.write_buffer` 是 staged + 下次 submit 执行;同一 submit 内多个 layer
1021// 依次 write_buffer 同一 buffer → 后写覆盖先写 → 所有 layer 的 draw 都用
1022// 最后一个 layer 的数据 → UI 元素放大/错乱。
1023// =================================================================
1024// 子模块
1025// =================================================================
1026mod batches;
1027mod composition;
1028mod render;
1029mod setup;
1030#[cfg(test)]
1031mod tests;