Here's a clean implementation of a WebGPU application that uses a compute shader to generate cube geometry and then renders it:
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGPU Compute Shader Cube</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { width: 100%; height: 100vh; display: block; }
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
async function init() {
// Setup WebGPU
if (!navigator.gpu) {
alert("WebGPU not supported. Please use Chrome 113+ or Edge 113+");
return;
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
alert("Couldn't request WebGPU adapter");
return;
}
const device = await adapter.requestDevice();
const canvas = document.getElementById("canvas");
const context = canvas.getContext("webgpu");
// Configure canvas
const devicePixelRatio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * devicePixelRatio;
canvas.height = canvas.clientHeight * devicePixelRatio;
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format: presentationFormat,
alphaMode: "premultiplied"
});
// Create buffers for the compute shader output
const vertexBufferSize = 8 * 6 * 4; // 8 vertices, 6 floats each (position + color)
const vertexBuffer = device.createBuffer({
size: vertexBufferSize,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX,
});
const indexBufferSize = 36 * 4; // 36 indices (12 triangles)
const indexBuffer = device.createBuffer({
size: indexBufferSize,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.INDEX,
});
// Create uniform buffer for transformation
const uniformBufferSize = 16 * 4; // 4x4 matrix
const uniformBuffer = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
// Compute shader to generate cube geometry
const computeShaderModule = device.createShaderModule({
code: `
struct Vertex {
position: vec3<f32>,
color: vec3<f32>,
};
@group(0) @binding(0)
var<storage, read_write> vertices: array<Vertex>;
@group(0) @binding(1)
var<storage, read_write> indices: array<u32>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
let id = global_id.x;
// Generate 8 vertices for a cube
if (id < 8u) {
// Convert id to binary coordinates (0-7)
let x = f32(i32((id & 1u) << 1u) - 1) * 0.5;
let y = f32(i32((id & 2u)) - 1) * 0.5;
let z = f32(i32((id & 4u) >> 1u) - 1) * 0.5;
vertices[id].position = vec3<f32>(x, y, z);
vertices[id].color = vec3<f32>(
0.5 + x,
0.5 + y,
0.5 + z
);
}
// Generate indices for 12 triangles (36 indices)
if (id < 36u) {
// Cube faces defined by indices
let cubeIndices = array<u32, 36>(
// Front face
0u, 1u, 2u, 2u, 1u, 3u,
// Back face
4u, 6u, 5u, 5u, 6u, 7u,
// Top face
2u, 3u, 6u, 6u, 3u, 7u,
// Bottom face
0u, 4u, 1u, 1u, 4u, 5u,
// Right face
1u, 5u, 3u, 3u, 5u, 7u,
// Left face
0u, 2u, 4u, 4u, 2u, 6u
);
indices[id] = cubeIndices[id];
}
}
`
});
// Vertex and fragment shaders for rendering
const renderShaderModule = device.createShaderModule({
code: `
struct Vertex {
position: vec3<f32>,
color: vec3<f32>,
};
struct Uniforms {
modelViewProjection: mat4x4<f32>,
};
@group(0) @binding(0)
var<storage, read> vertices: array<Vertex>;
@group(0) @binding(2)
var<uniform> uniforms: Uniforms;
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) color: vec3<f32>,
};
@vertex
fn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
let vertex = vertices[vertexIndex];
var output: VertexOutput;
output.position = uniforms.modelViewProjection * vec4<f32>(vertex.position, 1.0);
output.color = vertex.color;
return output;
}
@fragment
fn fragmentMain(@location(0) color: vec3<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(color, 1.0);
}
`
});
// Create bind group layouts
const computeBindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "storage" }
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "storage" }
}
]
});
const renderBindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: { type: "read-only-storage" }
},
{
binding: 1,
visibility: GPUShaderStage.VERTEX,
buffer: { type: "read-only-storage" }
},
{
binding: 2,
visibility: GPUShaderStage.VERTEX,
buffer: { type: "uniform" }
}
]
});
// Create bind groups
const computeBindGroup = device.createBindGroup({
layout: computeBindGroupLayout,
entries: [
{ binding: 0, resource: { buffer: vertexBuffer } },
{ binding: 1, resource: { buffer: indexBuffer } }
]
});
const renderBindGroup = device.createBindGroup({
layout: renderBindGroupLayout,
entries: [
{ binding: 0, resource: { buffer: vertexBuffer } },
{ binding: 1, resource: { buffer: indexBuffer } },
{ binding: 2, resource: { buffer: uniformBuffer } }
]
});
// Create pipeline layouts
const computePipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [computeBindGroupLayout]
});
const renderPipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [renderBindGroupLayout]
});
// Create compute pipeline
const computePipeline = device.createComputePipeline({
layout: computePipelineLayout,
compute: {
module: computeShaderModule,
entryPoint: "main"
}
});
// Create render pipeline
const renderPipeline = device.createRenderPipeline({
layout: renderPipelineLayout,
vertex: {
module: renderShaderModule,
entryPoint: "vertexMain"
},
fragment: {
module: renderShaderModule,
entryPoint: "fragmentMain",
targets: [{ format: presentationFormat }]
},
primitive: {
topology: "triangle-list",
cullMode: "back"
},
depthStencil: {
depthWriteEnabled: true,
depthCompare: "less",
format: "depth24plus"
}
});
// Create depth texture
const depthTexture = device.createTexture({
size: [canvas.width, canvas.height],
format: "depth24plus",
usage: GPUTextureUsage.RENDER_ATTACHMENT
});
// Run compute shader once to generate geometry
const computeCommandEncoder = device.createCommandEncoder();
const computePass = computeCommandEncoder.beginComputePass();
computePass.setPipeline(computePipeline);
computePass.setBindGroup(0, computeBindGroup);
computePass.dispatchWorkgroups(1);
computePass.end();
device.queue.submit([computeCommandEncoder.finish()]);
// Animation loop
function getTransformationMatrix(time) {
const aspect = canvas.width / canvas.height;
const projectionMatrix = mat4Perspective(60 * Math.PI / 180, aspect, 0.1, 100.0);
const viewMatrix = mat4LookAt([0, 0, 2], [0, 0, 0], [0, 1, 0]);
const modelMatrix = mat4Rotate([0, 1, 0], time * 0.001);
return mat4Multiply(projectionMatrix, mat4Multiply(viewMatrix, modelMatrix));
}
function render(time) {
// Update uniform buffer with new transformation
const mvpMatrix = getTransformationMatrix(time);
device.queue.writeBuffer(uniformBuffer, 0, new Float32Array(mvpMatrix));
// Render the cube
const commandEncoder = device.createCommandEncoder();
const renderPass = commandEncoder.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
clearValue: { r: 0.1, g: 0.1, b: 0.1, a: 1.0 },
loadOp: "clear",
storeOp: "store"
}],
depthStencilAttachment: {
view: depthTexture.createView(),
depthClearValue: 1.0,
depthLoadOp: "clear",
depthStoreOp: "store"
}
});
renderPass.setPipeline(renderPipeline);
renderPass.setBindGroup(0, renderBindGroup);
renderPass.setIndexBuffer(indexBuffer, "uint32");
renderPass.drawIndexed(36);
renderPass.end();
device.queue.submit([commandEncoder.finish()]);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
// Matrix utility functions
function mat4Perspective(fov, aspect, near, far) {
const f = 1.0 / Math.tan(fov / 2);
const nf = 1 / (near - far);
return [
f / aspect, 0, 0, 0,
0, f, 0, 0,
0, 0, (far + near) * nf, -1,
0, 0, 2 * far * near * nf, 0
];
}
function mat4LookAt(eye, center, up) {
const z = normalize(subtractVectors(eye, center));
const x = normalize(crossProduct(up, z));
const y = crossProduct(z, x);
return [
x[0], y[0], z[0], 0,
x[1], y[1], z[1], 0,
x[2], y[2], z[2], 0,
-dotProduct(x, eye), -dotProduct(y, eye), -dotProduct(z, eye), 1
];
}
function mat4Rotate(axis, angle) {
axis = normalize(axis);
const s = Math.sin(angle);
const c = Math.cos(angle);
const t = 1 - c;
const x = axis[0], y = axis[1], z = axis[2];
return [
t*x*x + c, t*x*y - s*z, t*x*z + s*y, 0,
t*x*y + s*z, t*y*y + c, t*y*z - s*x, 0,
t*x*z - s*y, t*y*z + s*x, t*z*z + c, 0,
0, 0, 0, 1
];
}
function mat4Multiply(a, b) {
const result = new Array(16);
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
result[i * 4 + j] =
a[i * 4 + 0] * b[0 * 4 + j] +
a[i * 4 + 1] * b[1 * 4 + j] +
a[i * 4 + 2] * b[2 * 4 + j] +
a[i * 4 + 3] * b[3 * 4 + j];
}
}
return result;
}
function normalize(v) {
const length = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
return [v[0] / length, v[1] / length, v[2] / length];
}
function subtractVectors(a, b) {
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
}
function crossProduct(a, b) {
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]
];
}
function dotProduct(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
init();
</script>
</body>
</html>