Learn WebGPU

Reference

WebGPU Reference

Core concepts

GPUAdapter

An object that exposes access to a physical GPU device.

const adapter = await navigator.gpu.requestAdapter();

GPUDevice

The logical device used to create GPU resources and submit commands.

const device = await adapter.requestDevice();

GPUCommandEncoder

Encodes GPU commands into a command buffer.

const encoder = device.createCommandEncoder();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);

Shaders (WGSL)

Basic structure

// Vertex shader
@vertex
fn vs_main(@location(0) position: vec3f) -> @builtin(position) vec4f {
  return vec4f(position, 1.0);
}

// Fragment shader
@fragment
fn fs_main() -> @location(0) vec4f {
  return vec4f(1.0, 0.0, 0.0, 1.0);
}

Data types

  • f32 — 32-bit floating-point
  • i32 — 32-bit signed integer
  • u32 — 32-bit unsigned integer
  • bool — boolean
  • vec2f, vec3f, vec4f — vector types
  • mat4x4f — 4×4 matrix

Pipelines

Render pipeline

const pipeline = device.createRenderPipeline({
  layout: 'auto',
  vertex: {
    module: shaderModule,
    entryPoint: 'vs_main',
    buffers: [{
      arrayStride: 12,
      attributes: [{
        format: 'float32x3',
        offset: 0,
        shaderLocation: 0
      }]
    }]
  },
  fragment: {
    module: shaderModule,
    entryPoint: 'fs_main',
    targets: [{
      format: canvasFormat
    }]
  },
  primitive: {
    topology: 'triangle-list'
  }
});

Resource management

Buffer

const buffer = device.createBuffer({
  size: vertices.byteLength,
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
});

device.queue.writeBuffer(buffer, 0, vertices);

Texture

const texture = device.createTexture({
  size: { width: 256, height: 256 },
  format: 'rgba8unorm',
  usage: GPUTextureUsage.TEXTURE_BINDING |
         GPUTextureUsage.COPY_DST
});

Helpful links

Learn WebGPU — interactive tutorials for learning WebGPU

GitHub