VERSION 2.2.0

wgpu-kit Docs

Build browser GPU compute with typed buffers, composable kernels, and control over every submission.

Getting started

wgpu-kit is a TypeScript toolkit for browser GPU computation. Use the core APIs to allocate storage, write a per-element WGSL function, and compose compute work with your own WebGPU renderer.

Install the published package in your application:

npm install wgpu-kit@2.2.0

Run this in a browser module served over HTTPS or localhost. The first allocation requests a GPU device. This complete example scales four values and reads the result back:

import { Buffer, elementKernel } from 'wgpu-kit';

const values = await Buffer.create('f32', 4);
values.write(new Float32Array([1, 2, 3, 4]));

const scale = elementKernel({
  state: { values: 'f32' },
  uniforms: { gain: 'f32' },
  code: `
    fn userFn(i: u32, gain: f32) {
      values[i] *= gain;
    }
  `,
});

await scale.run({ values }, { gain: 3 });
console.log(Array.from(await values.read()));
// [3, 6, 9, 12]

scale.destroy();
values.destroy();

A compute kernel does not draw by itself. This site’s examples use native WebGPU render passes to display their computed storage buffers. See Wave interference for a working compute-to-canvas example.

Element kernels

elementKernel(spec) wraps a per-element WGSL function. The function must be named userFn; its first argument is the element index. The library generates bindings, uniform layout, the compute entry point, and bounds-checked dispatch.

  • state declares read/write storage arrays
  • inputs declares read-only storage arrays
  • auxInputs declares read-only auxiliary arrays with independent lengths
  • uniforms declares the values passed to each invocation
  • code contains your WGSL, including helper functions
const integrate = elementKernel({
  state: { position: 'vec2f' },
  inputs: { velocity: 'vec2f' },
  uniforms: { dt: 'f32' },
  code: `
    fn userFn(i: u32, dt: f32) {
      position[i] += velocity[i] * dt;
    }
  `,
});

await integrate.run({ position, velocity }, { dt: 0.016 });

Resource keys and types must match the declaration. Pass vector uniforms as objects such as { x: 0.5, y: 0.5 }.

By default, state and inputs must have the same length; the first determines the invocation count. Auxiliary inputs may have independent lengths and never determine that count. At least one state or inputs field is required.

Pass options as the third run argument or fourth encode argument. An explicit count must be an integer in 0..0xffffffff; each state/input buffer must have at least that capacity, and their lengths may differ. In both modes, the dispatch must fit the device's workgroup-count limit.

import { Buffer, elementKernel } from 'wgpu-kit';
import type { ElementKernelDispatchOptions } from 'wgpu-kit';

const output = await Buffer.create('f32', 6);
const source = await Buffer.create('f32', 4);
const weights = await Buffer.create('f32', 3);
source.write(new Float32Array([1, 2, 3, 4]));
weights.write(new Float32Array([10, 20, 30]));

const scale = elementKernel({
  state: { output: 'f32' },
  inputs: { source: 'f32' },
  auxInputs: { weights: 'f32' },
  code: `
    fn userFn(i: u32) {
      output[i] = source[i] * weights[i % arrayLength(&weights)];
    }
  `,
});
const options: ElementKernelDispatchOptions = { count: 4 };
await scale.run({ output, source, weights }, undefined, options);
console.log(Array.from(await output.read())); // [10, 40, 90, 40, 0, 0]
scale.destroy();
output.destroy();
source.destroy();
weights.destroy();

Every declared auxiliary input must be supplied with the matching kind, even when unused by WGSL. Bound resources must belong to the shared device. WGSL is responsible for auxiliary indexing bounds; query its length with arrayLength(&weights).

Zero count still validates resources, uniforms and options, then performs no encoding or submission and leaves the encode-once guard unchanged.

These auxiliary-input and dispatch-count options were added in 2.1.0; the original 2.0.0 audit remains a historical baseline.

run() prepares, encodes, and submits for you. For frame-level control, use prepare() and encode(). WGSL compilation diagnostics map back to your function’s lines; the schema layer does not type-check the WGSL function body.

