Web 图形与 3D / 系统课时
用双缓冲保存粒子模拟状态
用双缓冲保存粒子模拟状态
粒子模拟既要读取上一帧的位置、速度,又要写入新状态。如果让多个 GPU 线程原地更新共享数组,依赖旧状态的计算可能读到本帧的部分结果。本篇用两套缓冲区交替读写,再把更新完成的缓冲区直接交给渲染通道。
学习目标
- 计算粒子状态的内存布局和双缓冲容量。
- 创建 A→B、B→A 两组计算绑定,逐帧切换输入与输出。
- 让渲染通道读取当前帧新状态,并检查交换顺序。
确定读写规则
每个粒子保存 position.xy 和 velocity.xy,共四个 f32,占 16 字节。1024 个粒子需要每块 16384 字节,两块合计 32768 字节(不含其他 GPU 资源)。第一帧只需向 A 写入初始数据;B 会被计算着色器完整覆盖。
| 帧 | 计算只读输入 | 计算写入输出 | 渲染读取 |
|---|---|---|---|
| 0 | A | B | B |
| 1 | B | A | A |
| 2 | A | B | B |

实现计算和渲染
把下面的完整示例保存为 index.html。它使用 1024 个粒子、每工作组 64 个调用;两块缓冲同时设置 STORAGE 和 VERTEX 用途,使计算输出能直接作为顶点输入。渲染采用一个粒子对应一个屏幕像素的 point-list,便于检查状态是否连续。
<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>WebGPU 粒子双缓冲</title></head>
<body>
<canvas id="scene" width="640" height="360"></canvas>
<p id="status">初始化中</p>
<script type="module">
async function main() {
const status = document.querySelector("#status");
if (!navigator.gpu) {
status.textContent = "浏览器不支持 WebGPU";
return;
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
status.textContent = "无法获取 GPU 适配器";
return;
}
const device = await adapter.requestDevice();
const canvas = document.querySelector("#scene");
const context = canvas.getContext("webgpu");
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format, alphaMode: "opaque" });
const count = 1024;
const initial = new Float32Array(count * 4);
for (let i = 0; i < count; i++) {
const col = i % 32;
const row = Math.floor(i / 32);
// 四个浮点数依次对应位置 xy、速度 xy
initial.set([
-0.9 + col * 1.8 / 31,
-0.9 + row * 1.8 / 31,
i % 2 === 0 ? 0.18 : -0.18,
i % 3 === 0 ? -0.13 : 0.13
], i * 4);
}
const buffers = [0, 1].map(() => device.createBuffer({
size: initial.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX |
GPUBufferUsage.COPY_DST
}));
device.queue.writeBuffer(buffers[0], 0, initial);
const computeModule = device.createShaderModule({ code: `
struct Particle {
position: vec2f,
velocity: vec2f,
}
@group(0) @binding(0) var<storage, read> source: array<Particle>;
@group(0) @binding(1) var<storage, read_write> target: array<Particle>;
@compute @workgroup_size(64)
fn simulate(@builtin(global_invocation_id) id: vec3u) {
let i = id.x;
if (i >= arrayLength(&source)) { return; }
var p = source[i];
let next = p.position + p.velocity * (1.0 / 60.0);
if (abs(next.x) >= 0.98) { p.velocity.x = -p.velocity.x; }
if (abs(next.y) >= 0.98) { p.velocity.y = -p.velocity.y; }
p.position = clamp(next, vec2f(-0.98, -0.98), vec2f(0.98, 0.98));
target[i] = p;
}
` });
const computePipeline = device.createComputePipeline({
layout: "auto",
compute: { module: computeModule, entryPoint: "simulate" }
});
// 两组绑定在创建阶段固定好,帧循环只选择其中一组
const computeGroups = [
[buffers[0], buffers[1]],
[buffers[1], buffers[0]]
].map(([src, dst]) => device.createBindGroup({
layout: computePipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: src } },
{ binding: 1, resource: { buffer: dst } }
]
}));
const renderModule = device.createShaderModule({ code: `
@vertex
fn vs(@location(0) position: vec2f) -> @builtin(position) vec4f {
return vec4f(position, 0.0, 1.0);
}
@fragment
fn fs() -> @location(0) vec4f {
return vec4f(0.18, 0.9, 0.7, 1.0);
}
` });
const renderPipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: renderModule,
entryPoint: "vs",
buffers: [{
arrayStride: 16,
attributes: [{ shaderLocation: 0, offset: 0, format: "float32x2" }]
}]
},
fragment: {
module: renderModule, entryPoint: "fs", targets: [{ format }]
},
primitive: { topology: "point-list" }
});
let frameIndex = 0;
function frame() {
const input = frameIndex & 1;
const output = 1 - input;
const encoder = device.createCommandEncoder();
const compute = encoder.beginComputePass();
compute.setPipeline(computePipeline);
compute.setBindGroup(0, computeGroups[input]);
compute.dispatchWorkgroups(Math.ceil(count / 64));
compute.end();
const render = encoder.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
clearValue: { r: 0.025, g: 0.04, b: 0.09, a: 1 },
loadOp: "clear",
storeOp: "store"
}]
});
render.setPipeline(renderPipeline);
// 必须绘制刚更新的输出缓冲区
render.setVertexBuffer(0, buffers[output]);
render.draw(count);
render.end();
device.queue.submit([encoder.finish()]);
frameIndex++;
requestAnimationFrame(frame);
}
status.textContent = "运行中:1024 个粒子,双缓冲交替";
requestAnimationFrame(frame);
}
main().catch(error => {
console.error(error);
document.querySelector("#status").textContent = `初始化失败:${error.message}`;
});
</script>
</body>
</html>预期结果:页面出现 640×360 的深色画布,青绿色粒子持续移动且不会隔帧重置;状态文字为:
运行中:1024 个粒子,双缓冲交替运行并核对帧交换
在保存 index.html 的目录使用 Python 3 启动本地静态服务器,以满足 WebGPU 的安全上下文要求:
python3 -m http.server 8000预期结果:终端提示 HTTP 服务监听 8000 端口,保持该终端运行。在支持 WebGPU 的浏览器中访问 http://localhost:8000/index.html;访问日志中的时间、客户端地址可能不同。
重点检查三处对应关系:computeGroups[0] 为 A→B,computeGroups[1] 为 B→A;帧索引决定计算输入,buffers[output] 决定渲染顶点来源;同一个命令编码器中计算 Pass 先结束,渲染 Pass 再读取输出,提交后无需 CPU 回读或复制 A/B 数据。这里每帧固定模拟 1/60 秒,仅适合演示;产品中应依据实际时间使用固定步长累积器。
若状态停在“初始化中”或出现失败提示,先确认浏览器支持 WebGPU、当前地址是 localhost 或 HTTPS,再查看开发者工具中的设备或着色器校验错误。若能渲染但粒子不动,检查计算派发是否为 1024 / 64 = 16 组、两个缓冲区是否反向绑定以及顶点输入步长是否为 16 字节。