Skip to main content

rgpui_wgpu/
shared_context.rs

1//! 进程级共享的 wgpu GPU 上下文。
2//!
3//! 当 rgpui 平台创建第一个 `WgpuContext` 时,会在此处注册共享的
4//! `wgpu::Device` 和 `wgpu::Queue`。`rgpui-3d` 等第三方渲染器
5//! 可以获取这些共享资源,避免创建多个 `wgpu::Instance`。
6
7use std::sync::{Arc, OnceLock};
8
9/// 共享的 wgpu GPU 上下文,用于跨 crate 复用同一 wgpu 实例。
10pub struct SharedGpuContext {
11    /// 共享的 wgpu 实例
12    pub instance: wgpu::Instance,
13    /// 共享的 wgpu 设备
14    pub device: Arc<wgpu::Device>,
15    /// 共享的 wgpu 队列
16    pub queue: Arc<wgpu::Queue>,
17}
18
19static SHARED: OnceLock<SharedGpuContext> = OnceLock::new();
20
21/// 注册共享的 wgpu GPU 上下文。仅第一次调用生效,后续调用被忽略。
22pub fn register(instance: wgpu::Instance, device: Arc<wgpu::Device>, queue: Arc<wgpu::Queue>) {
23    let _ = SHARED.set(SharedGpuContext {
24        instance,
25        device,
26        queue,
27    });
28}
29
30/// 获取共享的 wgpu GPU 上下文(如果已注册)。
31pub fn try_get() -> Option<&'static SharedGpuContext> {
32    SHARED.get()
33}