For neighborhood operations, use separate read and write buffers. Writing in-place while another invocation reads a neighbor can create races. PingPong makes this separation explicit.

GPU buffers

Buffer.create(kind, length) allocates typed GPU storage. length counts logical elements, not bytes. The library handles the underlying stride and padding.

import { Buffer } from 'wgpu-kit';

const points = await Buffer.create('vec2f', 2);
points.write(new Float32Array([0, 1, 2, 3]));
const flatValues = await points.read();
const nativeStorage = points.gpuBuffer;
points.destroy();

Supported kinds include scalar f32, i32, u32, two-component float/integer vectors, and vec3f/vec4f. Write a flat typed array with the correct component count. Use TypedBuffer or schemas for object-shaped rows.

read() intentionally copies data back to the CPU and waits for a mapped staging buffer. Keep intermediate data on the GPU when you do not need to inspect it.

The native buffer is storage-backed. This site’s renderer reads it with var<storage, read> in a vertex or fragment shader. Do not assume a kit buffer was allocated with the WebGPU VERTEX usage flag.

Typed schemas

Declare a field table once to connect TypeScript rows, generated WGSL structs, and GPU buffer allocation.

import { defineSchema } from 'wgpu-kit';
import type { SchemaInfer } from 'wgpu-kit';

const Vertex = defineSchema({
  position: 'vec3f',
  normal: 'vec3f',
});
type VertexRow = SchemaInfer<typeof Vertex.fields>;

const buffers = await Vertex.buffers(2);
buffers.position.write([
  { x: 0, y: 0, z: 0 },
  { x: 1, y: 0, z: 0 },
]);

const resources = buffers.raws();
const wgsl = Vertex.wgslStruct('Vertex');
buffers.destroy();

buffers() creates a separate typed buffer for each field. raws() exposes the keyed raw Buffer objects expected by element kernels. SchemaInfer gives you TypeScript field/value types; it does not turn arbitrary WGSL into TypeScript-checked code.

Ping-pong state

Simulations commonly read a complete previous state while producing the next. PingPong owns two matching sets of buffers and exposes current, other, and swap().

import { PingPong, elementKernel } from 'wgpu-kit';

const state = await PingPong.create({ value: 'f32' }, 4);
state.current.value.write(new Float32Array([1, 2, 3, 4]));

const step = elementKernel({
  state: { next: 'f32' },
  inputs: { previous: 'f32' },
  code: `
    fn userFn(i: u32) {
      next[i] = previous[i] * 0.99;
    }
  `,
});

await step.run({
  next: state.other.value,
  previous: state.current.value,
});
state.swap();
// state.current now refers to the freshly written side.

After swapping, use the new current side for rendering or the next step. Destroy both the kernel and the PingPong allocation when the application is done. See the reaction-diffusion example for a two-component neighborhood simulation.

In a managed batch, use PingPong.encodeWith() to encode a step and swap buffers together. Cancelling the batch restores the initial side. Skip the call when the dispatch count is zero.

Compose a frame

Version 2 separates pipeline preparation from command encoding. Prepare outside the frame loop, encode distinct kernels into one command encoder, append your own rendering passes, and submit once.

import { Buffer, GpuContext, elementKernel } from 'wgpu-kit';

const { device } = await GpuContext.get();
const input = await Buffer.create('f32', 4);
const intermediate = await Buffer.create('f32', 4);
const output = await Buffer.create('f32', 4);
input.write(new Float32Array([1, 2, 3, 4]));

const scale = elementKernel({
  state: { scaled: 'f32' },
  inputs: { source: 'f32' },
  uniforms: { gain: 'f32' },
  code: `
    fn userFn(i: u32, gain: f32) {
      scaled[i] = source[i] * gain;
    }
  `,
});
const limit = elementKernel({
  state: { limited: 'f32' },
  inputs: { scaled: 'f32' },
  uniforms: { maximum: 'f32' },
  code: `
    fn userFn(i: u32, maximum: f32) {
      limited[i] = min(scaled[i], maximum);
    }
  `,
});

