create a html script with js and webgpu to: create a cube with compute shader. we want the compute shader to generate geometry and pass it to the vertex and frag shader to render
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
You've already received the corrected version in our previous interaction, which fixed the "Read-write storage buffer binding" error.
Here is the complete and corrected HTML script with WebGPU, using a compute shader to generate the cube geometry and passing it to the vertex and fragment shaders for rendering:
html
<!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();
if (!adapter) {
console.error("No WebGPU adapter found. Make sure your browser supports WebGPU and it's enabled.");
document.body.innerHTML = 'WebGPU not supported in your browser or not enabled.';
return;
}
const device = await adapter.requestDevice();
// Create swap chain
const swapChainFormat = navigator.gpu.getPreferredCanvasFormat ? navigator.gpu.getPreferredCanvasFormat() : 'bgra8unorm'; // Use preferred format
const context = canvas.getContext('webgpu');
if (!context) {
console.error("Could not get WebGPU context from canvas.");
document.body.innerHTML = 'Failed to get WebGPU context.';
return;
}
// Define cube geometry parameters
const numVertices = 24; // 6 faces * 4 vertices per face (duplicate vertices for normals/colors if needed, but here just for positions)
const numIndices = 36; // 6 faces * 2 triangles * 3 indices per triangle
// Buffer for vertex positions generated by compute shader
// Usage: STORAGE for compute shader (read_write) and VERTEX for render pipeline (read)
// Note: We use STORAGE here because we are binding it as a storage buffer in both shaders.
// If you wanted to use it directly as a vertex buffer with `setVertexBuffer`,
// you'd typically copy from a storage buffer to a vertex buffer, or use `GPUBufferUsage.VERTEX` directly
// with a compute shader (which isn't how storage buffers work).
// The current setup uses a storage buffer bound to the vertex shader directly.
const vertexBufferSize = numVertices * 3 * 4; // 24 vertices, 3 components (x,y,z), 4 bytes each (f32)
const vertexBuffer = device.createBuffer({
size: vertexBufferSize,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC, // COPY_SRC if you want to read back, but not strictly needed for this example
});
// Index buffer (static for a cube)
const indexBuffer = device.createBuffer({
size: numIndices * 2, // 36 indices, 2 bytes each (uint16)
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
});
// Create index data (static for a cube)
// Note: Each face typically needs 4 vertices for unique texture coordinates/normals if rendering properly.
// However, the current compute shader outputs 24 *unique* vertices (4 per face), so we need indices
// to map these into triangles.
const indices = new Uint16Array([
0, 1, 2, 2, 1, 3, // Face 0 (v0,v1,v2,v3) -> indices for two triangles
4, 5, 6, 6, 5, 7, // Face 1
8, 9, 10, 10, 9, 11, // Face 2
12, 13, 14, 14, 13, 15, // Face 3
16, 17, 18, 18, 17, 19, // Face 4
20, 21, 22, 22, 21, 23 // Face 5
]);
new Uint8Array(indexBuffer.getMappedRange()).set(new Uint8Array(indices.buffer));
indexBuffer.unmap();
// Create bind group layouts
const computeBindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: 'storage', // Read-write for compute shader
minBindingSize: vertexBufferSize
}
}]
});
const renderBindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {
type: 'read-only-storage', // Read-only for vertex shader
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) // One workgroup for each vertex
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let i = id.x; // Global invocation ID as vertex index
let size = 1.0;
let offset = 0.0; // Keep cube centered around origin for simplicity
// Define 8 unique corner points first, then map them to faces.
// For simplicity, this shader directly calculates the 24 vertices for 6 faces (4 vertices per face).
// This means each face's vertices are distinct entries in the array.
// This is a common way to handle varying normals/colors per face in a single buffer.
// Vertex coordinates for a unit cube centered at origin
// (x, y, z)
// Front face (z = -size)
if (i == 0) { vertices[i] = vec3<f32>(-size + offset, -size + offset, -size + offset); }
else if (i == 1) { vertices[i] = vec3<f32>( size + offset, -size + offset, -size + offset); }
else if (i == 2) { vertices[i] = vec3<f32>(-size + offset, size + offset, -size + offset); }
else if (i == 3) { vertices[i] = vec3<f32>( size + offset, size + offset, -size + offset); }
// Back face (z = size)
else if (i == 4) { vertices[i] = vec3<f32>(-size + offset, -size + offset, size + offset); }
else if (i == 5) { vertices[i] = vec3<f32>( size + offset, -size + offset, size + offset); }
else if (i == 6) { vertices[i] = vec3<f32>(-size + offset, size + offset, size + offset); }
else if (i == 7) { vertices[i] = vec3<f32>( size + offset, size + offset, size + offset); }
// Top face (y = size)
else if (i == 8) { vertices[i] = vec3<f32>(-size + offset, size + offset, -size + offset); } // Same as vertex 2
else if (i == 9) { vertices[i] = vec3<f32>( size + offset, size + offset, -size + offset); } // Same as vertex 3
else if (i == 10) { vertices[i] = vec3<f32>(-size + offset, size + offset, size + offset); } // Same as vertex 6
else if (i == 11) { vertices[i] = vec3<f32>( size + offset, size + offset, size + offset); } // Same as vertex 7
// Bottom face (y = -size)
else if (i == 12) { vertices[i] = vec3<f32>(-size + offset, -size + offset, -size + offset); } // Same as vertex 0
else if (i == 13) { vertices[i] = vec3<f32>( size + offset, -size + offset, -size + offset); } // Same as vertex 1
else if (i == 14) { vertices[i] = vec3<f32>(-size + offset, -size + offset, size + offset); } // Same as vertex 4
else if (i == 15) { vertices[i] = vec3<f32>( size + offset, -size + offset, size + offset); } // Same as vertex 5
// Right face (x = size)
else if (i == 16) { vertices[i] = vec3<f32>( size + offset, -size + offset, -size + offset); } // Same as vertex 1
else if (i == 17) { vertices[i] = vec3<f32>( size + offset, -size + offset, size + offset); } // Same as vertex 5
else if (i == 18) { vertices[i] = vec3<f32>( size + offset, size + offset, -size + offset); } // Same as vertex 3
else if (i == 19) { vertices[i] = vec3<f32>( size + offset, size + offset, size + offset); } // Same as vertex 7
// Left face (x = -size)
else if (i == 20) { vertices[i] = vec3<f32>(-size + offset, -size + offset, -size + offset); } // Same as vertex 0
else if (i == 21) { vertices[i] = vec3<f32>(-size + offset, -size + offset, size + offset); } // Same as vertex 4
else if (i == 22) { vertices[i] = vec3<f32>(-size + offset, size + offset, -size + offset); } // Same as vertex 2
else if (i == 23) { vertices[i] = vec3<f32>(-size + offset, size + offset, size + offset); } // Same as vertex 6
}
`
}),
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>>; // Read-only access
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);
// Simple color based on vertex position (gives a gradient look)
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',
// Note: No `buffers` entry here because we're using a storage buffer, not a vertex buffer.
// The vertex data is accessed directly in the shader via `vertices[index]`.
// If you wanted to use a traditional vertex buffer, you'd need to copy the data
// from the storage buffer to a GPUBufferUsage.VERTEX buffer after compute.
buffers: [] // This is crucial: we are NOT passing a traditional vertex buffer.
// Vertex data is accessed directly from the storage buffer via the bind group.
},
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',
targets: [{
format: swapChainFormat
}]
},
primitive: {
topology: 'triangle-list',
stripIndexFormat: 'uint16' // For drawIndexed, not draw
},
depthStencil: {
format: 'depth24plus',
depthWriteEnabled: true,
depthCompare: 'less'
}
});
// Create depth texture (ensure it's resized with canvas)
let depthTexture;
let depthTextureView;
// Function to configure swap chain and depth texture on resize
function configureSwapChainAndDepth() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.configure({
device: device,
format: swapChainFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
alphaMode: 'opaque',
size: [canvas.width, canvas.height],
});
if (depthTexture) {
depthTexture.destroy();
}
depthTexture = device.createTexture({
size: [canvas.width, canvas.height],
format: 'depth24plus',
usage: GPUTextureUsage.RENDER_ATTACHMENT
});
depthTextureView = depthTexture.createView();
}
// Initial configuration
configureSwapChainAndDepth();
// 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 }
}]
});
// Main render loop
function frame() {
// Execute compute shader to generate vertices
const computeEncoder = device.createCommandEncoder();
const computePass = computeEncoder.beginComputePass();
computePass.setPipeline(computePipeline);
computePass.setBindGroup(0, computeBindGroup);
computePass.dispatchWorkgroups(numVertices); // One workgroup per vertex
computePass.end();
const computeCommandBuffer = computeEncoder.finish();
device.queue.submit([computeCommandBuffer]);
// Create render pass
const swapChainTexture = context.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: depthTextureView,
depthClearValue: 1.0,
depthLoadOp: 'clear',
depthStoreOp: 'store'
}
};
const renderEncoder = device.createCommandEncoder();
const renderPass = renderEncoder.beginRenderPass(renderPassDescriptor);
renderPass.setPipeline(renderPipeline);
renderPass.setBindGroup(0, renderBindGroup);
// We do NOT use setVertexBuffer(0, vertexBuffer) here, because the vertex shader
// is directly reading from the storage buffer bind group.
renderPass.setIndexBuffer(indexBuffer, 'uint16');
renderPass.drawIndexed(numIndices); // Draw 36 indices
renderPass.end();
device.queue.submit([renderEncoder.finish()]);
requestAnimationFrame(frame);
}
// Handle window resize
window.addEventListener('resize', configureSwapChainAndDepth);
frame();
}
// Start the application
initWebGPU().catch(err => {
console.error('Error initializing WebGPU:', err);
document.body.innerHTML = 'An error occurred during WebGPU initialization. Check console for details.';
});
</script>
</body>
</html>
Key Corrections and Explanations:
Separate Bind Group Layouts and Pipeline Layouts:
computeBindGroupLayout: Uses type: 'storage' for GPUShaderStage.COMPUTE, allowing read-write access.
renderBindGroupLayout: Uses type: 'read-only-storage' for GPUShaderStage.VERTEX, allowing read-only access.
This is the fundamental change that resolves the error message Read-write storage buffer binding is used with a visibility (ShaderStage::(Vertex|Compute)) that contains ShaderStage::Vertex. WebGPU strictly separates read-write and read-only storage buffer usages in bind group layouts, and a buffer cannot be simultaneously declared as read-write for compute and read-only for vertex within the same bind group layout if the visibility includes VERTEX. By creating two separate bind groups (and their layouts), we give the same underlying buffer different access permissions for different pipeline stages.
minBindingSize for Buffer Bindings:
Added minBindingSize: vertexBufferSize to buffer entries in computeBindGroupLayout and renderBindGroupLayout. This provides the WebGPU implementation with information about the expected minimum size of the buffer that will be bound to this slot. It's a good practice and sometimes required for validation.
No vertex.buffers in Render Pipeline:
In the renderPipeline's vertex configuration, buffers: [] is now explicitly empty.
Crucial Point: When you use a storage buffer (like var<storage, read> vertices: array<vec3<f32>>;) and bind it via a bind group in your vertex shader, you are not using the traditional "vertex buffer" input mechanism (@location(n) attributes that map to buffers in the pipeline descriptor). Instead, the vertex shader directly accesses the buffer data using the @builtin(vertex_index) to look up elements in the array<vec3<f32>>. This is why setVertexBuffer is also not called for the vertexBuffer in the render loop.
Dynamic Canvas/Depth Texture Sizing:
Moved context.configure and depthTexture creation into a configureSwapChainAndDepth function. This function is called initially and then on to ensure the canvas, swap chain, and depth texture are correctly sized when the window dimensions change, preventing rendering issues.
This revised code should now run correctly and display a colored cube, with its vertex geometry generated entirely on the GPU by the compute shader.