velox-engine 0.5.0

Velox core UI engine: arena, pod state, 1D fixed-point layout solver, damage tracker, SDF scanline rasterizer, and cross-platform GPU/software backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! GPU 离屏渲染目标复用池(`LayerTargetPool`)与 SVG Path `R8Unorm` 遮罩缓存。
//!
//! 按 64 像素桶复用离屏纹理,零帧间显存反复申请/销毁,供隔离图层、Dual Kawase Blur、
//! 实时毛玻璃(`backdrop-filter`)与可编程 W3C 混合模式共享。

use ::wgpu;
use std::collections::HashMap;
use std::vec;
use std::vec::Vec;

use crate::display::{PixelFormat, Rgba8888};
use crate::solver::Region;
use crate::style::Color;
use crate::svg::{rasterize_svg, rasterize_svg_path, SvgRenderOptions};

/// 毛玻璃(`backdrop-filter`)模糊小纹理跨帧缓存键(包含外扩采样区域与量化模糊半径)。
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct BackdropCacheKey {
    pub(crate) sx: u32,
    pub(crate) sy: u32,
    pub(crate) sw: u32,
    pub(crate) sh: u32,
    pub(crate) blur_px_q4: u16,
    pub(crate) is_srgb: bool,
}

pub(crate) struct PooledTarget {
    pub(crate) texture: wgpu::Texture,
    pub(crate) view: wgpu::TextureView,
    pub(crate) width: u32,
    pub(crate) height: u32,
    pub(crate) byte_size: usize,
    pub(crate) generation: u64,
    last_used_frame: u64,
    in_use: bool,
    /// 若该槽位承载了可跨帧复用的已模糊毛玻璃小纹理,记录 `(cache_key, underlay_hash)`。
    pinned_backdrop: Option<(BackdropCacheKey, u64)>,
}

pub(crate) struct CachedPathMask {
    pub(crate) _texture: wgpu::Texture,
    pub(crate) view: wgpu::TextureView,
    byte_size: usize,
    last_used_frame: u64,
}

const MAX_POOLED_TARGETS: usize = 32;
const MAX_CACHED_MASKS: usize = 64;
/// 默认空闲离屏纹理池显存预算(16 MiB:兼顾热点毛玻璃/离屏复用与低显存占用,多特效页切换时立即压回预算内)。
pub(crate) const DEFAULT_IDLE_TARGET_BUDGET_BYTES: usize = 16 * 1024 * 1024;
/// 默认空闲离屏纹理最大滞留帧数(切回普通页约 1 秒 @60fps 后自动全部释放)。
pub(crate) const DEFAULT_IDLE_TARGET_MAX_AGE_FRAMES: u64 = 60;
/// 默认 SVG Path `R8Unorm` 遮罩缓存字节预算(8 MiB)。
pub(crate) const DEFAULT_MASK_BUDGET_BYTES: usize = 8 * 1024 * 1024;
/// 默认跨帧毛玻璃模糊小纹理缓存字节预算(8 MiB)。
pub(crate) const DEFAULT_BACKDROP_CACHE_BUDGET_BYTES: usize = 8 * 1024 * 1024;

#[inline]
fn format_bytes_per_pixel(format: wgpu::TextureFormat) -> usize {
    match format {
        wgpu::TextureFormat::R8Unorm | wgpu::TextureFormat::R8Snorm => 1,
        wgpu::TextureFormat::Rg8Unorm
        | wgpu::TextureFormat::Rg8Snorm
        | wgpu::TextureFormat::R16Float => 2,
        wgpu::TextureFormat::Rgba16Float => 8,
        wgpu::TextureFormat::Rgba32Float => 16,
        _ => 4,
    }
}

#[inline]
fn target_byte_size(w: u32, h: u32, format: wgpu::TextureFormat) -> usize {
    (w as usize)
        .saturating_mul(h as usize)
        .saturating_mul(format_bytes_per_pixel(format))
}

pub(crate) struct LayerTargetPool {
    format: wgpu::TextureFormat,
    targets: Vec<PooledTarget>,
    next_gen: u64,
    frame_index: u64,
    total_target_bytes: usize,
    idle_target_budget_bytes: usize,
    idle_target_max_age_frames: u64,
    white_mask: CachedPathMask,
    path_masks: HashMap<u64, CachedPathMask>,
    total_mask_bytes: usize,
    mask_budget_bytes: usize,
    masks_evicted: bool,
    backdrop_cache_budget_bytes: usize,
    backdrop_cache_hits: u64,
    backdrop_cache_misses: u64,
}

