WebGPU Points(WebGPU 点渲染)

原文作者:webgpufundamentals Contributors


关键的三点

  1. 用实例化四边形替代原生 point-list
    WebGPU 原生点只有 1×1 像素。用 stepMode: 'instance' 把每个点扩成 6 个顶点的四边形,大小、纹理、旋转随便玩,跨平台也稳。

  2. 对点位置乘 clipPos.w,锁死屏幕尺寸
    3D 点渲染里把偏移量乘上裁剪空间的 w 分量,GPU 的透视除法就被抵消了。点不管离相机多远,屏幕上的像素大小都一样。

  3. 紧凑顶点布局 + 实例化绘制,少折腾 CPU 和 GPU
    位置、大小、旋转这些属性全塞进一个顶点缓冲,再用 draw(6, kNumPoints) 一次画完,省掉逐点切缓冲和多次 draw call。


原生点渲染:point-list

WebGPU 能画点。渲染管线里把图元拓扑(primitive topology)设成 'point-list' 就行。

先来个最简的顶点/片元着色器。位置直接用裁剪空间坐标,片元着色器写死黄色:

struct Vertex {
  @location(0) position: vec2f,
};

struct VSOutput {
  @builtin(position) position: vec4f,
};

@vertex fn vs(vert: Vertex) -> VSOutput {
  var vsOut: VSOutput;
  vsOut.position = vec4f(vert.position, 0, 1);
  return vsOut;
}

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
  return vec4f(1, 1, 0, 1); // 黄色
}

建管线时把拓扑设成 'point-list':

const pipeline = device.createRenderPipeline({
  label: '1 pixel points',
  layout: 'auto',
  vertex: {
    module,
    buffers: [
      {
        arrayStride: 2 * 4, // 2 个 float,各 4 字节
        attributes: [
          {shaderLocation: 0, offset: 0, format: 'float32x2'},  // position
        ],
      },
    ],
  },
  fragment: {
    module,
    targets: [{ format: presentationFormat }],
  },
  + primitive: {
  +   topology: 'point-list',
  + },
});

塞 100 个随机裁剪空间点进去:

const rand = (min, max) => min + Math.random() * (max - min);

const kNumPoints = 100;
const vertexData = new Float32Array(kNumPoints * 2);
for (let i = 0; i < kNumPoints; ++i) {
  const offset = i * 2;
  vertexData[offset + 0] = rand(-1, 1);
  vertexData[offset + 1] = rand(-1, 1);
}

const vertexBuffer = device.createBuffer({
  label: "vertex buffer vertices",
  size: vertexData.byteLength,
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vertexBuffer, 0, vertexData);

画一下:

const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
pass.draw(kNumPoints);
pass.end();

这样就有了 100 个 1 像素的黄点。毛病也很明显:所有点都只有 1 像素。WebGPU 原生就这点尺寸,想画大点得自己拼四边形,再上实例化。


可调大小的点:实例化四边形

顶点着色器里加上四边形顶点数组和尺寸属性,再传一个 uniform 把目标纹理分辨率带进去:

struct Vertex {
  @location(0) position: vec2f,
  + @location(1) size: f32,
};

+ struct Uniforms {
+   resolution: vec2f,
+ };

struct VSOutput {
  @builtin(position) position: vec4f,
};

+ @group(0) @binding(0) `var<uniform>` uni: Uniforms;

@vertex fn vs(
    vert: Vertex,
    + @builtin(vertex_index) vNdx: u32,
) -> VSOutput {
+   let points = array(
+     vec2f(-1, -1),
+     vec2f( 1, -1),
+     vec2f(-1,  1),
+     vec2f(-1,  1),
+     vec2f( 1, -1),
+     vec2f( 1,  1),
+   );
    var vsOut: VSOutput;
+   let pos = points[vNdx];
-   vsOut.position = vec4f(vert.position, 0, 1);
+   vsOut.position = vec4f(vert.position + pos * vert.size / uni.resolution, 0, 1);
    return vsOut;
}

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
  return vec4f(1, 1, 0, 1); // 黄色
}

JS 这边加个逐实例属性(size),把 stepMode 设成 'instance',point-list 拓扑去掉:

const pipeline = device.createRenderPipeline({
  label: 'sizeable points',
  layout: 'auto',
  vertex: {
    module,
    buffers: [
      {
-       arrayStride: 2 * 4, // 2 个 float,各 4 字节
+       arrayStride: (2 + 1) * 4, // 3 个 float,各 4 字节
+       stepMode: 'instance',
        attributes: [
          {shaderLocation: 0, offset: 0, format: 'float32x2'},  // position
+         {shaderLocation: 1, offset: 8, format: 'float32'},    // size
        ],
      },
    ],
  },
  fragment: {
    module,
    targets: [{ format: presentationFormat }],
  },
- primitive: {
-   topology: 'point-list',
- },
});

顶点数据里加个随机尺寸:

const kNumPoints = 100;
- const vertexData = new Float32Array(kNumPoints * 2);
+ const vertexData = new Float32Array(kNumPoints * 3);
for (let i = 0; i < kNumPoints; ++i) {
- const offset = i * 2;
+ const offset = i * 3;
  vertexData[offset + 0] = rand(-1, 1);
  vertexData[offset + 1] = rand(-1, 1);
+ vertexData[offset + 2] = rand(1, 32);
}

建一个 uniform buffer 把分辨率传进去:

const uniformValues = new Float32Array(2);
const uniformBuffer = device.createBuffer({
  size: uniformValues.byteLength,
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const kResolutionOffset = 0;
const resolutionValue = uniformValues.subarray(
  kResolutionOffset,
  kResolutionOffset + 2,
);

绑定组:

const bindGroup = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [{ binding: 0, resource: uniformBuffer }],
});

渲染时更新分辨率,按实例画:

// 从 canvas context 获取当前纹理
const canvasTexture = context.getCurrentTexture();
renderPassDescriptor.colorAttachments[0].view = canvasTexture.createView();

+(
  // 更新 uniform buffer 中的分辨率
  (+resolutionValue.set([canvasTexture.width, canvasTexture.height]))
);
+device.queue.writeBuffer(uniformBuffer, 0, uniformValues);

const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
+pass.setBindGroup(0, bindGroup);
-pass.draw(kNumPoints);
+pass.draw(6, kNumPoints);
pass.end();

现在点想多大就多大。更关键的是,这套做法不靠原生点支持,哪都能跑。


纹理化点

顶点着色器把纹理坐标传给片元着色器:

struct VSOutput {
  @builtin(position) position: vec4f,
+ @location(0) texcoord: vec2f,
};

@vertex fn vs(
    vert: Vertex,
    @builtin(vertex_index) vNdx: u32,
) -> VSOutput {
  let points = array(
    vec2f(-1, -1),
    vec2f( 1, -1),
    vec2f(-1,  1),
    vec2f(-1,  1),
    vec2f( 1, -1),
    vec2f( 1,  1),
  );
  var vsOut: VSOutput;
  let pos = points[vNdx];
  vsOut.position = vec4f(vert.position + pos * vert.size / uni.resolution, 0, 1);
+ vsOut.texcoord = pos * 0.5 + 0.5;
  return vsOut;
}

片元着色器里用采样器和纹理:

+ @group(0) @binding(1) var s: sampler;
+ @group(0) @binding(2) var t: `texture_2d<f32>`;

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
- return vec4f(1, 1, 0, 1); // 黄色
+ return textureSample(t, s, vsOut.texcoord);
}

用离屏 canvas 造张纹理(跟前面讲导入纹理那篇一样):

const ctx = new OffscreenCanvas(32, 32).getContext("2d");
ctx.font = "27px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("🥑", 16, 16);

const texture = device.createTexture({
  size: [32, 32],
  format: "rgba8unorm",
  usage:
    GPUTextureUsage.TEXTURE_BINDING |
    GPUTextureUsage.COPY_DST |
    GPUTextureUsage.RENDER_ATTACHMENT,
});
device.queue.copyExternalImageToTexture(
  { source: ctx.canvas, flipY: true },
  { texture, premultipliedAlpha: true },
  [32, 32],
);

建采样器,加进绑定组:

const sampler = device.createSampler({
  minFilter: "linear",
  magFilter: "linear",
});

const bindGroup = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [
    { binding: 0, resource: uniformBuffer },
    +{ binding: 1, resource: sampler },
    +{ binding: 2, resource: texture },
  ],
});

开混合,让透明度生效:

