<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebGPU Compute Shader Cube</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
canvas {
display: block;
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="module">
// WebGPU setup
async function initWebGPU() {
const canvas = document.getElementById('canvas');
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
// Create swap chain
const swapChainFormat = 'bgra8unorm';
const context = canvas.getContext('webgpu');
const swapChain = context.configureSwapChain({
device: device,
format: swapChainFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
alphaMode: 'opaque'
});
// Create buffers
const vertexBufferSize = 36 * 3 * 4; // 36 vertices, 3 components (x,y,z), 4 bytes each
const vertexBuffer = device.createBuffer({
size: vertexBufferSize,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
});
// Create index buffer (static for a cube)
const indexBufferSize = 36 * 2; // 36 indices, 2 bytes each
const indexBuffer = device.createBuffer({
size: indexBufferSize,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
});
// Create index data (static for a cube)
const indices = new Uint16Array([
0, 1, 2, 2, 1, 3, // front
4, 5, 6, 6, 5, 7, // back
8, 9, 10, 10, 9, 11, // top
12, 13, 14, 14, 13, 15, // bottom
16, 17, 18, 18, 17, 19, // right
20, 21, 22, 22, 21, 23 // left
]);
new Uint8Array(indexBuffer.getMappedRange()).set(indices);
indexBuffer.unmap();
// Create bind group layouts
const computeBindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: 'storage',
hasDynamicOffset: false,
minBindingSize: vertexBufferSize
}
}]
});
const renderBindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {
type: 'read-only-storage',
hasDynamicOffset: false,
minBindingSize: vertexBufferSize
}
}]
});
// 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: device.createShaderModule({
code: `
@group(0) @binding(0) var<storage, read_write> vertices: array<vec3<f32>>;
@compute @workgroup_size(1)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
// Generate cube vertices
let size = 1.0;
let offset = 0.0;
// Front face
if (id.x < 4) {
let i = id.x;
vertices[id.x] = vec3<f32>(
(i % 2 == 0 ? -size : size) + offset,
(i < 2 ? -size : size) + offset,
-size + offset
);
}
// Back face
else if (id.x < 8) {
let i = id.x - 4;
vertices[id.x] = vec3<f32>(
(i % 2 == 0 ? -size : size) + offset,
(i < 2 ? -size : size) + offset,
size + offset
);
}
// Top face
else if (id.x < 12) {
let i = id.x - 8;
vertices[id.x] = vec3<f32>(
(i % 2 == 0 ? -size : size) + offset,
size + offset,
(i < 2 ? -size : size) + offset
);
}
// Bottom face
else if (id.x < 16) {
let i = id.x - 12;
vertices[id.x] = vec3<f32>(
(i % 2 == 0 ? -size : size) + offset,
-size + offset,
(i < 2 ? -size : size) + offset
);
}
// Right face
else if (id.x < 20) {
let i = id.x - 16;
vertices[id.x] = vec3<f32>(
size + offset,
(i % 2 == 0 ? -size : size) + offset,
(i < 2 ? -size : size) + offset
);
}
// Left face
else if (id.x < 24) {
let i = id.x - 20;
vertices[id.x] = vec3<f32>(
-size + offset,
(i % 2 == 0 ? -size : size) + offset,
(i < 2 ? -size : size) + offset
);
}
}
`
}),
entryPoint: 'main'
}
});
// Create render pipeline
const renderPipeline = device.createRenderPipeline({
layout: renderPipelineLayout,
vertex: {
module: device.createShaderModule({
code: `
@group(0) @binding(0) var<storage, read> vertices: array<vec3<f32>>;
struct Output {
@builtin(position) position: vec4<f32>,
@location(0) color: vec3<f32>
};
@vertex
fn main(@builtin(vertex_index) index: u32) -> Output {
let pos = vertices[index];
var output: Output;
output.position = vec4<f32>(pos, 1.0);
// Color based on vertex position
output.color = vec3<f32>(
(pos.x + 1.0) * 0.5,
(pos.y + 1.0) * 0.5,
(pos.z + 1.0) * 0.5
);
return output;
}
`
}),
entryPoint: 'main',
buffers: [{
arrayStride: 12,
attributes: [{
shaderLocation: 0,
offset: 0,
format: 'float32x3'
}]
}]
},
fragment: {
module: device.createShaderModule({
code: `
@fragment
fn main(@location(0) color: vec3<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(color, 1.0);
}
`
}),
entryPoint: 'main'
},
primitive: {
topology: 'triangle-list',
stripIndexFormat: 'uint16'
},
depthStencil: {
format: 'depth24plus',
depthWriteEnabled: true,
depthCompare: 'less'
}
});
// Create depth texture
const depthTexture = device.createTexture({
size: [canvas.width, canvas.height],
format: 'depth24plus',
usage: GPUTextureUsage.RENDER_ATTACHMENT
});
// Create bind groups
const computeBindGroup = device.createBindGroup({
layout: computeBindGroupLayout,
entries: [{
binding: 0,
resource: { buffer: vertexBuffer }
}]
});
const renderBindGroup = device.createBindGroup({
layout: renderBindGroupLayout,
entries: [{
binding: 0,
resource: { buffer: vertexBuffer }
}]
});
// Create command encoder and command buffer for compute shader
function createComputeCommandBuffer() {
const computeEncoder = device.createCommandEncoder();
const computePass = computeEncoder.beginComputePass();
computePass.setPipeline(computePipeline);
computePass.setBindGroup(0, computeBindGroup);
computePass.dispatchWorkgroups(36); // 36 vertices
computePass.end();
return computeEncoder.finish();
}
// Main render loop
function frame() {
// Execute compute shader to generate vertices
const computeCommandBuffer = createComputeCommandBuffer();
device.queue.submit([computeCommandBuffer]);
// Create render pass
const swapChainTexture = swapChain.getCurrentTexture();
const renderPassDescriptor = {
colorAttachments: [{
view: swapChainTexture.createView(),
clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
loadOp: 'clear',
storeOp: 'store'
}],
depthStencilAttachment: {
view: depthTexture.createView(),
depthClearValue: 1.0,
depthLoadOp: 'clear',
depthStoreOp: 'store'
}
};
const renderEncoder = device.createCommandEncoder();
const renderPass = renderEncoder.beginRenderPass(renderPassDescriptor);
renderPass.setPipeline(renderPipeline);
renderPass.setBindGroup(0, renderBindGroup);
renderPass.setVertexBuffer(0, vertexBuffer);
renderPass.setIndexBuffer(indexBuffer, 'uint16');
renderPass.drawIndexed(36);
renderPass.end();
device.queue.submit([renderEncoder.finish()]);
requestAnimationFrame(frame);
}
// Handle window resize
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
swapChain.configure({
device: device,
format: swapChainFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
alphaMode: 'opaque',
width: canvas.width,
height: canvas.height
});
depthTexture.destroy();
depthTexture = device.createTexture({
size: [canvas.width, canvas.height],
format: 'depth24plus',
usage: GPUTextureUsage.RENDER_ATTACHMENT
});
}
window.addEventListener('resize', resize);
resize();
frame();
}
// Start the application
initWebGPU().catch(err => {
console.error('Error initializing WebGPU:', err);
document.body.innerHTML = 'WebGPU not supported in your browser';
});
</script>
</body>
</html>