WebGPU 的原理
原作者: webgpufundamentals Contributors
这篇想换个办法解释 WebGPU:用 JavaScript 把 GPU 在顶点着色器和片元着色器里干的事模仿一遍。希望这样能让你直观感受到背后到底发生了什么。
如果你熟 Array.map,稍微想一下就能体会这两种着色器函数是怎么干活的。用 Array.map 的时候,你给一个函数,它负责把一个值转成另一个值。
比如:
const shader = (v) => v * 2; // double the input
const input = [1, 2, 3, 4];
const output = input.map(shader); // result [2, 4, 6, 8]
上面给 array.map 写的那个“着色器”就是个函数,进去一个数字,出来它的两倍。这大概是 JavaScript 里最接近“着色器”的类比了。着色器是个返回值、生成值的函数,你不用直接调它,只负责把它交代清楚,然后由系统来调。
GPU 的顶点着色器不一样,它不是对某个输入数组做映射。你只要说清楚这个函数要被调多少次就行。
function draw(count, vertexShaderFn) {
const internalBuffer = [];
for (let i = 0; i < count; ++i) {
internalBuffer[i] = vertexShaderFn(i);
}
console.log(JSON.stringify(internalBuffer));
}
结果就是,跟 Array.map 不同,我们不需要源数组也能干点活。
const shader = (v) => v * 2;
const count = 4;
draw(count, shader);
// outputs [0, 2, 4, 6]
GPU 的活之所以麻烦,是因为这些函数跑在机器里另一套独立系统上——GPU。也就是说,你建出来、要引用的数据,都得想办法送到 GPU 那边,然后还得告诉着色器数据放哪、怎么取。
顶点着色器和片元着色器拿数据有 6 条路:Uniforms、Attributes、Buffers、Textures、Inter-Stage Variables、Constants。
Uniforms
Uniforms 是每次迭代都不变的值,你可以把它当成常量全局变量。着色器跑之前把它设好,跑的过程中它就不动了——所谓“uniform”,说的就是一致。
来改一下 draw,把 uniforms 传进去。做法是建一个叫 bindings 的数组,靠它把 uniforms 递过去。
function draw(count, vertexShaderFn, bindings) {
const internalBuffer = [];
for (let i = 0; i < count; ++i) {
internalBuffer[i] = vertexShaderFn(i, bindings);
}
console.log(JSON.stringify(internalBuffer));
}
然后把着色器改成用 uniforms:
const vertexShader = (v, bindings) => {
const uniforms = bindings[0];
return v * uniforms.multiplier;
};
const count = 4;
const uniforms1 = { multiplier: 3 };
const uniforms2 = { multiplier: 5 };
const bindings1 = [uniforms1];
const bindings2 = [uniforms2];
draw(count, vertexShader, bindings1);
// outputs [0, 3, 6, 9]
draw(count, vertexShader, bindings2);
// outputs [0, 5, 10, 15]
所以 uniforms 这个概念挺好懂。绕一层 bindings 去访问,是因为 WebGPU 里真就这么干。前面说过,这些东西都靠位置/索引来取,这里就是 bindings[0]。
Attributes(仅顶点着色器)
Attributes 给的是每次迭代各不相同的数据。前面 Array.map 里,值 v 是从 input 里取出来自动塞给函数的,着色器里的 attribute 跟这个很像。
区别在于,我们并没有对输入做映射,只是在数数,所以得告诉 WebGPU 这些输入是什么、怎么从里面取值。
假设把 draw 改成这样:
function draw(count, vertexShaderFn, bindings, attribsSpec) {
const internalBuffer = [];
for (let i = 0; i < count; ++i) {
const attribs = getAttribs(attribsSpec, i);
internalBuffer[i] = vertexShaderFn(i, bindings, attribs);
}
console.log(JSON.stringify(internalBuffer));
}
function getAttribs(attribs, ndx) {
return attribs.map(
({ source, offset, stride }) => source[ndx * stride + offset],
);
}
然后可以这样调用:
const buffer1 = [0, 1, 2, 3, 4, 5, 6, 7];
const buffer2 = [11, 22, 33, 44];
const attribsSpec = [
{ source: buffer1, offset: 0, stride: 2 },
{ source: buffer1, offset: 1, stride: 2 },
{ source: buffer2, offset: 0, stride: 1 },
];
const vertexShader = (v, bindings, attribs) =>
(attribs[0] + attribs[1]) * attribs[2];
const bindings = [];
const count = 4;
draw(count, vertexShader, bindings, attribsSpec);
// outputs [11, 110, 297, 572]
可以看到,getAttribs 用 offset 和 stride 算出对应 source 缓冲区里的索引,再把值取出来,送进着色器。每次迭代的 attribs 都不一样。
iteration | attribs
----------+-------------
0 | [0, 1, 11]
1 | [2, 3, 22]
2 | [4, 5, 33]
3 | [6, 7, 44]
Raw Buffers
Buffers 说白了就是数组。再类比一次,写个用 buffers 的 draw。这些 buffers 也走 bindings 传,跟传 uniforms 一个路子。
const buffer1 = [0, 1, 2, 3, 4, 5, 6, 7];
const buffer2 = [11, 22, 33, 44];
const attribsSpec = [];
const bindings = [buffer1, buffer2];
const vertexShader = (ndx, bindings, attribs) =>
(bindings[0][ndx * 2] + bindings[0][ndx * 2 + 1]) * bindings[1][ndx];
const count = 4;
draw(count, vertexShader, bindings, attribsSpec);
// outputs [11, 110, 297, 572]
这里结果跟 attributes 那版一模一样,但这次没让系统去 buffers 里取,索引是我们自己算的。这比 attributes 灵活,基本等于能随便访问数组。不过也正因为这样,它可能更慢。attributes 那套里,GPU 提前知道值会按顺序取,就能顺着这个做优化。举个例子,顺序访问一般对缓存友好。换成自己算索引,GPU 直到你真去取的那一刻,都不知道你要摸缓冲区的哪一块。
Textures
Textures 是 1 维、2 维或 3 维的数据数组。当然,用 buffers 也能自己搭出 2 维、3 维数组。Textures 特别的地方是能被采样(sampled)——也就是让 GPU 在你给的值之间算出一个中间值。这块在纹理那篇里会细讲。现在先再做个 JavaScript 类比。
先写个 textureSample 函数,让它在一串值之间采样:
function textureSample(texture, ndx) {
const startNdx = ndx | 0; // round down to an int
const fraction = ndx % 1; // get the fractional part between indices
const start = texture[startNdx];
const end = texture[startNdx + 1];
return start + (end - start) * fraction; // compute value between start and end
}
差不多这样的函数,GPU 上本来就有。
拿到着色器里用:
const texture = [10, 20, 30, 40, 50, 60, 70, 80];
const attribsSpec = [];
const bindings = [texture];
const vertexShader = (ndx, bindings, attribs) =>
textureSample(bindings[0], ndx * 1.75);
const count = 4;
draw(count, vertexShader, bindings, attribsSpec);
// outputs [10, 27.5, 45, 62.5]
ndx 为 3 时,传进 textureSample 的是 3 * 1.75,也就是 5.25。算出来 startNdx 是 5,于是取索引 5 和 6 的值,分别是 60 和 70。fraction 是 0.25,所以结果是 60 + (70 - 60) * 0.25,也就是 62.5。
看上面的代码,textureSample 其实可以自己在着色器里写,手动取两个值插一下。GPU 专门做这个,是因为它更快,而且看设置,一次可能读多达十六个 4-float 值,最后生成一个 4-float 值。这活让人手工干,量太大了。
Inter-Stage Variables(仅片元着色器)
Inter-Stage Variables 是顶点着色器输出、再传到片元着色器里的变量。前面提过,顶点着色器输出位置,用来画(光栅化)点、线和三角形。
假设要画一条线,顶点着色器跑了两次,第一次输出相当于 5,0,第二次相当于 25,4。有这两个点,GPU 就从 5,0 画到 25,4(不含终点)。为了画这条线,它会调 20 次片元着色器,线上每个像素一次。每次调的时候,返回什么颜色由你决定。
假设有两个函数帮忙画两点之间的线。第一个算要画多少像素,顺带算几个辅助值。第二个拿这些信息加上像素编号,给出像素位置。比如:
const line = calcLine([10, 10], [13, 13]);
for (let i = 0; i < line.numPixels; ++i) {
const p = calcLinePoint(line, i);
console.log(p);
}
// prints
// 10,10
// 11,11
// 12,12
注意:calcLine 和 calcLinePoint 具体怎么写的无所谓,能跑通、能让上面那个循环吐出一条线的像素位置就行。要是好奇,文章靠底部有实时代码示例。
现在把顶点着色器改成每次迭代输出两个值。写法有好几种,这里挑一种:
const buffer1 = [5, 0, 25, 4];
const attribsSpec = [
{ source: buffer1, offset: 0, stride: 2 },
{ source: buffer1, offset: 1, stride: 2 },
];
const bindings = [];
const dest = new Array(2);
const vertexShader = (ndx, bindings, attribs) => [attribs[0], attribs[1]];
const count = 2;
draw(count, vertexShader, bindings, attribsSpec);
// outputs [[5, 0], [25, 4]]
接着写点代码,每次取两个点,调 rasterizeLines 光栅化出一条线:
function rasterizeLines(dest, destWidth, inputs, fragShaderFn, bindings) {
for (let ndx = 0; ndx < inputs.length - 1; ndx += 2) {
const p0 = inputs[ndx];
const p1 = inputs[ndx + 1];
const line = calcLine(p0, p1);
for (let i = 0; i < line.numPixels; ++i) {
const p = calcLinePoint(line, i);
const offset = p[1] * destWidth + p[0]; // y * width + x
dest[offset] = fragShaderFn(bindings);
}
}
}
draw 改成这样就能用上那段代码:
function draw(
dest,
destWidth,
count,
vertexShaderFn,
fragmentShaderFn,
bindings,
attribsSpec,
) {
const internalBuffer = [];
for (let i = 0; i < count; ++i) {
const attribs = getAttribs(attribsSpec, i);
internalBuffer[i] = vertexShaderFn(i, bindings, attribs);
}
rasterizeLines(dest, destWidth, internalBuffer, fragmentShaderFn, bindings);
}
现在我们真正用上了 internalBuffer 😃!
更新调用 draw 的代码:
const buffer1 = [5, 0, 25, 4];
const attribsSpec = [
{ source: buffer1, offset: 0, stride: 2 },
{ source: buffer1, offset: 1, stride: 2 },
];
const bindings = [];
const vertexShader = (ndx, bindings, attribs) => [attribs[0], attribs[1]];
const count = 2;
const width = 30;
const height = 5;
const pixels = new Array(width * height).fill(0);
const fragShader = (bindings) => 6;
draw(pixels, width, count, vertexShader, fragShader, bindings, attribsSpec);
把 pixels 按矩形打出来,0 换成 .,会看到这样:
.....666......................
........66666.................
.............66666............
..................66666.......
.......................66.....
可惜片元着色器没拿到每次迭代都变的输入,所以每个像素吐出来的值都一样。这正是 inter-stage variables 的用处。把第一个着色器改成多输出一个值:
const buffer1 = [5, 0, 25, 4];
const buffer2 = [9, 3];
const attribsSpec = [
{ source: buffer1, offset: 0, stride: 2 },
{ source: buffer1, offset: 1, stride: 2 },
{ source: buffer2, offset: 0, stride: 1 },
];
const bindings = [];
const dest = new Array(2);
const vertexShader = (ndx, bindings, attribs) => [
[attribs[0], attribs[1]],
[attribs[2]],
];
别的地方不动,draw 里的循环跑完,internalBuffer 里是这样的:
[
[[5, 0], [9]],
[[25, 4], [3]],
];
沿线的进度很好算,0.0 到 1.0 一个数就够了。拿它去插值刚加的那个额外值:
function rasterizeLines(dest, destWidth, inputs, fragShaderFn, bindings) {
for (let ndx = 0; ndx < inputs.length - 1; ndx += 2) {
const p0 = inputs[ndx][0];
const p1 = inputs[ndx + 1][0];
const v0 = inputs[ndx].slice(1); // everything but the first value
const v1 = inputs[ndx + 1].slice(1);
const line = calcLine(p0, p1);
for (let i = 0; i < line.numPixels; ++i) {
const p = calcLinePoint(line, i);
const t = i / line.numPixels;
const interStageVariables = interpolateArrays(v0, v1, t);
const offset = p[1] * destWidth + p[0]; // y * width + x
dest[offset] = fragShaderFn(bindings, interStageVariables);
}
}
}
// interpolateArrays([[1,2]], [[3,4]], 0.25) => [[1.5, 2.5]]
function interpolateArrays(v0, v1, t) {
return v0.map((array0, ndx) => {
const array1 = v1[ndx];
return interpolateValues(array0, array1, t);
});
}
// interpolateValues([1,2], [3,4], 0.25) => [1.5, 2.5]
function interpolateValues(array0, array1, t) {
return array0.map((a, ndx) => {
const b = array1[ndx];
return a + (b - a) * t;
});
}
然后片元着色器就能用这些 inter-stage variables 了:
const fragShader = (bindings, interStageVariables) =>
interStageVariables[0] | 0; // convert to int
跑一下,结果大概是这样:
.....988......................
........87776.................
.............66655............
..................54443.......
.......................33.....
顶点着色器第一次迭代输出 [[5,0], [9]],第二次输出 [[25,4], [3]]。片元着色器一次次被调用的过程中,数组里第二个值就在 9 和 3 之间一路插过去,效果一眼能看出来。
还能再写个 mapTriangle,给它 3 个点,光栅化出一个三角形,三角形里每个点都调一次片元着色器。插值的时候是从 3 个点插,不是 2 个。
下面这些例子的实时版本,随便改着玩,帮助理解:
上面这些 JavaScript 说到底只是个类比。真到 WebGPU 里,inter-stage variables 怎么插值、线怎么画、缓冲区怎么访问、纹理怎么采样、uniforms 和 attributes 怎么指定,细节都不一样,但概念很接近。所以希望这个 JavaScript 类比能在你脑子里搭起一个模型,知道背后大概在发生什么。
为什么要这么设计?看看 draw 和 rasterizeLines 就会发现,每次迭代跟别的迭代完全独立。换句话说,你按什么顺序处理都行。不按 0、1、2、3、4 来,改成 3、1、4、0、2,结果一模一样。迭代之间互不相干,意味着每次迭代可以丢给不同的处理器并行跑。2021 年的顶级 GPU 有一万个以上的处理器,也就是说最多能同时跑一万个任务。GPU 猛就猛在这儿。顺着这些模式写,系统就能大规模并行起来。
不过限制也挺硬:
- 着色器函数只能引用自己的输入(attributes、buffers、textures、uniforms、inter-stage variables)。
- 着色器不能分配内存。
- 着色器引用自己正在写的那个对象时得格外小心,也就是它正在给这个对象生成值。
仔细想想也合理。假设上面那个 fragShader 直接去引用 dest,一旦要并行就没法协调了:到底哪次迭代先跑?第 3 次迭代引用了 dest[0],那第 0 次就得先跑;可要是第 0 次迭代又引用了 dest[3],那又变成第 3 次得先跑。
在 CPU 上写多线程、多进程也得绕开这个限制来设计,但 GPU 这边一万个处理器同时跑,协调起来要特殊处理。后面文章里会讲些技巧。
关键的三点
充分利用迭代独立性以最大化并行度。着色器每次迭代都互不相干,GPU 上几千上万个处理器能同时跑。写着色器和渲染流程时,尽量别让迭代之间互相依赖,系统才敢放心大规模并行。这是把 GPU 算力榨出来的前提。
优先使用顺序访问的数据传递方式(Attributes 优于 Buffer 随机索引)。顶点属性(Attributes)能让 GPU 提前知道数据会按顺序取,这样就能做缓存友好的优化。反过来,在着色器里自己算 Buffer 索引属于随机访问,GPU 猜不到访问模式,性能可能就掉下来了。访问模式可预测的时候,尽量走顶点属性。
利用纹理采样硬件加速插值与过滤。GPU 内置的纹理采样器用硬件速度做插值,一次采样甚至能读多达 16 个 4-float 值,最后吐一个 4-float 值,比在着色器里用 Buffer 手搓快得多。碰上插值、过滤、多维数据访问这类场景,最好先用纹理采样,别自己算。
术语对照
这篇讲的其实是 WebGPU,不是 WebGL/GLSL,但两边都属于 GPU 渲染管线,术语大多能对上或相通。下面列出文中关键术语的中文规范译法,也标了跟 WebGL/GLSL 的对应关系:
| 英文术语 | 中文规范译法 | 对应 WebGL/GLSL 术语 | 备注 |
|---|---|---|---|
| Uniforms | 统一变量(或 Uniform 变量) | Uniform | 所有顶点/片元同值的全局变量 |
| Attributes | 顶点属性 | Attribute | WebGL/GLSL 中的 attribute,仅在顶点着色器中使用 |
| Buffers | 缓冲区 | Buffer Object / VBO | WebGPU 中更细分为 Vertex Buffer / Storage Buffer |
| Textures | 纹理 | Texture | 带硬件采样能力的 1D/2D/3D 数据数组 |
| Inter-Stage Variables | 阶段间变量 | Varying | WebGL/GLSL 中用 varying 实现顶点到片元的数据传递 |
| Constants | 常量 | const / #define | 编译期确定的固定值 |
| Bindings | 绑定(资源绑定) | Bindings / Texture Units | WebGPU 通过 bind group 组织资源绑定 |
| Sampling | 采样 | Sampling | GPU 硬件在纹理值之间插值 |
| Rasterize | 光栅化 | Rasterization | 将图元转化为片元/像素 |
| Interpolation | 插值 | Interpolation | 阶段间变量在光栅化过程中自动插值 |
| Stride | 步长(步幅) | Stride | 顶点属性从一个元素到下一个元素的字节间距 |
| Offset | 偏移量 | Offset | 属性在缓冲区中的起始偏移 |
| Cache friendly | 缓存友好 | Cache-friendly | 顺序访问有助于缓存命中 |
| Compute Shader | 计算着色器 | Compute Shader | 侧边栏提及,通用 GPU 并行计算 |
| Storage Buffer | 存储缓冲区 | SSBO | 可读写的大容量缓冲区 |
| Multisampling | 多重采样 | MSAA | 抗锯齿技术 |
| Bind Group Layout | 绑定组布局 | - | WebGPU 专有名词,描述资源绑定结构 |
重点说一句:GLSL 里的 varying 关键字,WebGPU 里没有。顶点到片元的传值在 WGSL 里靠函数返回值和入口参数实现,官方叫法是 “inter-stage variables”。另外 WebGPU 用 Bind Group 换掉了 WebGL 里零散的纹理单元和 uniform 绑定接口,设计上更接近 Vulkan、Metal 这类现代底层 API。
