WebGPU: The Era of Compute Shaders
It's 2024, and WebGL is officially legacy. While WebGL was a wrapper around OpenGL ES, WebGPU is a modern API designed from the ground up to match the capabilities of Metal, Vulkan, and Direct3D 12. The most exciting addition? Compute Shaders.
Beyond Rendering: GPGPU
In the past, if you wanted to do general-purpose computing on the GPU (GPGPU), you had to trick WebGL by encoding data into textures and rendering to a quad. With WebGPU, we have first-class compute stages.
The WGSL Language
WebGPU uses WGSL (WebGPU Shading Language). It's more modern and safer than GLSL. Here's a simple compute shader that squares an array of numbers:
@group(0) @binding(0) var<storage, read_write> data: array<f32>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let index = id.x;
if (index >= arrayLength(&data)) {
return;
}
data[index] = data[index] * data[index];
}
The CPU-Side Pipeline
Setting up a WebGPU pipeline is more verbose than WebGL, but it's much more predictable and performance-oriented because it validates the state up front.
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const shaderModule = device.createShaderModule({ code: wgslSource });
const computePipeline = device.createComputePipeline({
layout: 'auto',
compute: { module: shaderModule, entryPoint: 'main' }
});
// Setup buffers and bind groups...
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginComputePass();
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(dataSize / 64));
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
Why It Matters for AI
In 2024, WebGPU is the backbone of the "Local AI" movement. Libraries like transformers.js and WebLLM use WebGPU compute shaders to run large language models directly in the browser with performance that rivals native Python implementations.
We're finally moving past the browser as a simple document viewer and into the era of the browser as a high-performance compute platform.
Aunimeda develops mobile and PC games - from casual hyper-casual titles to mid-core games with complex progression systems.
Contact us to discuss your game project. See also: Game Development, Mobile Game Development