WebGPU 计算着色器——图像直方图 Part 2
上一篇文章里,我们聊了怎么在 JavaScript 里做图像直方图,再把它搬到 WebGPU,中间还过了几轮优化。
这篇接着往下做点更多的事。

一次性生成 4 个直方图
假设有这么一张图:

一般要生成好几个直方图:


左边三个直方图,对应红、绿、蓝三个通道,画的时候叠在一起。右边是亮度直方图,也就是上一篇里做的那种。
一次把 4 个直方图全生成出来,改动其实很小。
JavaScript 这边,一次出 4 个直方图要改的地方是这样:
function computeHistogram(numBins, imgData) {
const { width, height, data } = imgData;
const bins = new Array(numBins * 4).fill(0);
for (let y = 0; y < height; ++y) {
for (let x = 0; x < width; ++x) {
const offset = (y * width + x) * 4;
for (const ch = 0; ch < 4; ++ch) {
const v =
ch < 3
? data[offset + ch] / 255
: srgbLuminance(
data[offset + 0] / 255,
data[offset + 1] / 255,
data[offset + 2] / 255,
);
const bin = Math.min(numBins - 1, v * numBins) | 0;
++bins[bin * 4 + ch];
}
}
}
return bins;
}
这样出来的是交错排列的直方图:r, g, b, l, r, g, b, l, r, g, b, l ……
绘制代码跟着改一下:
function drawHistogram(histogram, numEntries, channels, height = 100) {
// 找出每个通道的最大值
const numBins = histogram.length / 4;
const max = [0, 0, 0, 0];
histogram.forEach((v, ndx) => {
const ch = ndx % 4;
max[ch] = Math.max(max[ch], v);
});
const scale = max.map((max) =>
Math.max(1 / max, (0.2 * numBins) / numEntries),
);
const canvas = document.createElement("canvas");
canvas.width = numBins;
canvas.height = height;
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
const colors = [
"rgb(255, 0, 0)",
"rgb(0, 255, 0)",
"rgb(0, 0, 255)",
"rgb(255, 255, 255)",
];
ctx.globalCompositeOperation = "screen";
for (let x = 0; x < numBins; ++x) {
const offset = x * 4;
for (const ch of channels) {
const v = histogram[offset + ch] * scale[ch] * height;
ctx.fillStyle = colors[ch];
ctx.fillRect(x, height - v, 1, v);
}
}
}
然后调两次:一次画颜色直方图,一次画亮度直方图:
const histogram = computeHistogram(numBins, imgData);
showImageBitmap(imgBitmap);
// 绘制红、绿、蓝通道
const numEntries = imgData.width * imgData.height;
drawHistogram(histogram, numEntries, [0, 1, 2]);
// 绘制亮度通道
drawHistogram(histogram, numEntries, [3]);
WGSL 那版改起来更简单。
比如最慢的那个例子,得这么改:
@group(0) @binding(0) `var<storage, read_write>` bins: `array<vec4u>`;
@group(0) @binding(1) var ourTexture: `texture_2d<f32>`;
// 来自: https://www.w3.org/WAI/GL/wiki/Relative_luminance
const kSRGBLuminanceFactors = vec3f(0.2126, 0.7152, 0.0722);
fn srgbLuminance(color: vec3f) -> f32 {
return saturate(dot(color, kSRGBLuminanceFactors));
}
@compute @workgroup_size(1, 1, 1) fn cs() {
let size = textureDimensions(ourTexture, 0);
let numBins = f32(arrayLength(&bins));
let lastBinIndex = u32(numBins - 1);
for (var y = 0u; y < size.y; y++) {
for (var x = 0u; x < size.x; x++) {
let position = vec2u(x, y);
var channels = textureLoad(ourTexture, position, 0);
channels.w = srgbLuminance(channels.rgb);
for (var ch = 0; ch < 4; ch++) {
let v = channels[ch];
let bin = min(u32(v * numBins), lastBinIndex);
bins[bin][ch] += 1;
}
}
}
}
要把 bins 从 array<u32> 改成 array<vec4u>,给 4 个通道腾地方。
然后从纹理里取颜色,算出亮度塞进 channels 的 w 分量:
var channels = textureLoad(ourTexture, position, 0);
channels.w = srgbLuminance(channels.rgb);
这样就能循环 4 个通道,各自给对得上的 bin 加一。
剩下唯一的改动,是把缓冲区内存开成 4 倍:
const histogramBuffer = device.createBuffer({
size: 256 * 4 * 4, // 256 个条目 * 4 (rgba) * 4 字节 (u32)
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
最快那版也照这样改:
const chunkWidth = 256;
const chunkHeight = 1;
const chunkSize = chunkWidth * chunkHeight;
`var<workgroup>` bins: `array<array<atomic<u32>`, 4>, chunkSize>;
@group(0) @binding(0) `var<storage, read_write>` chunks: `array<array<vec4u, chunkSize>`>;
@group(0) @binding(1) var ourTexture: `texture_2d<f32>`;
const kSRGBLuminanceFactors = vec3f(0.2126, 0.7152, 0.0722);
fn srgbLuminance(color: vec3f) -> f32 {
return saturate(dot(color, kSRGBLuminanceFactors));
}
@compute @workgroup_size(chunkWidth, chunkHeight, 1)
fn cs(
@builtin(workgroup_id) workgroup_id: vec3u,
@builtin(local_invocation_id) local_invocation_id: vec3u,
) {
let size = textureDimensions(ourTexture, 0);
let position = workgroup_id.xy * vec2u(chunkWidth, chunkHeight) +
local_invocation_id.xy;
if (all(position < size)) {
let numBins = f32(chunkSize);
let lastBinIndex = u32(numBins - 1);
var channels = textureLoad(ourTexture, position, 0);
channels.w = srgbLuminance(channels.rgb);
for (var ch = 0; ch < 4; ch++) {
let v = channels[ch];
let bin = min(u32(v * numBins), lastBinIndex);
atomicAdd(&bins[bin][ch], 1u);
}
}
workgroupBarrier();
let chunksAcross = (size.x + chunkWidth - 1) / chunkWidth;
let chunk = workgroup_id.y * chunksAcross + workgroup_id.x;
let bin = local_invocation_id.y * chunkWidth + local_invocation_id.x;
chunks[chunk][bin] = vec4u(
atomicLoad(&bins[bin][0]),
atomicLoad(&bins[bin][1]),
atomicLoad(&bins[bin][2]),
atomicLoad(&bins[bin][3]),
);
}
对于 reduce 着色器:
const chunkWidth = 256;
const chunkHeight = 1;
const chunkSize = chunkWidth * chunkHeight;
struct Uniforms {
stride: u32,
};
@group(0) @binding(0) `var<storage, read_write>` chunks: `array<array<vec4u, chunkSize>`>;
@group(0) @binding(1) `var<uniform>` uni: Uniforms;
@compute @workgroup_size(chunkSize, 1, 1) fn cs(
@builtin(local_invocation_id) local_invocation_id: vec3u,
@builtin(workgroup_id) workgroup_id: vec3u,
) {
let chunk0 = workgroup_id.x * uni.stride * 2;
let chunk1 = chunk0 + uni.stride;
let sum = chunks[chunk0][local_invocation_id.x] +
chunks[chunk1][local_invocation_id.x];
chunks[chunk0][local_invocation_id.x] = sum;
}
缓冲区尺寸同样得加大:
const chunksBuffer = device.createBuffer({
size: numChunks * chunkSize * 4 * 4, // 16 字节/条目 (vec4u)
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
const resultBuffer = device.createBuffer({
size: chunkSize * 4 * 4,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
就这样。

在 GPU 上绘制直方图
接下来直接在 GPU 上画直方图。JavaScript 里用 canvas 2D API 给每个 bin 画一个 1×height 的矩形,特别省事。WebGPU 也能这么干,不过画直方图这个具体问题,我觉得有更合适的路子。
干脆就画一个矩形。画矩形这事儿前面讲过不少次了,比如纹理那几篇文章里,大多数示例都是画矩形。
画直方图时,片段着色器里可以把纹理坐标传进去,水平方向从 0→1 映射到 0→numBins-1。再查这个 bin 的值,算出 0 到 1 之间的高度。然后拿它跟垂直纹理坐标比一比。纹理坐标比高度高,就画 0;比高度低,就画颜色。
单通道这样够用,但我们想画多个通道。那就每个通道占一位:高度超过纹理坐标的通道,对应位设 1。拿这 4 位去 16 种颜色里查一个。这样每个通道和它们的组合用什么颜色,也能自己定。
片段着色器这么写:
struct Uniforms {
matrix: mat4x4f, // <- 由顶点着色器使用
colors: `array<vec4f, 16>`,
channelMult: vec4u,
};
@group(0) @binding(0) `var<storage, read>` bins: `array<vec4u>`;
@group(0) @binding(1) `var<uniform>` uni: Uniforms;
@group(0) @binding(2) `var<storage, read_write>` scale: vec4f;
@fragment fn fs(fsInput: OurVertexShaderOutput) -> @location(0) vec4f {
let numBins = arrayLength(&bins);
let lastBinIndex = u32(numBins - 1);
let bin = clamp(
u32(fsInput.texcoord.x * f32(numBins)),
0,
lastBinIndex);
let heights = vec4f(bins[bin]) * scale;
let bits = heights > vec4f(fsInput.texcoord.y);
let ndx = dot(select(vec4u(0), uni.channelMult, bits), vec4u(1));
return uni.colors[ndx];
}
第一段按水平纹理坐标算 bin:
let numBins = arrayLength(&bins);
let lastBinIndex = u32(numBins - 1);
let bin = clamp(
u32(fsInput.texcoord.x * f32(numBins)),
0,
lastBinIndex);
下一段拿到 4 个通道的高度。跟 JavaScript 里一样乘 scale。这个值稍后得补上。
let heights = vec4f(bins[bin]) * scale;
接着在 vec4<bool> 里塞 4 个布尔值,一个通道一个。bin 高度高过纹理坐标就是 true。
let bits = heights > vec4f(fsInput.texcoord.y);
下一段按这 4 个布尔值从 uni.channelMult 里挑值,再把 4 个值加起来。传 uni.channelMult 跟 JavaScript 里的做法差不多,用来挑要画哪些通道。比如把 channelMult 设成 1, 2, 4, 0,出来的就是红、绿、蓝三个直方图。
let ndx = dot(select(vec4u(0), uni.channelMult, bits), vec4u(1));
最后一段从 16 种颜色里挑一个:
return uni.colors[ndx];
还得有个着色器来算 scale。JavaScript 里是这么写的:
const numBins = histogram.length / 4;
const max = [0, 0, 0, 0];
histogram.forEach((v, ndx) => {
const ch = ndx % 4;
max[ch] = Math.max(max[ch], v);
});
const scale = max.map((max) => Math.max(1 / max, (0.2 * numBins) / numEntries));
计算着色器里干同一件事:
@group(0) @binding(0) `var<storage, read>` bins: `array<vec4u>`;
@group(0) @binding(1) `var<storage, read_write>` scale: vec4f;
@group(0) @binding(2) var ourTexture: `texture_2d<f32>`;
@compute @workgroup_size(1, 1, 1) fn cs() {
let size = textureDimensions(ourTexture, 0);
let numEntries = f32(size.x * size.y);
var m = vec4u(0);
let numBins = arrayLength(&bins);
for (var i = 0u ; i < numBins; i++) {
m = max(m, bins[i]);
}
scale = max(1.0 / vec4f(m), vec4f(0.2 * f32(numBins) / numEntries));
}
注意,传 ourTexture 唯一的原因是要拿它的尺寸算 numEntries,而 JavaScript 里我们是直接传 numEntries。也能用 uniform 传 numEntries,但那样得建 uniform 缓冲区、更新值、绑定,一堆事。直接引用纹理本身看着更省事。
还有个要考虑的点:这里只用了单核。也能做归约,但总共才 numBins 步,也就是 256 步。调度一堆归约步骤的开销,可能比并行省下的还多。我实际计过时,大概 0.1ms,至少在一台机器上是这样。
剩下就是把这些拼起来。
既然要用 GPU 画到 canvas,就得先拿到首选画布格式:
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
接着建两个着色器模块(就是上面那两段),再各建一条管线:
const scaleModule = device.createShaderModule({
label: 'histogram scale shader',
code: /* wgsl */ `
@group(0) @binding(0) `var<storage, read>` bins: `array<vec4u>`;
@group(0) @binding(1) `var<storage, read_write>` scale: vec4f;
@group(0) @binding(2) var ourTexture: `texture_2d<f32>`;
@compute @workgroup_size(1, 1, 1) fn cs() {
let size = textureDimensions(ourTexture, 0);
let numEntries = f32(size.x * size.y);
var m = vec4u(0);
let numBins = arrayLength(&bins);
for (var i = 0u ; i < numBins; i++) {
m = max(m, bins[i]);
}
scale = max(1.0 / vec4f(m), vec4f(0.2 * f32(numBins) / numEntries));
}
`,
});
const drawHistogramModule = device.createShaderModule({
label: 'draw histogram shader',
code: /* wgsl */ `
struct OurVertexShaderOutput {
@builtin(position) position: vec4f,
@location(0) texcoord: vec2f,
};
struct Uniforms {
matrix: mat4x4f,
colors: `array<vec4f, 16>`,
channelMult: vec4u,
};
@group(0) @binding(0) `var<storage, read>` bins: `array<vec4u>`;
@group(0) @binding(1) `var<uniform>` uni: Uniforms;
@group(0) @binding(2) `var<storage, read_write>` scale: vec4f;
@vertex fn vs(
@builtin(vertex_index) vertexIndex : u32
) -> OurVertexShaderOutput {
let pos = array(
// 三角形 1
vec2f( 0.0, 0.0), // 中心
vec2f( 1.0, 0.0), // 右侧,中心
vec2f( 0.0, 1.0), // 中心,顶部
// 三角形 2
vec2f( 0.0, 1.0), // 中心,顶部
vec2f( 1.0, 0.0), // 右侧,中心
vec2f( 1.0, 1.0), // 右侧,顶部
);
var vsOutput: OurVertexShaderOutput;
let xy = pos[vertexIndex];
vsOutput.position = uni.matrix * vec4f(xy, 0.0, 1.0);
vsOutput.texcoord = xy;
return vsOutput;
}
@fragment fn fs(fsInput: OurVertexShaderOutput) -> @location(0) vec4f {
let numBins = arrayLength(&bins);
let lastBinIndex = u32(numBins - 1);
let bin = clamp(
u32(fsInput.texcoord.x * f32(numBins)),
0,
lastBinIndex);
let heights = vec4f(bins[bin]) * scale;
let bits = heights > vec4f(fsInput.texcoord.y);
let ndx = dot(select(vec4u(0), uni.channelMult, bits), vec4u(1));
return uni.colors[ndx];
}
`,
});
const scalePipeline = device.createComputePipeline({
label: 'scale',
layout: 'auto',
compute: {
module: scaleModule,
},
});
const drawHistogramPipeline = device.createRenderPipeline({
label: 'draw histogram',
layout: 'auto',
vertex: {
module: drawHistogramModule,
},
fragment: {
module: drawHistogramModule,
targets: [{ format: presentationFormat }],
},
});
result buffer 不用了,因为不回读值。但要一个 scale buffer 装算出来的 scale:
const scaleBuffer = device.createBuffer({
size: 4 * 4,
usage: GPUBufferUsage.STORAGE,
});
给 scale 管线建个绑定组,塞进 chunks、scale buffer 和纹理:
const scaleBindGroup = device.createBindGroup({
layout: scalePipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: {
buffer: chunksBuffer,
size: chunkSize * 4 * 4,
},
},
{ binding: 1, resource: scaleBuffer },
{ binding: 2, resource: texture },
],
});
上面把 chunksBuffer 的绑定大小设成了第一个 chunk 的大小。这样着色器里:
@group(0) @binding(0) `var<storage, read>` bins: `array<vec4u>`;
...
let numBins = arrayLength(&bins);
拿到的值才对。要是不指定大小,整个 chunksBuffer 都可用,numBins 就会按所有 chunk 来算,不只是第一个。
把 chunks 归约成一个 chunk 之后,就能跑 scale 计算着色器了。没有 result buffer 了,所以不用把第一个 chunk 拷过去,不用映射,也不用传 numEntries(已经用纹理算过了)。数据就在 chunksBuffer 里:
// 计算各通道的 scale
pass.setPipeline(scalePipeline);
pass.setBindGroup(0, scaleBindGroup);
pass.dispatchWorkgroups(1);
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
showImageBitmap(imgBitmap);
// 绘制红、绿、蓝通道
drawHistogram([0, 1, 2]);
// 绘制亮度通道
drawHistogram([3]);
现在把 drawHistogram 改成用 GPU 渲染。
先建个 uniform buffer 传 uniforms。对着着色器里的结构来:
struct Uniforms {
matrix: mat4x4f,
colors: `array<vec4f, 16>`,
channelMult: vec4u,
};
建 buffer 并填值的代码如下:
function drawHistogram(channels, height = 100) {
const numBins = chunkSize;
// matrix: mat4x4f;
// colors: `array<vec4f, 16>`;
// channelMult; vec4u,
const uniformValuesAsF32 = new Float32Array(16 + 64 + 4 + 4);
const uniformValuesAsU32 = new Uint32Array(uniformValuesAsF32.buffer);
const uniformBuffer = device.createBuffer({
label: 'draw histogram uniform buffer',
size: uniformValuesAsF32.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const subpart = (view, offset, length) => view.subarray(offset, offset + length);
const matrix = subpart(uniformValuesAsF32, 0, 16);
const colors = subpart(uniformValuesAsF32, 16, 64);
const channelMult = subpart(uniformValuesAsU32, 16 + 64, 4);
const range = (i, fn) => new Array(i).fill(0).map((_, i) => fn(i));
channelMult.set(range(4, i => channels.indexOf(i) >= 0 ? 2 ** i : 0));
colors.set([
[0, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 0, 1],
[1, 1, 0, 1],
[0, 0, 1, 1],
[1, 0, 1, 1],
[0, 1, 1, 1],
[0.5, 0.5, 0.5, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
].flat());
还得用矩阵数学算一个矩阵,跟矩阵数学那几篇里讲的一样。
具体说,着色器里写死了一个 X、Y 都从 0 到 1 的单位四边形。把 X 和 Y 都放大 2 再减 1,就得到一个裁剪空间里 -1 到 +1 的四边形。这种单四边形套路很常见,因为只靠一点矩阵运算,就能在任意位置、任意方向画矩形,不用专门做顶点数据。
mat4.identity(matrix);
mat4.translate(matrix, [-1, -1, 0], matrix);
mat4.scale(matrix, [2, 2, 1], matrix);
device.queue.writeBuffer(uniformBuffer, 0, uniformValuesAsF32);
再给这些建个 bindGroup:
const bindGroup = device.createBindGroup({
layout: drawHistogramPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: chunksBuffer, size: chunkSize * 4 * 4 } },
{ binding: 1, resource: uniformBuffer },
{ binding: 2, resource: scaleBuffer },
],
});
还需要一个配好 WebGPU 的 canvas:
const canvas = document.createElement("canvas");
const context = canvas.getContext("webgpu");
context.configure({
device,
format: presentationFormat,
});
canvas.width = numBins;
canvas.height = height;
document.body.appendChild(canvas);
最后渲染:
// 从 canvas context 获取当前纹理并设置为渲染目标
const renderPassDescriptor = {
label: 'our basic canvas renderPass',
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
clearValue: [0.3, 0.3, 0.3, 1],
loadOp: 'clear',
storeOp: 'store',
},
],
};
const encoder = device.createCommandEncoder({ label: 'render histogram' });
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(drawHistogramPipeline);
pass.setBindGroup(0, bindGroup);
pass.draw(6); // 调用顶点着色器 6 次
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
到这儿就齐了,现在整条链路都在 GPU 上跑。

让视频也拥有直方图
最后再做一件事——拿视频的直方图。其实就是把外部视频那篇的示例和前面的示例合到一起。
HTML 和 CSS 得照着视频示例改:
<style>
@import url(resources/webgpu-lesson.css);
html, body {
margin: 0; /* 移除默认边距 */
height: 100%; /* 让 html,body 充满页面 */
}
canvas {
display: block; /* 让 canvas 像块元素一样 */
width: 100%; /* 让 canvas 充满容器 */
height: 100%;
}
#start {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#start>div {
font-size: 200px;
cursor: pointer;
}
</style>
</head>
<body>
<canvas></canvas>
<div id="start">
<div>▶️</div>
</div>
</body>
开头先把 canvas 配好:
// 从 canvas 获取 WebGPU context 并配置
const canvas = document.querySelector("canvas");
const context = canvas.getContext("webgpu");
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format: presentationFormat,
});
用了外部纹理,着色器里纹理类型的声明要改:
const chunkSize = chunkWidth * chunkHeight;
`var<workgroup>` bins: `array<array<atomic<u32>`, 4>, chunkSize>;
@group(0) @binding(0) `var<storage, read_write>` chunks: `array<array<vec4u, chunkSize>`>;
@group(0) @binding(1) var ourTexture: texture_external;
const kSRGBLuminanceFactors = vec3f(0.2126, 0.7152, 0.0722);
fn srgbLuminance(color: vec3f) -> f32 {
return saturate(dot(color, kSRGBLuminanceFactors));
}
@compute @workgroup_size(chunkWidth, chunkHeight, 1)
fn cs(
@builtin(workgroup_id) workgroup_id: vec3u,
@builtin(local_invocation_id) local_invocation_id: vec3u,
) {
let size = textureDimensions(ourTexture);
let position = workgroup_id.xy * vec2u(chunkWidth, chunkHeight) +
local_invocation_id.xy;
if (all(position < size)) {
let numBins = f32(chunkSize);
let lastBinIndex = u32(numBins - 1);
var channels = textureLoad(ourTexture, position);
channels.w = srgbLuminance(channels.rgb);
for (var ch = 0; ch < 4; ch++) {
let v = channels[ch];
let bin = min(u32(v * numBins), lastBinIndex);
atomicAdd(&bins[bin][ch], 1u);
}
}
...
scale 计算着色器也照样改:
@group(0) @binding(0) `var<storage, read>` bins: `array<vec4u>`;
@group(0) @binding(1) `var<storage, read_write>` scale: vec4f;
@group(0) @binding(2) var ourTexture: texture_external;
@compute @workgroup_size(1, 1, 1) fn cs() {
let size = textureDimensions(ourTexture);
let numEntries = f32(size.x * size.y);
...
画视频的着色器模块直接从视频那篇抄,建渲染管线的代码也一样,采样器、uniform buffer、画视频的 render pass 都照搬。等点击、开始播放那段也一样。
视频一开跑就能配直方图计算了。唯一的不同是尺寸从视频拿,不从纹理拿:
const chunksAcross = Math.ceil(video.videoWidth / k.chunkWidth);
const chunksDown = Math.ceil(video.videoHeight / k.chunkHeight);
把原来的 drawHistogram 拆开,两个要画的直方图各自建 uniform buffer 和 bind group:
const histogramDrawInfos = [[0, 1, 2], [3]].map((channels) => {
const uniformValuesAsF32 = new Float32Array(16 + 64 + 4 + 4);
const uniformValuesAsU32 = new Uint32Array(uniformValuesAsF32.buffer);
const uniformBuffer = device.createBuffer({
label: "draw histogram uniform buffer",
size: uniformValuesAsF32.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
thingsToDestroy.push(uniformBuffer);
const subpart = (view, offset, length) =>
view.subarray(offset, offset + length);
const matrix = subpart(uniformValuesAsF32, 0, 16);
const colors = subpart(uniformValuesAsF32, 16, 64);
const channelMult = subpart(uniformValuesAsU32, 16 + 64, 4);
colors.set(
[
[0, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 0, 1],
[1, 1, 0, 1],
[0, 0, 1, 1],
[1, 0, 1, 1],
[0, 1, 1, 1],
[0.5, 0.5, 0.5, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
].flat(),
);
const drawHistogramBindGroup = device.createBindGroup({
layout: drawHistogramPipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: chunksBuffer, size: chunkSize * 4 * 4 },
},
{ binding: 1, resource: uniformBuffer },
{ binding: 2, resource: scaleBuffer },
],
});
return {
drawHistogramBindGroup,
matrix,
uniformBuffer,
uniformValuesAsF32,
};
});
渲染时先导入视频纹理。记住它只在一次 JavaScript 事件里有效,所以每帧都得重新建引用这个纹理的 bind group:
function render() {
const texture = device.importExternalTexture({source: video});
const histogramBindGroup = device.createBindGroup({
layout: histogramChunkPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: chunksBuffer },
{ binding: 1, resource: texture },
],
});
const scaleBindGroup = device.createBindGroup({
layout: scalePipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: chunksBuffer, size: chunkSize * 4 * 4 }},
{ binding: 1, resource: scaleBuffer },
{ binding: 2, resource: texture },
],
});
... 此处插入直方图计算代码 ...
画视频跟外部视频那篇差不多。区别在算矩阵的代码:我们做的是放大 2 再减 1,但 y 用 -2 加 1,把 Y 翻过来。同时按比例缩放做出 cover 效果,让视频始终填满 canvas,宽高比又不变:
// 绘制到 canvas
{
const canvasTexture = context.getCurrentTexture().createView();
renderPassDescriptor.colorAttachments[0].view = canvasTexture;
const pass = encoder.beginRenderPass(renderPassDescriptor);
// 绘制视频
const bindGroup = device.createBindGroup({
layout: videoPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: videoSampler },
{ binding: 1, resource: texture },
{ binding: 2, resource: videoUniformBuffer },
],
});
// 'cover' canvas
const canvasAspect = canvas.clientWidth / canvas.clientHeight;
const videoAspect = video.videoWidth / video.videoHeight;
const scale = canvasAspect > videoAspect
? [1, canvasAspect / videoAspect, 1]
: [videoAspect / canvasAspect, 1, 1];
const matrix = mat4.identity(videoMatrix);
mat4.scale(matrix, scale, matrix);
mat4.translate(matrix, [-1, 1, 0], matrix);
mat4.scale(matrix, [2, -2, 1], matrix);
device.queue.writeBuffer(videoUniformBuffer, 0, videoUniformValues);
pass.setPipeline(videoPipeline);
pass.setBindGroup(0, bindGroup);
pass.draw(6);
画直方图就是把 drawHistogram 里的代码搬上来:
// 绘制直方图
histogramDrawInfos.forEach(({
matrix,
uniformBuffer,
uniformValuesAsF32,
drawHistogramBindGroup,
}, i) => {
mat4.identity(matrix);
mat4.translate(matrix, [-0.95 + i, -1, 0], matrix);
mat4.scale(matrix, [0.9, 0.5, 1], matrix);
device.queue.writeBuffer(uniformBuffer, 0, uniformValuesAsF32);
pass.setPipeline(drawHistogramPipeline);
pass.setBindGroup(0, drawHistogramBindGroup);
pass.draw(6);
});
pass.end();
}
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
上面这套矩阵运算,会在左半边或右半边画一个四边形:宽是 canvas 一半宽的 90%,在那个半区居中,高是 canvas 高的四分之一。
关键的三点
-
存储和计算都向量化。用
vec4u顶掉u32标量,把 RGBA 四个通道打包存,内存带宽一下提到 4 倍,存储 buffer 的绑定数量也少了。着色器里再用atomicAdd对向量分量做原子操作,多通道直方图的并行累加问题就解决了。 -
共享内存 + 原子操作,两阶段归约。先在 workgroup 里用共享内存(
var<workgroup>)做本地 bin 累加,靠atomicAdd躲开竞争,再用workgroupBarrier同步,把结果写进全局 storage buffer。之后再单独跑一遍归约着色器合并各个 chunk,省掉了对全局内存的频繁原子操作。 -
直方图直接在 GPU 上画。原来用 JavaScript canvas 2D 画,现在改由片段着色器直接画。用位掩码
channelMult选通道,select加dot在片段着色器里查 16 种组合颜色,省掉 JS 读回和 CPU 绘图的开销。视频场景里每帧动态导入外部纹理,整套实时直方图都在 GPU 上跑。
术语对照
| 术语 | 建议译法 | 备注 |
|---|---|---|
| Compute Shader | 计算着色器 | WebGPU 术语,与 WebGL 无直接对应 |
| Workgroup | 工作组 | 类似 CUDA 的 thread block |
| Storage Buffer | 存储缓冲区 | WebGPU 术语 |
| Uniform Buffer | 统一缓冲区 | 对应 GLSL 的 uniform buffer object (UBO) |
| Atomic Operation | 原子操作 | 如 atomicAdd、atomicLoad |
| Bind Group | 绑定组 | WebGPU 专有概念 |
| Texture | 纹理 | 通用 |
| External Texture | 外部纹理 | WebGPU 专有,给视频帧用 |
| Texture Coordinate | 纹理坐标 | 通用 |
| Fragment Shader | 片段着色器 | 对应 GLSL 的 fragment shader |
| Vertex Shader | 顶点着色器 | 通用 |
| Render Pass | 渲染通道 | WebGPU 术语,类似 WebGL 的 draw call 批次 |
| Render Pipeline | 渲染管线 | WebGPU 术语 |
| Compute Pipeline | 计算管线 | WebGPU 术语 |
| Clip Space | 裁剪空间 | 通用 |
| Workgroup Barrier | 工作组屏障 | 类似 GLSL 的 barrier() |
| Invocation | 调用 | 着色器的一次执行 |
| Reduction | 归约 | 通用并行计算术语 |
| Luminance | 亮度 | 通用 |
| SRGB | sRGB | 颜色空间 |
vec4f / vec4u | 四分量浮点/无符号整数向量 | WGSL 类型 |
mat4x4f | 4×4 浮点矩阵 | WGSL 类型 |
texture_2d<f32> | 二维浮点纹理 | WGSL 类型 |
texture_external | 外部纹理 | WGSL 类型 |
textureLoad | 纹理加载 | WGSL 内置函数 |
textureDimensions | 纹理尺寸 | WGSL 内置函数 |
atomicAdd | 原子加法 | WGSL 内置函数 |
atomicLoad | 原子读取 | WGSL 内置函数 |
arrayLength | 数组长度 | WGSL 内置函数 |
saturate | 饱和截断到 [0,1] | 对应 GLSL clamp(x, 0.0, 1.0) |
dot | 点积 | 通用 |
select | 选择 | WGSL 内置函数,类似 GLSL mix 处理向量 |
clamp | 截断 | 通用 |
原文最后还聊了些直方图的应用场景:给用户看图像调整的参考、直方图均衡化、自适应直方图均衡化、按直方图做图像分割、直方图阈值化这些,留着以后再说。