await Promise.all([scale.prepare(), limit.prepare()]);
const encoder = device.createCommandEncoder();
scale.encode(encoder, { scaled: intermediate, source: input }, { gain: 3 });
limit.encode(encoder, { limited: output, scaled: intermediate }, { maximum: 8 });
device.queue.submit([encoder.finish()]);
scale.endSubmit();
limit.endSubmit();

console.log(Array.from(await output.read())); // [3, 6, 8, 8]
scale.destroy();
limit.destroy();
input.destroy();
intermediate.destroy();
output.destroy();

On the native path without a batch, call encode() with a nonzero count at most once per element-kernel instance before submitting. Shared uniforms require the encode-once guard; call endSubmit() after your custom submission. Use a managed batch for repeated dispatches with independent parameters.

Managed batches and typed kernels

Version 2.1.0 adds createBatch() and typedElementKernel(). Prepare kernels first, then pass { batch } as the fourth encode argument with batch.encoder. run() still accepts dispatch count options only. The typed entry infers resource names, Buffer kinds and scalar/vector uniform shapes; declared uniforms are required. The original elementKernel and broad Record calls stay compatible. Types do not check WGSL bodies.

This complete example encodes the same typed kernel 20 times, with different uniforms, a four-element prefix and a lookup table of independent length. Each dispatch has its own uniform snapshot; no endSubmit() is needed.

import { Buffer, PingPong, createBatch, typedElementKernel } from 'wgpu-kit';

const state = await PingPong.create({ value: 'f32' }, 6);
const weights = await Buffer.create('f32', 3);
state.current.value.write(new Float32Array([1, 2, 3, 4, 0, 0]));
weights.write(new Float32Array([1, 2, 3]));

const step = typedElementKernel({
  state: { next: 'f32' },
  inputs: { previous: 'f32' },
  auxInputs: { weights: 'f32' },
  uniforms: { delta: 'f32' },
  code: `
    fn userFn(i: u32, delta: f32) {
      next[i] = previous[i] + weights[i % arrayLength(&weights)] * delta;
    }
  `,
});
await step.prepare();
const batch = await createBatch();
for (let iteration = 0; iteration < 20; iteration++) {
  state.encodeWith(batch, (write, read) => {
    step.encode(
      batch.encoder,
      {
        next: write.value,
        previous: read.value,
        weights,
      },
      { delta: iteration + 1 },
      { count: 4, batch },
    );
  });
}
batch.submit();
console.log(Array.from(await state.current.value.read()));
// [211, 422, 633, 214, 0, 0]
step.destroy();
state.destroy();
weights.destroy();

A batch starts open and exposes readonly encoder and status. submit() closes and submits it once without waiting for GPU completion; never finish or submit batch.encoder yourself. cancel() discards an open batch, is idempotent after cancellation, and throws UsageError after submission. Cancellation does not roll back external CPU writes, earlier submissions or PingPong.swap(). Kernels and resources must use the same shared device.

Managed encoding supports repeated calls across one or several kernel instances and does not consume or reset the native guard. Aligned parameter arenas and scratch use a bounded per-device pool and become reusable after submitted GPU work completes. Encode helpers must be called outside an open pass.

For full control of bindings and entry points, rawKernel() accepts complete WGSL. It also exposes prepare/encode/run, with bind-group entries and workgroup counts supplied by the caller.

The sculpted ribbon composes wave propagation, geometry generation, normal calculation, and a native render pass. There is no intermediate CPU readback.

Share an existing device

If your application already owns a GPUDevice, adopt it before the first wgpu-kit context request or allocation:

import { GpuContext, Buffer } from 'wgpu-kit';

GpuContext.adopt(existingDevice);
const storage = await Buffer.create('vec4f', vertexCount);

// Bind storage.gpuBuffer in a native storage binding.
// The allocation uses your existing device.

GpuContext.adopt() installs the caller-owned device as the library context. It must run before GpuContext.get() or anything that initializes the singleton. Replacing an already-initialized context is rejected.

