Web 图形与 3D / 系统课时
用索引绘制复用网格顶点
用索引绘制复用网格顶点
两个三角形拼成一个矩形,只需四个不同的顶点;普通非索引绘制会重复存储共享顶点。本篇用 Uint16Array 创建索引缓冲区,绑定 uint16 格式,通过 drawIndexed() 绘制并检查复用结果。
学习目标
- 区分顶点数据、索引数据和索引数量。
- 使用
setIndexBuffer()与drawIndexed()绘制共享顶点的网格。 - 验证三角形连接顺序,排查格式和缓冲区绑定错误。
四个顶点如何组成两个三角形
顶点缓冲区按编号存储四个二维位置:0 为左下角 (-0.6, -0.6),1 为右下角 (0.6, -0.6),2 为右上角 (0.6, 0.6),3 为左上角 (-0.6, 0.6)。索引数组 [0, 1, 2, 0, 2, 3] 每三个值定义一个三角形;顶点 0 和 2 被两次引用,却只在顶点缓冲区中存储一次。

使用 triangle-list 拓扑时,六个索引生成两个互不依赖的三角形。索引值并不是字节偏移,而是顶点编号;绘制命令的 indexCount 应为 6,不能误填顶点数量 4。当前两组三角形的顶点顺序均为逆时针,便于后续启用背面剔除。
创建索引缓冲区并提交绘制
将下列内容保存为 index.html。示例使用 WebGPU 的 WGSL 顶点着色器读取 float32x2 位置,片元着色器给矩形填充青绿色。顶点缓冲区需要 VERTEX 用途,索引缓冲区需要 INDEX 用途;因为通过 queue.writeBuffer() 上传数据,两者还需要 COPY_DST。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>WebGPU 索引绘制</title>
<style>
body { font: 16px system-ui; margin: 24px; }
canvas { display: block; width: 480px; max-width: 100%; height: auto; }
</style>
</head>
<body>
<canvas id="view" width="480" height="480"></canvas>
<p id="status">正在初始化...</p>
<script type="module">
async function main() {
if (!navigator.gpu) throw new Error("当前环境不支持 WebGPU");
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error("无法获取 GPU 适配器");
const device = await adapter.requestDevice();
const canvas = document.querySelector("#view");
const context = canvas.getContext("webgpu");
if (!context) throw new Error("无法获取 WebGPU 画布上下文");
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format, alphaMode: "opaque" });
const vertices = new Float32Array([
-0.6, -0.6, // 0 左下
0.6, -0.6, // 1 右下
0.6, 0.6, // 2 右上
-0.6, 0.6, // 3 左上
]);
// 两组三角形共享顶点 0 和 2
const indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
const vertexBuffer = device.createBuffer({
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vertexBuffer, 0, vertices);
const indexBuffer = device.createBuffer({
size: indices.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(indexBuffer, 0, indices);
const shader = device.createShaderModule({ code: `
@vertex
fn vs(@location(0) pos: vec2f) -> @builtin(position) vec4f {
return vec4f(pos, 0.0, 1.0);
}
@fragment
fn fs() -> @location(0) vec4f {
return vec4f(0.02, 0.62, 0.58, 1.0);
}
` });
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: shader,
entryPoint: "vs",
buffers: [{
arrayStride: 8,
attributes: [{ shaderLocation: 0, offset: 0, format: "float32x2" }],
}],
},
fragment: {
module: shader,
entryPoint: "fs",
targets: [{ format }],
},
primitive: { topology: "triangle-list" },
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
clearValue: { r: 0.96, g: 0.98, b: 1, a: 1 },
loadOp: "clear",
storeOp: "store",
}],
});
// 索引格式必须与上传的 Uint16Array 一致
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
pass.setIndexBuffer(indexBuffer, "uint16");
pass.drawIndexed(indices.length, 1, 0, 0, 0);
pass.end();
device.queue.submit([encoder.finish()]);
document.querySelector("#status").textContent =
"已提交绘制:4 个顶点、6 个索引、2 个三角形";
}
main().catch(error => {
document.querySelector("#status").textContent = error.message;
console.error(error);
});
</script>
</body>
</html>预期结果:画布中央出现一个完整的青绿色正方形,背景为接近白色;下方显示“已提交绘制:4 个顶点、6 个索引、2 个三角形”。这里的提示表示命令已提交,不代表已读取 GPU 执行完成信号。
启动页面并核对结果
在 index.html 所在目录运行 Python 3 的静态文件服务;浏览器必须支持 WebGPU,并在 localhost 或 HTTPS 等安全上下文访问页面。
python3 -m http.server 8000预期结果:终端显示服务监听 8000 端口的提示,访问 http://localhost:8000/index.html 后出现正方形。服务实际绑定的网络地址和终端提示文字会因系统与 Python 版本而异。
可用两个局部改动检查索引是否真正生效:先把绘制调用临时改为 pass.drawIndexed(3, 1, 3, 0, 0),重载后应只剩左上半个三角形,说明 firstIndex=3 跳过了前三个索引;再恢复绘制调用,把索引数组改为 [0, 1, 2, 0, 1, 2],此时两个三角形重叠,只显示右下半个三角形。第二次修改仍保留六个索引,可避免 16 位数据上传时出现非 4 字节对齐问题。检查后恢复原始代码。
何时使用 uint16 与 uint32
Uint16Array 对应 setIndexBuffer(indexBuffer, "uint16"),可以表示 0~65535 的顶点索引;若网格需要引用更大编号,则改为 Uint32Array 并绑定 "uint32"。不要只更改绑定字符串,否则 GPU 会按错误宽度解释数据。writeBuffer() 的写入字节数必须为 4 的倍数,本例六个 16 位索引占 12 字节,满足要求。
以只包含二维位置的网格为例,两个三角形不使用索引时要存六份顶点位置,共 6 × 8 = 48 字节;使用索引后是 4 × 8 + 6 × 2 = 44 字节,节省很小。若换成 10×10 个方格组成的连续网格,121 个唯一顶点与 600 个索引只需 121 × 8 + 600 × 2 = 2168 字节;非索引方案需 600 × 8 = 4800 字节。顶点属性越多、复用越充分,索引绘制通常越划算。