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    canvas_engine: Option<super::canvas_pipeline::CanvasGpuEngine>,
121    external_textures: HashMap<ExternalTextureId, ExternalTextureEntry>,
122    next_external_id: u32,
123    target_format: wgpu::TextureFormat,
124    primitives: Vec<GpuPrimitive>,
125    sprite_scratch: Vec<Rgba8888>,
126    #[cfg(not(target_endian = "little"))]
127    sprite_bytes_scratch: Vec<u8>,
128    text_layout_cache: HashMap<TextLayoutKey, Arc<CachedTextLayout>>,
129    text_layout_hits: u64,
130    target_is_srgb: bool,
131}
132
133impl WgpuRenderer {
134    /// 基于已有 `wgpu::Device` 与目标表面像素格式创建 2D SDF 渲染管线。
135    pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
136        let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
137        let t0 = std::time::Instant::now();
138        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
139            label: Some("velox_wgpu_2d_shader"),
140            source: wgpu::ShaderSource::Wgsl(SDF_WGSL.into()),
141        });
142        let t_shader = t0.elapsed();
143
144        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
145            label: Some("velox_wgpu_bgl"),
146            entries: &[
147                wgpu::BindGroupLayoutEntry {
148                    binding: 0,
149                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
150                    ty: wgpu::BindingType::Buffer {
151                        ty: wgpu::BufferBindingType::Uniform,
152                        has_dynamic_offset: true,
153                        min_binding_size: wgpu::BufferSize::new(
154                            core::mem::size_of::<ViewportUniform>() as u64,
155                        ),
156                    },
157                    count: None,
158                },
159                wgpu::BindGroupLayoutEntry {
160                    binding: 1,
161                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
162                    ty: wgpu::BindingType::Buffer {
163                        ty: wgpu::BufferBindingType::Storage { read_only: true },
164                        has_dynamic_offset: false,
165                        min_binding_size: None,
166                    },
167                    count: None,
168                },
169                wgpu::BindGroupLayoutEntry {
170                    binding: 2,
171                    visibility: wgpu::ShaderStages::FRAGMENT,
172                    ty: wgpu::BindingType::Texture {
173                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
174                        view_dimension: wgpu::TextureViewDimension::D2,
175                        multisampled: false,
176                    },
177                    count: None,
178                },
179                wgpu::BindGroupLayoutEntry {
180                    binding: 3,
181                    visibility: wgpu::ShaderStages::FRAGMENT,
182                    ty: wgpu::BindingType::Texture {
183                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
184                        view_dimension: wgpu::TextureViewDimension::D2,
185                        multisampled: false,
186                    },
187                    count: None,
188                },
189                wgpu::BindGroupLayoutEntry {
190                    binding: 4,
191                    visibility: wgpu::ShaderStages::FRAGMENT,
192                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
193                    count: None,
194                },
195                wgpu::BindGroupLayoutEntry {
196                    binding: 5,
197                    visibility: wgpu::ShaderStages::FRAGMENT,
198                    ty: wgpu::BindingType::Texture {
199                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
200                        view_dimension: wgpu::TextureViewDimension::D2,
201                        multisampled: false,
202                    },
203                    count: None,
204                },
205                wgpu::BindGroupLayoutEntry {
206                    binding: 6,
207                    visibility: wgpu::ShaderStages::FRAGMENT,
208                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
209                    count: None,
210                },
211            ],
212        });
213
214        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
215            label: Some("velox_wgpu_pipeline_layout"),
216            bind_group_layouts: &[Some(&bind_group_layout)],
217            immediate_size: 0,
218        });
219
220        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
221            label: Some("velox_wgpu_2d_pipeline"),
222            layout: Some(&pipeline_layout),
223            vertex: wgpu::VertexState {
224                module: &shader,
225                entry_point: Some("vs_main"),
226                compilation_options: wgpu::PipelineCompilationOptions::default(),
227                buffers: &[],
228            },
229            primitive: wgpu::PrimitiveState {
230                topology: wgpu::PrimitiveTopology::TriangleList,
231                strip_index_format: None,
232                front_face: wgpu::FrontFace::Ccw,
233                cull_mode: None,
234                unclipped_depth: false,
235                polygon_mode: wgpu::PolygonMode::Fill,
236                conservative: false,
237            },
238            depth_stencil: None,
239            multisample: wgpu::MultisampleState::default(),
240            fragment: Some(wgpu::FragmentState {
241                module: &shader,
242                entry_point: Some("fs_main"),
243                compilation_options: wgpu::PipelineCompilationOptions::default(),
244                targets: &[Some(wgpu::ColorTargetState {
245                    format: target_format,
246                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
247                    write_mask: wgpu::ColorWrites::ALL,
248                })],
249            }),
250            multiview_mask: None,
251            cache: None,
252        });
253        let t_pso = t0.elapsed();
254        if trace {
255            std::println!(
256                "[VELOX_STARTUP_TRACE]   pipeline detail: create_shader_module={:.1}ms, create_render_pipeline=+{:.1}ms",
257                t_shader.as_secs_f64() * 1000.0,
258                (t_pso - t_shader).as_secs_f64() * 1000.0,
259            );
260        }
261
262        let viewport_buf = Self::create_viewport_buffer(device, INIT_VIEWPORT_SLOTS);
263        let instance_buf = Self::create_instance_buffer(device, INITIAL_INSTANCE_CAPACITY);
264        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
265            label: Some("velox_atlas_sampler"),
266            address_mode_u: wgpu::AddressMode::ClampToEdge,
267            address_mode_v: wgpu::AddressMode::ClampToEdge,
268            address_mode_w: wgpu::AddressMode::ClampToEdge,
269            mag_filter: wgpu::FilterMode::Nearest,
270            min_filter: wgpu::FilterMode::Nearest,
271            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
272            ..Default::default()
273        });
274        let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
275            label: Some("velox_linear_sampler"),
276            address_mode_u: wgpu::AddressMode::ClampToEdge,
277            address_mode_v: wgpu::AddressMode::ClampToEdge,
278            address_mode_w: wgpu::AddressMode::ClampToEdge,
279            mag_filter: wgpu::FilterMode::Linear,
280            min_filter: wgpu::FilterMode::Linear,
281            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
282            ..Default::default()
283        });
284
285        let glyph_atlas = GlyphAtlas::new(device, GLYPH_ATLAS_INIT_SIZE);
286        let sprite_atlas = SpriteAtlas::new(device, 1);
287        let ramp_atlas = GradientRampAtlas::new(device);
288        let bind_group = Self::create_bind_group(
289            device,
290            &bind_group_layout,
291            &viewport_buf,
292            &instance_buf,
293            &glyph_atlas.view,
294            &sprite_atlas.view,
295            &sampler,
296            &ramp_atlas.view,
297            &linear_sampler,
298        );
299
300        Self {
301            pipeline,
302            bind_group_layout,
303            bind_group,
304            viewport_buf,
305            viewport_capacity: INIT_VIEWPORT_SLOTS,
306            viewport_slots: Vec::with_capacity(INIT_VIEWPORT_SLOTS),
307            instance_buf,
308            instance_capacity: INITIAL_INSTANCE_CAPACITY,
309            sampler,
310            linear_sampler,
311            glyph_atlas,
312            sprite_atlas,
313            ramp_atlas,
314            effects: None,
315            canvas_engine: None,
316            external_textures: HashMap::new(),
317            next_external_id: 1,
318            target_format,
319            primitives: Vec::with_capacity(INITIAL_INSTANCE_CAPACITY),
320            sprite_scratch: Vec::new(),
321            #[cfg(not(target_endian = "little"))]
322            sprite_bytes_scratch: Vec::new(),
323            text_layout_cache: HashMap::with_capacity(64),
324            text_layout_hits: 0,
325            target_is_srgb: target_format.is_srgb(),
326        }
327    }
328
329    fn create_viewport_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
330        device.create_buffer(&wgpu::BufferDescriptor {
331            label: Some("velox_wgpu_viewport"),
332            size: (capacity.max(1) * core::mem::size_of::<AlignedViewportSlot>()) as u64,
333            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
334            mapped_at_creation: false,
335        })
336    }
337
338    fn create_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
339        device.create_buffer(&wgpu::BufferDescriptor {
340            label: Some("velox_wgpu_instances"),
341            size: (capacity.max(1) * core::mem::size_of::<GpuPrimitive>()) as u64,
342            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
343            mapped_at_creation: false,
344        })
345    }
346
347    #[allow(clippy::too_many_arguments)]
348    fn create_bind_group(
349        device: &wgpu::Device,
350        layout: &wgpu::BindGroupLayout,
351        viewport_buf: &wgpu::Buffer,
352        instance_buf: &wgpu::Buffer,
353        glyph_view: &wgpu::TextureView,
354        sprite_view: &wgpu::TextureView,
355        sampler: &wgpu::Sampler,
356        ramp_view: &wgpu::TextureView,
357        linear_sampler: &wgpu::Sampler,
358    ) -> wgpu::BindGroup {
359        device.create_bind_group(&wgpu::BindGroupDescriptor {
360            label: Some("velox_wgpu_bg"),
361            layout,
362            entries: &[
363                wgpu::BindGroupEntry {
364                    binding: 0,
365                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
366                        buffer: viewport_buf,
367                        offset: 0,
368                        size: wgpu::BufferSize::new(core::mem::size_of::<ViewportUniform>() as u64),
369                    }),
370                },
371                wgpu::BindGroupEntry {
372                    binding: 1,
373                    resource: instance_buf.as_entire_binding(),
374                },
375                wgpu::BindGroupEntry {
376                    binding: 2,
377                    resource: wgpu::BindingResource::TextureView(glyph_view),
378                },
379                wgpu::BindGroupEntry {
380                    binding: 3,
381                    resource: wgpu::BindingResource::TextureView(sprite_view),
382                },
383                wgpu::BindGroupEntry {
384                    binding: 4,
385                    resource: wgpu::BindingResource::Sampler(sampler),
386                },
387                wgpu::BindGroupEntry {
388                    binding: 5,
389                    resource: wgpu::BindingResource::TextureView(ramp_view),
390                },
391                wgpu::BindGroupEntry {
392                    binding: 6,
393                    resource: wgpu::BindingResource::Sampler(linear_sampler),
394                },
395            ],
396        })
397    }
398
399    /// 返回最近一帧合批提交的 [`GpuPrimitive`] 实例数量。
400    #[inline]
401    pub fn last_primitive_count(&self) -> usize {
402        self.primitives.len()
403    }
404
405    /// 返回当前字形图集与精灵图集的物理像素边长 `(glyph_size, sprite_size)`。
406    #[inline]
407    pub const fn atlas_sizes(&self) -> (u32, u32) {
408        (self.glyph_atlas.width, self.sprite_atlas.width)
409    }
410
411    /// 返回静态精灵跨帧驻留缓存累计命中次数。
412    #[inline]
413    pub const fn sprite_cache_hits(&self) -> u64 {
414        self.sprite_atlas.cache_hits
415    }
416
417    /// 返回跨帧文本行排版缓存(`TextLayoutCache`)累计命中次数。
418    #[inline]
419    pub const fn text_layout_cache_hits(&self) -> u64 {
420        self.text_layout_hits
421    }
422
423    /// 返回跨帧文本行排版缓存当前驻留条目数。
424    #[inline]
425    pub fn text_layout_cache_len(&self) -> usize {
426        self.text_layout_cache.len()
427    }
428
429    /// 注册一张外部零拷贝 GPU 纹理(如海图、雷达、视频解码器或 3D 视口产出的 `wgpu::TextureView`),
430    /// 返回可供 `div().external_texture(id)` 或 `SurfaceCanvas` 引用的句柄 ID。
431    pub fn register_external_texture(
432        &mut self,
433        view: wgpu::TextureView,
434        sampler: Option<wgpu::Sampler>,
435    ) -> ExternalTextureId {
436        let mut id = self.next_external_id;
437        while id == 0 || self.external_textures.contains_key(&ExternalTextureId(id)) {
438            id = id.wrapping_add(1);
439        }
440        self.next_external_id = id.wrapping_add(1).max(1);
441        let tex_id = ExternalTextureId(id);
442        self.external_textures
443            .insert(tex_id, ExternalTextureEntry { view, sampler });
444        tex_id
445    }
446
447    /// 按显式 ID 注册或替换外部零拷贝 GPU 纹理(便于固定槽位号与跨语言 FFI 绑定)。
448    pub fn register_external_texture_with_id(
449        &mut self,
450        id: ExternalTextureId,
451        view: wgpu::TextureView,
452        sampler: Option<wgpu::Sampler>,
453    ) {
454        self.external_textures
455            .insert(id, ExternalTextureEntry { view, sampler });
456    }
457
458    /// 原地更新已注册外部纹理的 `wgpu::TextureView`(如外部引擎 Resize 或双缓冲翻页时调用)。
459    pub fn update_external_texture(&mut self, id: ExternalTextureId, view: wgpu::TextureView) -> bool {
460        if let Some(entry) = self.external_textures.get_mut(&id) {
461            entry.view = view;
462            true
463        } else {
464            false
465        }
466    }
467
468    /// 注销外部零拷贝纹理槽位并释放 `TextureView` 引用。
469    pub fn unregister_external_texture(&mut self, id: ExternalTextureId) -> bool {
470        self.external_textures.remove(&id).is_some()
471    }
472
473    /// 返回当前已注册的外部零拷贝 GPU 纹理数量。
474    #[inline]
475    pub fn external_texture_count(&self) -> usize {
476        self.external_textures.len()
477    }
478
479    fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
480        self.bind_group = Self::create_bind_group(
481            device,
482            &self.bind_group_layout,
483            &self.viewport_buf,
484            &self.instance_buf,
485            &self.glyph_atlas.view,
486            &self.sprite_atlas.view,
487            &self.sampler,
488            &self.ramp_atlas.view,
489            &self.linear_sampler,
490        );
491    }
492
493    #[inline]
494    fn sprite_cache_hash(sprite: SpriteSource<'_>, rel_x: i16, rel_y: i16, sb_w: i16, sb_h: i16) -> u64 {
495        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
496        let mix = |h: &mut u64, v: u64| {
497            *h ^= v;
498            *h = h.wrapping_mul(0x0100_0000_01b3);
499        };
500        mix(&mut h, ((rel_x as u16 as u64) << 16) | (rel_y as u16 as u64));
501        mix(&mut h, ((sb_w as u16 as u64) << 16) | (sb_h as u16 as u64));
502        match sprite {
503            SpriteSource::Bitmap {
504                bytes,
505                format,
506                tint,
507            } => {
508                mix(&mut h, 1);
509                mix(&mut h, bytes.as_ptr() as usize as u64);
510                mix(&mut h, bytes.len() as u64);
511                mix(&mut h, format as u64);
512                mix(&mut h, tint.0 as u64);
513            }
514            SpriteSource::Shader { state_hash, .. } => {
515                mix(&mut h, 2);
516                mix(&mut h, state_hash as u64);
517            }
518            SpriteSource::Svg {
519                source,
520                is_path_only,
521                tint,
522                stroke_width_x10,
523            } => {
524                mix(&mut h, 3);
525                mix(&mut h, if is_path_only { 1 } else { 0 });
526                mix(&mut h, stroke_width_x10 as u64);
527                mix(&mut h, tint.0 as u64);
528                let s = source.as_str().as_bytes();
529                mix(&mut h, s.len() as u64);
530                for &b in s {
531                    mix(&mut h, b as u64);
532                }
533            }
534            SpriteSource::Arc { .. } => {}
535        }
536        h
537    }
538
539    /// 将单条非图层 `DrawOp` 编码追加到 `self.primitives`,并将所有屏幕坐标减去 `(origin_x, origin_y)`。
540    #[allow(clippy::too_many_arguments)]
541    fn encode_single_op(
542        &mut self,
543        queue: &wgpu::Queue,
544        op: &DrawOp<'_>,
545        eff_clip: Region,
546        viewport: Region,
547        sf: f32,
548        use_ttf: bool,
549        origin_x: f32,
550        origin_y: f32,
551    ) -> Result<(), AtlasGrowNeed> {
552        let mut sb_f = snap_bounds(op.bounds, sf);
553        let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
554        let mut sc_f = snap_clip(clip_region, sf);
555        if (op.bounds.w == 1 && eff_clip.w == 1) || (op.bounds.h == 1 && eff_clip.h == 1) {
556            let vp_clip_f = snap_clip(viewport, sf);
557            if op.bounds.w == 1 && eff_clip.w == 1 {
558                sc_f[2] = sc_f[2].max(sb_f[0] + sb_f[2]).min(vp_clip_f[2]);
559            }
560            if op.bounds.h == 1 && eff_clip.h == 1 {
561                sc_f[3] = sc_f[3].max(sb_f[1] + sb_f[3]).min(vp_clip_f[3]);
562            }
563        }
564        let clip_radius_px = (op.clip_radius as f32) * sf;
565        let shifted_sb = [sb_f[0] - origin_x, sb_f[1] - origin_y, sb_f[2], sb_f[3]];
566        let shifted_sc = [
567            sc_f[0] - origin_x,
568            sc_f[1] - origin_y,
569            sc_f[2] - origin_x,
570            sc_f[3] - origin_y,
571        ];
572
573        match op.payload {
574            DrawPayload::Quad {
575                bg,
576                bg_grad,
577                border_color,
578                rounded,
579                border_width,
580            } => {
581                let raw_bw = border_width & 0x7F;
582                let bw = if raw_bw == 0 {
583                    0.0
584                } else {
585                    ((raw_bw as f32) * sf).round().max(1.0)
586                };
587                let horiz = (border_width & 0x80) != 0;
588                let r = (rounded as f32) * sf;
589                let is_shadow = border_color.a() == 0 && raw_bw > 0;
590                if is_shadow {
591                    if bg.a() > 0 {
592                        self.primitives.push(make_shadow_primitive(
593                            shifted_sb,
594                            shifted_sc,
595                            clip_radius_px,
596                            r,
597                            (raw_bw as f32) * sf,
598                            bg,
599                        ));
600                    }
601                } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0) {
602                    self.primitives.push(make_quad_primitive(
603                        shifted_sb,
604                        shifted_sc,
605                        clip_radius_px,
606                        r,
607                        bw,
608                        horiz,
609                        bg,
610                        bg_grad,
611                        border_color,
612                    ));
613                }
614            }
615            DrawPayload::StyledQuad(sq) => {
616                let ramp_v = match sq.paint {
617                    Paint::Solid(_) => None,
618                    Paint::LinearGradient { stops, space, .. }
619                    | Paint::RadialGradient { stops, space, .. }
620                    | Paint::ConicGradient { stops, space, .. } => {
621                        let Some(v) = self.ramp_atlas.get_or_insert(queue, stops, space, sq.opacity)
622                        else {
623                            return Err(AtlasGrowNeed {
624                                glyph_full: false,
625                                sprite_need: None,
626                                ramp_full: true,
627                            });
628                        };
629                        Some(v)
630                    }
631                };
632                if let Some(prim) = make_styled_quad_primitive(
633                    shifted_sb,
634                    shifted_sc,
635                    clip_radius_px,
636                    sq,
637                    sf,
638                    ramp_v,
639                ) {
640                    self.primitives.push(prim);
641                }
642            }
643            DrawPayload::TextRun {
644                text,
645                color,
646                font_size,
647                text_flags,
648            } => {
649                if text.is_empty() || color.a() == 0 {
650                    return Ok(());
651                }
652                let sb = Region::new(
653                    sb_f[0] as i16,
654                    sb_f[1] as i16,
655                    sb_f[2] as i16,
656                    sb_f[3] as i16,
657                );
658                let sc = Region::new(
659                    sc_f[0] as i16,
660                    sc_f[1] as i16,
661                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
662                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
663                );
664                let (adj_bounds, adj_sc, adj_flags, logical_fs, fs_q4) = compute_scaled_text_box(
665                    op.bounds,
666                    op.clip,
667                    viewport,
668                    sb,
669                    sc,
670                    text.as_str(),
671                    font_size,
672                    text_flags,
673                    sf,
674                );
675                let adj_sc_f = [
676                    adj_sc.x as f32 - origin_x,
677                    adj_sc.y as f32 - origin_y,
678                    adj_sc.right() as f32 - origin_x,
679                    adj_sc.bottom() as f32 - origin_y,
680                ];
681                let prim_before = self.primitives.len();
682                if !self.encode_text_run(
683                    queue,
684                    adj_bounds,
685                    adj_sc,
686                    adj_sc_f,
687                    clip_radius_px,
688                    text.as_str(),
689                    color,
690                    logical_fs,
691                    fs_q4,
692                    adj_flags,
693                    use_ttf,
694                ) {
695                    return Err(AtlasGrowNeed {
696                        glyph_full: true,
697                        sprite_need: None,
698                        ramp_full: false,
699                    });
700                }
701                if origin_x != 0.0 || origin_y != 0.0 {
702                    for p in &mut self.primitives[prim_before..] {
703                        p.bounds[0] -= origin_x;
704                        p.bounds[1] -= origin_y;
705                    }
706                }
707            }
708            DrawPayload::Sprite(SpriteSource::Arc {
709                thickness,
710                start_deg10,
711                sweep_deg10,
712                fill_sweep_deg10,
713                track_color,
714                fill_color,
715            }) => {
716                self.primitives.push(make_arc_primitive(
717                    shifted_sb,
718                    shifted_sc,
719                    clip_radius_px,
720                    ((thickness.max(1) as f32) * sf).max(1.5),
721                    start_deg10,
722                    sweep_deg10,
723                    fill_sweep_deg10,
724                    track_color,
725                    fill_color,
726                ));
727            }
728            DrawPayload::Sprite(sprite) => {
729                sb_f[0] = sb_f[0].round();
730                sb_f[1] = sb_f[1].round();
731                let sb = Region::new(
732                    sb_f[0] as i16,
733                    sb_f[1] as i16,
734                    sb_f[2] as i16,
735                    sb_f[3] as i16,
736                );
737                let sc = Region::new(
738                    sc_f[0] as i16,
739                    sc_f[1] as i16,
740                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
741                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
742                );
743                let eff = sc.intersect(sb);
744                if eff.is_empty() {
745                    return Ok(());
746                }
747                let w = eff.w.max(1) as usize;
748                let h = eff.h.max(1) as usize;
749                let cache_key = SpriteCacheKey {
750                    w: w as u32,
751                    h: h as u32,
752                    hash: Self::sprite_cache_hash(
753                        sprite,
754                        eff.x.saturating_sub(sb.x),
755                        eff.y.saturating_sub(sb.y),
756                        sb.w,
757                        sb.h,
758                    ),
759                };
760
761                let uv = if let Some(cached_uv) = self.sprite_atlas.lookup(cache_key) {
762                    cached_uv
763                } else {
764                    let len = w * h;
765                    if self.sprite_scratch.len() < len {
766                        self.sprite_scratch.resize(len, Rgba8888(0));
767                    }
768                    let slice = &mut self.sprite_scratch[..len];
769                    slice.fill(Rgba8888(0));
770                    rasterize_sprite_source(sb, eff, sprite, eff.x, eff.y, w, slice);
771
772                    #[cfg(target_endian = "little")]
773                    let rgba_bytes: &[u8] = pod_as_bytes(slice);
774                    #[cfg(not(target_endian = "little"))]
775                    let rgba_bytes: &[u8] = {
776                        self.sprite_bytes_scratch.clear();
777                        self.sprite_bytes_scratch.reserve(len * 4);
778                        for px in slice.iter() {
779                            self.sprite_bytes_scratch
780                                .extend_from_slice(&px.to_rgba_bytes());
781                        }
782                        &self.sprite_bytes_scratch
783                    };
784
785                    let Some(uv) = self
786                        .sprite_atlas
787                        .insert_and_upload(queue, cache_key, rgba_bytes)
788                    else {
789                        return Err(AtlasGrowNeed {
790                            glyph_full: false,
791                            sprite_need: Some((w as u32, h as u32)),
792                            ramp_full: false,
793                        });
794                    };
795                    uv
796                };
797
798                self.primitives.push(GpuPrimitive {
799                    bounds: [
800                        eff.x as f32 - origin_x,
801                        eff.y as f32 - origin_y,
802                        w as f32,
803                        h as f32,
804                    ],
805                    clip: shifted_sc,
806                    uv,
807                    color0: [1.0; 4],
808                    color1: [0.0; 4],
809                    border_color: [0.0; 4],
810                    params: [0.0, 0.0, KIND_SPRITE, 0.0],
811                    extra: [clip_radius_px, 0.0, 0.0, 0.0],
812                    radii: [0.0; 4],
813                    grad_a: [0.0; 4],
814                    grad_b: [0.0; 4],
815                    xform: IDENTITY_XFORM,
816                });
817            }
818            DrawPayload::RichText(rt) => {
819                let sb = snap_bounds_region_scaled(op.bounds, sf);
820                let sc = Region::new(
821                    sc_f[0] as i16,
822                    sc_f[1] as i16,
823                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
824                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
825                );
826                let eff = sc.intersect(sb);
827                if eff.is_empty() {
828                    return Ok(());
829                }
830                let w = eff.w.max(1) as usize;
831                let h = eff.h.max(1) as usize;
832                let mut kh: u32 = 0x5254_4558;
833                rt.mix_hash(&mut kh);
834                let hash = ((kh as u64) << 32)
835                    | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
836                        | (eff.y.saturating_sub(sb.y) as u16 as u64))
837                    ^ ((sf * 16.0).round() as u64);
838                let cache_key = SpriteCacheKey {
839                    w: w as u32,
840                    h: h as u32,
841                    hash,
842                };
843                let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
844                    cached
845                } else {
846                    let len = w * h;
847                    if self.sprite_scratch.len() < len {
848                        self.sprite_scratch.resize(len, Rgba8888(0));
849                    }
850                    let slice = &mut self.sprite_scratch[..len];
851                    slice.fill(Rgba8888(0));
852                    crate::renderers::software::rasterize_rich_text(
853                        rt, sb, eff, sf, eff.x, eff.y, w, slice,
854                    );
855                    let rgba_bytes = pod_as_bytes(slice);
856                    let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
857                    else {
858                        return Err(AtlasGrowNeed {
859                            glyph_full: false,
860                            sprite_need: Some((w as u32, h as u32)),
861                            ramp_full: false,
862                        });
863                    };
864                    u
865                };
866                self.primitives.push(GpuPrimitive {
867                    bounds: [
868                        eff.x as f32 - origin_x,
869                        eff.y as f32 - origin_y,
870                        w as f32,
871                        h as f32,
872                    ],
873                    clip: shifted_sc,
874                    uv,
875                    color0: [1.0; 4],
876                    color1: [0.0; 4],
877                    border_color: [0.0; 4],
878                    params: [0.0, 0.0, KIND_SPRITE, 0.0],
879                    extra: [clip_radius_px, 0.0, 0.0, 0.0],
880                    radii: [0.0; 4],
881                    grad_a: [0.0; 4],
882                    grad_b: [0.0; 4],
883                    xform: IDENTITY_XFORM,
884                });
885            }
886            DrawPayload::DecodedImage(img) => {
887                let sb = snap_bounds_region_scaled(op.bounds, sf);
888                let sc = Region::new(
889                    sc_f[0] as i16,
890                    sc_f[1] as i16,
891                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
892                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
893                );
894                let eff = sc.intersect(sb);
895                if eff.is_empty() {
896                    return Ok(());
897                }
898                let w = eff.w.max(1) as usize;
899                let h = eff.h.max(1) as usize;
900                let cache_rev = crate::image_pipeline::get_cached_image(img.id)
901                    .map(|p| p.revision)
902                    .unwrap_or(0);
903                let mut kh: u32 = 0x4449_4D47 ^ (cache_rev as u32);
904                img.mix_hash(&mut kh);
905                let hash = ((kh as u64) << 32)
906                    | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
907                        | (eff.y.saturating_sub(sb.y) as u16 as u64))
908                    ^ ((sf * 16.0).round() as u64);
909                let cache_key = SpriteCacheKey {
910                    w: w as u32,
911                    h: h as u32,
912                    hash,
913                };
914                let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
915                    cached
916                } else {
917                    let len = w * h;
918                    if self.sprite_scratch.len() < len {
919                        self.sprite_scratch.resize(len, Rgba8888(0));
920                    }
921                    let slice = &mut self.sprite_scratch[..len];
922                    slice.fill(Rgba8888(0));
923                    crate::renderers::software::rasterize_decoded_image(
924                        img, sb, eff, sf, eff.x, eff.y, w, slice,
925                    );
926                    let rgba_bytes = pod_as_bytes(slice);
927                    let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
928                    else {
929                        return Err(AtlasGrowNeed {
930                            glyph_full: false,
931                            sprite_need: Some((w as u32, h as u32)),
932                            ramp_full: false,
933                        });
934                    };
935                    u
936                };
937                self.primitives.push(GpuPrimitive {
938                    bounds: [
939                        eff.x as f32 - origin_x,
940                        eff.y as f32 - origin_y,
941                        w as f32,
942                        h as f32,
943                    ],
944                    clip: shifted_sc,
945                    uv,
946                    color0: [1.0; 4],
947                    color1: [0.0; 4],
948                    border_color: [0.0; 4],
949                    params: [0.0, 0.0, KIND_SPRITE, 0.0],
950                    extra: [clip_radius_px, 0.0, 0.0, 0.0],
951                    radii: [0.0; 4],
952                    grad_a: [0.0; 4],
953                    grad_b: [0.0; 4],
954                    xform: IDENTITY_XFORM,
955                });
956            }
957            DrawPayload::Vector(vec_spec) => {
958                let sb = snap_bounds_region_scaled(op.bounds, sf);
959                let sc = Region::new(
960                    sc_f[0] as i16,
961                    sc_f[1] as i16,
962                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
963                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
964                );
965                let eff = sc.intersect(sb);
966                if eff.is_empty() {
967                    return Ok(());
968                }
969                let w = eff.w.max(1) as usize;
970                let h = eff.h.max(1) as usize;
971                let mut kh: u32 = 0x5645_4354;
972                vec_spec.mix_hash(&mut kh);
973                let hash = ((kh as u64) << 32)
974                    | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
975                        | (eff.y.saturating_sub(sb.y) as u16 as u64))
976                    ^ ((sf * 16.0).round() as u64);
977                let cache_key = SpriteCacheKey {
978                    w: w as u32,
979                    h: h as u32,
980                    hash,
981                };
982                let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
983                    cached
984                } else {
985                    let len = w * h;
986                    if self.sprite_scratch.len() < len {
987                        self.sprite_scratch.resize(len, Rgba8888(0));
988                    }
989                    let slice = &mut self.sprite_scratch[..len];
990                    slice.fill(Rgba8888(0));
991                    crate::vector_canvas::rasterize_vector_spec(
992                        vec_spec, sb, eff, sf, eff.x, eff.y, w, slice,
993                    );
994                    let rgba_bytes = pod_as_bytes(slice);
995                    let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
996                    else {
997                        return Err(AtlasGrowNeed {
998                            glyph_full: false,
999                            sprite_need: Some((w as u32, h as u32)),
1000                            ramp_full: false,
1001                        });
1002                    };
1003                    u
1004                };
1005                self.primitives.push(GpuPrimitive {
1006                    bounds: [
1007                        eff.x as f32 - origin_x,
1008                        eff.y as f32 - origin_y,
1009                        w as f32,
1010                        h as f32,
1011                    ],
1012                    clip: shifted_sc,
1013                    uv,
1014                    color0: [1.0; 4],
1015                    color1: [0.0; 4],
1016                    border_color: [0.0; 4],
1017                    params: [0.0, 0.0, KIND_SPRITE, 0.0],
1018                    extra: [clip_radius_px, 0.0, 0.0, 0.0],
1019                    radii: [0.0; 4],
1020                    grad_a: [0.0; 4],
1021                    grad_b: [0.0; 4],
1022                    xform: IDENTITY_XFORM,
1023                });
1024            }
1025            DrawPayload::SceneCanvas(spec) => {
1026                // 隔离图层/多 Pass 兜底路径:通过软件光栅同步到精灵图集以保持与复杂混合模式兼容
1027                let sb = snap_bounds_region_scaled(op.bounds, sf);
1028                let sc = Region::new(
1029                    sc_f[0] as i16,
1030                    sc_f[1] as i16,
1031                    (sc_f[2] - sc_f[0]).max(0.0) as i16,
1032                    (sc_f[3] - sc_f[1]).max(0.0) as i16,
1033                );
1034                let eff = sc.intersect(sb);
1035                if eff.is_empty() {
1036                    return Ok(());
1037                }
1038                let w = eff.w.max(1) as usize;
1039                let h = eff.h.max(1) as usize;
1040                let hash = ((spec.content_hash() as u64) << 32)
1041                    | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
1042                        | (eff.y.saturating_sub(sb.y) as u16 as u64))
1043                    ^ ((sf * 16.0).round() as u64);
1044                let cache_key = SpriteCacheKey {
1045                    w: w as u32,
1046                    h: h as u32,
1047                    hash,
1048                };
1049                let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
1050                    cached
1051                } else {
1052                    let len = w * h;
1053                    if self.sprite_scratch.len() < len {
1054                        self.sprite_scratch.resize(len, Rgba8888(0));
1055                    }
1056                    let slice = &mut self.sprite_scratch[..len];
1057                    slice.fill(Rgba8888(0));
1058                    crate::canvas_scene::rasterize_scene_canvas(
1059                        sb, eff, spec, sf, eff.x, eff.y, w, slice,
1060                    );
1061                    let rgba_bytes = pod_as_bytes(slice);
1062                    let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
1063                    else {
1064                        return Err(AtlasGrowNeed {
1065                            glyph_full: false,
1066                            sprite_need: Some((w as u32, h as u32)),
1067                            ramp_full: false,
1068                        });
1069                    };
1070                    u
1071                };
1072                self.primitives.push(GpuPrimitive {
1073                    bounds: [
1074                        eff.x as f32 - origin_x,
1075                        eff.y as f32 - origin_y,
1076                        w as f32,
1077                        h as f32,
1078                    ],
1079                    clip: shifted_sc,
1080                    uv,
1081                    color0: [1.0; 4],
1082                    color1: [0.0; 4],
1083                    border_color: [0.0; 4],
1084                    params: [0.0, 0.0, KIND_SPRITE, 0.0],
1085                    extra: [clip_radius_px, 0.0, 0.0, 0.0],
1086                    radii: [0.0; 4],
1087                    grad_a: [0.0; 4],
1088                    grad_b: [0.0; 4],
1089                    xform: IDENTITY_XFORM,
1090                });
1091            }
1092            DrawPayload::PushLayer(_)
1093            | DrawPayload::PopLayer
1094            | DrawPayload::ExternalTexture(_) => {}
1095        }
1096        Ok(())
1097    }
1098
1099    /// 单 Pass 无图层快路径:将 `DrawOp` 编码为 `self.primitives` 并按需上传字形、精灵与渐变图集。
1100    fn try_encode_ops(
1101        &mut self,
1102        queue: &wgpu::Queue,
1103        ops: &[DrawOp<'_>],
1104        viewport: Region,
1105        scale_factor: f32,
1106    ) -> Result<(), AtlasGrowNeed> {
1107        self.primitives.clear();
1108        if viewport.is_empty() {
1109            return Ok(());
1110        }
1111
1112        let sf = scale_factor.clamp(0.5, 4.0);
1113        let use_ttf = crate::display::ttf_atlas::has_system_font();
1114
1115        for (idx, op) in ops.iter().enumerate() {
1116            let raw_clip = match op.payload {
1117                DrawPayload::StyledQuad(sq) if sq.transform.is_some() => viewport.intersect(op.clip),
1118                _ => viewport.intersect(op.clip).intersect(op.bounds),
1119            };
1120            if raw_clip.is_empty() {
1121                continue;
1122            }
1123            let eff_clip = compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]);
1124            if eff_clip.is_empty() {
1125                continue;
1126            }
1127            self.encode_single_op(queue, op, eff_clip, viewport, sf, use_ttf, 0.0, 0.0)?;
1128        }
1129        Ok(())
1130    }
1131
1132    fn get_or_build_text_layout(
1133        &mut self,
1134        text: &str,
1135        logical_font_size: u8,
1136        font_size_q4: u16,
1137        max_width: i16,
1138        text_flags: u8,
1139        use_ttf: bool,
1140    ) -> Arc<CachedTextLayout> {
1141        let logical_fs = logical_font_size.max(8);
1142        let q4 = font_size_q4.clamp(32, 1020);
1143        let key = TextLayoutKey {
1144            text_hash: hash_layout_text(text),
1145            text_len: text.len() as u32,
1146            logical_font_size: logical_fs,
1147            font_size_q4: q4,
1148            max_width,
1149            text_flags,
1150            use_ttf,
1151        };
1152        if let Some(hit) = self.text_layout_cache.get(&key) {
1153            if hit.text.as_str() == text {
1154                self.text_layout_hits = self.text_layout_hits.wrapping_add(1);
1155                return Arc::clone(hit);
1156            }
1157        }
1158
1159        let render_fs = (q4 as f32) * 0.25;
1160        let fs_u8 = ((q4 + 2) >> 2).clamp(8, 255) as u8;
1161        let scale_ratio = render_fs / (logical_fs as f32);
1162        let is_ellipsis = (text_flags & 0x04) != 0;
1163        let is_nowrap = (text_flags & 0x08) != 0;
1164        let lines = if use_ttf {
1165            let logical_max_w = ((max_width as f32) / scale_ratio)
1166                .round()
1167                .clamp(1.0, i16::MAX as f32) as i16;
1168            split_text_lines(text, logical_fs, logical_max_w, is_nowrap || is_ellipsis)
1169        } else {
1170            split_text_lines(text, fs_u8, max_width, is_nowrap || is_ellipsis)
1171        };
1172        let line_count = lines.len();
1173        let char_h = if use_ttf {
1174            (render_fs.round() as i16).max(8)
1175        } else {
1176            (fs_u8 as i16).max(8)
1177        };
1178        let line_step = if use_ttf {
1179            ((render_fs * 1.25).round() as i16).max(char_h)
1180        } else {
1181            ((fs_u8 as i16) * 5 / 4).max(char_h)
1182        };
1183        let ascent = if use_ttf {
1184            crate::display::ttf_atlas::get_font_ascent_f32(render_fs) as i16
1185        } else {
1186            char_h
1187        };
1188        let dot_w = measure_char_advance('.', fs_u8);
1189        let dot_adv_f = if use_ttf {
1190            crate::display::ttf_atlas::measure_ttf_char_advance_f32('.', logical_fs)
1191                .map(|a| a * scale_ratio)
1192                .unwrap_or(dot_w as f32)
1193        } else {
1194            dot_w as f32
1195        };
1196        let total_h = if line_count == 0 {
1197            0
1198        } else {
1199            char_h.saturating_add(line_step.saturating_mul((line_count as i16) - 1))
1200        };
1201
1202        let mut glyphs = Vec::with_capacity(text.len().min(128));
1203        for (line_idx, &(b_start, b_end, raw_line_w_orig)) in lines.as_slice().iter().enumerate() {
1204            let line_str = &text[b_start..b_end];
1205            let raw_line_w = if use_ttf {
1206                (crate::display::measure_line_width_f32(line_str, logical_fs) * scale_ratio).ceil()
1207                    as i16
1208            } else {
1209                raw_line_w_orig
1210            };
1211            let need_ellipsis = is_ellipsis && raw_line_w > max_width && max_width > dot_w * 3;
1212            let eff_w = if need_ellipsis {
1213                max_width
1214            } else {
1215                raw_line_w.min(max_width)
1216            };
1217            let start_rel_x = align_offset_x(max_width, eff_w, text_flags);
1218            let rel_y = if use_ttf {
1219                ascent.saturating_add((line_idx as i16).saturating_mul(line_step))
1220            } else {
1221                (line_idx as i16).saturating_mul(line_step)
1222            };
1223
1224            if use_ttf {
1225                let mut pen_x = start_rel_x as f32;
1226                let max_x_before_dots_f = (max_width as f32) - dot_adv_f * 3.0;
1227                let mut prev_ch: Option<char> = None;
1228                for ch in line_str.chars() {
1229                    if let Some(p) = prev_ch {
1230                        pen_x += crate::display::ttf_atlas::measure_ttf_kerning_f32(
1231                            p, ch, logical_fs,
1232                        ) * scale_ratio;
1233                    }
1234                    let adv_f =
1235                        crate::display::ttf_atlas::measure_ttf_char_advance_f32(ch, logical_fs)
1236                            .map(|a| a * scale_ratio)
1237                            .unwrap_or_else(|| {
1238                                (measure_char_advance(ch, logical_fs) as f32) * scale_ratio
1239                            });
1240                    if need_ellipsis && pen_x + adv_f > max_x_before_dots_f + 0.01 {
1241                        for _ in 0..3 {
1242                            glyphs.push(ShapedGlyphPos {
1243                                ch: '.',
1244                                rel_x: pen_x.round() as i16,
1245                                rel_y,
1246                            });
1247                            pen_x += dot_adv_f;
1248                        }
1249                        break;
1250                    }
1251                    if ch != ' ' {
1252                        glyphs.push(ShapedGlyphPos {
1253                            ch,
1254                            rel_x: pen_x.round() as i16,
1255                            rel_y,
1256                        });
1257                    }
1258                    pen_x += adv_f;
1259                    prev_ch = Some(ch);
1260                }
1261            } else {
1262                let mut rel_x = start_rel_x;
1263                let max_x_before_dots = max_width.saturating_sub(dot_w * 3);
1264                let mut prev_ch: Option<char> = None;
1265                for ch in line_str.chars() {
1266                    if let Some(p) = prev_ch {
1267                        rel_x = rel_x.saturating_add(measure_char_kerning(p, ch, fs_u8));
1268                    }
1269                    let adv = measure_char_advance(ch, fs_u8);
1270                    if need_ellipsis && rel_x.saturating_add(adv) > max_x_before_dots {
1271                        for _ in 0..3 {
1272                            glyphs.push(ShapedGlyphPos {
1273                                ch: '.',
1274                                rel_x,
1275                                rel_y,
1276                            });
1277                            rel_x = rel_x.saturating_add(dot_w);
1278                        }
1279                        break;
1280                    }
1281                    if ch != ' ' {
1282                        glyphs.push(ShapedGlyphPos { ch, rel_x, rel_y });
1283                    }
1284                    rel_x = rel_x.saturating_add(adv);
1285                    prev_ch = Some(ch);
1286                }
1287            }
1288        }
1289
1290        let built = Arc::new(CachedTextLayout {
1291            text: String::from(text),
1292            total_h,
1293            glyphs,
1294        });
1295        if self.text_layout_cache.len() >= MAX_TEXT_LAYOUT_CACHE_ENTRIES {
1296            self.text_layout_cache.clear();
1297        }
1298        self.text_layout_cache.insert(key, Arc::clone(&built));
1299        built
1300    }
1301
1302    #[allow(clippy::too_many_arguments)]
1303    fn encode_text_run(
1304        &mut self,
1305        queue: &wgpu::Queue,
1306        bounds: Region,
1307        clip: Region,
1308        clip_f32: [f32; 4],
1309        clip_radius_px: f32,
1310        text: &str,
1311        color: Color,
1312        logical_font_size: u8,
1313        font_size_q4: u16,
1314        text_flags: u8,
1315        use_ttf: bool,
1316    ) -> bool {
1317        let layout = self.get_or_build_text_layout(
1318            text,
1319            logical_font_size,
1320            font_size_q4,
1321            bounds.w,
1322            text_flags,
1323            use_ttf,
1324        );
1325        if layout.glyphs.is_empty() {
1326            return true;
1327        }
1328        let top_y = bounds
1329            .y
1330            .saturating_add(bounds.h.saturating_sub(layout.total_h).max(0) >> 1);
1331        let col_f32 = color_to_f32(color);
1332
1333        for g in &layout.glyphs {
1334            let Some(entry) = self
1335                .glyph_atlas
1336                .get_or_insert(queue, g.ch, font_size_q4, use_ttf)
1337            else {
1338                return false;
1339            };
1340            if entry.width > 0 && entry.height > 0 {
1341                let gx = bounds
1342                    .x
1343                    .saturating_add(g.rel_x)
1344                    .saturating_add(entry.xmin);
1345                let gy = if use_ttf {
1346                    top_y
1347                        .saturating_add(g.rel_y)
1348                        .saturating_sub(entry.height)
1349                        .saturating_sub(entry.ymin)
1350                } else {
1351                    top_y.saturating_add(g.rel_y)
1352                };
1353                let greg = Region::new(gx, gy, entry.width, entry.height);
1354                if !clip.intersect(greg).is_empty() {
1355                    self.primitives.push(GpuPrimitive {
1356                        bounds: [
1357                            gx as f32,
1358                            gy as f32,
1359                            entry.width as f32,
1360                            entry.height as f32,
1361                        ],
1362                        clip: clip_f32,
1363                        uv: entry.uv,
1364                        color0: col_f32,
1365                        color1: [0.0; 4],
1366                        border_color: [0.0; 4],
1367                        params: [0.0, 0.0, KIND_GLYPH, 0.0],
1368                        extra: [clip_radius_px, 0.0, 0.0, 0.0],
1369                        radii: [0.0; 4],
1370                        grad_a: [0.0; 4],
1371                        grad_b: [0.0; 4],
1372                        xform: IDENTITY_XFORM,
1373                    });
1374                }
1375            }
1376        }
1377        true
1378    }
1379
1380    fn handle_atlas_grow(&mut self, device: &wgpu::Device, need: AtlasGrowNeed) -> (bool, bool) {
1381        let mut dirty = false;
1382        let mut can_retry = true;
1383        if need.glyph_full && self.glyph_atlas.reset_or_grow(device) {
1384            dirty = true;
1385        }
1386        if need.ramp_full && self.ramp_atlas.reset_or_grow(device) {
1387            dirty = true;
1388        }
1389        if let Some((sw, sh)) = need.sprite_need {
1390            let (recreated, retry) = self.sprite_atlas.reset_or_grow(device, sw, sh);
1391            if recreated {
1392                dirty = true;
1393            }
1394            if !retry {
1395                can_retry = false;
1396            }
1397        }
1398        (dirty, can_retry)
1399    }
1400
1401    /// 将当前帧 `ops` 直接渲染至目标 `target_view`:
1402    /// - 无图层/混合模式时走单 RenderPass / 单 Draw Call 直出快路径(0 离屏拷贝);
1403    /// - 含 `PushLayer` / 混合 / 毛玻璃 / 滤镜时自动通过 `GpuEffectsEngine` 在单 `CommandEncoder` 内完成多 Pass 离屏合成。
1404    #[allow(clippy::too_many_arguments)]
1405    pub fn render_to_view(
1406        &mut self,
1407        device: &wgpu::Device,
1408        queue: &wgpu::Queue,
1409        ops: &[DrawOp<'_>],
1410        viewport: Region,
1411        scale_factor: f32,
1412        target_view: &wgpu::TextureView,
1413        phys_width: u32,
1414        phys_height: u32,
1415        clear_color: wgpu::Color,
1416    ) {
1417        if ops_have_layers_or_blend(ops) && !viewport.is_empty() {
1418            self.render_to_view_multi_pass(
1419                device,
1420                queue,
1421                ops,
1422                viewport,
1423                scale_factor,
1424                target_view,
1425                phys_width,
1426                phys_height,
1427                clear_color,
1428            );
1429            return;
1430        }
1431
1432        if ops
1433            .iter()
1434            .any(|op| matches!(op.payload, DrawPayload::SceneCanvas(_)))
1435            && !viewport.is_empty()
1436        {
1437            self.render_to_view_with_scene_canvas(
1438                device,
1439                queue,
1440                ops,
1441                viewport,
1442                scale_factor,
1443                target_view,
1444                phys_width,
1445                phys_height,
1446                clear_color,
1447            );
1448            return;
1449        }
1450
1451        let mut bind_group_dirty = false;
1452        for _attempt in 0..4 {
1453            match self.try_encode_ops(queue, ops, viewport, scale_factor) {
1454                Ok(()) => break,
1455                Err(need) => {
1456                    let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1457                    if dirty {
1458                        bind_group_dirty = true;
1459                    }
1460                    if !can_retry {
1461                        break;
1462                    }
1463                }
1464            }
1465        }
1466
1467        if self.primitives.len() > self.instance_capacity {
1468            self.instance_capacity = self.primitives.len().next_power_of_two();
1469            self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1470            bind_group_dirty = true;
1471        }
1472        if bind_group_dirty {
1473            self.rebuild_bind_group(device);
1474        }
1475
1476        let slot0 = AlignedViewportSlot {
1477            uniform: ViewportUniform {
1478                size: [phys_width.max(1) as f32, phys_height.max(1) as f32],
1479                is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
1480                _pad: 0.0,
1481            },
1482            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1483        };
1484        queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
1485
1486        if !self.primitives.is_empty() {
1487            queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1488        }
1489
1490        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1491            label: Some("velox_wgpu_render_encoder"),
1492        });
1493        {
1494            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1495                label: Some("velox_wgpu_render_pass"),
1496                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1497                    view: target_view,
1498                    depth_slice: None,
1499                    resolve_target: None,
1500                    ops: wgpu::Operations {
1501                        load: wgpu::LoadOp::Clear(clear_color),
1502                        store: wgpu::StoreOp::Store,
1503                    },
1504                })],
1505                depth_stencil_attachment: None,
1506                occlusion_query_set: None,
1507                timestamp_writes: None,
1508                multiview_mask: None,
1509            });
1510            if !self.primitives.is_empty() {
1511                rpass.set_pipeline(&self.pipeline);
1512                rpass.set_bind_group(0, &self.bind_group, &[0]);
1513                rpass.draw(0..6, 0..(self.primitives.len() as u32));
1514            }
1515        }
1516        queue.submit([encoder.finish()]);
1517    }
1518
1519    /// 面向持久离屏画布的 GPU 硬件脏区 Scissor 局部增量渲染(仅重绘 `dirty_regions` 覆盖的物理像素,保留未脏区域以压低 4K 功耗)。
1520    ///
1521    /// 若本帧包含复杂离屏图层/毛玻璃或 `dirty_regions` 为空,自动无缝回退至标准整帧 `render_to_view`。
1522    #[allow(clippy::too_many_arguments)]
1523    pub fn render_to_view_dirty(
1524        &mut self,
1525        device: &wgpu::Device,
1526        queue: &wgpu::Queue,
1527        ops: &[DrawOp<'_>],
1528        viewport: Region,
1529        scale_factor: f32,
1530        target_view: &wgpu::TextureView,
1531        phys_width: u32,
1532        phys_height: u32,
1533        dirty_regions: &[Region],
1534        clear_color: wgpu::Color,
1535    ) {
1536        if dirty_regions.is_empty()
1537            || crate::renderers::software::ops_have_layers_or_blend(ops)
1538            || ops
1539                .iter()
1540                .any(|op| matches!(op.payload, DrawPayload::SceneCanvas(_)))
1541        {
1542            self.render_to_view(
1543                device,
1544                queue,
1545                ops,
1546                viewport,
1547                scale_factor,
1548                target_view,
1549                phys_width,
1550                phys_height,
1551                clear_color,
1552            );
1553            return;
1554        }
1555        let sf = scale_factor.clamp(0.5, 4.0);
1556        let pw = phys_width.max(1);
1557        let ph = phys_height.max(1);
1558
1559        let mut bind_group_dirty = false;
1560        for _attempt in 0..4 {
1561            match self.try_encode_ops(queue, ops, viewport, sf) {
1562                Ok(()) => break,
1563                Err(need) => {
1564                    let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1565                    if dirty {
1566                        bind_group_dirty = true;
1567                    }
1568                    if !can_retry {
1569                        break;
1570                    }
1571                }
1572            }
1573        }
1574        if self.primitives.len() > self.instance_capacity {
1575            self.instance_capacity = self.primitives.len().next_power_of_two();
1576            self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1577            bind_group_dirty = true;
1578        }
1579        if bind_group_dirty {
1580            self.rebuild_bind_group(device);
1581        }
1582
1583        let slot0 = AlignedViewportSlot {
1584            uniform: ViewportUniform {
1585                size: [pw as f32, ph as f32],
1586                is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
1587                _pad: 0.0,
1588            },
1589            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1590        };
1591        queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
1592        if !self.primitives.is_empty() {
1593            queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1594        }
1595
1596        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1597            label: Some("velox_wgpu_dirty_scissor_encoder"),
1598        });
1599        {
1600            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1601                label: Some("velox_wgpu_dirty_scissor_pass"),
1602                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1603                    view: target_view,
1604                    depth_slice: None,
1605                    resolve_target: None,
1606                    ops: wgpu::Operations {
1607                        load: wgpu::LoadOp::Load,
1608                        store: wgpu::StoreOp::Store,
1609                    },
1610                })],
1611                depth_stencil_attachment: None,
1612                occlusion_query_set: None,
1613                timestamp_writes: None,
1614                multiview_mask: None,
1615            });
1616            if !self.primitives.is_empty() {
1617                rpass.set_pipeline(&self.pipeline);
1618                rpass.set_bind_group(0, &self.bind_group, &[0]);
1619                for &d in dirty_regions {
1620                    let pd = snap_clip_region_scaled(d.intersect(viewport), sf);
1621                    let sx = (pd.x.max(0) as u32).min(pw);
1622                    let sy = (pd.y.max(0) as u32).min(ph);
1623                    let sw = (pd.w.max(0) as u32).min(pw.saturating_sub(sx));
1624                    let sh = (pd.h.max(0) as u32).min(ph.saturating_sub(sy));
1625                    if sw > 0 && sh > 0 {
1626                        rpass.set_scissor_rect(sx, sy, sw, sh);
1627                        rpass.draw(0..6, 0..(self.primitives.len() as u32));
1628                    }
1629                }
1630            }
1631        }
1632        queue.submit([encoder.finish()]);
1633    }
1634
1635    #[allow(clippy::too_many_arguments)]
1636    fn render_to_view_multi_pass(
1637        &mut self,
1638        device: &wgpu::Device,
1639        queue: &wgpu::Queue,
1640        ops: &[DrawOp<'_>],
1641        viewport: Region,
1642        scale_factor: f32,
1643        target_view: &wgpu::TextureView,
1644        phys_width: u32,
1645        phys_height: u32,
1646        clear_color: wgpu::Color,
1647    ) {
1648        let pw = phys_width.max(1);
1649        let ph = phys_height.max(1);
1650        let sf = scale_factor.clamp(0.5, 4.0);
1651        let use_ttf = crate::display::ttf_atlas::has_system_font();
1652        let is_srgb = self.target_is_srgb;
1653
1654        if self.effects.is_none() {
1655            self.effects = Some(GpuEffectsEngine::new(device, queue, self.target_format));
1656        }
1657
1658        let mut bind_group_dirty = false;
1659        for _attempt in 0..4 {
1660            match self.try_plan_multi_pass(device, queue, ops, viewport, sf, use_ttf, pw, ph, clear_color, is_srgb) {
1661                Ok(()) => break,
1662                Err(need) => {
1663                    let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1664                    if dirty {
1665                        bind_group_dirty = true;
1666                    }
1667                    if !can_retry {
1668                        break;
1669                    }
1670                }
1671            }
1672        }
1673
1674        if self.primitives.len() > self.instance_capacity {
1675            self.instance_capacity = self.primitives.len().next_power_of_two();
1676            self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1677            bind_group_dirty = true;
1678        }
1679        if self.viewport_slots.len() > self.viewport_capacity {
1680            self.viewport_capacity = self.viewport_slots.len().next_power_of_two();
1681            self.viewport_buf = Self::create_viewport_buffer(device, self.viewport_capacity);
1682            bind_group_dirty = true;
1683        }
1684        if bind_group_dirty {
1685            self.rebuild_bind_group(device);
1686        }
1687
1688        if !self.viewport_slots.is_empty() {
1689            queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&self.viewport_slots));
1690        }
1691        if !self.primitives.is_empty() {
1692            queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1693        }
1694
1695        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1696            label: Some("velox_wgpu_multi_pass_encoder"),
1697        });
1698        if let Some(ref mut fx) = self.effects {
1699            fx.execute_steps(
1700                device,
1701                queue,
1702                &mut encoder,
1703                &self.pipeline,
1704                &self.bind_group,
1705                &self.linear_sampler,
1706                &self.external_textures,
1707                target_view,
1708            );
1709        }
1710        queue.submit([encoder.finish()]);
1711    }
1712
1713    #[allow(clippy::too_many_arguments)]
1714    fn try_plan_multi_pass(
1715        &mut self,
1716        device: &wgpu::Device,
1717        queue: &wgpu::Queue,
1718        ops: &[DrawOp<'_>],
1719        viewport: Region,
1720        sf: f32,
1721        use_ttf: bool,
1722        pw: u32,
1723        ph: u32,
1724        clear_color: wgpu::Color,
1725        is_srgb: bool,
1726    ) -> Result<(), AtlasGrowNeed> {
1727        struct LayerFrame<'a> {
1728            tex_idx: usize,
1729            active_w: u32,
1730            active_h: u32,
1731            origin_x: f32,
1732            origin_y: f32,
1733            viewport_slot: u32,
1734            cleared: bool,
1735            clear_col: wgpu::Color,
1736            batch_start: u32,
1737            spec: Option<&'a LayerSpec<'a>>,
1738            body_phys: Region,
1739            buf_rect: Region,
1740            parent_clip_phys: Region,
1741        }
1742
1743        self.primitives.clear();
1744        self.viewport_slots.clear();
1745        let mut fx = self.effects.take().expect("effects engine initialized");
1746        fx.begin_frame();
1747
1748        let root_idx = fx.pool.acquire(device, pw, ph);
1749        let root_tex_sz = (fx.pool.get(root_idx).width, fx.pool.get(root_idx).height);
1750        let root_vp_slot = 0u32;
1751        self.viewport_slots.push(AlignedViewportSlot {
1752            uniform: ViewportUniform {
1753                size: [root_tex_sz.0 as f32, root_tex_sz.1 as f32],
1754                is_srgb: if is_srgb { 1.0 } else { 0.0 },
1755                _pad: 0.0,
1756            },
1757            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1758        });
1759
1760        let mut stack: Vec<LayerFrame<'_>> = Vec::with_capacity(8);
1761        stack.push(LayerFrame {
1762            tex_idx: root_idx,
1763            active_w: pw,
1764            active_h: ph,
1765            origin_x: 0.0,
1766            origin_y: 0.0,
1767            viewport_slot: root_vp_slot,
1768            cleared: false,
1769            clear_col: clear_color,
1770            batch_start: 0,
1771            spec: None,
1772            body_phys: Region::new(0, 0, pw as i16, ph as i16),
1773            buf_rect: Region::new(0, 0, pw as i16, ph as i16),
1774            parent_clip_phys: Region::new(0, 0, pw as i16, ph as i16),
1775        });
1776
1777        let flush_top = |stack: &mut [LayerFrame<'_>], fx: &mut GpuEffectsEngine, prim_len: u32| {
1778            let Some(top) = stack.last_mut() else {
1779                return;
1780            };
1781            if !top.cleared || prim_len > top.batch_start {
1782                let clear = if !top.cleared {
1783                    top.cleared = true;
1784                    Some(top.clear_col)
1785                } else {
1786                    None
1787                };
1788                fx.steps.push(GpuPassStep::DrawBatch {
1789                    target_idx: top.tex_idx,
1790                    clear,
1791                    viewport_slot: top.viewport_slot,
1792                    prim_start: top.batch_start,
1793                    prim_end: prim_len,
1794                });
1795                top.batch_start = prim_len;
1796            }
1797        };
1798
1799        let result: Result<(), AtlasGrowNeed> = (|| {
1800            for op in ops {
1801                match op.payload {
1802                    DrawPayload::PushLayer(spec) => {
1803                        flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1804                        let parent = stack.last().unwrap();
1805                        let parent_idx = parent.tex_idx;
1806                        let parent_aw = parent.active_w;
1807                        let parent_ah = parent.active_h;
1808                        let parent_ox = parent.origin_x;
1809                        let parent_oy = parent.origin_y;
1810                        let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1811
1812                        let body_phys = snap_bounds_region_scaled(spec.bounds, sf);
1813                        let parent_clip_phys = snap_clip_region_scaled(op.clip, sf);
1814
1815                        // 1. 实时毛玻璃 `backdrop-filter`
1816                        if !spec.backdrop_filter.is_empty() && !body_phys.is_empty() {
1817                            let bd = spec.backdrop_filter;
1818                            let blur_px = (bd.blur_radius as f32) * sf;
1819                            let pad = (blur_px * 2.0).ceil() as i16;
1820                            let local_body = Region::new(
1821                                body_phys.x.saturating_sub(parent_ox as i16),
1822                                body_phys.y.saturating_sub(parent_oy as i16),
1823                                body_phys.w,
1824                                body_phys.h,
1825                            );
1826                            let raw_sample = Region::new(
1827                                local_body.x.saturating_sub(pad),
1828                                local_body.y.saturating_sub(pad),
1829                                local_body.w.saturating_add(pad.saturating_mul(2)),
1830                                local_body.h.saturating_add(pad.saturating_mul(2)),
1831                            );
1832                            let (sx, sy, sw, sh) = clamp_rect_u32(raw_sample, parent_aw, parent_ah);
1833                            if sw > 0 && sh > 0 {
1834                                let bd_raw = fx.pool.acquire(device, sw, sh);
1835                                fx.steps.push(GpuPassStep::CopyRect {
1836                                    src_idx: parent_idx,
1837                                    src_origin: (sx, sy),
1838                                    dst_idx: bd_raw,
1839                                    dst_origin: (0, 0),
1840                                    size: (sw, sh),
1841                                });
1842                                let bd_blurred = if blur_px >= 0.5 {
1843                                    let b = fx.plan_kawase_blur(device, bd_raw, sw, sh, blur_px, is_srgb);
1844                                    if b != bd_raw {
1845                                        fx.pool.release(bd_raw);
1846                                    }
1847                                    b
1848                                } else {
1849                                    bd_raw
1850                                };
1851
1852                                let dst_rect_bd = [
1853                                    local_body.x as f32,
1854                                    local_body.y as f32,
1855                                    local_body.w as f32,
1856                                    local_body.h as f32,
1857                                ];
1858                                let clip_rect_bd = [
1859                                    parent_clip_phys.x as f32 - parent_ox,
1860                                    parent_clip_phys.y as f32 - parent_oy,
1861                                    parent_clip_phys.right() as f32 - parent_ox,
1862                                    parent_clip_phys.bottom() as f32 - parent_oy,
1863                                ];
1864                                let (snap_idx, snap_ox, snap_oy, snap_tw, snap_th) = fx
1865                                    .acquire_subrect_snapshot(
1866                                        device,
1867                                        parent_idx,
1868                                        parent_aw,
1869                                        parent_ah,
1870                                        dst_rect_bd,
1871                                        clip_rect_bd,
1872                                    );
1873
1874                                let bd_tex_sz = (fx.pool.get(bd_blurred).width, fx.pool.get(bd_blurred).height);
1875                                let mut u = EffectUniform::default();
1876                                u.tex_sizes = [
1877                                    parent_tex_sz.0 as f32,
1878                                    parent_tex_sz.1 as f32,
1879                                    bd_tex_sz.0 as f32,
1880                                    bd_tex_sz.1 as f32,
1881                                ];
1882                                u.dst_rect = dst_rect_bd;
1883                                u.src_rect = [sx as f32, sy as f32, sw as f32, sh as f32];
1884                                u.clip_rect = clip_rect_bd;
1885                                u.body_rect = u.dst_rect;
1886                                u.radii = [
1887                                    (spec.clip_radii.tl as f32) * sf,
1888                                    (spec.clip_radii.tr as f32) * sf,
1889                                    (spec.clip_radii.br as f32) * sf,
1890                                    (spec.clip_radii.bl as f32) * sf,
1891                                ];
1892                                u.params = [
1893                                    (spec.opacity as f32) * (1.0 / 255.0),
1894                                    0.0,
1895                                    EFFECT_KIND_BACKDROP,
1896                                    0.0,
1897                                ];
1898                                u.set_color_matrix(bd.color_matrix);
1899                                u.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
1900                                u.flags[2] = (bd.noise_amount as f32) * (1.0 / 255.0) * 0.12;
1901                                u.flags[3] = if is_srgb { 1.0 } else { 0.0 };
1902                                u.tint = color_to_f32(bd.tint);
1903                                u.extra = [snap_ox, snap_oy, snap_tw, snap_th];
1904
1905                                let slot = fx.push_slot(u);
1906                                let mask_path = spec.clip_path.map(|p| {
1907                                    (
1908                                        std::string::String::from(p.as_str()),
1909                                        local_body.w.max(1) as u32,
1910                                        local_body.h.max(1) as u32,
1911                                    )
1912                                });
1913                                fx.steps.push(GpuPassStep::Effect {
1914                                    dst_idx: parent_idx,
1915                                    clear_dst: false,
1916                                    src_idx: bd_blurred,
1917                                    dst_snap_idx: snap_idx,
1918                                    mask_path,
1919                                    effect_slot: slot,
1920                                    use_hw_blend: false,
1921                                });
1922                                fx.pool.release(bd_blurred);
1923                                fx.pool.release(snap_idx);
1924                            }
1925                        }
1926
1927                        // 2. 为新隔离图层分配离屏目标并压栈
1928                        let (fl, ft, fr, fb) = spec.filter.outset();
1929                        let pl = ((fl as f32) * sf).ceil() as i16;
1930                        let pt = ((ft as f32) * sf).ceil() as i16;
1931                        let pr = ((fr as f32) * sf).ceil() as i16;
1932                        let pb = ((fb as f32) * sf).ceil() as i16;
1933                        let buf_rect = Region::new(
1934                            body_phys.x.saturating_sub(pl),
1935                            body_phys.y.saturating_sub(pt),
1936                            body_phys.w.saturating_add(pl).saturating_add(pr).max(1),
1937                            body_phys.h.saturating_add(pt).saturating_add(pb).max(1),
1938                        );
1939                        let lw = buf_rect.w.max(1) as u32;
1940                        let lh = buf_rect.h.max(1) as u32;
1941                        let layer_tex = fx.pool.acquire(device, lw, lh);
1942                        let ltex_sz = (fx.pool.get(layer_tex).width, fx.pool.get(layer_tex).height);
1943                        let vp_slot = self.viewport_slots.len() as u32;
1944                        self.viewport_slots.push(AlignedViewportSlot {
1945                            uniform: ViewportUniform {
1946                                size: [ltex_sz.0 as f32, ltex_sz.1 as f32],
1947                                is_srgb: if is_srgb { 1.0 } else { 0.0 },
1948                                _pad: 0.0,
1949                            },
1950                            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1951                        });
1952
1953                        stack.push(LayerFrame {
1954                            tex_idx: layer_tex,
1955                            active_w: lw,
1956                            active_h: lh,
1957                            origin_x: buf_rect.x as f32,
1958                            origin_y: buf_rect.y as f32,
1959                            viewport_slot: vp_slot,
1960                            cleared: false,
1961                            clear_col: wgpu::Color::TRANSPARENT,
1962                            batch_start: self.primitives.len() as u32,
1963                            spec: Some(spec),
1964                            body_phys,
1965                            buf_rect,
1966                            parent_clip_phys,
1967                        });
1968                    }
1969
1970                    DrawPayload::PopLayer => {
1971                        if stack.len() <= 1 {
1972                            continue;
1973                        }
1974                        flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1975                        let layer = stack.pop().unwrap();
1976                        if let Some(parent_mut) = stack.last_mut() {
1977                            parent_mut.batch_start = self.primitives.len() as u32;
1978                        }
1979                        let Some(spec) = layer.spec else {
1980                            continue;
1981                        };
1982                        let parent = stack.last().unwrap();
1983                        let parent_idx = parent.tex_idx;
1984                        let parent_aw = parent.active_w;
1985                        let parent_ah = parent.active_h;
1986                        let parent_ox = parent.origin_x;
1987                        let parent_oy = parent.origin_y;
1988                        let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1989
1990                        let local_buf = [
1991                            layer.buf_rect.x as f32 - parent_ox,
1992                            layer.buf_rect.y as f32 - parent_oy,
1993                            layer.buf_rect.w as f32,
1994                            layer.buf_rect.h as f32,
1995                        ];
1996                        let local_body = [
1997                            layer.body_phys.x as f32 - parent_ox,
1998                            layer.body_phys.y as f32 - parent_oy,
1999                            layer.body_phys.w as f32,
2000                            layer.body_phys.h as f32,
2001                        ];
2002                        let clip_f = [
2003                            layer.parent_clip_phys.x as f32 - parent_ox,
2004                            layer.parent_clip_phys.y as f32 - parent_oy,
2005                            layer.parent_clip_phys.right() as f32 - parent_ox,
2006                            layer.parent_clip_phys.bottom() as f32 - parent_oy,
2007                        ];
2008
2009                        // 计算经 2D 仿射变换后的目标绘制矩形
2010                        let dst_rect = if let Some(mut t) = spec.transform {
2011                            if !t.is_identity() {
2012                                t.e *= sf;
2013                                t.f *= sf;
2014                                let cx = local_body[0] + local_body[2] * 0.5;
2015                                let cy = local_body[1] + local_body[3] * 0.5;
2016                                let xreg = t.centered_at(cx, cy).transform_region(Region::new(
2017                                    local_buf[0] as i16,
2018                                    local_buf[1] as i16,
2019                                    local_buf[2] as i16,
2020                                    local_buf[3] as i16,
2021                                ));
2022                                [xreg.x as f32, xreg.y as f32, xreg.w as f32, xreg.h as f32]
2023                            } else {
2024                                local_buf
2025                            }
2026                        } else {
2027                            local_buf
2028                        };
2029
2030                        // 1. 若启用任意子树 `drop_shadow`:提取 Alpha(含 SVG Path 遮罩)-> Kawase Blur -> 变换偏移合成到父层
2031                        if let Some(ds) = spec.filter.drop_shadow {
2032                            if ds.is_active() {
2033                                let sh_raw = fx.pool.acquire(device, layer.active_w, layer.active_h);
2034                                let lsz = (fx.pool.get(layer.tex_idx).width, fx.pool.get(layer.tex_idx).height);
2035                                let sh_sz = (fx.pool.get(sh_raw).width, fx.pool.get(sh_raw).height);
2036                                let mut eu = EffectUniform::default();
2037                                eu.tex_sizes = [sh_sz.0 as f32, sh_sz.1 as f32, lsz.0 as f32, lsz.1 as f32];
2038                                eu.dst_rect = [0.0, 0.0, layer.active_w as f32, layer.active_h as f32];
2039                                eu.src_rect = eu.dst_rect;
2040                                eu.body_rect = [
2041                                    (layer.body_phys.x - layer.buf_rect.x) as f32,
2042                                    (layer.body_phys.y - layer.buf_rect.y) as f32,
2043                                    layer.body_phys.w as f32,
2044                                    layer.body_phys.h as f32,
2045                                ];
2046                                eu.params = [1.0, 0.0, EFFECT_KIND_SHADOW_EXTRACT, 0.0];
2047                                eu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
2048                                eu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
2049                                eu.tint = color_to_f32(ds.color);
2050                                let eslot = fx.push_slot(eu);
2051                                let sh_mask = spec.clip_path.map(|p| {
2052                                    (
2053                                        std::string::String::from(p.as_str()),
2054                                        layer.body_phys.w.max(1) as u32,
2055                                        layer.body_phys.h.max(1) as u32,
2056                                    )
2057                                });
2058                                fx.steps.push(GpuPassStep::Effect {
2059                                    dst_idx: sh_raw,
2060                                    clear_dst: true,
2061                                    src_idx: layer.tex_idx,
2062                                    dst_snap_idx: layer.tex_idx,
2063                                    mask_path: sh_mask,
2064                                    effect_slot: eslot,
2065                                    use_hw_blend: false,
2066                                });
2067
2068                                let ds_blur = (ds.blur as f32) * sf;
2069                                let sh_final = if ds_blur >= 0.5 {
2070                                    let b = fx.plan_kawase_blur(
2071                                        device,
2072                                        sh_raw,
2073                                        layer.active_w,
2074                                        layer.active_h,
2075                                        ds_blur,
2076                                        is_srgb,
2077                                    );
2078                                    if b != sh_raw {
2079                                        fx.pool.release(sh_raw);
2080                                    }
2081                                    b
2082                                } else {
2083                                    sh_raw
2084                                };
2085
2086                                let sh_tex_sz = (fx.pool.get(sh_final).width, fx.pool.get(sh_final).height);
2087                                let ox = (ds.offset_x as f32) * sf;
2088                                let oy = (ds.offset_y as f32) * sf;
2089                                let sh_dst_rect = [
2090                                    dst_rect[0] + ox,
2091                                    dst_rect[1] + oy,
2092                                    dst_rect[2],
2093                                    dst_rect[3],
2094                                ];
2095                                let sh_hw_blend = spec.blend_mode.is_normal();
2096                                let (sh_snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if sh_hw_blend {
2097                                    (None, 0.0, 0.0, 1.0, 1.0)
2098                                } else {
2099                                    let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
2100                                        device,
2101                                        parent_idx,
2102                                        parent_aw,
2103                                        parent_ah,
2104                                        sh_dst_rect,
2105                                        clip_f,
2106                                    );
2107                                    (Some(sidx), sx0, sy0, stw, sth)
2108                                };
2109
2110                                let mut cu = EffectUniform::default();
2111                                cu.tex_sizes = [
2112                                    parent_tex_sz.0 as f32,
2113                                    parent_tex_sz.1 as f32,
2114                                    sh_tex_sz.0 as f32,
2115                                    sh_tex_sz.1 as f32,
2116                                ];
2117                                cu.dst_rect = sh_dst_rect;
2118                                cu.src_rect = local_buf;
2119                                cu.clip_rect = clip_f;
2120                                cu.body_rect = local_body;
2121                                cu.params = [
2122                                    (spec.opacity as f32) * (1.0 / 255.0),
2123                                    if sh_hw_blend {
2124                                        -1.0
2125                                    } else {
2126                                        spec.blend_mode as u8 as f32
2127                                    },
2128                                    EFFECT_KIND_COMPOSITE,
2129                                    0.0,
2130                                ];
2131                                cu.set_color_matrix(None);
2132                                cu.set_transform(spec.transform, sf);
2133                                cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
2134                                cu.extra[0] += ox;
2135                                cu.extra[1] += oy;
2136                                cu.extra[2] = snap_tw;
2137                                cu.extra[3] = snap_th;
2138                                let cslot = fx.push_slot(cu);
2139                                fx.steps.push(GpuPassStep::Effect {
2140                                    dst_idx: parent_idx,
2141                                    clear_dst: false,
2142                                    src_idx: sh_final,
2143                                    dst_snap_idx: sh_snap_opt.unwrap_or(sh_final),
2144                                    mask_path: None,
2145                                    effect_slot: cslot,
2146                                    use_hw_blend: sh_hw_blend,
2147                                });
2148                                fx.pool.release(sh_final);
2149                                if let Some(sidx) = sh_snap_opt {
2150                                    fx.pool.release(sidx);
2151                                }
2152                            }
2153                        }
2154
2155                        // 2. 图层本体模糊(Dual Kawase Blur)
2156                        let blur_px = (spec.filter.blur_radius as f32) * sf;
2157                        let src_final = if blur_px >= 0.5 {
2158                            let b = fx.plan_kawase_blur(
2159                                device,
2160                                layer.tex_idx,
2161                                layer.active_w,
2162                                layer.active_h,
2163                                blur_px,
2164                                is_srgb,
2165                            );
2166                            if b != layer.tex_idx {
2167                                fx.pool.release(layer.tex_idx);
2168                            }
2169                            b
2170                        } else {
2171                            layer.tex_idx
2172                        };
2173
2174                        // 3. 合成回父层(SrcOver 走零拷贝硬件混合直出;其余 26 种混合模式走局部包围盒快照)
2175                        let use_hw_blend = spec.blend_mode.is_normal();
2176                        let (snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if use_hw_blend {
2177                            (None, 0.0, 0.0, 1.0, 1.0)
2178                        } else {
2179                            let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
2180                                device,
2181                                parent_idx,
2182                                parent_aw,
2183                                parent_ah,
2184                                dst_rect,
2185                                clip_f,
2186                            );
2187                            (Some(sidx), sx0, sy0, stw, sth)
2188                        };
2189                        let src_tex_sz = (fx.pool.get(src_final).width, fx.pool.get(src_final).height);
2190
2191                        let mut cu = EffectUniform::default();
2192                        cu.tex_sizes = [
2193                            parent_tex_sz.0 as f32,
2194                            parent_tex_sz.1 as f32,
2195                            src_tex_sz.0 as f32,
2196                            src_tex_sz.1 as f32,
2197                        ];
2198                        cu.dst_rect = dst_rect;
2199                        cu.src_rect = local_buf;
2200                        cu.clip_rect = clip_f;
2201                        cu.body_rect = local_body;
2202                        cu.radii = [
2203                            (spec.clip_radii.tl as f32) * sf,
2204                            (spec.clip_radii.tr as f32) * sf,
2205                            (spec.clip_radii.br as f32) * sf,
2206                            (spec.clip_radii.bl as f32) * sf,
2207                        ];
2208                        cu.params = [
2209                            (spec.opacity as f32) * (1.0 / 255.0),
2210                            if use_hw_blend {
2211                                -1.0
2212                            } else {
2213                                spec.blend_mode as u8 as f32
2214                            },
2215                            EFFECT_KIND_COMPOSITE,
2216                            0.0,
2217                        ];
2218                        cu.set_color_matrix(spec.filter.color_matrix);
2219                        cu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
2220                        cu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
2221                        cu.set_transform(spec.transform, sf);
2222                        cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
2223                        cu.extra[2] = snap_tw;
2224                        cu.extra[3] = snap_th;
2225                        let cslot = fx.push_slot(cu);
2226
2227                        let mask_path = spec.clip_path.map(|p| {
2228                            (
2229                                std::string::String::from(p.as_str()),
2230                                layer.body_phys.w.max(1) as u32,
2231                                layer.body_phys.h.max(1) as u32,
2232                            )
2233                        });
2234                        fx.steps.push(GpuPassStep::Effect {
2235                            dst_idx: parent_idx,
2236                            clear_dst: false,
2237                            src_idx: src_final,
2238                            dst_snap_idx: snap_opt.unwrap_or(src_final),
2239                            mask_path,
2240                            effect_slot: cslot,
2241                            use_hw_blend,
2242                        });
2243                        fx.pool.release(src_final);
2244                        if let Some(sidx) = snap_opt {
2245                            fx.pool.release(sidx);
2246                        }
2247                    }
2248
2249                    // 单图元非 `SrcOver` 混合:自动借用微型临时层执行精确 27 种 W3C 混合模式
2250                    DrawPayload::StyledQuad(sq) if !sq.blend_mode.is_normal() => {
2251                        flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
2252                        let parent = stack.last().unwrap();
2253                        let parent_idx = parent.tex_idx;
2254                        let parent_aw = parent.active_w;
2255                        let parent_ah = parent.active_h;
2256                        let parent_ox = parent.origin_x;
2257                        let parent_oy = parent.origin_y;
2258                        let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
2259
2260                        let body_phys = snap_bounds_region_scaled(op.bounds, sf);
2261                        let buf_rect = if let Some(mut t) = sq.transform {
2262                            if !t.is_identity() {
2263                                t.e *= sf;
2264                                t.f *= sf;
2265                                let cx = body_phys.x as f32 + body_phys.w as f32 * 0.5;
2266                                let cy = body_phys.y as f32 + body_phys.h as f32 * 0.5;
2267                                t.centered_at(cx, cy).transform_region(body_phys)
2268                            } else {
2269                                body_phys
2270                            }
2271                        } else {
2272                            body_phys
2273                        };
2274                        let lw = buf_rect.w.max(1) as u32;
2275                        let lh = buf_rect.h.max(1) as u32;
2276                        let tmp_tex = fx.pool.acquire(device, lw, lh);
2277                        let tmp_sz = (fx.pool.get(tmp_tex).width, fx.pool.get(tmp_tex).height);
2278                        let vp_slot = self.viewport_slots.len() as u32;
2279                        self.viewport_slots.push(AlignedViewportSlot {
2280                            uniform: ViewportUniform {
2281                                size: [tmp_sz.0 as f32, tmp_sz.1 as f32],
2282                                is_srgb: if is_srgb { 1.0 } else { 0.0 },
2283                                _pad: 0.0,
2284                            },
2285                            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
2286                        });
2287
2288                        let normal_sq = StyledQuad {
2289                            blend_mode: BlendMode::SrcOver,
2290                            ..*sq
2291                        };
2292                        let tmp_op = DrawOp {
2293                            payload: DrawPayload::StyledQuad(&normal_sq),
2294                            ..*op
2295                        };
2296                        let pstart = self.primitives.len() as u32;
2297                        self.encode_single_op(
2298                            queue,
2299                            &tmp_op,
2300                            op.clip,
2301                            viewport,
2302                            sf,
2303                            use_ttf,
2304                            buf_rect.x as f32,
2305                            buf_rect.y as f32,
2306                        )?;
2307                        let pend = self.primitives.len() as u32;
2308                        fx.steps.push(GpuPassStep::DrawBatch {
2309                            target_idx: tmp_tex,
2310                            clear: Some(wgpu::Color::TRANSPARENT),
2311                            viewport_slot: vp_slot,
2312                            prim_start: pstart,
2313                            prim_end: pend,
2314                        });
2315                        if let Some(top) = stack.last_mut() {
2316                            top.batch_start = pend;
2317                        }
2318
2319                        let clip_phys = snap_clip_region_scaled(op.clip, sf);
2320                        let local_buf = [
2321                            buf_rect.x as f32 - parent_ox,
2322                            buf_rect.y as f32 - parent_oy,
2323                            buf_rect.w as f32,
2324                            buf_rect.h as f32,
2325                        ];
2326                        let clip_f = [
2327                            clip_phys.x as f32 - parent_ox,
2328                            clip_phys.y as f32 - parent_oy,
2329                            clip_phys.right() as f32 - parent_ox,
2330                            clip_phys.bottom() as f32 - parent_oy,
2331                        ];
2332                        let (snap_idx, snap_ox, snap_oy, snap_tw, snap_th) = fx
2333                            .acquire_subrect_snapshot(
2334                                device,
2335                                parent_idx,
2336                                parent_aw,
2337                                parent_ah,
2338                                local_buf,
2339                                clip_f,
2340                            );
2341                        let mut cu = EffectUniform::default();
2342                        cu.tex_sizes = [
2343                            parent_tex_sz.0 as f32,
2344                            parent_tex_sz.1 as f32,
2345                            tmp_sz.0 as f32,
2346                            tmp_sz.1 as f32,
2347                        ];
2348                        cu.dst_rect = local_buf;
2349                        cu.src_rect = local_buf;
2350                        cu.clip_rect = clip_f;
2351                        cu.body_rect = local_buf;
2352                        cu.params = [1.0, sq.blend_mode as u8 as f32, EFFECT_KIND_COMPOSITE, 0.0];
2353                        cu.set_color_matrix(None);
2354                        cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
2355                        cu.inv_xform = [1.0, 0.0, 0.0, 1.0];
2356                        cu.extra = [0.0, 0.0, snap_tw, snap_th];
2357                        let cslot = fx.push_slot(cu);
2358                        fx.steps.push(GpuPassStep::Effect {
2359                            dst_idx: parent_idx,
2360                            clear_dst: false,
2361                            src_idx: tmp_tex,
2362                            dst_snap_idx: snap_idx,
2363                            mask_path: None,
2364                            effect_slot: cslot,
2365                            use_hw_blend: false,
2366                        });
2367                        fx.pool.release(tmp_tex);
2368                        fx.pool.release(snap_idx);
2369                    }
2370
2371                    // 外部零拷贝 GPU 纹理采样(直接消费外部引擎共享的 `wgpu::TextureView`)
2372                    DrawPayload::ExternalTexture(ext) => {
2373                        let raw_clip = viewport.intersect(op.clip).intersect(op.bounds);
2374                        if raw_clip.is_empty() {
2375                            continue;
2376                        }
2377                        if self.external_textures.contains_key(&ext.id) {
2378                            flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
2379                            let parent = stack.last().unwrap();
2380                            let parent_idx = parent.tex_idx;
2381                            let parent_aw = parent.active_w;
2382                            let parent_ah = parent.active_h;
2383                            let parent_ox = parent.origin_x;
2384                            let parent_oy = parent.origin_y;
2385                            let parent_tex_sz =
2386                                (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
2387
2388                            let body_phys = snap_bounds_region_scaled(op.bounds, sf);
2389                            let clip_phys = snap_clip_region_scaled(raw_clip, sf);
2390                            let local_body = [
2391                                body_phys.x as f32 - parent_ox,
2392                                body_phys.y as f32 - parent_oy,
2393                                body_phys.w as f32,
2394                                body_phys.h as f32,
2395                            ];
2396                            let clip_f = [
2397                                clip_phys.x as f32 - parent_ox,
2398                                clip_phys.y as f32 - parent_oy,
2399                                clip_phys.right() as f32 - parent_ox,
2400                                clip_phys.bottom() as f32 - parent_oy,
2401                            ];
2402
2403                            let use_hw_blend = ext.blend_mode.is_normal();
2404                            let (snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if use_hw_blend {
2405                                (None, 0.0, 0.0, 1.0, 1.0)
2406                            } else {
2407                                let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
2408                                    device,
2409                                    parent_idx,
2410                                    parent_aw,
2411                                    parent_ah,
2412                                    local_body,
2413                                    clip_f,
2414                                );
2415                                (Some(sidx), sx0, sy0, stw, sth)
2416                            };
2417
2418                            let mut eu = EffectUniform::default();
2419                            eu.tex_sizes = [
2420                                parent_tex_sz.0 as f32,
2421                                parent_tex_sz.1 as f32,
2422                                1.0,
2423                                1.0,
2424                            ];
2425                            eu.dst_rect = local_body;
2426                            eu.src_rect = ext.uv_rect;
2427                            eu.clip_rect = clip_f;
2428                            eu.body_rect = local_body;
2429                            eu.radii = [
2430                                (ext.radii.tl as f32) * sf,
2431                                (ext.radii.tr as f32) * sf,
2432                                (ext.radii.br as f32) * sf,
2433                                (ext.radii.bl as f32) * sf,
2434                            ];
2435                            eu.params = [
2436                                (ext.opacity as f32) * (1.0 / 255.0),
2437                                if use_hw_blend {
2438                                    -1.0
2439                                } else {
2440                                    ext.blend_mode as u8 as f32
2441                                },
2442                                EFFECT_KIND_EXTERNAL_TEX,
2443                                0.0,
2444                            ];
2445                            eu.flags = [
2446                                if ext.premultiplied { 1.0 } else { 0.0 },
2447                                0.0,
2448                                0.0,
2449                                if is_srgb { 1.0 } else { 0.0 },
2450                            ];
2451                            eu.inv_xform = [1.0, 0.0, 0.0, 1.0];
2452                            eu.extra = [snap_ox, snap_oy, snap_tw, snap_th];
2453                            let eslot = fx.push_slot(eu);
2454
2455                            fx.steps.push(GpuPassStep::DrawExternal {
2456                                dst_idx: parent_idx,
2457                                dst_snap_idx: snap_opt.unwrap_or(root_idx),
2458                                tex_id: ext.id,
2459                                effect_slot: eslot,
2460                                use_hw_blend,
2461                            });
2462                            if let Some(sidx) = snap_opt {
2463                                fx.pool.release(sidx);
2464                            }
2465                        } else if ext.fallback_bg.a() > 0 {
2466                            let fallback_sq = StyledQuad {
2467                                paint: Paint::Solid(ext.fallback_bg),
2468                                border_color: Color::TRANSPARENT,
2469                                border_width: 0,
2470                                radii: ext.radii,
2471                                opacity: ext.opacity,
2472                                blend_mode: BlendMode::SrcOver,
2473                                transform: None,
2474                            };
2475                            let tmp_op = DrawOp {
2476                                payload: DrawPayload::StyledQuad(&fallback_sq),
2477                                ..*op
2478                            };
2479                            let (ox, oy) = {
2480                                let top = stack.last().unwrap();
2481                                (top.origin_x, top.origin_y)
2482                            };
2483                            self.encode_single_op(
2484                                queue, &tmp_op, raw_clip, viewport, sf, use_ttf, ox, oy,
2485                            )?;
2486                        }
2487                    }
2488
2489                    _ => {
2490                        let raw_clip = match op.payload {
2491                            DrawPayload::StyledQuad(sq) if sq.transform.is_some() => {
2492                                viewport.intersect(op.clip)
2493                            }
2494                            _ => viewport.intersect(op.clip).intersect(op.bounds),
2495                        };
2496                        if raw_clip.is_empty() {
2497                            continue;
2498                        }
2499                        let (ox, oy) = {
2500                            let top = stack.last().unwrap();
2501                            (top.origin_x, top.origin_y)
2502                        };
2503                        self.encode_single_op(queue, op, raw_clip, viewport, sf, use_ttf, ox, oy)?;
2504                    }
2505                }
2506            }
2507
2508            // 冲刷根画布最后一批图元并 Blit 至外部 `target_view`
2509            flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
2510            let mut blit_u = EffectUniform::default();
2511            blit_u.tex_sizes = [pw as f32, ph as f32, root_tex_sz.0 as f32, root_tex_sz.1 as f32];
2512            blit_u.dst_rect = [0.0, 0.0, pw as f32, ph as f32];
2513            blit_u.src_rect = [0.0, 0.0, pw as f32, ph as f32];
2514            blit_u.params = [1.0, 0.0, EFFECT_KIND_BLIT, 0.0];
2515            let blit_slot = fx.push_slot(blit_u);
2516            fx.steps.push(GpuPassStep::BlitToTarget {
2517                src_idx: root_idx,
2518                effect_slot: blit_slot,
2519            });
2520            Ok(())
2521        })();
2522
2523        self.effects = Some(fx);
2524        result
2525    }
2526
2527    /// 针对包含 `DrawPayload::SceneCanvas` 的无图层帧执行零离屏拷贝交错渲染:
2528    /// 画布前 UI → 背景填充 → `CanvasGpuEngine`(bg_shaders + StaticMesh + 32B+4B Instanced SDF + fg_shaders)
2529    /// → ASCII 快速字形标签(含 Zoom Font Lock)+ 橡皮筋框选 → 画布后浮层 UI(Tooltip / Minimap)。
2530    #[allow(clippy::too_many_arguments)]
2531    fn render_to_view_with_scene_canvas(
2532        &mut self,
2533        device: &wgpu::Device,
2534        queue: &wgpu::Queue,
2535        ops: &[DrawOp<'_>],
2536        viewport: Region,
2537        scale_factor: f32,
2538        target_view: &wgpu::TextureView,
2539        phys_width: u32,
2540        phys_height: u32,
2541        clear_color: wgpu::Color,
2542    ) {
2543        enum InterleavedStep {
2544            UiBatch(u32, u32),
2545            Canvas {
2546                op_idx: usize,
2547                bounds_phys: [f32; 4],
2548                clip_phys: [f32; 4],
2549                scissor: Region,
2550            },
2551        }
2552
2553        let sf = scale_factor.clamp(0.5, 4.0);
2554        let pw = phys_width.max(1);
2555        let ph = phys_height.max(1);
2556        let use_ttf = crate::display::ttf_atlas::has_system_font();
2557        let mut steps: Vec<InterleavedStep> = Vec::with_capacity(8);
2558
2559        let mut bind_group_dirty = false;
2560        for _attempt in 0..4 {
2561            self.primitives.clear();
2562            steps.clear();
2563            let mut batch_start = 0u32;
2564            let mut err_need: Option<AtlasGrowNeed> = None;
2565
2566            for (op_idx, op) in ops.iter().enumerate() {
2567                let raw_clip = match op.payload {
2568                    DrawPayload::StyledQuad(sq) if sq.transform.is_some() => {
2569                        viewport.intersect(op.clip)
2570                    }
2571                    _ => viewport.intersect(op.clip).intersect(op.bounds),
2572                };
2573                if raw_clip.is_empty() {
2574                    continue;
2575                }
2576                if let DrawPayload::SceneCanvas(spec) = op.payload {
2577                    let bounds_phys = snap_bounds(op.bounds, sf);
2578                    let clip_phys = snap_clip(raw_clip, sf);
2579                    let scissor = snap_clip_region_scaled(raw_clip, sf);
2580
2581                    // 1. 先向 UI 批次推入画布纯色背景(位于 CustomShader / StaticMesh 下方)
2582                    if spec.bg.a() > 0 && spec.opacity > 0 {
2583                        let bg = spec.bg.scale_alpha(spec.opacity);
2584                        self.primitives.push(make_quad_primitive(
2585                            bounds_phys,
2586                            clip_phys,
2587                            (op.clip_radius as f32) * sf,
2588                            0.0,
2589                            0.0,
2590                            false,
2591                            bg,
2592                            Color::TRANSPARENT,
2593                            Color::TRANSPARENT,
2594                        ));
2595                    }
2596                    let batch_end = self.primitives.len() as u32;
2597                    if batch_end > batch_start {
2598                        steps.push(InterleavedStep::UiBatch(batch_start, batch_end));
2599                        batch_start = batch_end;
2600                    }
2601
2602                    // 2. 插入画布 GPU Instanced + Mesh + CustomShader Pass
2603                    steps.push(InterleavedStep::Canvas {
2604                        op_idx,
2605                        bounds_phys,
2606                        clip_phys,
2607                        scissor,
2608                    });
2609
2610                    // 3. 画布上方编码 ASCII 快速字形标签(Zoom Font Lock)与橡皮筋框选
2611                    if let Err(need) = self.encode_canvas_overlay_primitives(
2612                        queue,
2613                        spec,
2614                        bounds_phys,
2615                        clip_phys,
2616                        (op.clip_radius as f32) * sf,
2617                        sf,
2618                    ) {
2619                        err_need = Some(need);
2620                        break;
2621                    }
2622                } else if let Err(need) = self.encode_single_op(
2623                    queue, op, raw_clip, viewport, sf, use_ttf, 0.0, 0.0,
2624                ) {
2625                    err_need = Some(need);
2626                    break;
2627                }
2628            }
2629
2630            if let Some(need) = err_need {
2631                let (dirty, can_retry) = self.handle_atlas_grow(device, need);
2632                if dirty {
2633                    bind_group_dirty = true;
2634                }
2635                if !can_retry {
2636                    break;
2637                }
2638            } else {
2639                let final_end = self.primitives.len() as u32;
2640                if final_end > batch_start {
2641                    steps.push(InterleavedStep::UiBatch(batch_start, final_end));
2642                }
2643                break;
2644            }
2645        }
2646
2647        if self.primitives.len() > self.instance_capacity {
2648            self.instance_capacity = self.primitives.len().next_power_of_two();
2649            self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
2650            bind_group_dirty = true;
2651        }
2652        if bind_group_dirty {
2653            self.rebuild_bind_group(device);
2654        }
2655
2656        let slot0 = AlignedViewportSlot {
2657            uniform: ViewportUniform {
2658                size: [pw as f32, ph as f32],
2659                is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
2660                _pad: 0.0,
2661            },
2662            _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
2663        };
2664        queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
2665        if !self.primitives.is_empty() {
2666            queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
2667        }
2668
2669        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
2670            label: Some("velox_wgpu_scene_canvas_encoder"),
2671        });
2672
2673        let mut cleared = false;
2674        let is_srgb = self.target_is_srgb;
2675        let mut canvas_eng = self
2676            .canvas_engine
2677            .take()
2678            .unwrap_or_else(|| super::canvas_pipeline::CanvasGpuEngine::new(device, self.target_format));
2679
2680        for step in &steps {
2681            match *step {
2682                InterleavedStep::UiBatch(start, end) => {
2683                    let load = if !cleared {
2684                        cleared = true;
2685                        wgpu::LoadOp::Clear(clear_color)
2686                    } else {
2687                        wgpu::LoadOp::Load
2688                    };
2689                    let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2690                        label: Some("velox_canvas_ui_batch"),
2691                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2692                            view: target_view,
2693                            depth_slice: None,
2694                            resolve_target: None,
2695                            ops: wgpu::Operations {
2696                                load,
2697                                store: wgpu::StoreOp::Store,
2698                            },
2699                        })],
2700                        depth_stencil_attachment: None,
2701                        occlusion_query_set: None,
2702                        timestamp_writes: None,
2703                        multiview_mask: None,
2704                    });
2705                    if end > start {
2706                        rpass.set_pipeline(&self.pipeline);
2707                        rpass.set_bind_group(0, &self.bind_group, &[0]);
2708                        rpass.draw(0..6, start..end);
2709                    }
2710                }
2711                InterleavedStep::Canvas {
2712                    op_idx,
2713                    bounds_phys,
2714                    clip_phys,
2715                    scissor,
2716                } => {
2717                    if !cleared {
2718                        cleared = true;
2719                        let _clear_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2720                            label: Some("velox_canvas_clear"),
2721                            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2722                                view: target_view,
2723                                depth_slice: None,
2724                                resolve_target: None,
2725                                ops: wgpu::Operations {
2726                                    load: wgpu::LoadOp::Clear(clear_color),
2727                                    store: wgpu::StoreOp::Store,
2728                                },
2729                            })],
2730                            depth_stencil_attachment: None,
2731                            occlusion_query_set: None,
2732                            timestamp_writes: None,
2733                            multiview_mask: None,
2734                        });
2735                    }
2736                    if let DrawPayload::SceneCanvas(spec) = ops[op_idx].payload {
2737                        canvas_eng.render_canvas(
2738                            device,
2739                            queue,
2740                            &mut encoder,
2741                            target_view,
2742                            pw,
2743                            ph,
2744                            bounds_phys,
2745                            clip_phys,
2746                            scissor,
2747                            sf,
2748                            is_srgb,
2749                            spec,
2750                        );
2751                    }
2752                }
2753            }
2754        }
2755
2756        self.canvas_engine = Some(canvas_eng);
2757        queue.submit([encoder.finish()]);
2758    }
2759
2760    /// 编码画布近景 ASCII 快速标签(手势缩放时自动锁定 16px/32px 离散基准字号 + `O(1)` 查表防图集抖动)与橡皮筋框选矩形。
2761    fn encode_canvas_overlay_primitives(
2762        &mut self,
2763        queue: &wgpu::Queue,
2764        spec: &crate::canvas_scene::SceneCanvasSpec<'_>,
2765        bounds_phys: [f32; 4],
2766        clip_phys: [f32; 4],
2767        clip_radius_px: f32,
2768        sf: f32,
2769    ) -> Result<(), AtlasGrowNeed> {
2770        let vp_zoom = spec.viewport.zoom * sf;
2771        let vp_ox = bounds_phys[0] + spec.viewport.offset_x * sf;
2772        let vp_oy = bounds_phys[1] + spec.viewport.offset_y * sf;
2773
2774        // 1. ASCII 快速通道:绕过 CosmicEditor,直接按字节查表出字形实例
2775        for lbl in spec.labels {
2776            if lbl.text.is_empty() {
2777                continue;
2778            }
2779            let target_px = (lbl.font_px * sf).clamp(6.0, 48.0);
2780            let col_f32 = color_to_f32(lbl.color.scale_alpha(spec.opacity));
2781            let center_x = lbl.wx * vp_zoom + vp_ox;
2782            let center_y = lbl.wy * vp_zoom + vp_oy;
2783
2784            // Zoom Font Lock:缩放态锁定 16px / 32px 离散基准字号并顶点缩放纹理,手势停稳 120ms 后恢复 0.25px 精确光栅化
2785            let use_fast_lock = spec.zooming || lbl.text.is_ascii();
2786            if use_fast_lock && lbl.text.is_ascii() {
2787                let (large_32, base_px, q4_exact) = if spec.zooming {
2788                    let large = target_px > 20.0;
2789                    (large, if large { 32.0 } else { 16.0 }, 0u16)
2790                } else {
2791                    let q4 = (target_px * 4.0).round().clamp(24.0, 192.0) as u16;
2792                    (false, target_px, q4)
2793                };
2794                let ratio = if spec.zooming {
2795                    target_px / base_px
2796                } else {
2797                    1.0
2798                };
2799                let mut total_adv = 0.0f32;
2800                let mut cached_entries: [Option<super::atlas::GlyphAtlasEntry>; 16] = [None; 16];
2801                let bytes = lbl.text.as_bytes();
2802                let count = bytes.len().min(16);
2803                for i in 0..count {
2804                    let b = bytes[i];
2805                    let entry = if spec.zooming {
2806                        self.glyph_atlas.get_ascii_fast(queue, b, large_32)
2807                    } else {
2808                        self.glyph_atlas.get_or_insert(queue, b as char, q4_exact, true)
2809                    };
2810                    let Some(e) = entry else {
2811                        return Err(AtlasGrowNeed {
2812                            glyph_full: true,
2813                            sprite_need: None,
2814                            ramp_full: false,
2815                        });
2816                    };
2817                    total_adv += (e.advance.max(4) as f32) * ratio;
2818                    cached_entries[i] = Some(e);
2819                }
2820                let mut pen_x = center_x - total_adv * 0.5;
2821                let baseline_y = center_y + target_px * 0.34;
2822                for i in 0..count {
2823                    if let Some(e) = cached_entries[i] {
2824                        if e.width > 0 && e.height > 0 {
2825                            let gw = (e.width as f32) * ratio;
2826                            let gh = (e.height as f32) * ratio;
2827                            let gx = pen_x + (e.xmin as f32) * ratio;
2828                            let gy = baseline_y - gh - (e.ymin as f32) * ratio;
2829                            if gx + gw >= clip_phys[0]
2830                                && gx <= clip_phys[2]
2831                                && gy + gh >= clip_phys[1]
2832                                && gy <= clip_phys[3]
2833                            {
2834                                self.primitives.push(GpuPrimitive {
2835                                    bounds: [gx, gy, gw, gh],
2836                                    clip: clip_phys,
2837                                    uv: e.uv,
2838                                    color0: col_f32,
2839                                    color1: [0.0; 4],
2840                                    border_color: [0.0; 4],
2841                                    params: [0.0, 0.0, KIND_GLYPH, 0.0],
2842                                    extra: [clip_radius_px, 0.0, 0.0, 0.0],
2843                                    radii: [0.0; 4],
2844                                    grad_a: [0.0; 4],
2845                                    grad_b: [0.0; 4],
2846                                    xform: IDENTITY_XFORM,
2847                                });
2848                            }
2849                        }
2850                        pen_x += (e.advance.max(4) as f32) * ratio;
2851                    }
2852                }
2853            }
2854        }
2855
2856        // 2. 橡皮筋框选矩形
2857        if let Some([mx0, my0, mx1, my1]) = spec.marquee {
2858            let x0 = bounds_phys[0] + mx0.min(mx1) * sf;
2859            let y0 = bounds_phys[1] + my0.min(my1) * sf;
2860            let w = (mx1 - mx0).abs() * sf;
2861            let h = (my1 - my0).abs() * sf;
2862            if w > 1.0 && h > 1.0 {
2863                self.primitives.push(make_quad_primitive(
2864                    [x0, y0, w, h],
2865                    clip_phys,
2866                    clip_radius_px,
2867                    2.0 * sf,
2868                    1.5 * sf,
2869                    false,
2870                    spec.marquee_color.scale_alpha(52),
2871                    Color::TRANSPARENT,
2872                    spec.marquee_color.scale_alpha(220),
2873                ));
2874            }
2875        }
2876        Ok(())
2877    }
2878}