Skip to main content

velox_engine/renderers/wgpu/
pipeline.rs

1//! `WgpuRenderer` 核心 2D SDF 渲染管线(单 RenderPass / 单 Draw Call 合批编码、分数 DPI Pixel Snapping 与提交)。
2
3use ::wgpu;
4use std::collections::HashMap;
5use std::string::String;
6use std::sync::Arc;
7use std::vec::Vec;
8
9use crate::display::{measure_char_advance, measure_char_kerning, Rgba8888};
10use crate::element::SpriteSource;
11use crate::motion::{DrawOp, DrawPayload};
12use crate::renderers::software::{
13    align_offset_x, compute_scaled_text_box, compute_unoccluded_clip, rasterize_sprite_source,
14    split_text_lines,
15};
16use crate::solver::Region;
17use crate::style::Color;
18
19use super::atlas::{GlyphAtlas, SpriteAtlas, SpriteCacheKey, GLYPH_ATLAS_INIT_SIZE};
20use super::effects_pass::{
21    clamp_rect_u32, EffectUniform, GpuEffectsEngine, GpuPassStep, EFFECT_KIND_BACKDROP,
22    EFFECT_KIND_BLIT, EFFECT_KIND_COMPOSITE, EFFECT_KIND_EXTERNAL_TEX, EFFECT_KIND_SHADOW_EXTRACT,
23};
24use super::ramp::GradientRampAtlas;
25use super::{
26    color_to_f32, make_arc_primitive, make_quad_primitive, make_shadow_primitive,
27    make_styled_quad_primitive, pod_as_bytes, snap_bounds, snap_clip, GpuPrimitive,
28    ViewportUniform, IDENTITY_XFORM, KIND_GLYPH, KIND_SPRITE,
29};
30use crate::paint::{BlendMode, ExternalTextureId, LayerSpec, Paint, StyledQuad};
31use crate::renderers::software::{ops_have_layers_or_blend, snap_bounds_region_scaled, snap_clip_region_scaled};
32
33const SDF_WGSL: &str = include_str!("shader.wgsl");
34const INITIAL_INSTANCE_CAPACITY: usize = 512;
35const MAX_TEXT_LAYOUT_CACHE_ENTRIES: usize = 512;
36
37#[derive(Copy, Clone, PartialEq, Eq, Hash)]
38struct TextLayoutKey {
39    text_hash: u64,
40    text_len: u32,
41    logical_font_size: u8,
42    font_size_q4: u16,
43    max_width: i16,
44    text_flags: u8,
45    use_ttf: bool,
46}
47
48#[derive(Copy, Clone)]
49struct ShapedGlyphPos {
50    ch: char,
51    rel_x: i16,
52    rel_y: i16,
53}
54
55struct CachedTextLayout {
56    text: String,
57    total_h: i16,
58    glyphs: Vec<ShapedGlyphPos>,
59}
60
61#[inline]
62fn hash_layout_text(text: &str) -> u64 {
63    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
64    for &b in text.as_bytes() {
65        h ^= b as u64;
66        h = h.wrapping_mul(0x0100_0000_01b3);
67    }
68    h
69}
70
71/// 256 字节对齐的动态 `ViewportUniform` 槽位(供多 Pass 离屏图层共享单个 `viewport_buf`)。
72#[repr(C)]
73#[derive(Copy, Clone, Debug)]
74struct AlignedViewportSlot {
75    uniform: ViewportUniform,
76    _pad: [u8; 256 - core::mem::size_of::<ViewportUniform>()],
77}
78
79impl Default for AlignedViewportSlot {
80    fn default() -> Self {
81        Self {
82            uniform: ViewportUniform::default(),
83            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
84        }
85    }
86}
87
88const _: () = assert!(core::mem::size_of::<AlignedViewportSlot>() == 256);
89const INIT_VIEWPORT_SLOTS: usize = 8;
90
91/// 编码重试原因(任一图集满格触发扩容重编)。
92struct AtlasGrowNeed {
93    glyph_full: bool,
94    sprite_need: Option<(u32, u32)>,
95    ramp_full: bool,
96}
97
98/// 外部零拷贝 GPU 纹理注册条目(由外部渲染引擎共享 `wgpu::TextureView` 与可选采样器)。
99pub(crate) struct ExternalTextureEntry {
100    pub(crate) view: wgpu::TextureView,
101    pub(crate) sampler: Option<wgpu::Sampler>,
102}
103
104/// 自研轻量级 `wgpu` 2D SDF 渲染管线核心(绑定任意目标 `TextureView` 即可渲染)。
105pub struct WgpuRenderer {
106    pipeline: wgpu::RenderPipeline,
107    bind_group_layout: wgpu::BindGroupLayout,
108    bind_group: wgpu::BindGroup,
109    viewport_buf: wgpu::Buffer,
110    viewport_capacity: usize,
111    viewport_slots: Vec<AlignedViewportSlot>,
112    instance_buf: wgpu::Buffer,
113    instance_capacity: usize,
114    sampler: wgpu::Sampler,
115    linear_sampler: wgpu::Sampler,
116    glyph_atlas: GlyphAtlas,
117    sprite_atlas: SpriteAtlas,
118    ramp_atlas: GradientRampAtlas,
119    effects: Option<GpuEffectsEngine>,
120    external_textures: HashMap<ExternalTextureId, ExternalTextureEntry>,
121    next_external_id: u32,
122    target_format: wgpu::TextureFormat,
123    primitives: Vec<GpuPrimitive>,
124    sprite_scratch: Vec<Rgba8888>,
125    #[cfg(not(target_endian = "little"))]
126    sprite_bytes_scratch: Vec<u8>,
127    text_layout_cache: HashMap<TextLayoutKey, Arc<CachedTextLayout>>,
128    text_layout_hits: u64,
129    target_is_srgb: bool,
130}
131
132impl WgpuRenderer {
133    /// 基于已有 `wgpu::Device` 与目标表面像素格式创建 2D SDF 渲染管线。
134    pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
135        let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
136        let t0 = std::time::Instant::now();
137        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
138            label: Some("velox_wgpu_2d_shader"),
139            source: wgpu::ShaderSource::Wgsl(SDF_WGSL.into()),
140        });
141        let t_shader = t0.elapsed();
142
143        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
144            label: Some("velox_wgpu_bgl"),
145            entries: &[
146                wgpu::BindGroupLayoutEntry {
147                    binding: 0,
148                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
149                    ty: wgpu::BindingType::Buffer {
150                        ty: wgpu::BufferBindingType::Uniform,
151                        has_dynamic_offset: true,
152                        min_binding_size: wgpu::BufferSize::new(
153                            core::mem::size_of::<ViewportUniform>() as u64,
154                        ),
155                    },
156                    count: None,
157                },
158                wgpu::BindGroupLayoutEntry {
159                    binding: 1,
160                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
161                    ty: wgpu::BindingType::Buffer {
162                        ty: wgpu::BufferBindingType::Storage { read_only: true },
163                        has_dynamic_offset: false,
164                        min_binding_size: None,
165                    },
166                    count: None,
167                },
168                wgpu::BindGroupLayoutEntry {
169                    binding: 2,
170                    visibility: wgpu::ShaderStages::FRAGMENT,
171                    ty: wgpu::BindingType::Texture {
172                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
173                        view_dimension: wgpu::TextureViewDimension::D2,
174                        multisampled: false,
175                    },
176                    count: None,
177                },
178                wgpu::BindGroupLayoutEntry {
179                    binding: 3,
180                    visibility: wgpu::ShaderStages::FRAGMENT,
181                    ty: wgpu::BindingType::Texture {
182                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
183                        view_dimension: wgpu::TextureViewDimension::D2,
184                        multisampled: false,
185                    },
186                    count: None,
187                },
188                wgpu::BindGroupLayoutEntry {
189                    binding: 4,
190                    visibility: wgpu::ShaderStages::FRAGMENT,
191                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
192                    count: None,
193                },
194                wgpu::BindGroupLayoutEntry {
195                    binding: 5,
196                    visibility: wgpu::ShaderStages::FRAGMENT,
197                    ty: wgpu::BindingType::Texture {
198                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
199                        view_dimension: wgpu::TextureViewDimension::D2,
200                        multisampled: false,
201                    },
202                    count: None,
203                },
204                wgpu::BindGroupLayoutEntry {
205                    binding: 6,
206                    visibility: wgpu::ShaderStages::FRAGMENT,
207                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
208                    count: None,
209                },
210            ],
211        });
212
213        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
214            label: Some("velox_wgpu_pipeline_layout"),
215            bind_group_layouts: &[Some(&bind_group_layout)],
216            immediate_size: 0,
217        });
218
219        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
220            label: Some("velox_wgpu_2d_pipeline"),
221            layout: Some(&pipeline_layout),
222            vertex: wgpu::VertexState {
223                module: &shader,
224                entry_point: Some("vs_main"),
225                compilation_options: wgpu::PipelineCompilationOptions::default(),
226                buffers: &[],
227            },
228            primitive: wgpu::PrimitiveState {
229                topology: wgpu::PrimitiveTopology::TriangleList,
230                strip_index_format: None,
231                front_face: wgpu::FrontFace::Ccw,
232                cull_mode: None,
233                unclipped_depth: false,
234                polygon_mode: wgpu::PolygonMode::Fill,
235                conservative: false,
236            },
237            depth_stencil: None,
238            multisample: wgpu::MultisampleState::default(),
239            fragment: Some(wgpu::FragmentState {
240                module: &shader,
241                entry_point: Some("fs_main"),
242                compilation_options: wgpu::PipelineCompilationOptions::default(),
243                targets: &[Some(wgpu::ColorTargetState {
244                    format: target_format,
245                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
246                    write_mask: wgpu::ColorWrites::ALL,
247                })],
248            }),
249            multiview_mask: None,
250            cache: None,
251        });
252        let t_pso = t0.elapsed();
253        if trace {
254            std::println!(
255                "[VELOX_STARTUP_TRACE]   pipeline detail: create_shader_module={:.1}ms, create_render_pipeline=+{:.1}ms",
256                t_shader.as_secs_f64() * 1000.0,
257                (t_pso - t_shader).as_secs_f64() * 1000.0,
258            );
259        }
260
261        let viewport_buf = Self::create_viewport_buffer(device, INIT_VIEWPORT_SLOTS);
262        let instance_buf = Self::create_instance_buffer(device, INITIAL_INSTANCE_CAPACITY);
263        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
264            label: Some("velox_atlas_sampler"),
265            address_mode_u: wgpu::AddressMode::ClampToEdge,
266            address_mode_v: wgpu::AddressMode::ClampToEdge,
267            address_mode_w: wgpu::AddressMode::ClampToEdge,
268            mag_filter: wgpu::FilterMode::Nearest,
269            min_filter: wgpu::FilterMode::Nearest,
270            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
271            ..Default::default()
272        });
273        let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
274            label: Some("velox_linear_sampler"),
275            address_mode_u: wgpu::AddressMode::ClampToEdge,
276            address_mode_v: wgpu::AddressMode::ClampToEdge,
277            address_mode_w: wgpu::AddressMode::ClampToEdge,
278            mag_filter: wgpu::FilterMode::Linear,
279            min_filter: wgpu::FilterMode::Linear,
280            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
281            ..Default::default()
282        });
283
284        let glyph_atlas = GlyphAtlas::new(device, GLYPH_ATLAS_INIT_SIZE);
285        let sprite_atlas = SpriteAtlas::new(device, 1);
286        let ramp_atlas = GradientRampAtlas::new(device);
287        let bind_group = Self::create_bind_group(
288            device,
289            &bind_group_layout,
290            &viewport_buf,
291            &instance_buf,
292            &glyph_atlas.view,
293            &sprite_atlas.view,
294            &sampler,
295            &ramp_atlas.view,
296            &linear_sampler,
297        );
298
299        Self {
300            pipeline,
301            bind_group_layout,
302            bind_group,
303            viewport_buf,
304            viewport_capacity: INIT_VIEWPORT_SLOTS,
305            viewport_slots: Vec::with_capacity(INIT_VIEWPORT_SLOTS),
306            instance_buf,
307            instance_capacity: INITIAL_INSTANCE_CAPACITY,
308            sampler,
309            linear_sampler,
310            glyph_atlas,
311            sprite_atlas,
312            ramp_atlas,
313            effects: None,
314            external_textures: HashMap::new(),
315            next_external_id: 1,
316            target_format,
317            primitives: Vec::with_capacity(INITIAL_INSTANCE_CAPACITY),
318            sprite_scratch: Vec::new(),
319            #[cfg(not(target_endian = "little"))]
320            sprite_bytes_scratch: Vec::new(),
321            text_layout_cache: HashMap::with_capacity(64),
322            text_layout_hits: 0,
323            target_is_srgb: target_format.is_srgb(),
324        }
325    }
326
327    fn create_viewport_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
328        device.create_buffer(&wgpu::BufferDescriptor {
329            label: Some("velox_wgpu_viewport"),
330            size: (capacity.max(1) * core::mem::size_of::<AlignedViewportSlot>()) as u64,
331            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
332            mapped_at_creation: false,
333        })
334    }
335
336    fn create_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
337        device.create_buffer(&wgpu::BufferDescriptor {
338            label: Some("velox_wgpu_instances"),
339            size: (capacity.max(1) * core::mem::size_of::<GpuPrimitive>()) as u64,
340            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
341            mapped_at_creation: false,
342        })
343    }
344
345    #[allow(clippy::too_many_arguments)]
346    fn create_bind_group(
347        device: &wgpu::Device,
348        layout: &wgpu::BindGroupLayout,
349        viewport_buf: &wgpu::Buffer,
350        instance_buf: &wgpu::Buffer,
351        glyph_view: &wgpu::TextureView,
352        sprite_view: &wgpu::TextureView,
353        sampler: &wgpu::Sampler,
354        ramp_view: &wgpu::TextureView,
355        linear_sampler: &wgpu::Sampler,
356    ) -> wgpu::BindGroup {
357        device.create_bind_group(&wgpu::BindGroupDescriptor {
358            label: Some("velox_wgpu_bg"),
359            layout,
360            entries: &[
361                wgpu::BindGroupEntry {
362                    binding: 0,
363                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
364                        buffer: viewport_buf,
365                        offset: 0,
366                        size: wgpu::BufferSize::new(core::mem::size_of::<ViewportUniform>() as u64),
367                    }),
368                },
369                wgpu::BindGroupEntry {
370                    binding: 1,
371                    resource: instance_buf.as_entire_binding(),
372                },
373                wgpu::BindGroupEntry {
374                    binding: 2,
375                    resource: wgpu::BindingResource::TextureView(glyph_view),
376                },
377                wgpu::BindGroupEntry {
378                    binding: 3,
379                    resource: wgpu::BindingResource::TextureView(sprite_view),
380                },
381                wgpu::BindGroupEntry {
382                    binding: 4,
383                    resource: wgpu::BindingResource::Sampler(sampler),
384                },
385                wgpu::BindGroupEntry {
386                    binding: 5,
387                    resource: wgpu::BindingResource::TextureView(ramp_view),
388                },
389                wgpu::BindGroupEntry {
390                    binding: 6,
391                    resource: wgpu::BindingResource::Sampler(linear_sampler),
392                },
393            ],
394        })
395    }
396
397    /// 返回最近一帧合批提交的 [`GpuPrimitive`] 实例数量。
398    #[inline]
399    pub fn last_primitive_count(&self) -> usize {
400        self.primitives.len()
401    }
402
403    /// 返回当前字形图集与精灵图集的物理像素边长 `(glyph_size, sprite_size)`。
404    #[inline]
405    pub const fn atlas_sizes(&self) -> (u32, u32) {
406        (self.glyph_atlas.width, self.sprite_atlas.width)
407    }
408
409    /// 返回静态精灵跨帧驻留缓存累计命中次数。
410    #[inline]
411    pub const fn sprite_cache_hits(&self) -> u64 {
412        self.sprite_atlas.cache_hits
413    }
414
415    /// 返回跨帧文本行排版缓存(`TextLayoutCache`)累计命中次数。
416    #[inline]
417    pub const fn text_layout_cache_hits(&self) -> u64 {
418        self.text_layout_hits
419    }
420
421    /// 返回跨帧文本行排版缓存当前驻留条目数。
422    #[inline]
423    pub fn text_layout_cache_len(&self) -> usize {
424        self.text_layout_cache.len()
425    }
426
427    /// 注册一张外部零拷贝 GPU 纹理(如海图、雷达、视频解码器或 3D 视口产出的 `wgpu::TextureView`),
428    /// 返回可供 `div().external_texture(id)` 或 `SurfaceCanvas` 引用的句柄 ID。
429    pub fn register_external_texture(
430        &mut self,
431        view: wgpu::TextureView,
432        sampler: Option<wgpu::Sampler>,
433    ) -> ExternalTextureId {
434        let mut id = self.next_external_id;
435        while id == 0 || self.external_textures.contains_key(&ExternalTextureId(id)) {
436            id = id.wrapping_add(1);
437        }
438        self.next_external_id = id.wrapping_add(1).max(1);
439        let tex_id = ExternalTextureId(id);
440        self.external_textures
441            .insert(tex_id, ExternalTextureEntry { view, sampler });
442        tex_id
443    }
444
445    /// 按显式 ID 注册或替换外部零拷贝 GPU 纹理(便于固定槽位号与跨语言 FFI 绑定)。
446    pub fn register_external_texture_with_id(
447        &mut self,
448        id: ExternalTextureId,
449        view: wgpu::TextureView,
450        sampler: Option<wgpu::Sampler>,
451    ) {
452        self.external_textures
453            .insert(id, ExternalTextureEntry { view, sampler });
454    }
455
456    /// 原地更新已注册外部纹理的 `wgpu::TextureView`(如外部引擎 Resize 或双缓冲翻页时调用)。
457    pub fn update_external_texture(&mut self, id: ExternalTextureId, view: wgpu::TextureView) -> bool {
458        if let Some(entry) = self.external_textures.get_mut(&id) {
459            entry.view = view;
460            true
461        } else {
462            false
463        }
464    }
465
466    /// 注销外部零拷贝纹理槽位并释放 `TextureView` 引用。
467    pub fn unregister_external_texture(&mut self, id: ExternalTextureId) -> bool {
468        self.external_textures.remove(&id).is_some()
469    }
470
471    /// 返回当前已注册的外部零拷贝 GPU 纹理数量。
472    #[inline]
473    pub fn external_texture_count(&self) -> usize {
474        self.external_textures.len()
475    }
476
477    fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
478        self.bind_group = Self::create_bind_group(
479            device,
480            &self.bind_group_layout,
481            &self.viewport_buf,
482            &self.instance_buf,
483            &self.glyph_atlas.view,
484            &self.sprite_atlas.view,
485            &self.sampler,
486            &self.ramp_atlas.view,
487            &self.linear_sampler,
488        );
489    }
490
491    #[inline]
492    fn sprite_cache_hash(sprite: SpriteSource<'_>, rel_x: i16, rel_y: i16, sb_w: i16, sb_h: i16) -> u64 {
493        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
494        let mix = |h: &mut u64, v: u64| {
495            *h ^= v;
496            *h = h.wrapping_mul(0x0100_0000_01b3);
497        };
498        mix(&mut h, ((rel_x as u16 as u64) << 16) | (rel_y as u16 as u64));
499        mix(&mut h, ((sb_w as u16 as u64) << 16) | (sb_h as u16 as u64));
500        match sprite {
501            SpriteSource::Bitmap {
502                bytes,
503                format,
504                tint,
505            } => {
506                mix(&mut h, 1);
507                mix(&mut h, bytes.as_ptr() as usize as u64);
508                mix(&mut h, bytes.len() as u64);
509                mix(&mut h, format as u64);
510                mix(&mut h, tint.0 as u64);
511            }
512            SpriteSource::Shader { state_hash, .. } => {
513                mix(&mut h, 2);
514                mix(&mut h, state_hash as u64);
515            }
516            SpriteSource::Svg {
517                source,
518                is_path_only,
519                tint,
520                stroke_width_x10,
521            } => {
522                mix(&mut h, 3);
523                mix(&mut h, if is_path_only { 1 } else { 0 });
524                mix(&mut h, stroke_width_x10 as u64);
525                mix(&mut h, tint.0 as u64);
526                let s = source.as_str().as_bytes();
527                mix(&mut h, s.len() as u64);
528                for &b in s {
529                    mix(&mut h, b as u64);
530                }
531            }
532            SpriteSource::Arc { .. } => {}
533        }
534        h
535    }
536
537    /// 将单条非图层 `DrawOp` 编码追加到 `self.primitives`,并将所有屏幕坐标减去 `(origin_x, origin_y)`。
538    #[allow(clippy::too_many_arguments)]
539    fn encode_single_op(
540        &mut self,
541        queue: &wgpu::Queue,
542        op: &DrawOp<'_>,
543        eff_clip: Region,
544        viewport: Region,
545        sf: f32,
546        use_ttf: bool,
547        origin_x: f32,
548        origin_y: f32,
549    ) -> Result<(), AtlasGrowNeed> {
550        let mut sb_f = snap_bounds(op.bounds, sf);
551        let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
552        let mut sc_f = snap_clip(clip_region, sf);
553        if (op.bounds.w == 1 && eff_clip.w == 1) || (op.bounds.h == 1 && eff_clip.h == 1) {
554            let vp_clip_f = snap_clip(viewport, sf);
555            if op.bounds.w == 1 && eff_clip.w == 1 {
556                sc_f[2] = sc_f[2].max(sb_f[0] + sb_f[2]).min(vp_clip_f[2]);
557            }
558            if op.bounds.h == 1 && eff_clip.h == 1 {
559                sc_f[3] = sc_f[3].max(sb_f[1] + sb_f[3]).min(vp_clip_f[3]);
560            }
561        }
562        let clip_radius_px = (op.clip_radius as f32) * sf;
563        let shifted_sb = [sb_f[0] - origin_x, sb_f[1] - origin_y, sb_f[2], sb_f[3]];
564        let shifted_sc = [
565            sc_f[0] - origin_x,
566            sc_f[1] - origin_y,
567            sc_f[2] - origin_x,
568            sc_f[3] - origin_y,
569        ];
570
571        match op.payload {
572            DrawPayload::Quad {
573                bg,
574                bg_grad,
575                border_color,
576                rounded,
577                border_width,
578            } => {
579                let raw_bw = border_width & 0x7F;
580                let bw = if raw_bw == 0 {
581                    0.0
582                } else {
583                    ((raw_bw as f32) * sf).round().max(1.0)
584                };
585                let horiz = (border_width & 0x80) != 0;
586                let r = (rounded as f32) * sf;
587                let is_shadow = border_color.a() == 0 && raw_bw > 0;
588                if is_shadow {
589                    if bg.a() > 0 {
590                        self.primitives.push(make_shadow_primitive(
591                            shifted_sb,
592                            shifted_sc,
593                            clip_radius_px,
594                            r,
595                            (raw_bw as f32) * sf,
596                            bg,
597                        ));
598                    }
599                } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0) {
600                    self.primitives.push(make_quad_primitive(
601                        shifted_sb,
602                        shifted_sc,
603                        clip_radius_px,
604                        r,
605                        bw,
606                        horiz,
607                        bg,
608                        bg_grad,
609                        border_color,
610                    ));
611                }
612            }
613            DrawPayload::StyledQuad(sq) => {
614                let ramp_v = match sq.paint {
615                    Paint::Solid(_) => None,
616                    Paint::LinearGradient { stops, space, .. }
617                    | Paint::RadialGradient { stops, space, .. }
618                    | Paint::ConicGradient { stops, space, .. } => {
619                        let Some(v) = self.ramp_atlas.get_or_insert(queue, stops, space, sq.opacity)
620                        else {
621                            return Err(AtlasGrowNeed {
622                                glyph_full: false,
623                                sprite_need: None,
624                                ramp_full: true,
625                            });
626                        };
627                        Some(v)
628                    }
629                };
630                if let Some(prim) = make_styled_quad_primitive(
631                    shifted_sb,
632                    shifted_sc,
633                    clip_radius_px,
634                    sq,
635                    sf,
636                    ramp_v,
637                ) {
638                    self.primitives.push(prim);
639                }
640            }
641            DrawPayload::TextRun {
642                text,
643                color,
644                font_size,
645                text_flags,
646            } => {
647                if text.is_empty() || color.a() == 0 {
648                    return Ok(());
649                }
650                let sb = Region::new(
651                    sb_f[0] as i16,
652                    sb_f[1] as i16,
653                    sb_f[2] as i16,
654                    sb_f[3] as i16,
655                );
656                let sc = Region::new(
657                    sc_f[0] as i16,
658                    sc_f[1] as i16,
659                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
660                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
661                );
662                let (adj_bounds, adj_sc, adj_flags, logical_fs, fs_q4) = compute_scaled_text_box(
663                    op.bounds,
664                    op.clip,
665                    viewport,
666                    sb,
667                    sc,
668                    text.as_str(),
669                    font_size,
670                    text_flags,
671                    sf,
672                );
673                let adj_sc_f = [
674                    adj_sc.x as f32 - origin_x,
675                    adj_sc.y as f32 - origin_y,
676                    adj_sc.right() as f32 - origin_x,
677                    adj_sc.bottom() as f32 - origin_y,
678                ];
679                let prim_before = self.primitives.len();
680                if !self.encode_text_run(
681                    queue,
682                    adj_bounds,
683                    adj_sc,
684                    adj_sc_f,
685                    clip_radius_px,
686                    text.as_str(),
687                    color,
688                    logical_fs,
689                    fs_q4,
690                    adj_flags,
691                    use_ttf,
692                ) {
693                    return Err(AtlasGrowNeed {
694                        glyph_full: true,
695                        sprite_need: None,
696                        ramp_full: false,
697                    });
698                }
699                if origin_x != 0.0 || origin_y != 0.0 {
700                    for p in &mut self.primitives[prim_before..] {
701                        p.bounds[0] -= origin_x;
702                        p.bounds[1] -= origin_y;
703                    }
704                }
705            }
706            DrawPayload::Sprite(SpriteSource::Arc {
707                thickness,
708                start_deg10,
709                sweep_deg10,
710                fill_sweep_deg10,
711                track_color,
712                fill_color,
713            }) => {
714                self.primitives.push(make_arc_primitive(
715                    shifted_sb,
716                    shifted_sc,
717                    clip_radius_px,
718                    ((thickness.max(1) as f32) * sf).max(1.5),
719                    start_deg10,
720                    sweep_deg10,
721                    fill_sweep_deg10,
722                    track_color,
723                    fill_color,
724                ));
725            }
726            DrawPayload::Sprite(sprite) => {
727                sb_f[0] = sb_f[0].round();
728                sb_f[1] = sb_f[1].round();
729                let sb = Region::new(
730                    sb_f[0] as i16,
731                    sb_f[1] as i16,
732                    sb_f[2] as i16,
733                    sb_f[3] as i16,
734                );
735                let sc = Region::new(
736                    sc_f[0] as i16,
737                    sc_f[1] as i16,
738                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
739                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
740                );
741                let eff = sc.intersect(sb);
742                if eff.is_empty() {
743                    return Ok(());
744                }
745                let w = eff.w.max(1) as usize;
746                let h = eff.h.max(1) as usize;
747                let cache_key = SpriteCacheKey {
748                    w: w as u32,
749                    h: h as u32,
750                    hash: Self::sprite_cache_hash(
751                        sprite,
752                        eff.x.saturating_sub(sb.x),
753                        eff.y.saturating_sub(sb.y),
754                        sb.w,
755                        sb.h,
756                    ),
757                };
758
759                let uv = if let Some(cached_uv) = self.sprite_atlas.lookup(cache_key) {
760                    cached_uv
761                } else {
762                    let len = w * h;
763                    if self.sprite_scratch.len() < len {
764                        self.sprite_scratch.resize(len, Rgba8888(0));
765                    }
766                    let slice = &mut self.sprite_scratch[..len];
767                    slice.fill(Rgba8888(0));
768                    rasterize_sprite_source(sb, eff, sprite, eff.x, eff.y, w, slice);
769
770                    #[cfg(target_endian = "little")]
771                    let rgba_bytes: &[u8] = pod_as_bytes(slice);
772                    #[cfg(not(target_endian = "little"))]
773                    let rgba_bytes: &[u8] = {
774                        self.sprite_bytes_scratch.clear();
775                        self.sprite_bytes_scratch.reserve(len * 4);
776                        for px in slice.iter() {
777                            self.sprite_bytes_scratch
778                                .extend_from_slice(&px.to_rgba_bytes());
779                        }
780                        &self.sprite_bytes_scratch
781                    };
782
783                    let Some(uv) = self
784                        .sprite_atlas
785                        .insert_and_upload(queue, cache_key, rgba_bytes)
786                    else {
787                        return Err(AtlasGrowNeed {
788                            glyph_full: false,
789                            sprite_need: Some((w as u32, h as u32)),
790                            ramp_full: false,
791                        });
792                    };
793                    uv
794                };
795
796                self.primitives.push(GpuPrimitive {
797                    bounds: [
798                        eff.x as f32 - origin_x,
799                        eff.y as f32 - origin_y,
800                        w as f32,
801                        h as f32,
802                    ],
803                    clip: shifted_sc,
804                    uv,
805                    color0: [1.0; 4],
806                    color1: [0.0; 4],
807                    border_color: [0.0; 4],
808                    params: [0.0, 0.0, KIND_SPRITE, 0.0],
809                    extra: [clip_radius_px, 0.0, 0.0, 0.0],
810                    radii: [0.0; 4],
811                    grad_a: [0.0; 4],
812                    grad_b: [0.0; 4],
813                    xform: IDENTITY_XFORM,
814                });
815            }
816            DrawPayload::PushLayer(_)
817            | DrawPayload::PopLayer
818            | DrawPayload::ExternalTexture(_) => {}
819        }
820        Ok(())
821    }
822
823    /// 单 Pass 无图层快路径:将 `DrawOp` 编码为 `self.primitives` 并按需上传字形、精灵与渐变图集。
824    fn try_encode_ops(
825        &mut self,
826        queue: &wgpu::Queue,
827        ops: &[DrawOp<'_>],
828        viewport: Region,
829        scale_factor: f32,
830    ) -> Result<(), AtlasGrowNeed> {
831        self.primitives.clear();
832        if viewport.is_empty() {
833            return Ok(());
834        }
835
836        let sf = scale_factor.clamp(0.5, 4.0);
837        let use_ttf = crate::display::ttf_atlas::has_system_font();
838
839        for (idx, op) in ops.iter().enumerate() {
840            let raw_clip = match op.payload {
841                DrawPayload::StyledQuad(sq) if sq.transform.is_some() => viewport.intersect(op.clip),
842                _ => viewport.intersect(op.clip).intersect(op.bounds),
843            };
844            if raw_clip.is_empty() {
845                continue;
846            }
847            let eff_clip = compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]);
848            if eff_clip.is_empty() {
849                continue;
850            }
851            self.encode_single_op(queue, op, eff_clip, viewport, sf, use_ttf, 0.0, 0.0)?;
852        }
853        Ok(())
854    }
855
856    fn get_or_build_text_layout(
857        &mut self,
858        text: &str,
859        logical_font_size: u8,
860        font_size_q4: u16,
861        max_width: i16,
862        text_flags: u8,
863        use_ttf: bool,
864    ) -> Arc<CachedTextLayout> {
865        let logical_fs = logical_font_size.max(8);
866        let q4 = font_size_q4.clamp(32, 1020);
867        let key = TextLayoutKey {
868            text_hash: hash_layout_text(text),
869            text_len: text.len() as u32,
870            logical_font_size: logical_fs,
871            font_size_q4: q4,
872            max_width,
873            text_flags,
874            use_ttf,
875        };
876        if let Some(hit) = self.text_layout_cache.get(&key) {
877            if hit.text.as_str() == text {
878                self.text_layout_hits = self.text_layout_hits.wrapping_add(1);
879                return Arc::clone(hit);
880            }
881        }
882
883        let render_fs = (q4 as f32) * 0.25;
884        let fs_u8 = ((q4 + 2) >> 2).clamp(8, 255) as u8;
885        let scale_ratio = render_fs / (logical_fs as f32);
886        let is_ellipsis = (text_flags & 0x04) != 0;
887        let is_nowrap = (text_flags & 0x08) != 0;
888        let lines = if use_ttf {
889            let logical_max_w = ((max_width as f32) / scale_ratio)
890                .round()
891                .clamp(1.0, i16::MAX as f32) as i16;
892            split_text_lines(text, logical_fs, logical_max_w, is_nowrap || is_ellipsis)
893        } else {
894            split_text_lines(text, fs_u8, max_width, is_nowrap || is_ellipsis)
895        };
896        let line_count = lines.len();
897        let char_h = if use_ttf {
898            (render_fs.round() as i16).max(8)
899        } else {
900            (fs_u8 as i16).max(8)
901        };
902        let line_step = if use_ttf {
903            ((render_fs * 1.25).round() as i16).max(char_h)
904        } else {
905            ((fs_u8 as i16) * 5 / 4).max(char_h)
906        };
907        let ascent = if use_ttf {
908            crate::display::ttf_atlas::get_font_ascent_f32(render_fs) as i16
909        } else {
910            char_h
911        };
912        let dot_w = measure_char_advance('.', fs_u8);
913        let dot_adv_f = if use_ttf {
914            crate::display::ttf_atlas::measure_ttf_char_advance_f32('.', logical_fs)
915                .map(|a| a * scale_ratio)
916                .unwrap_or(dot_w as f32)
917        } else {
918            dot_w as f32
919        };
920        let total_h = if line_count == 0 {
921            0
922        } else {
923            char_h.saturating_add(line_step.saturating_mul((line_count as i16) - 1))
924        };
925
926        let mut glyphs = Vec::with_capacity(text.len().min(128));
927        for (line_idx, &(b_start, b_end, raw_line_w_orig)) in lines.as_slice().iter().enumerate() {
928            let line_str = &text[b_start..b_end];
929            let raw_line_w = if use_ttf {
930                (crate::display::measure_line_width_f32(line_str, logical_fs) * scale_ratio).ceil()
931                    as i16
932            } else {
933                raw_line_w_orig
934            };
935            let need_ellipsis = is_ellipsis && raw_line_w > max_width && max_width > dot_w * 3;
936            let eff_w = if need_ellipsis {
937                max_width
938            } else {
939                raw_line_w.min(max_width)
940            };
941            let start_rel_x = align_offset_x(max_width, eff_w, text_flags);
942            let rel_y = if use_ttf {
943                ascent.saturating_add((line_idx as i16).saturating_mul(line_step))
944            } else {
945                (line_idx as i16).saturating_mul(line_step)
946            };
947
948            if use_ttf {
949                let mut pen_x = start_rel_x as f32;
950                let max_x_before_dots_f = (max_width as f32) - dot_adv_f * 3.0;
951                let mut prev_ch: Option<char> = None;
952                for ch in line_str.chars() {
953                    if let Some(p) = prev_ch {
954                        pen_x += crate::display::ttf_atlas::measure_ttf_kerning_f32(
955                            p, ch, logical_fs,
956                        ) * scale_ratio;
957                    }
958                    let adv_f =
959                        crate::display::ttf_atlas::measure_ttf_char_advance_f32(ch, logical_fs)
960                            .map(|a| a * scale_ratio)
961                            .unwrap_or_else(|| {
962                                (measure_char_advance(ch, logical_fs) as f32) * scale_ratio
963                            });
964                    if need_ellipsis && pen_x + adv_f > max_x_before_dots_f + 0.01 {
965                        for _ in 0..3 {
966                            glyphs.push(ShapedGlyphPos {
967                                ch: '.',
968                                rel_x: pen_x.round() as i16,
969                                rel_y,
970                            });
971                            pen_x += dot_adv_f;
972                        }
973                        break;
974                    }
975                    if ch != ' ' {
976                        glyphs.push(ShapedGlyphPos {
977                            ch,
978                            rel_x: pen_x.round() as i16,
979                            rel_y,
980                        });
981                    }
982                    pen_x += adv_f;
983                    prev_ch = Some(ch);
984                }
985            } else {
986                let mut rel_x = start_rel_x;
987                let max_x_before_dots = max_width.saturating_sub(dot_w * 3);
988                let mut prev_ch: Option<char> = None;
989                for ch in line_str.chars() {
990                    if let Some(p) = prev_ch {
991                        rel_x = rel_x.saturating_add(measure_char_kerning(p, ch, fs_u8));
992                    }
993                    let adv = measure_char_advance(ch, fs_u8);
994                    if need_ellipsis && rel_x.saturating_add(adv) > max_x_before_dots {
995                        for _ in 0..3 {
996                            glyphs.push(ShapedGlyphPos {
997                                ch: '.',
998                                rel_x,
999                                rel_y,
1000                            });
1001                            rel_x = rel_x.saturating_add(dot_w);
1002                        }
1003                        break;
1004                    }
1005                    if ch != ' ' {
1006                        glyphs.push(ShapedGlyphPos { ch, rel_x, rel_y });
1007                    }
1008                    rel_x = rel_x.saturating_add(adv);
1009                    prev_ch = Some(ch);
1010                }
1011            }
1012        }
1013
1014        let built = Arc::new(CachedTextLayout {
1015            text: String::from(text),
1016            total_h,
1017            glyphs,
1018        });
1019        if self.text_layout_cache.len() >= MAX_TEXT_LAYOUT_CACHE_ENTRIES {
1020            self.text_layout_cache.clear();
1021        }
1022        self.text_layout_cache.insert(key, Arc::clone(&built));
1023        built
1024    }
1025
1026    #[allow(clippy::too_many_arguments)]
1027    fn encode_text_run(
1028        &mut self,
1029        queue: &wgpu::Queue,
1030        bounds: Region,
1031        clip: Region,
1032        clip_f32: [f32; 4],
1033        clip_radius_px: f32,
1034        text: &str,
1035        color: Color,
1036        logical_font_size: u8,
1037        font_size_q4: u16,
1038        text_flags: u8,
1039        use_ttf: bool,
1040    ) -> bool {
1041        let layout = self.get_or_build_text_layout(
1042            text,
1043            logical_font_size,
1044            font_size_q4,
1045            bounds.w,
1046            text_flags,
1047            use_ttf,
1048        );
1049        if layout.glyphs.is_empty() {
1050            return true;
1051        }
1052        let top_y = bounds
1053            .y
1054            .saturating_add(bounds.h.saturating_sub(layout.total_h).max(0) >> 1);
1055        let col_f32 = color_to_f32(color);
1056
1057        for g in &layout.glyphs {
1058            let Some(entry) = self
1059                .glyph_atlas
1060                .get_or_insert(queue, g.ch, font_size_q4, use_ttf)
1061            else {
1062                return false;
1063            };
1064            if entry.width > 0 && entry.height > 0 {
1065                let gx = bounds
1066                    .x
1067                    .saturating_add(g.rel_x)
1068                    .saturating_add(entry.xmin);
1069                let gy = if use_ttf {
1070                    top_y
1071                        .saturating_add(g.rel_y)
1072                        .saturating_sub(entry.height)
1073                        .saturating_sub(entry.ymin)
1074                } else {
1075                    top_y.saturating_add(g.rel_y)
1076                };
1077                let greg = Region::new(gx, gy, entry.width, entry.height);
1078                if !clip.intersect(greg).is_empty() {
1079                    self.primitives.push(GpuPrimitive {
1080                        bounds: [
1081                            gx as f32,
1082                            gy as f32,
1083                            entry.width as f32,
1084                            entry.height as f32,
1085                        ],
1086                        clip: clip_f32,
1087                        uv: entry.uv,
1088                        color0: col_f32,
1089                        color1: [0.0; 4],
1090                        border_color: [0.0; 4],
1091                        params: [0.0, 0.0, KIND_GLYPH, 0.0],
1092                        extra: [clip_radius_px, 0.0, 0.0, 0.0],
1093                        radii: [0.0; 4],
1094                        grad_a: [0.0; 4],
1095                        grad_b: [0.0; 4],
1096                        xform: IDENTITY_XFORM,
1097                    });
1098                }
1099            }
1100        }
1101        true
1102    }
1103
1104    fn handle_atlas_grow(&mut self, device: &wgpu::Device, need: AtlasGrowNeed) -> (bool, bool) {
1105        let mut dirty = false;
1106        let mut can_retry = true;
1107        if need.glyph_full && self.glyph_atlas.reset_or_grow(device) {
1108            dirty = true;
1109        }
1110        if need.ramp_full && self.ramp_atlas.reset_or_grow(device) {
1111            dirty = true;
1112        }
1113        if let Some((sw, sh)) = need.sprite_need {
1114            let (recreated, retry) = self.sprite_atlas.reset_or_grow(device, sw, sh);
1115            if recreated {
1116                dirty = true;
1117            }
1118            if !retry {
1119                can_retry = false;
1120            }
1121        }
1122        (dirty, can_retry)
1123    }
1124
1125    /// 将当前帧 `ops` 直接渲染至目标 `target_view`:
1126    /// - 无图层/混合模式时走单 RenderPass / 单 Draw Call 直出快路径(0 离屏拷贝);
1127    /// - 含 `PushLayer` / 混合 / 毛玻璃 / 滤镜时自动通过 `GpuEffectsEngine` 在单 `CommandEncoder` 内完成多 Pass 离屏合成。
1128    #[allow(clippy::too_many_arguments)]
1129    pub fn render_to_view(
1130        &mut self,
1131        device: &wgpu::Device,
1132        queue: &wgpu::Queue,
1133        ops: &[DrawOp<'_>],
1134        viewport: Region,
1135        scale_factor: f32,
1136        target_view: &wgpu::TextureView,
1137        phys_width: u32,
1138        phys_height: u32,
1139        clear_color: wgpu::Color,
1140    ) {
1141        if ops_have_layers_or_blend(ops) && !viewport.is_empty() {
1142            self.render_to_view_multi_pass(
1143                device,
1144                queue,
1145                ops,
1146                viewport,
1147                scale_factor,
1148                target_view,
1149                phys_width,
1150                phys_height,
1151                clear_color,
1152            );
1153            return;
1154        }
1155
1156        let mut bind_group_dirty = false;
1157        for _attempt in 0..4 {
1158            match self.try_encode_ops(queue, ops, viewport, scale_factor) {
1159                Ok(()) => break,
1160                Err(need) => {
1161                    let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1162                    if dirty {
1163                        bind_group_dirty = true;
1164                    }
1165                    if !can_retry {
1166                        break;
1167                    }
1168                }
1169            }
1170        }
1171
1172        if self.primitives.len() > self.instance_capacity {
1173            self.instance_capacity = self.primitives.len().next_power_of_two();
1174            self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1175            bind_group_dirty = true;
1176        }
1177        if bind_group_dirty {
1178            self.rebuild_bind_group(device);
1179        }
1180
1181        let slot0 = AlignedViewportSlot {
1182            uniform: ViewportUniform {
1183                size: [phys_width.max(1) as f32, phys_height.max(1) as f32],
1184                is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
1185                _pad: 0.0,
1186            },
1187            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1188        };
1189        queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
1190
1191        if !self.primitives.is_empty() {
1192            queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1193        }
1194
1195        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1196            label: Some("velox_wgpu_render_encoder"),
1197        });
1198        {
1199            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1200                label: Some("velox_wgpu_render_pass"),
1201                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1202                    view: target_view,
1203                    depth_slice: None,
1204                    resolve_target: None,
1205                    ops: wgpu::Operations {
1206                        load: wgpu::LoadOp::Clear(clear_color),
1207                        store: wgpu::StoreOp::Store,
1208                    },
1209                })],
1210                depth_stencil_attachment: None,
1211                occlusion_query_set: None,
1212                timestamp_writes: None,
1213                multiview_mask: None,
1214            });
1215            if !self.primitives.is_empty() {
1216                rpass.set_pipeline(&self.pipeline);
1217                rpass.set_bind_group(0, &self.bind_group, &[0]);
1218                rpass.draw(0..6, 0..(self.primitives.len() as u32));
1219            }
1220        }
1221        queue.submit([encoder.finish()]);
1222    }
1223
1224    #[allow(clippy::too_many_arguments)]
1225    fn render_to_view_multi_pass(
1226        &mut self,
1227        device: &wgpu::Device,
1228        queue: &wgpu::Queue,
1229        ops: &[DrawOp<'_>],
1230        viewport: Region,
1231        scale_factor: f32,
1232        target_view: &wgpu::TextureView,
1233        phys_width: u32,
1234        phys_height: u32,
1235        clear_color: wgpu::Color,
1236    ) {
1237        let pw = phys_width.max(1);
1238        let ph = phys_height.max(1);
1239        let sf = scale_factor.clamp(0.5, 4.0);
1240        let use_ttf = crate::display::ttf_atlas::has_system_font();
1241        let is_srgb = self.target_is_srgb;
1242
1243        if self.effects.is_none() {
1244            self.effects = Some(GpuEffectsEngine::new(device, queue, self.target_format));
1245        }
1246
1247        let mut bind_group_dirty = false;
1248        for _attempt in 0..4 {
1249            match self.try_plan_multi_pass(device, queue, ops, viewport, sf, use_ttf, pw, ph, clear_color, is_srgb) {
1250                Ok(()) => break,
1251                Err(need) => {
1252                    let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1253                    if dirty {
1254                        bind_group_dirty = true;
1255                    }
1256                    if !can_retry {
1257                        break;
1258                    }
1259                }
1260            }
1261        }
1262
1263        if self.primitives.len() > self.instance_capacity {
1264            self.instance_capacity = self.primitives.len().next_power_of_two();
1265            self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1266            bind_group_dirty = true;
1267        }
1268        if self.viewport_slots.len() > self.viewport_capacity {
1269            self.viewport_capacity = self.viewport_slots.len().next_power_of_two();
1270            self.viewport_buf = Self::create_viewport_buffer(device, self.viewport_capacity);
1271            bind_group_dirty = true;
1272        }
1273        if bind_group_dirty {
1274            self.rebuild_bind_group(device);
1275        }
1276
1277        if !self.viewport_slots.is_empty() {
1278            queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&self.viewport_slots));
1279        }
1280        if !self.primitives.is_empty() {
1281            queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1282        }
1283
1284        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1285            label: Some("velox_wgpu_multi_pass_encoder"),
1286        });
1287        if let Some(ref mut fx) = self.effects {
1288            fx.execute_steps(
1289                device,
1290                queue,
1291                &mut encoder,
1292                &self.pipeline,
1293                &self.bind_group,
1294                &self.linear_sampler,
1295                &self.external_textures,
1296                target_view,
1297            );
1298        }
1299        queue.submit([encoder.finish()]);
1300    }
1301
1302    #[allow(clippy::too_many_arguments)]
1303    fn try_plan_multi_pass(
1304        &mut self,
1305        device: &wgpu::Device,
1306        queue: &wgpu::Queue,
1307        ops: &[DrawOp<'_>],
1308        viewport: Region,
1309        sf: f32,
1310        use_ttf: bool,
1311        pw: u32,
1312        ph: u32,
1313        clear_color: wgpu::Color,
1314        is_srgb: bool,
1315    ) -> Result<(), AtlasGrowNeed> {
1316        struct LayerFrame<'a> {
1317            tex_idx: usize,
1318            active_w: u32,
1319            active_h: u32,
1320            origin_x: f32,
1321            origin_y: f32,
1322            viewport_slot: u32,
1323            cleared: bool,
1324            clear_col: wgpu::Color,
1325            batch_start: u32,
1326            spec: Option<&'a LayerSpec<'a>>,
1327            body_phys: Region,
1328            buf_rect: Region,
1329            parent_clip_phys: Region,
1330        }
1331
1332        self.primitives.clear();
1333        self.viewport_slots.clear();
1334        let mut fx = self.effects.take().expect("effects engine initialized");
1335        fx.begin_frame();
1336
1337        let root_idx = fx.pool.acquire(device, pw, ph);
1338        let root_tex_sz = (fx.pool.get(root_idx).width, fx.pool.get(root_idx).height);
1339        let root_vp_slot = 0u32;
1340        self.viewport_slots.push(AlignedViewportSlot {
1341            uniform: ViewportUniform {
1342                size: [root_tex_sz.0 as f32, root_tex_sz.1 as f32],
1343                is_srgb: if is_srgb { 1.0 } else { 0.0 },
1344                _pad: 0.0,
1345            },
1346            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1347        });
1348
1349        let mut stack: Vec<LayerFrame<'_>> = Vec::with_capacity(8);
1350        stack.push(LayerFrame {
1351            tex_idx: root_idx,
1352            active_w: pw,
1353            active_h: ph,
1354            origin_x: 0.0,
1355            origin_y: 0.0,
1356            viewport_slot: root_vp_slot,
1357            cleared: false,
1358            clear_col: clear_color,
1359            batch_start: 0,
1360            spec: None,
1361            body_phys: Region::new(0, 0, pw as i16, ph as i16),
1362            buf_rect: Region::new(0, 0, pw as i16, ph as i16),
1363            parent_clip_phys: Region::new(0, 0, pw as i16, ph as i16),
1364        });
1365
1366        let flush_top = |stack: &mut [LayerFrame<'_>], fx: &mut GpuEffectsEngine, prim_len: u32| {
1367            let Some(top) = stack.last_mut() else {
1368                return;
1369            };
1370            if !top.cleared || prim_len > top.batch_start {
1371                let clear = if !top.cleared {
1372                    top.cleared = true;
1373                    Some(top.clear_col)
1374                } else {
1375                    None
1376                };
1377                fx.steps.push(GpuPassStep::DrawBatch {
1378                    target_idx: top.tex_idx,
1379                    clear,
1380                    viewport_slot: top.viewport_slot,
1381                    prim_start: top.batch_start,
1382                    prim_end: prim_len,
1383                });
1384                top.batch_start = prim_len;
1385            }
1386        };
1387
1388        let result: Result<(), AtlasGrowNeed> = (|| {
1389            for op in ops {
1390                match op.payload {
1391                    DrawPayload::PushLayer(spec) => {
1392                        flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1393                        let parent = stack.last().unwrap();
1394                        let parent_idx = parent.tex_idx;
1395                        let parent_aw = parent.active_w;
1396                        let parent_ah = parent.active_h;
1397                        let parent_ox = parent.origin_x;
1398                        let parent_oy = parent.origin_y;
1399                        let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1400
1401                        let body_phys = snap_bounds_region_scaled(spec.bounds, sf);
1402                        let parent_clip_phys = snap_clip_region_scaled(op.clip, sf);
1403
1404                        // 1. 实时毛玻璃 `backdrop-filter`
1405                        if !spec.backdrop_filter.is_empty() && !body_phys.is_empty() {
1406                            let bd = spec.backdrop_filter;
1407                            let blur_px = (bd.blur_radius as f32) * sf;
1408                            let pad = (blur_px * 2.0).ceil() as i16;
1409                            let local_body = Region::new(
1410                                body_phys.x.saturating_sub(parent_ox as i16),
1411                                body_phys.y.saturating_sub(parent_oy as i16),
1412                                body_phys.w,
1413                                body_phys.h,
1414                            );
1415                            let raw_sample = Region::new(
1416                                local_body.x.saturating_sub(pad),
1417                                local_body.y.saturating_sub(pad),
1418                                local_body.w.saturating_add(pad.saturating_mul(2)),
1419                                local_body.h.saturating_add(pad.saturating_mul(2)),
1420                            );
1421                            let (sx, sy, sw, sh) = clamp_rect_u32(raw_sample, parent_aw, parent_ah);
1422                            if sw > 0 && sh > 0 {
1423                                let bd_raw = fx.pool.acquire(device, sw, sh);
1424                                fx.steps.push(GpuPassStep::CopyRect {
1425                                    src_idx: parent_idx,
1426                                    src_origin: (sx, sy),
1427                                    dst_idx: bd_raw,
1428                                    dst_origin: (0, 0),
1429                                    size: (sw, sh),
1430                                });
1431                                let bd_blurred = if blur_px >= 0.5 {
1432                                    let b = fx.plan_kawase_blur(device, bd_raw, sw, sh, blur_px, is_srgb);
1433                                    if b != bd_raw {
1434                                        fx.pool.release(bd_raw);
1435                                    }
1436                                    b
1437                                } else {
1438                                    bd_raw
1439                                };
1440
1441                                let snap_idx = fx.pool.acquire(device, parent_aw, parent_ah);
1442                                fx.steps.push(GpuPassStep::CopyRect {
1443                                    src_idx: parent_idx,
1444                                    src_origin: (0, 0),
1445                                    dst_idx: snap_idx,
1446                                    dst_origin: (0, 0),
1447                                    size: (parent_aw, parent_ah),
1448                                });
1449
1450                                let bd_tex_sz = (fx.pool.get(bd_blurred).width, fx.pool.get(bd_blurred).height);
1451                                let snap_tex_sz = (fx.pool.get(snap_idx).width, fx.pool.get(snap_idx).height);
1452                                let mut u = EffectUniform::default();
1453                                u.tex_sizes = [
1454                                    parent_tex_sz.0 as f32,
1455                                    parent_tex_sz.1 as f32,
1456                                    bd_tex_sz.0 as f32,
1457                                    bd_tex_sz.1 as f32,
1458                                ];
1459                                u.dst_rect = [
1460                                    local_body.x as f32,
1461                                    local_body.y as f32,
1462                                    local_body.w as f32,
1463                                    local_body.h as f32,
1464                                ];
1465                                u.src_rect = [sx as f32, sy as f32, sw as f32, sh as f32];
1466                                u.clip_rect = [
1467                                    parent_clip_phys.x as f32 - parent_ox,
1468                                    parent_clip_phys.y as f32 - parent_oy,
1469                                    parent_clip_phys.right() as f32 - parent_ox,
1470                                    parent_clip_phys.bottom() as f32 - parent_oy,
1471                                ];
1472                                u.body_rect = u.dst_rect;
1473                                u.radii = [
1474                                    (spec.clip_radii.tl as f32) * sf,
1475                                    (spec.clip_radii.tr as f32) * sf,
1476                                    (spec.clip_radii.br as f32) * sf,
1477                                    (spec.clip_radii.bl as f32) * sf,
1478                                ];
1479                                u.params = [
1480                                    (spec.opacity as f32) * (1.0 / 255.0),
1481                                    0.0,
1482                                    EFFECT_KIND_BACKDROP,
1483                                    0.0,
1484                                ];
1485                                u.set_color_matrix(bd.color_matrix);
1486                                u.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
1487                                u.flags[2] = (bd.noise_amount as f32) * (1.0 / 255.0) * 0.12;
1488                                u.flags[3] = if is_srgb { 1.0 } else { 0.0 };
1489                                u.tint = color_to_f32(bd.tint);
1490                                u.extra = [0.0, 0.0, snap_tex_sz.0 as f32, snap_tex_sz.1 as f32];
1491
1492                                let slot = fx.push_slot(u);
1493                                let mask_path = spec.clip_path.map(|p| {
1494                                    (
1495                                        std::string::String::from(p.as_str()),
1496                                        local_body.w.max(1) as u32,
1497                                        local_body.h.max(1) as u32,
1498                                    )
1499                                });
1500                                fx.steps.push(GpuPassStep::Effect {
1501                                    dst_idx: parent_idx,
1502                                    clear_dst: false,
1503                                    src_idx: bd_blurred,
1504                                    dst_snap_idx: snap_idx,
1505                                    mask_path,
1506                                    effect_slot: slot,
1507                                });
1508                                fx.pool.release(bd_blurred);
1509                                fx.pool.release(snap_idx);
1510                            }
1511                        }
1512
1513                        // 2. 为新隔离图层分配离屏目标并压栈
1514                        let (fl, ft, fr, fb) = spec.filter.outset();
1515                        let pl = ((fl as f32) * sf).ceil() as i16;
1516                        let pt = ((ft as f32) * sf).ceil() as i16;
1517                        let pr = ((fr as f32) * sf).ceil() as i16;
1518                        let pb = ((fb as f32) * sf).ceil() as i16;
1519                        let buf_rect = Region::new(
1520                            body_phys.x.saturating_sub(pl),
1521                            body_phys.y.saturating_sub(pt),
1522                            body_phys.w.saturating_add(pl).saturating_add(pr).max(1),
1523                            body_phys.h.saturating_add(pt).saturating_add(pb).max(1),
1524                        );
1525                        let lw = buf_rect.w.max(1) as u32;
1526                        let lh = buf_rect.h.max(1) as u32;
1527                        let layer_tex = fx.pool.acquire(device, lw, lh);
1528                        let ltex_sz = (fx.pool.get(layer_tex).width, fx.pool.get(layer_tex).height);
1529                        let vp_slot = self.viewport_slots.len() as u32;
1530                        self.viewport_slots.push(AlignedViewportSlot {
1531                            uniform: ViewportUniform {
1532                                size: [ltex_sz.0 as f32, ltex_sz.1 as f32],
1533                                is_srgb: if is_srgb { 1.0 } else { 0.0 },
1534                                _pad: 0.0,
1535                            },
1536                            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1537                        });
1538
1539                        stack.push(LayerFrame {
1540                            tex_idx: layer_tex,
1541                            active_w: lw,
1542                            active_h: lh,
1543                            origin_x: buf_rect.x as f32,
1544                            origin_y: buf_rect.y as f32,
1545                            viewport_slot: vp_slot,
1546                            cleared: false,
1547                            clear_col: wgpu::Color::TRANSPARENT,
1548                            batch_start: self.primitives.len() as u32,
1549                            spec: Some(spec),
1550                            body_phys,
1551                            buf_rect,
1552                            parent_clip_phys,
1553                        });
1554                    }
1555
1556                    DrawPayload::PopLayer => {
1557                        if stack.len() <= 1 {
1558                            continue;
1559                        }
1560                        flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1561                        let layer = stack.pop().unwrap();
1562                        if let Some(parent_mut) = stack.last_mut() {
1563                            parent_mut.batch_start = self.primitives.len() as u32;
1564                        }
1565                        let Some(spec) = layer.spec else {
1566                            continue;
1567                        };
1568                        let parent = stack.last().unwrap();
1569                        let parent_idx = parent.tex_idx;
1570                        let parent_aw = parent.active_w;
1571                        let parent_ah = parent.active_h;
1572                        let parent_ox = parent.origin_x;
1573                        let parent_oy = parent.origin_y;
1574                        let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1575
1576                        let local_buf = [
1577                            layer.buf_rect.x as f32 - parent_ox,
1578                            layer.buf_rect.y as f32 - parent_oy,
1579                            layer.buf_rect.w as f32,
1580                            layer.buf_rect.h as f32,
1581                        ];
1582                        let local_body = [
1583                            layer.body_phys.x as f32 - parent_ox,
1584                            layer.body_phys.y as f32 - parent_oy,
1585                            layer.body_phys.w as f32,
1586                            layer.body_phys.h as f32,
1587                        ];
1588                        let clip_f = [
1589                            layer.parent_clip_phys.x as f32 - parent_ox,
1590                            layer.parent_clip_phys.y as f32 - parent_oy,
1591                            layer.parent_clip_phys.right() as f32 - parent_ox,
1592                            layer.parent_clip_phys.bottom() as f32 - parent_oy,
1593                        ];
1594
1595                        // 计算经 2D 仿射变换后的目标绘制矩形
1596                        let dst_rect = if let Some(mut t) = spec.transform {
1597                            if !t.is_identity() {
1598                                t.e *= sf;
1599                                t.f *= sf;
1600                                let cx = local_body[0] + local_body[2] * 0.5;
1601                                let cy = local_body[1] + local_body[3] * 0.5;
1602                                let xreg = t.centered_at(cx, cy).transform_region(Region::new(
1603                                    local_buf[0] as i16,
1604                                    local_buf[1] as i16,
1605                                    local_buf[2] as i16,
1606                                    local_buf[3] as i16,
1607                                ));
1608                                [xreg.x as f32, xreg.y as f32, xreg.w as f32, xreg.h as f32]
1609                            } else {
1610                                local_buf
1611                            }
1612                        } else {
1613                            local_buf
1614                        };
1615
1616                        // 1. 若启用任意子树 `drop_shadow`:提取 Alpha(含 SVG Path 遮罩)-> Kawase Blur -> 变换偏移合成到父层
1617                        if let Some(ds) = spec.filter.drop_shadow {
1618                            if ds.is_active() {
1619                                let sh_raw = fx.pool.acquire(device, layer.active_w, layer.active_h);
1620                                let lsz = (fx.pool.get(layer.tex_idx).width, fx.pool.get(layer.tex_idx).height);
1621                                let sh_sz = (fx.pool.get(sh_raw).width, fx.pool.get(sh_raw).height);
1622                                let mut eu = EffectUniform::default();
1623                                eu.tex_sizes = [sh_sz.0 as f32, sh_sz.1 as f32, lsz.0 as f32, lsz.1 as f32];
1624                                eu.dst_rect = [0.0, 0.0, layer.active_w as f32, layer.active_h as f32];
1625                                eu.src_rect = eu.dst_rect;
1626                                eu.body_rect = [
1627                                    (layer.body_phys.x - layer.buf_rect.x) as f32,
1628                                    (layer.body_phys.y - layer.buf_rect.y) as f32,
1629                                    layer.body_phys.w as f32,
1630                                    layer.body_phys.h as f32,
1631                                ];
1632                                eu.params = [1.0, 0.0, EFFECT_KIND_SHADOW_EXTRACT, 0.0];
1633                                eu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
1634                                eu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
1635                                eu.tint = color_to_f32(ds.color);
1636                                let eslot = fx.push_slot(eu);
1637                                let sh_mask = spec.clip_path.map(|p| {
1638                                    (
1639                                        std::string::String::from(p.as_str()),
1640                                        layer.body_phys.w.max(1) as u32,
1641                                        layer.body_phys.h.max(1) as u32,
1642                                    )
1643                                });
1644                                fx.steps.push(GpuPassStep::Effect {
1645                                    dst_idx: sh_raw,
1646                                    clear_dst: true,
1647                                    src_idx: layer.tex_idx,
1648                                    dst_snap_idx: layer.tex_idx,
1649                                    mask_path: sh_mask,
1650                                    effect_slot: eslot,
1651                                });
1652
1653                                let ds_blur = (ds.blur as f32) * sf;
1654                                let sh_final = if ds_blur >= 0.5 {
1655                                    let b = fx.plan_kawase_blur(
1656                                        device,
1657                                        sh_raw,
1658                                        layer.active_w,
1659                                        layer.active_h,
1660                                        ds_blur,
1661                                        is_srgb,
1662                                    );
1663                                    if b != sh_raw {
1664                                        fx.pool.release(sh_raw);
1665                                    }
1666                                    b
1667                                } else {
1668                                    sh_raw
1669                                };
1670
1671                                let snap_idx = fx.pool.acquire(device, parent_aw, parent_ah);
1672                                fx.steps.push(GpuPassStep::CopyRect {
1673                                    src_idx: parent_idx,
1674                                    src_origin: (0, 0),
1675                                    dst_idx: snap_idx,
1676                                    dst_origin: (0, 0),
1677                                    size: (parent_aw, parent_ah),
1678                                });
1679                                let sh_tex_sz = (fx.pool.get(sh_final).width, fx.pool.get(sh_final).height);
1680                                let snap_sz = (fx.pool.get(snap_idx).width, fx.pool.get(snap_idx).height);
1681                                let ox = (ds.offset_x as f32) * sf;
1682                                let oy = (ds.offset_y as f32) * sf;
1683
1684                                let mut cu = EffectUniform::default();
1685                                cu.tex_sizes = [
1686                                    parent_tex_sz.0 as f32,
1687                                    parent_tex_sz.1 as f32,
1688                                    sh_tex_sz.0 as f32,
1689                                    sh_tex_sz.1 as f32,
1690                                ];
1691                                cu.dst_rect = [
1692                                    dst_rect[0] + ox,
1693                                    dst_rect[1] + oy,
1694                                    dst_rect[2],
1695                                    dst_rect[3],
1696                                ];
1697                                cu.src_rect = local_buf;
1698                                cu.clip_rect = clip_f;
1699                                cu.body_rect = local_body;
1700                                cu.params = [
1701                                    (spec.opacity as f32) * (1.0 / 255.0),
1702                                    spec.blend_mode as u8 as f32,
1703                                    EFFECT_KIND_COMPOSITE,
1704                                    0.0,
1705                                ];
1706                                cu.set_color_matrix(None);
1707                                cu.set_transform(spec.transform, sf);
1708                                cu.extra[0] += ox;
1709                                cu.extra[1] += oy;
1710                                cu.extra[2] = snap_sz.0 as f32;
1711                                cu.extra[3] = snap_sz.1 as f32;
1712                                let cslot = fx.push_slot(cu);
1713                                fx.steps.push(GpuPassStep::Effect {
1714                                    dst_idx: parent_idx,
1715                                    clear_dst: false,
1716                                    src_idx: sh_final,
1717                                    dst_snap_idx: snap_idx,
1718                                    mask_path: None,
1719                                    effect_slot: cslot,
1720                                });
1721                                fx.pool.release(sh_final);
1722                                fx.pool.release(snap_idx);
1723                            }
1724                        }
1725
1726                        // 2. 图层本体模糊(Dual Kawase Blur)
1727                        let blur_px = (spec.filter.blur_radius as f32) * sf;
1728                        let src_final = if blur_px >= 0.5 {
1729                            let b = fx.plan_kawase_blur(
1730                                device,
1731                                layer.tex_idx,
1732                                layer.active_w,
1733                                layer.active_h,
1734                                blur_px,
1735                                is_srgb,
1736                            );
1737                            if b != layer.tex_idx {
1738                                fx.pool.release(layer.tex_idx);
1739                            }
1740                            b
1741                        } else {
1742                            layer.tex_idx
1743                        };
1744
1745                        // 3. 合成回父层(ColorMatrix + SVG Path 遮罩 + Transform2D + Opacity + 27 种 BlendMode)
1746                        let snap_idx = fx.pool.acquire(device, parent_aw, parent_ah);
1747                        fx.steps.push(GpuPassStep::CopyRect {
1748                            src_idx: parent_idx,
1749                            src_origin: (0, 0),
1750                            dst_idx: snap_idx,
1751                            dst_origin: (0, 0),
1752                            size: (parent_aw, parent_ah),
1753                        });
1754                        let src_tex_sz = (fx.pool.get(src_final).width, fx.pool.get(src_final).height);
1755                        let snap_tex_sz = (fx.pool.get(snap_idx).width, fx.pool.get(snap_idx).height);
1756
1757                        let mut cu = EffectUniform::default();
1758                        cu.tex_sizes = [
1759                            parent_tex_sz.0 as f32,
1760                            parent_tex_sz.1 as f32,
1761                            src_tex_sz.0 as f32,
1762                            src_tex_sz.1 as f32,
1763                        ];
1764                        cu.dst_rect = dst_rect;
1765                        cu.src_rect = local_buf;
1766                        cu.clip_rect = clip_f;
1767                        cu.body_rect = local_body;
1768                        cu.radii = [
1769                            (spec.clip_radii.tl as f32) * sf,
1770                            (spec.clip_radii.tr as f32) * sf,
1771                            (spec.clip_radii.br as f32) * sf,
1772                            (spec.clip_radii.bl as f32) * sf,
1773                        ];
1774                        cu.params = [
1775                            (spec.opacity as f32) * (1.0 / 255.0),
1776                            spec.blend_mode as u8 as f32,
1777                            EFFECT_KIND_COMPOSITE,
1778                            0.0,
1779                        ];
1780                        cu.set_color_matrix(spec.filter.color_matrix);
1781                        cu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
1782                        cu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
1783                        cu.set_transform(spec.transform, sf);
1784                        cu.extra[2] = snap_tex_sz.0 as f32;
1785                        cu.extra[3] = snap_tex_sz.1 as f32;
1786                        let cslot = fx.push_slot(cu);
1787
1788                        let mask_path = spec.clip_path.map(|p| {
1789                            (
1790                                std::string::String::from(p.as_str()),
1791                                layer.body_phys.w.max(1) as u32,
1792                                layer.body_phys.h.max(1) as u32,
1793                            )
1794                        });
1795                        fx.steps.push(GpuPassStep::Effect {
1796                            dst_idx: parent_idx,
1797                            clear_dst: false,
1798                            src_idx: src_final,
1799                            dst_snap_idx: snap_idx,
1800                            mask_path,
1801                            effect_slot: cslot,
1802                        });
1803                        fx.pool.release(src_final);
1804                        fx.pool.release(snap_idx);
1805                    }
1806
1807                    // 单图元非 `SrcOver` 混合:自动借用微型临时层执行精确 27 种 W3C 混合模式
1808                    DrawPayload::StyledQuad(sq) if !sq.blend_mode.is_normal() => {
1809                        flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1810                        let parent = stack.last().unwrap();
1811                        let parent_idx = parent.tex_idx;
1812                        let parent_aw = parent.active_w;
1813                        let parent_ah = parent.active_h;
1814                        let parent_ox = parent.origin_x;
1815                        let parent_oy = parent.origin_y;
1816                        let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1817
1818                        let body_phys = snap_bounds_region_scaled(op.bounds, sf);
1819                        let buf_rect = if let Some(mut t) = sq.transform {
1820                            if !t.is_identity() {
1821                                t.e *= sf;
1822                                t.f *= sf;
1823                                let cx = body_phys.x as f32 + body_phys.w as f32 * 0.5;
1824                                let cy = body_phys.y as f32 + body_phys.h as f32 * 0.5;
1825                                t.centered_at(cx, cy).transform_region(body_phys)
1826                            } else {
1827                                body_phys
1828                            }
1829                        } else {
1830                            body_phys
1831                        };
1832                        let lw = buf_rect.w.max(1) as u32;
1833                        let lh = buf_rect.h.max(1) as u32;
1834                        let tmp_tex = fx.pool.acquire(device, lw, lh);
1835                        let tmp_sz = (fx.pool.get(tmp_tex).width, fx.pool.get(tmp_tex).height);
1836                        let vp_slot = self.viewport_slots.len() as u32;
1837                        self.viewport_slots.push(AlignedViewportSlot {
1838                            uniform: ViewportUniform {
1839                                size: [tmp_sz.0 as f32, tmp_sz.1 as f32],
1840                                is_srgb: if is_srgb { 1.0 } else { 0.0 },
1841                                _pad: 0.0,
1842                            },
1843                            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1844                        });
1845
1846                        let normal_sq = StyledQuad {
1847                            blend_mode: BlendMode::SrcOver,
1848                            ..*sq
1849                        };
1850                        let tmp_op = DrawOp {
1851                            payload: DrawPayload::StyledQuad(&normal_sq),
1852                            ..*op
1853                        };
1854                        let pstart = self.primitives.len() as u32;
1855                        self.encode_single_op(
1856                            queue,
1857                            &tmp_op,
1858                            op.clip,
1859                            viewport,
1860                            sf,
1861                            use_ttf,
1862                            buf_rect.x as f32,
1863                            buf_rect.y as f32,
1864                        )?;
1865                        let pend = self.primitives.len() as u32;
1866                        fx.steps.push(GpuPassStep::DrawBatch {
1867                            target_idx: tmp_tex,
1868                            clear: Some(wgpu::Color::TRANSPARENT),
1869                            viewport_slot: vp_slot,
1870                            prim_start: pstart,
1871                            prim_end: pend,
1872                        });
1873                        if let Some(top) = stack.last_mut() {
1874                            top.batch_start = pend;
1875                        }
1876
1877                        let snap_idx = fx.pool.acquire(device, parent_aw, parent_ah);
1878                        fx.steps.push(GpuPassStep::CopyRect {
1879                            src_idx: parent_idx,
1880                            src_origin: (0, 0),
1881                            dst_idx: snap_idx,
1882                            dst_origin: (0, 0),
1883                            size: (parent_aw, parent_ah),
1884                        });
1885                        let snap_sz = (fx.pool.get(snap_idx).width, fx.pool.get(snap_idx).height);
1886                        let clip_phys = snap_clip_region_scaled(op.clip, sf);
1887                        let local_buf = [
1888                            buf_rect.x as f32 - parent_ox,
1889                            buf_rect.y as f32 - parent_oy,
1890                            buf_rect.w as f32,
1891                            buf_rect.h as f32,
1892                        ];
1893                        let mut cu = EffectUniform::default();
1894                        cu.tex_sizes = [
1895                            parent_tex_sz.0 as f32,
1896                            parent_tex_sz.1 as f32,
1897                            tmp_sz.0 as f32,
1898                            tmp_sz.1 as f32,
1899                        ];
1900                        cu.dst_rect = local_buf;
1901                        cu.src_rect = local_buf;
1902                        cu.clip_rect = [
1903                            clip_phys.x as f32 - parent_ox,
1904                            clip_phys.y as f32 - parent_oy,
1905                            clip_phys.right() as f32 - parent_ox,
1906                            clip_phys.bottom() as f32 - parent_oy,
1907                        ];
1908                        cu.body_rect = local_buf;
1909                        cu.params = [1.0, sq.blend_mode as u8 as f32, EFFECT_KIND_COMPOSITE, 0.0];
1910                        cu.set_color_matrix(None);
1911                        cu.inv_xform = [1.0, 0.0, 0.0, 1.0];
1912                        cu.extra = [0.0, 0.0, snap_sz.0 as f32, snap_sz.1 as f32];
1913                        let cslot = fx.push_slot(cu);
1914                        fx.steps.push(GpuPassStep::Effect {
1915                            dst_idx: parent_idx,
1916                            clear_dst: false,
1917                            src_idx: tmp_tex,
1918                            dst_snap_idx: snap_idx,
1919                            mask_path: None,
1920                            effect_slot: cslot,
1921                        });
1922                        fx.pool.release(tmp_tex);
1923                        fx.pool.release(snap_idx);
1924                    }
1925
1926                    // 外部零拷贝 GPU 纹理采样(直接消费外部引擎共享的 `wgpu::TextureView`)
1927                    DrawPayload::ExternalTexture(ext) => {
1928                        let raw_clip = viewport.intersect(op.clip).intersect(op.bounds);
1929                        if raw_clip.is_empty() {
1930                            continue;
1931                        }
1932                        if self.external_textures.contains_key(&ext.id) {
1933                            flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1934                            let parent = stack.last().unwrap();
1935                            let parent_idx = parent.tex_idx;
1936                            let parent_aw = parent.active_w;
1937                            let parent_ah = parent.active_h;
1938                            let parent_ox = parent.origin_x;
1939                            let parent_oy = parent.origin_y;
1940                            let parent_tex_sz =
1941                                (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1942
1943                            let snap_idx = fx.pool.acquire(device, parent_aw, parent_ah);
1944                            fx.steps.push(GpuPassStep::CopyRect {
1945                                src_idx: parent_idx,
1946                                src_origin: (0, 0),
1947                                dst_idx: snap_idx,
1948                                dst_origin: (0, 0),
1949                                size: (parent_aw, parent_ah),
1950                            });
1951                            let snap_sz =
1952                                (fx.pool.get(snap_idx).width, fx.pool.get(snap_idx).height);
1953
1954                            let body_phys = snap_bounds_region_scaled(op.bounds, sf);
1955                            let clip_phys = snap_clip_region_scaled(raw_clip, sf);
1956                            let local_body = [
1957                                body_phys.x as f32 - parent_ox,
1958                                body_phys.y as f32 - parent_oy,
1959                                body_phys.w as f32,
1960                                body_phys.h as f32,
1961                            ];
1962
1963                            let mut eu = EffectUniform::default();
1964                            eu.tex_sizes = [
1965                                parent_tex_sz.0 as f32,
1966                                parent_tex_sz.1 as f32,
1967                                1.0,
1968                                1.0,
1969                            ];
1970                            eu.dst_rect = local_body;
1971                            eu.src_rect = ext.uv_rect;
1972                            eu.clip_rect = [
1973                                clip_phys.x as f32 - parent_ox,
1974                                clip_phys.y as f32 - parent_oy,
1975                                clip_phys.right() as f32 - parent_ox,
1976                                clip_phys.bottom() as f32 - parent_oy,
1977                            ];
1978                            eu.body_rect = local_body;
1979                            eu.radii = [
1980                                (ext.radii.tl as f32) * sf,
1981                                (ext.radii.tr as f32) * sf,
1982                                (ext.radii.br as f32) * sf,
1983                                (ext.radii.bl as f32) * sf,
1984                            ];
1985                            eu.params = [
1986                                (ext.opacity as f32) * (1.0 / 255.0),
1987                                ext.blend_mode as u8 as f32,
1988                                EFFECT_KIND_EXTERNAL_TEX,
1989                                0.0,
1990                            ];
1991                            eu.flags = [
1992                                if ext.premultiplied { 1.0 } else { 0.0 },
1993                                0.0,
1994                                0.0,
1995                                if is_srgb { 1.0 } else { 0.0 },
1996                            ];
1997                            eu.inv_xform = [1.0, 0.0, 0.0, 1.0];
1998                            eu.extra = [0.0, 0.0, snap_sz.0 as f32, snap_sz.1 as f32];
1999                            let eslot = fx.push_slot(eu);
2000
2001                            fx.steps.push(GpuPassStep::DrawExternal {
2002                                dst_idx: parent_idx,
2003                                dst_snap_idx: snap_idx,
2004                                tex_id: ext.id,
2005                                effect_slot: eslot,
2006                            });
2007                            fx.pool.release(snap_idx);
2008                        } else if ext.fallback_bg.a() > 0 {
2009                            let fallback_sq = StyledQuad {
2010                                paint: Paint::Solid(ext.fallback_bg),
2011                                border_color: Color::TRANSPARENT,
2012                                border_width: 0,
2013                                radii: ext.radii,
2014                                opacity: ext.opacity,
2015                                blend_mode: BlendMode::SrcOver,
2016                                transform: None,
2017                            };
2018                            let tmp_op = DrawOp {
2019                                payload: DrawPayload::StyledQuad(&fallback_sq),
2020                                ..*op
2021                            };
2022                            let (ox, oy) = {
2023                                let top = stack.last().unwrap();
2024                                (top.origin_x, top.origin_y)
2025                            };
2026                            self.encode_single_op(
2027                                queue, &tmp_op, raw_clip, viewport, sf, use_ttf, ox, oy,
2028                            )?;
2029                        }
2030                    }
2031
2032                    _ => {
2033                        let raw_clip = match op.payload {
2034                            DrawPayload::StyledQuad(sq) if sq.transform.is_some() => {
2035                                viewport.intersect(op.clip)
2036                            }
2037                            _ => viewport.intersect(op.clip).intersect(op.bounds),
2038                        };
2039                        if raw_clip.is_empty() {
2040                            continue;
2041                        }
2042                        let (ox, oy) = {
2043                            let top = stack.last().unwrap();
2044                            (top.origin_x, top.origin_y)
2045                        };
2046                        self.encode_single_op(queue, op, raw_clip, viewport, sf, use_ttf, ox, oy)?;
2047                    }
2048                }
2049            }
2050
2051            // 冲刷根画布最后一批图元并 Blit 至外部 `target_view`
2052            flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
2053            let mut blit_u = EffectUniform::default();
2054            blit_u.tex_sizes = [pw as f32, ph as f32, root_tex_sz.0 as f32, root_tex_sz.1 as f32];
2055            blit_u.dst_rect = [0.0, 0.0, pw as f32, ph as f32];
2056            blit_u.src_rect = [0.0, 0.0, pw as f32, ph as f32];
2057            blit_u.params = [1.0, 0.0, EFFECT_KIND_BLIT, 0.0];
2058            let blit_slot = fx.push_slot(blit_u);
2059            fx.steps.push(GpuPassStep::BlitToTarget {
2060                src_idx: root_idx,
2061                effect_slot: blit_slot,
2062            });
2063            Ok(())
2064        })();
2065
2066        self.effects = Some(fx);
2067        result
2068    }
2069}