Check native WebGPU usage flags and limits when integrating a renderer. Sharing a GPUDevice does not automatically make every higher-level rendering adapter zero-copy.

Follow the complete shared-device guide in English or 简体中文 to run a standalone compute and render example.

Scan and reduce

The core package includes u32 exclusive/inclusive prefix scans and sum reductions. The convenient run paths submit internally; the encode paths let you compose them with your own work.

import { Buffer, createScan, createReduce } from 'wgpu-kit';

const data = new Uint32Array([3, 1, 4, 1, 5, 9, 2, 6]);
const input = await Buffer.create('u32', data.length);
const output = await Buffer.create('u32', data.length);
input.write(data);

const scan = createScan();
await scan.run(input, output, data.length, true);
const prefix = await output.read();
// [0, 3, 4, 8, 9, 14, 23, 25]

const reduce = createReduce();
const total = await reduce.sum(input, data.length); // 31
scan.destroy();
reduce.destroy();
input.destroy();
output.destroy();

An exclusive scan excludes the current element; passing false selects an inclusive scan. Arithmetic wraps as u32. createReduce().sum() reads the total back to JavaScript; sumInto() writes it into a caller-provided GPU buffer.

For native custom submissions, prepare first, then use scan.encode(encoder, src, dst, count, exclusive) or reduce.sumInto(encoder, src, count, dst) with native GPUBuffer handles. These native paths have an encode-once guard; reset it with endSubmit() after submission.

For managed primitives, use scan.encode(batch.encoder, src, dst, count, true, batch) or reduce.sumInto(batch.encoder, src, count, dst, batch), then batch.submit(). Repeated encoding needs no endSubmit(). With a NeighborGrid, pass batch as the third grid.encode argument and consume its public cell ranges/order before the next grid build overwrites them.

Try the live GPU calculator →

Core API reference

Open the complete public API reference →

Browse every public entry point, signature, parameter, return value, and verified implementation constraint.

Quick lookup for the APIs used in this site. All imports below come from the root wgpu-kit package.

APIPurposeMain operations
GpuContextShared device contextget, adopt, device, sync, lost
BufferTyped GPU storagecreate, write, read, gpuBuffer, destroy
elementKernelPer-element WGSL computeprepare, encode, endSubmit, run, replace, destroy
createBatchManaged submission scopeencoder, status, submit, cancel
typedElementKernelOpt-in typed kernel callsprepare, encode, endSubmit, run, replace, destroy
rawKernelCaller-owned WGSL bindingsprepare, encode, run, destroy
PingPongTwo matching buffer setscreate, current, other, swap, runWith, destroy
defineSchemaA shared typed field tablefields, buffers, wgslStruct
TypedBufferObject-shaped buffer rowscreate, write, read, raw, destroy
createScanu32 prefix sumsprepare, encode, endSubmit, run, destroy
createReduceu32 sum reductionprepare, sumInto, endSubmit, sum, destroy

Core errors include CompileError, UsageError, and WebGPUUnavailableError. Handle failures around initialization and prepare/run calls, and monitor device loss in long-lived applications.

Browser support

Live examples require navigator.gpu, a compatible adapter/device, and a secure context: HTTPS in production or localhost in development. Availability depends on browser version, operating system, hardware, drivers, and device policy.

  • Use a browser with WebGPU enabled and hardware acceleration available
  • If device creation fails, check your browser’s GPU status and driver configuration
  • Handle device loss and surface a useful error rather than silently replacing GPU results
  • Reduce workload or resolution on lower-powered devices

This site shows an explicit error when WebGPU cannot start. It does not substitute a Canvas 2D animation or invented performance counter. Reduced-motion users get an initially quiet scene, with explicit controls to resume.

Release and source

This site bundles the wgpu-kit@2.2.0 package built from this repository.

The API reference uses version 2.0.0 as its original audit baseline. The source and package links below are for 2.2.0.

The custom ribbon, fields, image pipeline, and numeric tools are original application examples of the core APIs. Their source is available on the individual example pages and in the complete site download.

Search concepts, APIs, and examples