fragment: {
  module,
- targets: [{ format: presentationFormat }],
+ targets: [
+   {
+     format: presentationFormat,
+     blend: {
+       color: {
+         srcFactor: 'one',
+         dstFactor: 'one-minus-src-alpha',
+         operation: 'add',
+       },
+       alpha: {
+         srcFactor: 'one',
+         dstFactor: 'one-minus-src-alpha',
+         operation: 'add',
+       },
+     },
+   },
+ ],
},

带纹理的点就出来了。


逐点旋转

加个旋转属性,用矩阵算(cos/sin 拼个 2x2 旋转矩阵):

struct Vertex {
  @location(0) position: vec2f,
  @location(1) size: f32,
+ @location(2) rotation: f32,
};

@vertex fn vs(
    vert: Vertex,
    @builtin(vertex_index) vNdx: u32,
) -> VSOutput {
  let points = array(
    vec2f(-1, -1),
    vec2f( 1, -1),
    vec2f(-1,  1),
    vec2f(-1,  1),
    vec2f( 1, -1),
    vec2f( 1,  1),
  );
  var vsOut: VSOutput;
  let pos = points[vNdx];
+ let c = cos(vert.rotation);
+ let s = sin(vert.rotation);
+ let rot = mat2x2f(
+    c, s,
+   -s, c,
+ );
- vsOut.position = vec4f(vert.position + pos * vert.size / uni.resolution, 0, 1);
+ vsOut.position = vec4f(vert.position + rot * pos * vert.size / uni.resolution, 0, 1);
  vsOut.texcoord = pos * 0.5 + 0.5;
  return vsOut;
}

管线里加上旋转属性:

arrayStride: (2 + 1 + 1) * 4, // 4 个 float,各 4 字节
stepMode: 'instance',
attributes: [
  {shaderLocation: 0, offset: 0, format: 'float32x2'},  // position
  {shaderLocation: 1, offset: 8, format: 'float32'},    // size
+ {shaderLocation: 2, offset: 12, format: 'float32'},   // rotation
],

顶点数据:

const vertexData = new Float32Array(kNumPoints * 4);
for (let i = 0; i < kNumPoints; ++i) {
  const offset = i * 4;
  vertexData[offset + 0] = rand(-1, 1);
  vertexData[offset + 1] = rand(-1, 1);
  vertexData[offset + 2] = rand(10, 64);
+ vertexData[offset + 3] = rand(0, Math.PI * 2);
}

换个有方向感的 emoji 纹理:

-ctx.fillText("🥑", 16, 16);
+ctx.fillText("👉", 16, 16);

3D 点

思路跟 2D 一样,先把标准 3D 顶点变换走完,再在裁剪空间里加四边形偏移。

先来一批斐波那契球面顶点:

function createFibonacciSphereVertices({ numSamples, radius }) {
  const vertices = [];
  const increment = Math.PI * (3 - Math.sqrt(5));
  for (let i = 0; i < numSamples; ++i) {
    const offset = 2 / numSamples;
    const y = i * offset - 1 + offset / 2;
    const r = Math.sqrt(1 - Math.pow(y, 2));
    const phi = (i % numSamples) * increment;
    const x = Math.cos(phi) * r;
    const z = Math.sin(phi) * r;
    vertices.push(x * radius, y * radius, z * radius);
  }
  return new Float32Array(vertices);
}

3D 点的着色器(一开始还是原生 point-list,就 1px):

struct Vertex {
  @location(0) position: vec4f,
};

struct Uniforms {
  matrix: mat4x4f,
};

struct VSOutput {
  @builtin(position) position: vec4f,
};

@group(0) @binding(0) `var<uniform>` uni: Uniforms;

@vertex fn vs(vert: Vertex) -> VSOutput {
  var vsOut: VSOutput;
  let clipPos = uni.matrix * vert.position;
  vsOut.position = clipPos;
  return vsOut;
}

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
  return vec4f(1, 0.5, 0.2, 1); // 橙色
}

管线和缓冲的设置跟 2D 版本差不多,只是顶点格式换成 float32x3,topology 设成 'point-list'。渲染循环用 requestAnimationFrame,每帧更新 MVP 矩阵。

1px 的 3D 点看着太惨了,所以还是套 2D 那招,把点扩成四边形:

struct Uniforms {
  matrix: mat4x4f,
+ resolution: vec2f,
+ size: f32,
};

