WebGPU 顶点缓冲区:从存储缓冲到索引绘制
原文标题:WebGPU Vertex Buffers
这篇是对 WebGPU 系列教程里“顶点缓冲区(Vertex Buffers)”那篇的深度解读加编译,不是逐字全盘翻译。WGSL/JavaScript 核心代码都留着,关键地方补了中文说明,帮你看清 WebGPU 怎么把顶点数据从存储缓冲区挪到传统的顶点缓冲区,再一路做到实例化、归一化属性和索引绘制。
为什么需要顶点缓冲区?
上一篇讲存储缓冲区(Storage Buffers)时,我们靠内建变量 vertex_index 在着色器里索引顶点数据。这路子现在慢慢流行起来了,但传统做法还是把顶点数据塞进顶点缓冲区,再通过顶点属性(Vertex Attributes)交给顶点着色器。
顶点缓冲区本质上跟普通 WebGPU 缓冲区没区别,差别在用法:我们不在着色器里直接访问它,而是把缓冲区里的数据布局告诉 WebGPU,让 GPU 的固定功能部件自己去取,填到着色器入口。
从存储缓冲区切换到顶点缓冲区
2.1 着色器修改
先给 Vertex 结构体里的 position 字段加上 @location(0),表示这个值从顶点缓冲区的 0 号位置读:
struct OtherStruct {
scale: vec2f,
};
struct Vertex {
@location(0) position: vec2f, // 关键变化:增加 @location(0)
};
struct VSOutput {
@builtin(position) position: vec4f,
@location(0) color: vec4f,
};
@group(0) @binding(0) `var<storage, read>` ourStructs: `array<OurStruct>`;
@group(0) @binding(1) `var<storage, read>` otherStructs: `array<OtherStruct>`;
// 移除:@group(0) @binding(2) `var<storage, read>` pos: `array<Vertex>`;
@vertex fn vs(
vert: Vertex, // 不再使用 @builtin(vertex_index)
@builtin(instance_index) instanceIndex: u32
) -> VSOutput {
let otherStruct = otherStructs[instanceIndex];
let ourStruct = ourStructs[instanceIndex];
var vsOut: VSOutput;
vsOut.position = vec4f(
vert.position * otherStruct.scale + ourStruct.offset, 0.0, 1.0);
vsOut.color = ourStruct.color;
return vsOut;
}
核心就两处改动:
- 把
@group(0) @binding(2)那个存pos的存储缓冲区删了。 @builtin(vertex_index)换成直接收一个Vertex结构体。
2.2 渲染管线描述顶点缓冲区
建渲染管线的时候,得把缓冲区布局(buffers 数组)描述出来:
const pipeline = device.createRenderPipeline({
label: "vertex buffer pipeline",
layout: "auto",
vertex: {
module,
buffers: [
{
arrayStride: 2 * 4, // 2 个 float32,共 8 字节
attributes: [
{ shaderLocation: 0, offset: 0, format: "float32x2" }, // position
],
},
],
},
fragment: {
module,
targets: [{ format: presentationFormat }],
},
});
arrayStride:从一个顶点走到下一个顶点要跨多少字节(步长)。attributes:每个顶点属性的位置、偏移和格式。shaderLocation: 0跟着色器里的@location(0)对得上。format: 'float32x2'表示读两个 32 位浮点数。
2.3 创建顶点缓冲区并设置到渲染通道
缓冲区的用途从 STORAGE 换成 VERTEX:
const vertexBuffer = device.createBuffer({
label: "vertex buffer vertices",
size: vertexData.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vertexBuffer, 0, vertexData);
绘制时用 setVertexBuffer(0, vertexBuffer) 绑上去:
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
这里的 0 对应管线描述里 buffers 数组的第 0 项。
实例化(Instancing)与多缓冲区
除了逐顶点属性,属性还能逐实例(per-instance)往前走一步。之前用 instance_index 索引存储缓冲区那套,正好被它替掉。
3.1 着色器改为纯顶点属性
struct Vertex {
@location(0) position: vec2f,
@location(1) color: vec4f,
@location(2) offset: vec2f,
@location(3) scale: vec2f,
};
struct VSOutput {
@builtin(position) position: vec4f,
@location(0) color: vec4f,
};
@vertex fn vs(
vert: Vertex,
) -> VSOutput {
var vsOut: VSOutput;
vsOut.position = vec4f(
vert.position * vert.scale + vert.offset, 0.0, 1.0);
vsOut.color = vert.color;
return vsOut;
}
3.2 管线描述多缓冲区与实例步进模式
vertex: {
module,
buffers: [
{
arrayStride: 2 * 4, // position
attributes: [
{shaderLocation: 0, offset: 0, format: 'float32x2'},
],
},
{
arrayStride: 6 * 4, // color + offset,共 6 个 float32
stepMode: 'instance', // 逐实例推进
attributes: [
{shaderLocation: 1, offset: 0, format: 'float32x4'}, // color
{shaderLocation: 2, offset: 16, format: 'float32x2'}, // offset
],
},
{
arrayStride: 2 * 4, // scale
stepMode: 'instance',
attributes: [
{shaderLocation: 3, offset: 0, format: 'float32x2'}, // scale
],
},
],
},
stepMode: 'instance' 说的是这个属性每个实例才往前走一步,默认的 'vertex' 则是每个顶点走一步。
3.3 绑定多个顶点缓冲区
pass.setVertexBuffer(0, vertexBuffer);
pass.setVertexBuffer(1, staticVertexBuffer);
pass.setVertexBuffer(2, changingVertexBuffer);
到这儿,存储缓冲区和 bind group 就彻底用不上了。
交错属性与默认值
多个属性可以交错存在同一个缓冲区里。比如给每个顶点加个颜色 perVertexColor:
struct Vertex {
@location(0) position: vec2f,
@location(1) color: vec4f,
@location(2) offset: vec2f,
@location(3) scale: vec2f,
@location(4) perVertexColor: vec3f,
};
对应的缓冲区布局(position 2 个 float 加 perVertexColor 3 个 float):
{
arrayStride: 5 * 4, // 5 个 float32 = 20 字节
attributes: [
{shaderLocation: 0, offset: 0, format: 'float32x2'}, // position
{shaderLocation: 4, offset: 8, format: 'float32x3'}, // perVertexColor
],
},
有意思的是:着色器里 perVertexColor 声明成 vec3f,你把它改成 vec4f 也行,JavaScript 那边的数据一个字都不用动。因为 GPU 会自动把缺的第四个分量补成默认值 1(也就是 (0,0,0,1))。
@location(4) perVertexColor: vec4f,
这样 vert.perVertexColor 就能直接当 vec4f 使,第四个分量自动是 1。
使用归一化属性节省空间
颜色用不着 32 位浮点那么高的精度。换成 8 位无符号整数、让 GPU 自动归一化到 [0,1],带宽能省很多。
5.1 修改数据布局
原来 perVertexColor 用 3 个 float32,一共 12 字节;换成 unorm8x4 之后只要 4 字节(RGB 各 1 字节,再加 1 字节填充或 alpha)。实例颜色也从 float32x4 改成 unorm8x4。
const staticUnitSize =
4 + // color 为 4 字节(unorm8x4)
2 * 4; // offset 仍为 2 个 float32
写数据时用 Uint8Array 视图:
const staticVertexValuesU8 = new Uint8Array(staticVertexBufferSize);
const staticVertexValuesF32 = new Float32Array(staticVertexValuesU8.buffer);
// 设置颜色(0~255)
staticVertexValuesU8.set(
[rand() * 255, rand() * 255, rand() * 255, 255],
staticOffsetU8 + kColorOffset,
);
// 设置偏移(float32,注意偏移单位)
staticVertexValuesF32.set(
[rand(-0.9, 0.9), rand(-0.9, 0.9)],
staticOffsetF32 + kOffsetOffset,
);
5.2 更新管线属性格式
{
arrayStride: 2 * 4 + 4, // position(8字节) + color(4字节)
attributes: [
{shaderLocation: 0, offset: 0, format: 'float32x2'}, // position
{shaderLocation: 4, offset: 8, format: 'unorm8x4'}, // perVertexColor
],
},
{
arrayStride: 4 + 2 * 4, // color(4字节) + offset(8字节)
stepMode: 'instance',
attributes: [
{shaderLocation: 1, offset: 0, format: 'unorm8x4'}, // color
{shaderLocation: 2, offset: 4, format: 'float32x2'}, // offset
],
},
这样一来,每个顶点的颜色从 12 字节掉到 4 字节,实例颜色从 16 字节掉到 4 字节,总带宽能省 40–50%。
索引缓冲区(Index Buffers)
索引缓冲区管的是顶点处理的顺序。原来的圆形每个细分生成 6 个顶点(有重复),现在只生成 4 个不重复的,靠索引来复用:
const numVertices = (numSubdivisions + 1) * 2; // 仅 4 个顶点/细分
const indexData = new Uint32Array(numSubdivisions * 6);
let ndx = 0;
// 索引序列:0,1,2, 2,1,3, ...
for (let i = 0; i < numSubdivisions; ++i) {
const ndxOffset = i * 2;
// 第一个三角形
indexData[ndx++] = ndxOffset;
indexData[ndx++] = ndxOffset + 1;
indexData[ndx++] = ndxOffset + 2;
// 第二个三角形
indexData[ndx++] = ndxOffset + 2;
indexData[ndx++] = ndxOffset + 1;
indexData[ndx++] = ndxOffset + 3;
}
建索引缓冲区(usage: INDEX):
const indexBuffer = device.createBuffer({
label: "index buffer",
size: indexData.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(indexBuffer, 0, indexData);
绘制时设好索引缓冲区,调 drawIndexed:
pass.setIndexBuffer(indexBuffer, "uint32");
pass.drawIndexed(numVertices, kNumObjects);
顶点内存占用少了 33%,顶点着色器的缓存命中率也可能跟着上去。
关键的三点
用顶点缓冲区替代存储缓冲区,配合实例化减少 CPU→GPU 数据传输。顶点缓冲区让 GPU 的固定功能部件直接装配顶点属性,不用在着色器里靠 vertex_index 和 instance_index 手动索引存储缓冲区。再配上 stepMode: 'instance',每个实例的共性数据可以单独放,不用给每个顶点都拷一遍同一份实例数据,显存带宽和 CPU 那边的开销都省了。
颜色这类低精度数据优先用归一化整数格式(如 unorm8x4)。颜色、法线这些归一化向量用不着 32 位浮点精度。改用 unorm8x4 / snorm8x4 之类的格式,既能保住 [0,1] 或 [-1,1] 的范围,属性占的带宽和显存又能砍掉 50% 甚至更多。例子里每个顶点的颜色从 12 字节降到 4 字节,实例颜色从 16 字节降到 4 字节。
用索引缓冲区复用重复顶点,减少冗余处理。网格这种共享顶点一大堆的几何体,索引缓冲区能明显缩小顶点缓冲区,还能让 GPU 有机会复用顶点着色器的计算结果(靠缓存)。例子里圆形每个细分的顶点数从 6 个减到 4 个,省下约 33% 的顶点存储,顶点着色器的计算量也跟着少。
GLSL/WebGL 与 WGSL/WebGPU 术语对照检查
原文用的是 WGSL/WebGPU,不是 GLSL/WebGL,但底层的图形概念是相通的。下面这些关键术语的中文译法和适用性都过了一遍:
| 英文原文 | 简体中文推荐译法 | 备注 |
|---|---|---|
| Vertex Buffer | 顶点缓冲区 | WebGL 中同为 Vertex Buffer |
| Storage Buffer | 存储缓冲区 | WebGPU 特有,类似 GLSL 中的 SSBO |
| Bind Group | 绑定组 | WebGPU 的资源绑定概念,对应 WebGL 的 uniform/attribute 绑定 |
| Render Pipeline | 渲染管线 | WebGL 中对应 WebGLProgram + 状态集合 |
| Vertex Shader | 顶点着色器 | 通用 |
| Fragment Shader | 片元着色器 | WebGPU 官方中文也称“片段着色器”,本文采用“片元”以区分 |
| Attribute | 属性 / 顶点属性 | 注意:WGSL 中 attribute 指输入参数,与 WebGL 的 vertex attrib 概念一致 |
| Location | 位置 / 定位 | @location 对应 GLSL 中的 layout(location = N) |
| Builtin | 内建变量 | 如 @builtin(position)、@builtin(vertex_index) |
| Stride | 步长 | 指相邻顶点/实例数据之间的字节距离 |
| Offset | 偏移量 | 属性在缓冲区中的起始字节偏移 |
| Interleaved | 交错 | 多个属性在缓冲区中相邻存储 |
| Normalized | 归一化 | 如 unorm8x4 将整数 0 |
| Instance / Instancing | 实例 / 实例化 | stepMode: 'instance' |
| Index Buffer | 索引缓冲区 | 与 WebGL 的 ELEMENT_ARRAY_BUFFER 对应 |
| Draw Call | 绘制调用 | draw / drawIndexed |
| GPUBufferUsage | GPU 缓冲区用途标志 | 保留英文,不翻译 |
| Render Pass | 渲染通道 | WebGPU 概念,类似 WebGL 的 framebuffer 绑定过程 |
校验说明:这篇涉及 WGSL 里显式的
@location、@builtin这些语法,思路跟 GLSL 的layout(location=...)一致,但 WebGPU 的顶点缓冲区描述是在渲染管线里一次配好的,WebGL 一般是在gl.vertexAttribPointer里动态设。翻译时“顶点缓冲区”“索引缓冲区”“实例化”这些业界通用叫法都留着,同时没把 WebGPU 特有的“渲染通道”“绑定组”硬套成 WebGL 术语。
小结
这篇把 WebGPU 顶点缓冲区的核心用法从头捋了一遍:先是从存储缓冲区简单替换过来,然后多缓冲区加实例化,再到归一化属性省空间、索引缓冲区省顶点。这些机制搞明白了,在 WebGPU 里搭高效、低带宽的渲染管线就顺手了。
下一步可以接着看教程里的 纹理(Textures) 章节。
