GPUContext API
WebGPU 设备和资源管理的核心类。
构造函数
GPUContext()
创建新的 GPUContext 实例。
typescript
const context = new GPUContext();1
方法
init()
异步初始化 WebGPU 设备和适配器。
typescript
await context.init();1
抛出:
WebGPUNotSupportedError- 浏览器不支持 WebGPUDeviceInitializationError- 设备初始化失败
getDevice()
获取 WebGPU 设备实例。
typescript
const device: GPUDevice = context.getDevice();1
getQueue()
获取命令队列用于提交计算命令。
typescript
const queue: GPUQueue = context.getQueue();1
createBuffer(descriptor)
创建 GPU 缓冲区。
typescript
const buffer = context.createBuffer({
size: 1024,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
mappedAtCreation: false
});1
2
3
4
5
2
3
4
5
参数:
descriptor- GPUBufferDescriptor 配置
返回: GPUBuffer
deferDestroy(buffer)
延迟销毁缓冲区,用于资源管理优化。
typescript
context.deferDestroy(buffer);1
这将在下一帧实际释放资源,避免立即回收导致的性能问题。
sync()
等待所有待处理的 GPU 工作完成。
typescript
await context.sync();1
用于确保 GPU 计算完成后再读取结果。
destroy()
销毁上下文及其所有资源。
typescript
context.destroy();1
这将释放:
- WebGPU 设备连接
- 所有未销毁的缓冲区
- 管线和绑定组资源
示例
完整使用流程
typescript
const context = new GPUContext();
try {
// 初始化
await context.init();
// 创建缓冲区
const buffer = context.createBuffer({
size: 256,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
});
// 使用缓冲区...
// 清理
context.deferDestroy(buffer);
await context.sync();
} catch (error) {
console.error('GPU 初始化失败:', error);
} finally {
context.destroy();
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
相关资源
- GPU 上下文指南 - 详细使用说明
- Tensor API - 数据结构 API
- 错误类型 - 错误处理