impl LayerTargetPool {
    pub(crate) fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self {
        let white_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("velox_white_mask_1x1"),
            size: wgpu::Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &white_tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &[255u8],
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(1),
                rows_per_image: Some(1),
            },
            wgpu::Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
        );
        let white_view = white_tex.create_view(&wgpu::TextureViewDescriptor::default());
        Self {
            format,
            targets: Vec::with_capacity(8),
            next_gen: 1,
            frame_index: 0,
            total_target_bytes: 0,
            idle_target_budget_bytes: DEFAULT_IDLE_TARGET_BUDGET_BYTES,
            idle_target_max_age_frames: DEFAULT_IDLE_TARGET_MAX_AGE_FRAMES,
            white_mask: CachedPathMask {
                _texture: white_tex,
                view: white_view,
                byte_size: 1,
                last_used_frame: 0,
            },
            path_masks: HashMap::with_capacity(16),
            total_mask_bytes: 0,
            mask_budget_bytes: DEFAULT_MASK_BUDGET_BYTES,
            masks_evicted: false,
            backdrop_cache_budget_bytes: DEFAULT_BACKDROP_CACHE_BUDGET_BYTES,
            backdrop_cache_hits: 0,
            backdrop_cache_misses: 0,
        }
    }

    /// 帧开始时推进帧计数并归还所有已借出的离屏目标(保留热点纹理跨帧复用)。
    #[inline]
    pub(crate) fn begin_frame(&mut self) {
        self.frame_index = self.frame_index.saturating_add(1);
        for t in &mut self.targets {
            t.in_use = false;
        }
    }

    /// 借用一张尺寸不小于 `(req_w, req_h)` 的离屏目标纹理,返回其在池中的稳定索引。
    pub(crate) fn acquire(&mut self, device: &wgpu::Device, req_w: u32, req_h: u32) -> usize {
        let bw = req_w.max(1).div_ceil(64) * 64;
        let bh = req_h.max(1).div_ceil(64) * 64;

        // 寻找最紧凑的空闲槽位(面积不大于需求 4 倍,且跳过跨帧钉住的毛玻璃缓存槽位)
        let mut best: Option<(usize, u64)> = None;
        let req_area = (bw as u64) * (bh as u64);
        for (idx, t) in self.targets.iter().enumerate() {
            if !t.in_use && t.pinned_backdrop.is_none() && t.width >= bw && t.height >= bh {
                let area = (t.width as u64) * (t.height as u64);
                if area <= req_area.saturating_mul(4).max(65_536) {
                    if best.is_none_or(|(_, best_a)| area < best_a) {
                        best = Some((idx, area));
                    }
                }
            }
        }
        if let Some((idx, _)) = best {
            let t = &mut self.targets[idx];
            t.in_use = true;
            t.last_used_frame = self.frame_index;
            return idx;
        }

        let byte_size = target_byte_size(bw, bh, self.format);
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("velox_pooled_layer_target"),
            size: wgpu::Extent3d {
                width: bw,
                height: bh,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: self.format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        let generation = self.next_gen;
        self.next_gen = self.next_gen.wrapping_add(1).max(1);
        let entry = PooledTarget {
            texture: tex,
            view,
            width: bw,
            height: bh,
            byte_size,
            generation,
            last_used_frame: self.frame_index,
            in_use: true,
            pinned_backdrop: None,
        };

        // 若池已达数量上限,按最久未用优先回收一个空闲槽位重建(优先非 pinned 槽位)
        if self.targets.len() >= MAX_POOLED_TARGETS {
            if let Some((evict, _)) = self
                .targets
                .iter()
                .enumerate()
                .filter(|(_, t)| !t.in_use)
                .min_by_key(|(_, t)| {
                    (
                        t.pinned_backdrop.is_some(),
                        t.last_used_frame,
                        core::cmp::Reverse(t.byte_size),
                    )
                })
            {
                let old_bytes = self.targets[evict].byte_size;
                self.total_target_bytes = self
                    .total_target_bytes
                    .saturating_sub(old_bytes)
                    .saturating_add(byte_size);
                self.targets[evict] = entry;
                return evict;
            }
        }
        let idx = self.targets.len();
        self.total_target_bytes = self.total_target_bytes.saturating_add(byte_size);
        self.targets.push(entry);
        idx
    }

    #[inline]
    pub(crate) fn release(&mut self, idx: usize) {
        if let Some(t) = self.targets.get_mut(idx) {
            t.in_use = false;
            t.last_used_frame = self.frame_index;
        }
    }

    /// 查找匹配 `(key, underlay_hash)` 的跨帧已模糊毛玻璃小纹理槽位(命中时完全跳过 Kawase 模糊 Pass)。
    pub(crate) fn lookup_backdrop(&mut self, key: BackdropCacheKey, underlay_hash: u64) -> Option<usize> {
        for (idx, t) in self.targets.iter_mut().enumerate() {
            if !t.in_use {
                if let Some((k, h)) = t.pinned_backdrop {
                    if k == key && h == underlay_hash {
                        t.in_use = true;
                        t.last_used_frame = self.frame_index;
                        self.backdrop_cache_hits = self.backdrop_cache_hits.saturating_add(1);
                        return Some(idx);
                    }
                }
            }
        }
        None
    }

    /// 记录一次毛玻璃模糊未命中并将刚计算完成的 `bd_idx` 原地钉住供后续帧复用(零额外显存拷贝)。
    pub(crate) fn pin_backdrop(
        &mut self,
        bd_idx: usize,
        key: BackdropCacheKey,
        underlay_hash: u64,
    ) {
        self.backdrop_cache_misses = self.backdrop_cache_misses.saturating_add(1);
        // 解除同 key 的陈旧缓存槽位,使其立即可回池复用
        for (idx, t) in self.targets.iter_mut().enumerate() {
            if idx != bd_idx {
                if let Some((k, _)) = t.pinned_backdrop {
                    if k == key {
                        t.pinned_backdrop = None;
                    }
                }
            }
        }
        if let Some(t) = self.targets.get_mut(bd_idx) {
            t.pinned_backdrop = Some((key, underlay_hash));
            t.in_use = false;
            t.last_used_frame = self.frame_index;
        }
        // 若钉住的毛玻璃小纹理总字节超预算,按最久未用解除旧钉住标记
        let mut pinned_bytes: usize = self
            .targets
            .iter()
            .filter(|t| t.pinned_backdrop.is_some())
            .map(|t| t.byte_size)
            .sum();
        while pinned_bytes > self.backdrop_cache_budget_bytes {
            let Some((victim, b)) = self
                .targets
                .iter()
                .enumerate()
                .filter(|&(i, t)| i != bd_idx && t.pinned_backdrop.is_some() && !t.in_use)
                .min_by_key(|(_, t)| (t.last_used_frame, core::cmp::Reverse(t.byte_size)))
                .map(|(i, t)| (i, t.byte_size))
            else {
                break;
            };
            self.targets[victim].pinned_backdrop = None;
            pinned_bytes = pinned_bytes.saturating_sub(b);
        }
    }

    /// 使全部跨帧毛玻璃模糊缓存失效(例如视口尺寸变化或手动内存回收时)。
    pub(crate) fn invalidate_backdrop_cache(&mut self) {
        for t in &mut self.targets {
            t.pinned_backdrop = None;
        }
    }

    #[inline]
    pub(crate) fn backdrop_cache_stats(&self) -> (u64, u64) {
        (self.backdrop_cache_hits, self.backdrop_cache_misses)
    }

    /// 多 Pass 帧提交完成后调用:归还本帧全部槽位并按字节预算与闲置年龄回收多余空闲纹理。
    /// 返回是否销毁了任意纹理或遮罩(调用方据此清理失效 `BindGroup`)。
    pub(crate) fn end_frame_reclaim(&mut self) -> bool {
        for t in &mut self.targets {
            t.in_use = false;
        }
        self.reclaim_idle()
    }

    /// 普通单 Pass 帧(无特效/图层)推进帧计数并按年龄与字节预算回收闲置离屏纹理。
    pub(crate) fn tick_idle_frame(&mut self) -> bool {
        self.frame_index = self.frame_index.saturating_add(1);
        for t in &mut self.targets {
            t.in_use = false;
        }
        self.reclaim_idle()
    }

    /// 按闲置年龄与字节预算回收空闲离屏纹理与 SVG 遮罩缓存。
    fn reclaim_idle(&mut self) -> bool {
        let mut evicted = false;

        // 1. 回收超过最大闲置帧数的陈旧空闲纹理
        let max_age = self.idle_target_max_age_frames;
        let cur_frame = self.frame_index;
        if max_age > 0 {
            let mut i = 0;
            while i < self.targets.len() {
                let t = &self.targets[i];
                if !t.in_use && cur_frame.saturating_sub(t.last_used_frame) >= max_age {
                    let removed = self.targets.swap_remove(i);
                    self.total_target_bytes = self.total_target_bytes.saturating_sub(removed.byte_size);
                    evicted = true;
                } else {
                    i += 1;
                }
            }
        }

        // 2. 若空闲纹理总字节仍超过预算,按「最久未用优先、同帧下最大纹理优先」逐个回收
        let mut idle_bytes: usize = self
            .targets
            .iter()
            .filter(|t| !t.in_use)
            .map(|t| t.byte_size)
            .sum();
        while idle_bytes > self.idle_target_budget_bytes {
            let Some((victim, _)) = self
                .targets
                .iter()
                .enumerate()
                .filter(|(_, t)| !t.in_use)
                .min_by_key(|(_, t)| (t.last_used_frame, core::cmp::Reverse(t.byte_size)))
            else {
                break;
            };
            let removed = self.targets.swap_remove(victim);
            idle_bytes = idle_bytes.saturating_sub(removed.byte_size);
            self.total_target_bytes = self.total_target_bytes.saturating_sub(removed.byte_size);
            evicted = true;
        }

        // 3. 遮罩缓存超出字节预算或数量上限时按 LRU 淘汰
        if self.evict_masks_to_budget(0) {
            evicted = true;
        }
        if self.masks_evicted {
            self.masks_evicted = false;
            evicted = true;
        }

        evicted
    }

    /// 视口尺寸变化(尤其是窗口缩小)时,立即回收明显大于新视口的空闲大纹理。
    pub(crate) fn on_viewport_resized(&mut self, new_w: u32, new_h: u32) -> bool {
        self.invalidate_backdrop_cache();
        let nbw = new_w.max(1).div_ceil(64) * 64;
        let nbh = new_h.max(1).div_ceil(64) * 64;
        let mut evicted = false;
        let mut i = 0;
        while i < self.targets.len() {
            let t = &self.targets[i];
            if !t.in_use && (t.width > nbw || t.height > nbh) {
                let removed = self.targets.swap_remove(i);
                self.total_target_bytes = self.total_target_bytes.saturating_sub(removed.byte_size);
                evicted = true;
            } else {
                i += 1;
            }
        }
        if self.reclaim_idle() {
            evicted = true;
        }
        evicted
    }

    /// 后台化或内存警告时立即释放全部空闲离屏纹理与 SVG 遮罩缓存。
    pub(crate) fn trim_all_idle(&mut self) -> bool {
        self.invalidate_backdrop_cache();
        let mut evicted = false;
        let mut i = 0;
        while i < self.targets.len() {
            if !self.targets[i].in_use {
                let removed = self.targets.swap_remove(i);
                self.total_target_bytes = self.total_target_bytes.saturating_sub(removed.byte_size);
                evicted = true;
            } else {
                i += 1;
            }
        }
        if !self.path_masks.is_empty() {
            self.path_masks.clear();
            self.total_mask_bytes = 0;
            self.masks_evicted = false;
            evicted = true;
        }
        evicted
    }

    fn evict_masks_to_budget(&mut self, incoming_bytes: usize) -> bool {
        let mut evicted = false;
        let cap = MAX_CACHED_MASKS.saturating_sub(usize::from(incoming_bytes > 0));
        while !self.path_masks.is_empty()
            && (self.total_mask_bytes.saturating_add(incoming_bytes) > self.mask_budget_bytes
                || self.path_masks.len() > cap)
        {
            let Some((&victim_key, _)) = self
                .path_masks
                .iter()
                .min_by_key(|(_, m)| (m.last_used_frame, core::cmp::Reverse(m.byte_size)))
            else {
                break;
            };
            if let Some(removed) = self.path_masks.remove(&victim_key) {
                self.total_mask_bytes = self.total_mask_bytes.saturating_sub(removed.byte_size);
                evicted = true;
            }
        }
        evicted
    }

    #[inline]
    pub(crate) fn take_masks_evicted(&mut self) -> bool {
        let v = self.masks_evicted;
        self.masks_evicted = false;
        v
    }

    #[inline]
    pub(crate) fn has_live_generation(&self, generation: u64) -> bool {
        self.targets.iter().any(|t| t.generation == generation)
    }

    #[inline]
    pub(crate) fn has_live_mask(&self, mask_key: u64) -> bool {
        mask_key == 0 || self.path_masks.contains_key(&mask_key)
    }

    #[inline]
    pub(crate) fn target_bytes(&self) -> usize {
        self.total_target_bytes
    }

    #[inline]
    pub(crate) fn mask_bytes(&self) -> usize {
        self.total_mask_bytes
    }

    #[inline]
    pub(crate) fn target_count(&self) -> usize {
        self.targets.len()
    }

    #[inline]
    pub(crate) fn mask_count(&self) -> usize {
        self.path_masks.len()
    }

    #[inline]
    pub(crate) fn set_idle_target_budget_bytes(&mut self, bytes: usize) -> bool {
        self.idle_target_budget_bytes = bytes;
        self.reclaim_idle()
    }

    #[inline]
    pub(crate) fn set_idle_target_max_age_frames(&mut self, frames: u64) -> bool {
        self.idle_target_max_age_frames = frames;
        self.reclaim_idle()
    }

    #[inline]
    pub(crate) fn set_mask_budget_bytes(&mut self, bytes: usize) -> bool {
        self.mask_budget_bytes = bytes;
        self.reclaim_idle()
    }

    #[inline]
    pub(crate) fn get(&self, idx: usize) -> &PooledTarget {
        &self.targets[idx]
    }

    #[inline]
    pub(crate) fn white_mask_view(&self) -> &wgpu::TextureView {
        &self.white_mask.view
    }

    /// 确保指定 SVG Path 抗锯齿 `R8Unorm` 裁剪遮罩已上传缓存,返回其缓存键(按字节预算与 LRU 淘汰)。
    pub(crate) fn ensure_path_mask(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        path_d: &str,
        w: u32,
        h: u32,
    ) -> u64 {
        let w = w.max(1);
        let h = h.max(1);
        let mut key: u64 = 0xcbf2_9ce4_8422_2325;
        let mix = |k: &mut u64, v: u64| {
            *k ^= v;
            *k = k.wrapping_mul(0x0100_0000_01b3);
        };
        mix(&mut key, w as u64);
        mix(&mut key, h as u64);
        for &b in path_d.as_bytes() {
            mix(&mut key, b as u64);
        }

        if let Some(entry) = self.path_masks.get_mut(&key) {
            entry.last_used_frame = self.frame_index;
            return key;
        }
        let incoming_bytes = (w as usize).saturating_mul(h as usize);
        if self.evict_masks_to_budget(incoming_bytes) {
            self.masks_evicted = true;
        }

        let mut rgba = vec![Rgba8888(0); (w as usize) * (h as usize)];
        let reg = Region::new(0, 0, w as i16, h as i16);
        if path_d.trim_start().starts_with('<') {
            rasterize_svg(
                path_d,
                reg,
                reg,
                SvgRenderOptions::default(),
                0,
                0,
                w as usize,
                &mut rgba,
            );
        } else {
            rasterize_svg_path(
                path_d,
                reg,
                reg,
                Color::WHITE,
                0,
                0,
                0,
                w as usize,
                &mut rgba,
            );
        }
        let mask_bytes: Vec<u8> = rgba.into_iter().map(|p| p.to_color().a()).collect();

        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("velox_svg_clip_mask"),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &mask_bytes,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(w),
                rows_per_image: Some(h),
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        self.total_mask_bytes = self.total_mask_bytes.saturating_add(incoming_bytes);
        self.path_masks.insert(
            key,
            CachedPathMask {
                _texture: tex,
                view,
                byte_size: incoming_bytes,
                last_used_frame: self.frame_index,
            },
        );
        key
    }

    /// 按缓存键只读获取已上传的 SVG Path 遮罩视图(缺省回退至 1×1 全白遮罩)。
    #[inline]
    pub(crate) fn path_mask_view(&self, key: Option<u64>) -> &wgpu::TextureView {
        key.and_then(|k| self.path_masks.get(&k).map(|m| &m.view))
            .unwrap_or(&self.white_mask.view)
    }
}