Skip to main content

velox_engine/renderers/wgpu/
shared_exporter.rs

1//! 无锁三缓冲共享显存导出渲染器(`WgpuSharedExportRenderer`)。
2//!
3//! 专为将 Velox 2D SDF GPU 渲染结果零拷贝嵌入外部宿主框架(Qt6 `QQuickRhiItem`、GTK4 `GdkDmabufTextureBuilder`、
4//! WinUI 3 `SurfaceImageSource`、WPF `D3DImage`、Android `ASurfaceTransaction`、iOS `IOSurface` 与 Wayland `zwp_linux_dmabuf_v1`)设计:
5//! - **无锁三缓冲邮箱(Write / Ready / Read)**:原子 CAS 交换最新完成槽位,渲染与宿主合成线程零锁争用;
6//! - **3 帧脏区合并防残影**:自动合并最近 3 帧脏矩形并集,并结合 GPU-to-GPU 极速局部拷贝消除三缓冲 3 帧老画面闪烁;
7//! - **预乘透明背景(Premultiplied Alpha)**:默认清屏色 `wgpu::Color::TRANSPARENT`,原生支持镂空悬浮 HUD 叠放;
8//! - **安全 Resize 代数隔离与延迟回收(`generation_id` + `retired_pools`)**:宿主持有旧句柄期间绝不悬垂释放。
9
10use ::wgpu;
11use core::sync::atomic::{AtomicU64, AtomicU8, Ordering};
12use std::collections::VecDeque;
13use std::vec;
14use std::vec::Vec;
15
16use crate::arena::SmallVec;
17use crate::engine::VeloxEngine;
18use crate::motion::DrawOp;
19use crate::paint::ExternalTextureId;
20use crate::solver::Region;
21
22use super::interop::{
23    allocate_shared_texture, create_shared_fence, ExportedHandle, ExportedTextureAlloc,
24    ExternalSyncHandle, PlatformSharedFence,
25};
26use super::pipeline::WgpuRenderer;
27use super::window::PreparedWgpuContext;
28
29/// 单个三缓冲共享显存槽位(包装外部显存句柄纹理与最新就绪栅栏值)。
30pub struct SharedSlot {
31    alloc: ExportedTextureAlloc,
32    ready_fence_val: AtomicU64,
33}
34
35impl SharedSlot {
36    /// 返回底层共享 `wgpu::Texture` 引用。
37    #[inline]
38    pub fn texture(&self) -> &wgpu::Texture {
39        &self.alloc.texture
40    }
41
42    /// 返回底层共享 `wgpu::TextureView` 引用。
43    #[inline]
44    pub fn view(&self) -> &wgpu::TextureView {
45        &self.alloc.view
46    }
47
48    /// 返回跨平台共享显存句柄描述符。
49    #[inline]
50    pub const fn handle(&self) -> ExportedHandle {
51        self.alloc.handle
52    }
53
54    /// 返回该槽位最近一次写入完成对应的 GPU 栅栏值。
55    #[inline]
56    pub fn ready_fence_value(&self) -> u64 {
57        self.ready_fence_val.load(Ordering::Acquire)
58    }
59}
60
61/// 宿主调用 [`WgpuSharedExportRenderer::acquire_shared_frame`] 获得的只读共享帧租约。
62#[derive(Clone, Debug)]
63pub struct SharedFrameLease {
64    /// 表面重建代数(窗口 Resize 后递增,宿主据以检测并重新导入共享句柄)。
65    pub generation_id: u32,
66    /// 当前锁定的三缓冲槽位索引(`0..3`)。
67    pub slot_index: u8,
68    /// 物理像素宽度。
69    pub width: u32,
70    /// 物理像素高度。
71    pub height: u32,
72    /// 像素格式(默认 `Bgra8Unorm` 或 `Rgba8Unorm`,预乘 Alpha)。
73    pub format: wgpu::TextureFormat,
74    /// 跨 API 显存导出句柄(Win32 NT HANDLE / Linux dma_buf fd / Apple IOSurface / Android AHB)。
75    pub handle: ExportedHandle,
76    /// 跨 API GPU 同步栅栏/信号量句柄。
77    pub sync_handle: ExternalSyncHandle,
78    /// 宿主采样前需等待的 GPU 栅栏单调计数值。
79    pub fence_value: u64,
80    /// 合并最近 3 帧后的有效脏矩形列表(供宿主做局部合成优化)。
81    pub dirty_rects: SmallVec<Region, 8>,
82    /// 本次获取是否为新提交帧(`false` 表示复用了上次最新帧)。
83    pub is_fresh: bool,
84}
85
86/// 等待宿主归还或 GPU 栅栏通过后延迟释放的旧代数三缓冲池。
87struct RetiredPool {
88    generation_id: u32,
89    last_fence_val: u64,
90    in_use_by_host: bool,
91    _slots: [SharedSlot; 3],
92}
93
94/// 打包无锁三缓冲状态字:`ready (0..2) | read (2..4) | write (4..6) | fresh (6)`。
95#[inline(always)]
96const fn pack_mailbox(ready: u8, read: u8, write: u8, fresh: bool) -> u8 {
97    (ready & 0x3) | ((read & 0x3) << 2) | ((write & 0x3) << 4) | (if fresh { 1 << 6 } else { 0 })
98}
99
100#[inline(always)]
101const fn unpack_mailbox(state: u8) -> (u8, u8, u8, bool) {
102    (
103        state & 0x3,
104        (state >> 2) & 0x3,
105        (state >> 4) & 0x3,
106        (state & (1 << 6)) != 0,
107    )
108}
109
110/// 跨框架零拷贝显存共享导出渲染器(无锁三缓冲邮箱 + 3 帧脏区合并 + 预乘 Alpha HUD + 延迟回收)。
111pub struct WgpuSharedExportRenderer {
112    ctx: PreparedWgpuContext,
113    sdf_renderer: WgpuRenderer,
114    format: wgpu::TextureFormat,
115    width: u32,
116    height: u32,
117    clear_color: wgpu::Color,
118    /// 持久增量画布纹理(承载本帧渲染,通过 GPU-to-GPU 拷贝同步至三缓冲导出槽,彻底避免三缓冲 3 帧残影)。
119    canvas_tex: wgpu::Texture,
120    canvas_view: wgpu::TextureView,
121    slots: [SharedSlot; 3],
122    /// 无锁三缓冲邮箱状态字(初始 `ready=0, read=1, write=2, fresh=false`)。
123    mailbox_state: AtomicU8,
124    shared_fence: PlatformSharedFence,
125    next_fence_val: AtomicU64,
126    generation_id: u32,
127    /// 最近 2 帧的物理脏矩形历史(用于计算三缓冲 `Union(Dirty[N], Dirty[N-1], Dirty[N-2])`)。
128    dirty_history: [SmallVec<Region, 8>; 2],
129    last_merged_dirty: SmallVec<Region, 8>,
130    force_full_sync: bool,
131    retired_pools: VecDeque<RetiredPool>,
132}
133
134impl WgpuSharedExportRenderer {
135    /// 按宿主物理显卡 LUID / UUID 对齐并初始化三缓冲共享导出渲染器。
136    ///
137    /// 默认使用 `Bgra8Unorm`(Windows/macOS/Linux 原生合成格式)与 `wgpu::Color::TRANSPARENT` 预乘透明清屏,
138    /// 直接支持镂空悬浮 HUD 叠放至外部窗口上方。
139    pub fn new(
140        width: u32,
141        height: u32,
142        adapter_luid: Option<[u8; 8]>,
143        device_uuid: Option<[u8; 16]>,
144    ) -> Option<Self> {
145        let ctx = PreparedWgpuContext::from_host_adapter_id(adapter_luid, device_uuid)?;
146        Some(Self::from_context(
147            ctx,
148            width,
149            height,
150            wgpu::TextureFormat::Bgra8Unorm,
151        ))
152    }
153
154    /// 从已有的 [`PreparedWgpuContext`](支持与外部渲染器共享同一 `wgpu::Device`)创建三缓冲共享导出渲染器。
155    pub fn from_context(
156        mut ctx: PreparedWgpuContext,
157        width: u32,
158        height: u32,
159        format: wgpu::TextureFormat,
160    ) -> Self {
161        let w = width.max(1);
162        let h = height.max(1);
163        let sdf_renderer = ctx.take_or_create_renderer(format);
164        let luid = ctx.adapter_luid().unwrap_or([0u8; 8]);
165        let (canvas_tex, canvas_view) = Self::create_canvas(ctx.device(), w, h, format);
166        let slots = Self::create_slot_triple(ctx.device(), w, h, format, luid);
167        let shared_fence = create_shared_fence(ctx.device());
168
169        Self {
170            ctx,
171            sdf_renderer,
172            format,
173            width: w,
174            height: h,
175            clear_color: wgpu::Color::TRANSPARENT,
176            canvas_tex,
177            canvas_view,
178            slots,
179            mailbox_state: AtomicU8::new(pack_mailbox(0, 1, 2, false)),
180            shared_fence,
181            next_fence_val: AtomicU64::new(1),
182            generation_id: 1,
183            dirty_history: [SmallVec::new(), SmallVec::new()],
184            last_merged_dirty: SmallVec::new(),
185            force_full_sync: true,
186            retired_pools: VecDeque::new(),
187        }
188    }
189
190    fn create_canvas(
191        device: &wgpu::Device,
192        width: u32,
193        height: u32,
194        format: wgpu::TextureFormat,
195    ) -> (wgpu::Texture, wgpu::TextureView) {
196        let tex = device.create_texture(&wgpu::TextureDescriptor {
197            label: Some("velox_shared_exporter_canvas"),
198            size: wgpu::Extent3d {
199                width: width.max(1),
200                height: height.max(1),
201                depth_or_array_layers: 1,
202            },
203            mip_level_count: 1,
204            sample_count: 1,
205            dimension: wgpu::TextureDimension::D2,
206            format,
207            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
208                | wgpu::TextureUsages::COPY_SRC
209                | wgpu::TextureUsages::TEXTURE_BINDING,
210            view_formats: &[],
211        });
212        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
213        (tex, view)
214    }
215
216    fn create_slot_triple(
217        device: &wgpu::Device,
218        width: u32,
219        height: u32,
220        format: wgpu::TextureFormat,
221        luid: [u8; 8],
222    ) -> [SharedSlot; 3] {
223        [
224            SharedSlot {
225                alloc: allocate_shared_texture(device, width, height, format, luid),
226                ready_fence_val: AtomicU64::new(0),
227            },
228            SharedSlot {
229                alloc: allocate_shared_texture(device, width, height, format, luid),
230                ready_fence_val: AtomicU64::new(0),
231            },
232            SharedSlot {
233                alloc: allocate_shared_texture(device, width, height, format, luid),
234                ready_fence_val: AtomicU64::new(0),
235            },
236        ]
237    }
238
239    /// 设置清屏背景色(默认 `wgpu::Color::TRANSPARENT`,供镂空悬浮 HUD 预乘 Alpha 合成)。
240    #[inline]
241    pub fn set_clear_color(&mut self, color: wgpu::Color) {
242        self.clear_color = color;
243    }
244
245    /// 返回当前共享表面重建代数 `generation_id`。
246    #[inline]
247    pub const fn generation_id(&self) -> u32 {
248        self.generation_id
249    }
250
251    /// 返回当前共享目标物理像素尺寸 `(width, height)`。
252    #[inline]
253    pub const fn size(&self) -> (u32, u32) {
254        (self.width, self.height)
255    }
256
257    /// 返回当前像素格式。
258    #[inline]
259    pub const fn format(&self) -> wgpu::TextureFormat {
260        self.format
261    }
262
263    /// 返回底层 `wgpu::Device` 引用(可用于同设备创建外部纹理并注册零拷贝导入)。
264    #[inline]
265    pub fn device(&self) -> &wgpu::Device {
266        self.ctx.device()
267    }
268
269    /// 返回底层 `wgpu::Queue` 引用。
270    #[inline]
271    pub fn queue(&self) -> &wgpu::Queue {
272        self.ctx.queue()
273    }
274
275    /// 返回物理适配器名称与图形 API 名称。
276    #[inline]
277    pub fn adapter_info(&self) -> (&str, &'static str) {
278        (self.ctx.adapter_name(), self.ctx.backend_name())
279    }
280
281    /// 返回当前匹配到的 Windows DX12 物理显卡 LUID(若可用)。
282    #[inline]
283    pub const fn adapter_luid(&self) -> Option<[u8; 8]> {
284        self.ctx.adapter_luid()
285    }
286
287    /// 返回当前匹配到的 Vulkan 物理显卡 UUID(若可用)。
288    #[inline]
289    pub const fn device_uuid(&self) -> Option<[u8; 16]> {
290        self.ctx.device_uuid()
291    }
292
293    /// 返回跨平台共享 GPU 同步栅栏句柄。
294    #[inline]
295    pub fn sync_handle(&self) -> ExternalSyncHandle {
296        self.shared_fence.export_handle()
297    }
298
299    /// 返回内部 `WgpuRenderer` 可变引用。
300    #[inline]
301    pub fn renderer_mut(&mut self) -> &mut WgpuRenderer {
302        &mut self.sdf_renderer
303    }
304
305    /// 注册外部零拷贝 GPU 纹理(支持“导入外部海图 -> Velox 叠加毛玻璃 HUD -> 导出共享句柄”全链路闭环)。
306    #[inline]
307    pub fn register_external_texture(
308        &mut self,
309        view: wgpu::TextureView,
310        sampler: Option<wgpu::Sampler>,
311    ) -> ExternalTextureId {
312        self.sdf_renderer.register_external_texture(view, sampler)
313    }
314
315    /// 原地更新已注册的外部零拷贝 GPU 纹理视图。
316    #[inline]
317    pub fn update_external_texture(
318        &mut self,
319        id: ExternalTextureId,
320        view: wgpu::TextureView,
321    ) -> bool {
322        self.sdf_renderer.update_external_texture(id, view)
323    }
324
325    /// 注销外部零拷贝纹理。
326    #[inline]
327    pub fn unregister_external_texture(&mut self, id: ExternalTextureId) -> bool {
328        self.sdf_renderer.unregister_external_texture(id)
329    }
330
331    /// 返回待延迟销毁的旧代数池数量(用于验证 Resize 后的延迟回收机制)。
332    #[inline]
333    pub fn retired_pool_count(&self) -> usize {
334        self.retired_pools.len()
335    }
336
337    /// 调整导出表面物理尺寸:重建三缓冲并递增 `generation_id`,将旧槽位移入延迟回收队列防悬垂。
338    pub fn resize(&mut self, width: u32, height: u32) {
339        let w = width.max(1);
340        let h = height.max(1);
341        if self.width == w && self.height == h {
342            return;
343        }
344        let luid = self.ctx.adapter_luid().unwrap_or([0u8; 8]);
345        let new_slots = Self::create_slot_triple(self.ctx.device(), w, h, self.format, luid);
346        let old_slots = core::mem::replace(&mut self.slots, new_slots);
347        let last_fence = self.next_fence_val.load(Ordering::Acquire).saturating_sub(1);
348        self.retired_pools.push_back(RetiredPool {
349            generation_id: self.generation_id,
350            last_fence_val: last_fence,
351            in_use_by_host: true,
352            _slots: old_slots,
353        });
354
355        let (ct, cv) = Self::create_canvas(self.ctx.device(), w, h, self.format);
356        self.canvas_tex = ct;
357        self.canvas_view = cv;
358        self.width = w;
359        self.height = h;
360        self.generation_id = self.generation_id.wrapping_add(1).max(1);
361        self.mailbox_state
362            .store(pack_mailbox(0, 1, 2, false), Ordering::Release);
363        self.dirty_history[0].clear();
364        self.dirty_history[1].clear();
365        self.last_merged_dirty.clear();
366        self.force_full_sync = true;
367        self.gc_retired_pools();
368    }
369
370    /// 回收宿主已释放且 GPU 栅栏已完成的旧代数共享池。
371    pub fn gc_retired_pools(&mut self) {
372        let completed = self.shared_fence.completed_value();
373        while let Some(front) = self.retired_pools.front() {
374            if !front.in_use_by_host && completed >= front.last_fence_val {
375                self.retired_pools.pop_front();
376            } else {
377                break;
378            }
379        }
380    }
381
382    /// 计算三缓冲安全的 3 帧脏矩形并集 `Union(Dirty[N], Dirty[N-1], Dirty[N-2])`。
383    fn merge_3_frame_dirty(&mut self, current_dirty: &[Region], sf: f32) -> SmallVec<Region, 8> {
384        let full = Region::new(0, 0, self.width as i16, self.height as i16);
385        let mut cur_phys: SmallVec<Region, 8> = SmallVec::new();
386        for &r in current_dirty {
387            if r.is_empty() {
388                continue;
389            }
390            let x0 = ((r.x as f32) * sf).floor().max(0.0) as i16;
391            let y0 = ((r.y as f32) * sf).floor().max(0.0) as i16;
392            let x1 = ((r.right() as f32) * sf).ceil().min(self.width as f32) as i16;
393            let y1 = ((r.bottom() as f32) * sf).ceil().min(self.height as f32) as i16;
394            if x1 > x0 && y1 > y0 {
395                let _ = cur_phys.push(Region::new(x0, y0, x1 - x0, y1 - y0));
396            }
397        }
398
399        let mut merged: SmallVec<Region, 8> = SmallVec::new();
400        if self.force_full_sync || cur_phys.is_empty() {
401            let _ = merged.push(full);
402            self.force_full_sync = false;
403        } else {
404            let mut push_or_union = |r: Region| {
405                if !merged.push(r) {
406                    // 超过 8 块时合并进首块包围盒,保证零堆且绝对不丢脏区
407                    let mut u = merged[0];
408                    let x0 = u.x.min(r.x);
409                    let y0 = u.y.min(r.y);
410                    let x1 = u.right().max(r.right());
411                    let y1 = u.bottom().max(r.bottom());
412                    u = Region::new(x0, y0, x1 - x0, y1 - y0);
413                    merged[0] = u;
414                }
415            };
416            for &r in cur_phys.as_slice() {
417                push_or_union(r);
418            }
419            for &r in self.dirty_history[0].as_slice() {
420                push_or_union(r);
421            }
422            for &r in self.dirty_history[1].as_slice() {
423                push_or_union(r);
424            }
425        }
426
427        self.dirty_history[1] = self.dirty_history[0].clone();
428        self.dirty_history[0] = cur_phys;
429        self.last_merged_dirty = merged.clone();
430        merged
431    }
432
433    /// 将当前帧 `DrawOp` 渲染并零拷贝发布到三缓冲邮箱的 `Ready` 槽位,返回该帧对应的 GPU 栅栏值。
434    pub fn render_draw_ops(
435        &mut self,
436        ops: &[DrawOp<'_>],
437        viewport: Region,
438        scale_factor: f32,
439        dirty_regions: &[Region],
440    ) -> u64 {
441        let sf = scale_factor.clamp(0.5, 4.0);
442        let pw = ((viewport.w.max(1) as f32) * sf).round().max(1.0) as u32;
443        let ph = ((viewport.h.max(1) as f32) * sf).round().max(1.0) as u32;
444        if pw != self.width || ph != self.height {
445            self.resize(pw, ph);
446        }
447
448        let merged_dirty = self.merge_3_frame_dirty(dirty_regions, sf);
449
450        // 1. 100% 复用现有 WgpuRenderer 渲染到持久画布纹理(零破坏现有 SDF + 渐变 + 毛玻璃 + 外部导入管线)
451        self.sdf_renderer.render_to_view(
452            self.ctx.device(),
453            self.ctx.queue(),
454            ops,
455            viewport,
456            sf,
457            &self.canvas_view,
458            self.width,
459            self.height,
460            self.clear_color,
461        );
462
463        // 2. 确定当前渲染线程独占的 `write_idx` 槽位,执行 GPU-to-GPU 极速脏区拷贝
464        let (_, _, write_idx, _) = unpack_mailbox(self.mailbox_state.load(Ordering::Acquire));
465        let dst_tex = &self.slots[write_idx as usize].alloc.texture;
466        let mut copy_enc =
467            self.ctx
468                .device()
469                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
470                    label: Some("velox_shared_exporter_copy"),
471                });
472        for &r in merged_dirty.as_slice() {
473            let x = (r.x.max(0) as u32).min(self.width);
474            let y = (r.y.max(0) as u32).min(self.height);
475            let cw = (r.w.max(0) as u32).min(self.width.saturating_sub(x));
476            let ch = (r.h.max(0) as u32).min(self.height.saturating_sub(y));
477            if cw == 0 || ch == 0 {
478                continue;
479            }
480            copy_enc.copy_texture_to_texture(
481                wgpu::TexelCopyTextureInfo {
482                    texture: &self.canvas_tex,
483                    mip_level: 0,
484                    origin: wgpu::Origin3d { x, y, z: 0 },
485                    aspect: wgpu::TextureAspect::All,
486                },
487                wgpu::TexelCopyTextureInfo {
488                    texture: dst_tex,
489                    mip_level: 0,
490                    origin: wgpu::Origin3d { x, y, z: 0 },
491                    aspect: wgpu::TextureAspect::All,
492                },
493                wgpu::Extent3d {
494                    width: cw,
495                    height: ch,
496                    depth_or_array_layers: 1,
497                },
498            );
499        }
500        self.ctx.queue().submit([copy_enc.finish()]);
501
502        // 3. 在 GPU 命令队列末尾写入单调递增的共享栅栏值
503        let fence_val = self.next_fence_val.fetch_add(1, Ordering::AcqRel);
504        self.shared_fence
505            .signal_on_queue(self.ctx.device(), fence_val);
506        self.slots[write_idx as usize]
507            .ready_fence_val
508            .store(fence_val, Ordering::Release);
509
510        // 4. 无锁 CAS 交换 `write_idx <-> ready_idx` 并置 `fresh = true`
511        loop {
512            let cur = self.mailbox_state.load(Ordering::Acquire);
513            let (ready, read, write, _fresh) = unpack_mailbox(cur);
514            let next = pack_mailbox(write, read, ready, true);
515            if self
516                .mailbox_state
517                .compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire)
518                .is_ok()
519            {
520                break;
521            }
522        }
523
524        self.gc_retired_pools();
525        fence_val
526    }
527
528    /// 推进一帧 [`VeloxEngine`] 并在有脏区(或首帧)时渲染发布至共享三缓冲邮箱。
529    pub fn step_and_render(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> Option<u64> {
530        let mut dirty: SmallVec<Region, 8> = SmallVec::new();
531        for &r in engine.step_frame_dt(dt_ms) {
532            let _ = dirty.push(r);
533        }
534        if dirty.is_empty() && !self.force_full_sync {
535            return None;
536        }
537        let vp = engine.viewport_region();
538        let sf = engine.scale_factor();
539        let ops = engine.cached_draw_ops();
540        Some(self.render_draw_ops(ops, vp, sf, dirty.as_slice()))
541    }
542
543    /// 宿主合成线程无锁获取最新就绪的共享显存帧句柄(若无新帧则返回当前 `read` 槽位且 `is_fresh = false`)。
544    pub fn acquire_shared_frame(&self) -> SharedFrameLease {
545        let (slot_idx, is_fresh) = loop {
546            let cur = self.mailbox_state.load(Ordering::Acquire);
547            let (ready, read, write, fresh) = unpack_mailbox(cur);
548            if !fresh {
549                break (read, false);
550            }
551            let next = pack_mailbox(read, ready, write, false);
552            if self
553                .mailbox_state
554                .compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire)
555                .is_ok()
556            {
557                break (ready, true);
558            }
559        };
560
561        let slot = &self.slots[slot_idx as usize];
562        SharedFrameLease {
563            generation_id: self.generation_id,
564            slot_index: slot_idx,
565            width: self.width,
566            height: self.height,
567            format: self.format,
568            handle: slot.handle(),
569            sync_handle: self.shared_fence.export_handle(),
570            fence_value: slot.ready_fence_value(),
571            dirty_rects: self.last_merged_dirty.clone(),
572            is_fresh,
573        }
574    }
575
576    /// 宿主完成采样后归还帧租约;若为旧代数租约则标记为可安全回收并触发延迟垃圾回收。
577    pub fn release_shared_frame(&mut self, generation_id: u32, _slot_index: u8) {
578        if generation_id != self.generation_id {
579            for pool in &mut self.retired_pools {
580                if pool.generation_id == generation_id {
581                    pool.in_use_by_host = false;
582                }
583            }
584            self.gc_retired_pools();
585        }
586    }
587
588    /// 阻塞等待指定栅栏值在 GPU 上执行完毕(主要供同步测试或同步宿主使用)。
589    pub fn wait_fence_cpu(&self, fence_value: u64, timeout_ms: u32) -> bool {
590        self.shared_fence
591            .wait_cpu(self.ctx.device(), fence_value, timeout_ms)
592    }
593
594    /// 测试与诊断辅助:将指定共享槽位的显存内容回读为直通 RGBA/BGRA 字节流(验证真实渲染像素与透明通道)。
595    pub fn readback_slot_bytes(&self, slot_index: u8) -> Option<Vec<u8>> {
596        let slot = self.slots.get(slot_index as usize)?;
597        let fence_val = slot.ready_fence_value();
598        if fence_val > 0 {
599            let _ = self.wait_fence_cpu(fence_val, 3000);
600        }
601        let unpadded = self.width * 4;
602        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
603        let padded = unpadded.div_ceil(align) * align;
604        let rb = self.ctx.device().create_buffer(&wgpu::BufferDescriptor {
605            label: Some("velox_shared_slot_readback"),
606            size: (padded as u64) * (self.height as u64),
607            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
608            mapped_at_creation: false,
609        });
610        let mut enc =
611            self.ctx
612                .device()
613                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
614                    label: Some("velox_shared_slot_readback_enc"),
615                });
616        enc.copy_texture_to_buffer(
617            wgpu::TexelCopyTextureInfo {
618                texture: slot.texture(),
619                mip_level: 0,
620                origin: wgpu::Origin3d::ZERO,
621                aspect: wgpu::TextureAspect::All,
622            },
623            wgpu::TexelCopyBufferInfo {
624                buffer: &rb,
625                layout: wgpu::TexelCopyBufferLayout {
626                    offset: 0,
627                    bytes_per_row: Some(padded),
628                    rows_per_image: Some(self.height),
629                },
630            },
631            wgpu::Extent3d {
632                width: self.width,
633                height: self.height,
634                depth_or_array_layers: 1,
635            },
636        );
637        self.ctx.queue().submit([enc.finish()]);
638
639        let slice = rb.slice(..);
640        let (tx, rx) = std::sync::mpsc::channel();
641        slice.map_async(wgpu::MapMode::Read, move |res| {
642            let _ = tx.send(res);
643        });
644        let _ = self.ctx.device().poll(wgpu::PollType::wait_indefinitely());
645        rx.recv().ok()?.ok()?;
646
647        let mapped = slice.get_mapped_range().ok()?;
648        let mut out = vec![0u8; (self.width as usize) * (self.height as usize) * 4];
649        let row_bytes = (self.width as usize) * 4;
650        let stride = padded as usize;
651        for y in 0..(self.height as usize) {
652            let src = &mapped[y * stride..y * stride + row_bytes];
653            out[y * row_bytes..(y + 1) * row_bytes].copy_from_slice(src);
654        }
655        drop(mapped);
656        rb.unmap();
657        Some(out)
658    }
659}