@vertex fn vs(
    vert: Vertex,
+   @builtin(vertex_index) vNdx: u32,
) -> VSOutput {
+ let points = array(
+   vec2f(-1, -1),
+   vec2f( 1, -1),
+   vec2f(-1,  1),
+   vec2f(-1,  1),
+   vec2f( 1, -1),
+   vec2f( 1,  1),
+ );
  var vsOut: VSOutput;
+ let pos = points[vNdx];
  let clipPos = uni.matrix * vert.position;
+ let pointPos = vec4f(pos * uni.size / uni.resolution, 0, 0);
- vsOut.position = clipPos;
+ vsOut.position = clipPos + pointPos;
  return vsOut;
}

JS 里把 uniform buffer 撑大,装矩阵(16 floats)、分辨率(2 floats)和尺寸(1 float,还得补 padding)。顶点缓冲设 stepMode: 'instance'(每个点就是一个实例)。最后把 pass.draw(kNumPoints) 换成 pass.draw(6, kNumPoints)。

3D 点就有了,而且会跟着离相机的距离自然缩放(透视)。


固定屏幕尺寸的 3D 点

想让点在屏幕上一直是固定像素大小,就得把透视除法抵消掉。GPU 会把顶点着色器输出的位置除以 w,远的自然就小了。算点偏移时先乘上 clipPos.w,除完大小就还是原样:

var vsOut: VSOutput;
let pos = points[vNdx];
let clipPos = uni.matrix * vert.position;
- let pointPos = vec4f(pos * uni.size / uni.resolution, 0, 0);
+ let pointPos = vec4f(pos * uni.size / uni.resolution * clipPos.w, 0, 0);
vsOut.position = clipPos + pointPos;
return vsOut;

现在点离多远,屏幕上的大小都一样。


为什么 WebGPU 原生只支持 1×1 像素点?

WebGPU 架在 Vulkan、Metal、DirectX 这些原生 GPU API 上,可它们对点的支持各不相同:

  • 有些 API 对点的最大尺寸有限制,还跟设备有关;
  • 有些 API 在点中心跑到裁剪空间外时就不画了,另一些照画;
  • 有些 API 里,上面这些行为甚至看驱动怎么实现。

所以 WebGPU 为了可移植,最后只支持 1×1 像素的点。好在像上面那样自己画大点很容易。这套方案跨设备都能用,没有尺寸限制,裁剪行为也一致——点的中心在不在裁剪空间外都一样,落在里面的部分照常画。

另外自定义方案更灵活。比如旋转点,原生 API 根本不支持。自己实现就能顺手加更多特性,扩展起来方便。


术语对照

英文术语推荐中文翻译备注
primitive topology图元拓扑WebGPU 中 primitive.topology 的值,常见 point-list、triangle-list
point-list点列表渲染点时的图元拓扑模式
vertex buffer顶点缓冲存放顶点属性数据
arrayStride数组步长相邻顶点(或实例)之间的字节数
stepMode: 'instance'步进模式:实例逐实例推进顶点属性,核心优化点之一
instancing实例化一次绘制调用渲染多个实例
uniform buffer统一缓冲存储全局只读数据,对 GPU 高效
bind group绑定组组织和绑定资源到着色器
clip space裁剪空间顶点着色器输出的坐标空间,GPU 随后执行透视除法
perspective divide透视除法GPU 自动将位置除以 w,产生近大远小效果
W component / clipPos.wW 分量裁剪空间齐次坐标的第四分量,固定屏幕尺寸就靠它
fragment shader片元着色器决定像素颜色
vertex shader顶点着色器处理顶点变换
render pipeline渲染管线封装着色器、混合、拓扑等状态
blending混合透明度/混合模式配置
sampler采样器定义纹理过滤方式(如 linear)
texture coordinates纹理坐标采样纹理用的 UV 坐标
mipmap多级纹理本文章未涉及,但注意不要与 WebGL 术语混淆
rgba8unormRGBA8 无符号归一化纹理格式
offscreen canvas离屏 Canvas生成纹理图案用
premultipliedAlpha预乘 Alpha处理透明纹理时的重要概念

上面这些术语都按 WebGPU/WGSL 的语义校过,免得跟 GLSL/WebGL 的老叫法混了。比如 WebGPU 里的“uniform buffer”对应 GLSL 的 uniform block,底层语义是一回事,都是全局只读数据。