To render a 3D ground, a light, and a static camera using the raw WebGPU API and raw shaders, you'll need to set up the WebGPU context, create the necessary buffers and shaders, and render the scene. Below is a simplified example to achieve this:
Setup WebGPU Context
First, you need to initialize the WebGPU context and get the necessary references.
async function initWebGPU(canvas) {
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device: device,
format: format,
});
return { device, context, format };
}
Create Shaders
Define the vertex and fragment shaders.
const vertexShader = `
[[stage(vertex)]] fn main([[location(0)]] position: vec3<f32>) -> [[builtin(position)]] vec4<f32> {
return vec4<f32>(position, 1.0);
}
`;
const fragmentShader = `
[[stage(fragment)]] fn main() -> [[location(0)]] vec4<f32> {
return vec4<f32>(0.0, 1.0, 0.0, 1.0); // Green color for the ground
}
`;
Create Ground
Create a simple ground plane using a buffer.
function createGroundBuffer(device) {
const positions = new Float32Array([
-3.0, 0.0, -3.0,
3.0, 0.0, -3.0,
-3.0, 0.0, 3.0,
3.0, 0.0, 3.0
]);
const indices = new Uint16Array([
0, 1, 2,
1, 3, 2
]);
const vertexBuffer = device.createBuffer({
size: positions.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
});
new Float32Array(vertexBuffer.getMappedRange()).set(positions);
vertexBuffer.unmap();
const indexBuffer = device.createBuffer({
size: indices.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
});
new Uint16Array(indexBuffer.getMappedRange()).set(indices);
indexBuffer.unmap();
return { vertexBuffer, indexBuffer };
}
Create Pipeline and Bind Group
Set up the render pipeline and bind group.
async function createPipeline(device, format) {
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: device.createShaderModule({ code: vertexShader }),
entryPoint: 'main',
buffers: [{
arrayStride: 12, // 3 floats * 4 bytes each
attributes: [{
shaderLocation: 0,
offset: 0,
format: 'float32x3',
}],
}],
},
fragment: {
module: device.createShaderModule({ code: fragmentShader }),
entryPoint: 'main',
targets: [{ format: format }],
},
primitive: {
topology: 'triangle-list',
},
});
return pipeline;
}
Render Function
Create the render function to draw the scene.
async function render(device, context, format) {
const { vertexBuffer, indexBuffer } = createGroundBuffer(device);
const pipeline = await createPipeline(device, format);
const commandEncoder = device.createCommandEncoder();
const textureView = context.getCurrentTexture().createView();
const renderPassDescriptor = {
colorAttachments: [{
view: textureView,
loadValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
storeOp: 'store',
}],
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(pipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.setIndexBuffer(indexBuffer, 'uint16');
passEncoder.drawIndexed(6); // 6 indices for 2 triangles
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
}
(async () => {
const canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);
const { device, context, format } = await initWebGPU(canvas);
await render(device, context, format);
})();
Explanation
- Initialize WebGPU: Set up the WebGPU context and configure the canvas.
- Create Shaders: Define simple vertex and fragment shaders.
- Create Ground Buffer: Generate vertex and index buffers for a simple ground plane.
- Create Pipeline: Set up the render pipeline with the shaders and buffer layout.
- Render Function: Create a command encoder, begin a render pass, set the pipeline and buffers, and submit the commands to the GPU.
This code will render a green ground plane using WebGPU and raw shaders.