API REFERENCE · 2.2.0

wgpu-kit

Compute, buffers, composition, typed schemas, pack contracts and diagnostics.

Auxiliary inputs, dispatch counts, managed batches and typed kernels are released in 2.1.0. The original API retains the published npm 2.0.0 declarations and implementation as its historical audit baseline; Additions in 2.1.0 and 2.2.0 are identified on affected APIs and cite src files, without claiming a fresh audit of the entire API. Only actual public exports of this entry point are listed.

GpuContextclass

Shared, lazily created WebGPU device context. Construct through get() or adopt(); the constructor is private.

export declare class GpuContext

Behavior & constraints

  • get() prefers a high-performance adapter, then requests a fallback adapter only if the first result is null. It requests supported storage limits and timestamp-query when available.

Fields & related types

NameTypeRequiredDefaultMeaning
devicereadonly GPUDevice——Native shared device.
adapterInforeadonly string——Diagnostic vendor/architecture/description string; adopted device may use "adopted device".
lostreadonly Promise<GPUDeviceLostInfo>——Returns device.lost. It resolves with loss information; the declaration comment saying reject is inaccurate.

getmethod

Get or create the library singleton. A failed creation clears the cache so a later call can retry.

static get(): Promise<GpuContext>;

Parameters

This call takes no arguments.

Returns

Promise<GpuContext> The shared context.

Errors & failure cases

  • WebGPUUnavailableError / ERR_WGPU_UNAVAILABLE if navigator.gpu is absent or no adapter is returned. Adapter/device request failures may also reject.

Examples

Example
import { GpuContext } from 'wgpu-kit';
const ctx = await GpuContext.get();
await ctx.sync();

adoptmethod

Install an existing device as the shared context before any get() call.

static adopt(device: GPUDevice): GpuContext;

Parameters

NameTypeRequiredDefaultMeaning
deviceGPUDeviceYes—Existing device to use for all kit resources.

Returns

GpuContext Context wrapping the same device; the device is not cloned.

Errors & failure cases

  • Throws WebGPUUnavailableError if the singleton already exists, including a pending get().

Examples

Example
import { GpuContext } from 'wgpu-kit';
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error('No adapter');
const device = await adapter.requestDevice();
const ctx = GpuContext.adopt(device);

resetForTestsmethod

Clear only the singleton reference; intended for tests/device-recovery integration.

static resetForTests(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Does not destroy the old device or migrate existing resources. Do not use to switch a live resource graph.

Examples

Example
import { GpuContext } from 'wgpu-kit';
GpuContext.resetForTests(); // isolated test/recovery setup only

syncmethod

Wait until all previously submitted queue work completes.

sync(): Promise<void>;

Parameters

This call takes no arguments.

Returns

Promise<void> Resolves after device.queue.onSubmittedWorkDone().

Examples

Example
import { GpuContext } from 'wgpu-kit';
await (await GpuContext.get()).sync();

Source reference: dist/core/context.js

Bufferclass

Typed storage-buffer wrapper with validated uploads and staged readback.

export declare class Buffer<K extends ScalarKind = ScalarKind>

Behavior & constraints

  • No VERTEX, INDEX, UNIFORM or MAP usage is added. For zero-readback rendering, read gpuBuffer as storage in a native render shader.

Fields & related types

NameTypeRequiredDefaultMeaning
kindreadonly K——Chosen element kind.
lengthreadonly number——Number of elements.
gpuBufferreadonly GPUBuffer——Native handle with STORAGE | COPY_SRC | COPY_DST usage only.
NumArrayFloat32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer>——Reachable declaration type; not a root named export. f32/vector floats use Float32Array; signed integer kinds use Int32Array; unsigned kinds use Uint32Array.

createmethod

Allocate length × TYPES[kind].stride bytes on the shared device.

static create<K extends ScalarKind>(kind: K, length: number): Promise<Buffer<K>>;

Parameters

NameTypeRequiredDefaultMeaning
kindK extends ScalarKindYes—Element kind; selects WGSL type, scalar representation and storage stride.
lengthnumberYes—Positive integer number of elements, not scalar components or bytes.

Returns

Promise<Buffer<K>> New typed GPU buffer.

Errors & failure cases

  • UsageError / ERR_BUFFER_CREATE for an unknown kind or non-positive/non-integer length. GPU allocation can fail due to device limits.

Examples

Example
import { Buffer } from 'wgpu-kit';
const b = await Buffer.create('vec3f', 2);
b.write(new Float32Array([1, 2, 3, 4, 5, 6]));
console.log(await b.read());
b.destroy();

writemethod

Upload the whole buffer. vec3f input is tightly packed and padded internally to 16-byte storage stride.

write(data: NumArray): void;

Parameters

NameTypeRequiredDefaultMeaning
dataFloat32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer>Yes—Matching typed array with exactly length × component-count values. No offset/partial-write overload.

Returns

void No return value.

Errors & failure cases

  • UsageError / ERR_BUFFER_WRITE for wrong typed-array constructor or component count. Float contents are not checked for finiteness by Buffer.write.

Examples

Example
import { Buffer } from 'wgpu-kit';
const b = await Buffer.create('vec3f', 2);
b.write(new Float32Array([1, 2, 3, 4, 5, 6]));
console.log(await b.read());
b.destroy();

readmethod

Copy to a cached staging buffer, map, copy the bytes into a new typed array, unmap; vec3f padding is removed. Concurrent read calls share the in-flight read.

read(): Promise<NumArray>;

Parameters

This call takes no arguments.

Returns

Promise<Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer>> CPU-owned tightly packed scalar components.

Examples

Example
import { Buffer } from 'wgpu-kit';
const b = await Buffer.create('vec3f', 2);
b.write(new Float32Array([1, 2, 3, 4, 5, 6]));
console.log(await b.read());
b.destroy();

destroymethod

Destroy the storage buffer and any staging allocation.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer } from 'wgpu-kit';
const b = await Buffer.create('vec3f', 2);
b.write(new Float32Array([1, 2, 3, 4, 5, 6]));
console.log(await b.read());
b.destroy();

Examples

Example
import { Buffer } from 'wgpu-kit';
const b = await Buffer.create('vec3f', 2);
b.write(new Float32Array([1, 2, 3, 4, 5, 6]));
console.log(await b.read());
b.destroy();

Source reference: dist/core/buffer.js

elementKernelfunction

Generate and manage a one-invocation-per-element compute kernel. Creation itself is synchronous; GPU preparation is lazy.

export declare function elementKernel(spec: ElementKernelSpec): ElementKernel;

Parameters

NameTypeRequiredDefaultMeaning
specElementKernelSpecYes—Kernel resource declarations, uniforms and WGSL function.

Returns

ElementKernel Prepared/lazy kernel controller.

Behavior & constraints

  • New in 2.1.0: auxInputs, options.count and ElementKernelDispatchOptions are documented from src/core/kernel.ts and src/index.ts; these additions extend the historical npm 2.0.0 audit baseline.
  • All declared state/input/auxInputs buffers must be present and have the declared kind, including statically unused fields. Bound resources must belong to the shared device. Extra resource/uniform keys are ignored.
  • Without options.count, state and inputs must have equal lengths and the first such buffer determines the invocation count. At least one state or inputs field is required; auxInputs do not determine the count.
  • An explicit count must be an integer in 0..0xffffffff. State/input lengths may differ, but every such buffer must contain at least count elements. In either mode, ceil(count / workgroupSize) must not exceed device.limits.maxComputeWorkgroupsPerDimension.
  • Auxiliary arrays are read-only and may have independent lengths. They do not participate in per-element capacity checks; auxiliary indexing bounds are the WGSL author's responsibility. Query their lengths with arrayLength(&weights).
  • count: 0 validates all resources, uniforms and options, then performs no encoding or submission. It neither consumes nor clears an existing encode-once guard.
  • Field names must be unique across state, inputs, auxInputs and uniforms. The uniform name count is reserved and automatically injected. Use valid WGSL identifiers; the compiler checks reserved words.
  • Do not read neighboring elements from a buffer being concurrently written in the same dispatch; use separate input/output buffers or PingPong. The library does not provide global synchronization inside a dispatch.
  • The generated source uses lexical resource-use analysis; shadowing a resource name with a local variable is a known analysis limitation.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Errors & failure cases

  • Construction: ERR_WORKGROUP_SIZE for an invalid workgroup size; ERR_RESOURCE_MISSING for no arrays; ERR_USAGE for empty code, duplicate names or reserved count uniform.
  • Preparation/replacement: CompileError / ERR_COMPILE reports WGSL errors with line numbers mapped to user code. Other native WebGPU validation/device failures may occur.

Examples

Example
import { Buffer, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
values.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { values: 'f32' },
  uniforms: { gain: 'f32' },
  code: 'fn userFn(i:u32,gain:f32){values[i]*=gain;}',
});
await k.run({ values }, { gain: 3 });
console.log(await values.read());
k.destroy();
values.destroy();
Manual command-encoder composition
import { Buffer, GpuContext, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
const k = elementKernel({
  state: { values: 'f32' },
  code: 'fn userFn(i:u32){values[i]=f32(i);}',
});
await k.prepare();
const { device } = await GpuContext.get();
const encoder = device.createCommandEncoder();
k.encode(encoder, { values });
device.queue.submit([encoder.finish()]);
k.endSubmit();
console.log(await values.read());
k.destroy();
values.destroy();
Independent auxiliary length and an explicit buffer prefix (new in 2.1.0)
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();

Source reference: src/core/kernel.ts

createBatchfunction

Create an open, owned compute submission scope. Added in 2.1.0.

createBatch(): Promise<ComputeBatch>;

Parameters

This call takes no arguments.

Returns

Promise<ComputeBatch> A new batch with a readonly encoder and status on the shared device. Does not prepare kernels for you.

Behavior & constraints

  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.
  • The batch owns encoder completion and submission: never call encoder.finish() or device.queue.submit() for batch.encoder yourself. Append native passes only while open, and call managed helpers outside any active pass.
  • Each managed dispatch receives an independent aligned parameter range and any required private scratch. Resources are pooled per device with bounded retained memory; submitted allocations are recycled only after GPU completion. Caller-owned storage outputs remain shared.
  • Cancellation discards encoded commands and managed allocations; it does not roll back external CPU writes, earlier submissions, or PingPong.swap().

Examples

Create and cancel an unsubmitted scope
import { createBatch } from 'wgpu-kit';
const batch = await createBatch();
console.log(batch.status); // 'open'
batch.cancel();
batch.cancel(); // idempotent
console.log(batch.status); // 'cancelled'

Source reference: src/core/batch.ts

ComputeBatchinterface

Owned submission lifecycle returned by createBatch(). Added in 2.1.0.

export interface ComputeBatch {
  readonly encoder: GPUCommandEncoder;
  readonly status: 'open' | 'submitted' | 'cancelled';
  submit(): void;
  cancel(): void;
}

Behavior & constraints

  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.
  • The batch owns encoder completion and submission: never call encoder.finish() or device.queue.submit() for batch.encoder yourself. Append native passes only while open, and call managed helpers outside any active pass.
  • Encoding or submitting after submit/cancel throws UsageError. cancel() on a submitted batch throws UsageError; cancel() on an already cancelled batch is idempotent.
  • Cancellation discards encoded commands and managed allocations; it does not roll back external CPU writes, earlier submissions, or PingPong.swap().

Fields & related types

NameTypeRequiredDefaultMeaning
encoderGPUCommandEncoderYes—Readonly encoder owned by this scope; append work while open.
status'open' | 'submitted' | 'cancelled'YesopenReadonly state; created open and closed permanently by submit/cancel.

submitmethod

Finish and submit the open batch once; returns before GPU completion.

submit(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • The batch owns encoder completion and submission: never call encoder.finish() or device.queue.submit() for batch.encoder yourself. Append native passes only while open, and call managed helpers outside any active pass.
  • Each managed dispatch receives an independent aligned parameter range and any required private scratch. Resources are pooled per device with bounded retained memory; submitted allocations are recycled only after GPU completion. Caller-owned storage outputs remain shared.

Errors & failure cases

  • Encoding or submitting after submit/cancel throws UsageError. cancel() on a submitted batch throws UsageError; cancel() on an already cancelled batch is idempotent.

cancelmethod

Discard an open batch; repeated cancellation is idempotent.

cancel(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Cancellation discards encoded commands and managed allocations; it does not roll back external CPU writes, earlier submissions, or PingPong.swap().

Errors & failure cases

  • Encoding or submitting after submit/cancel throws UsageError. cancel() on a submitted batch throws UsageError; cancel() on an already cancelled batch is idempotent.

Source reference: src/core/batch.ts

typedElementKernelfunction

Opt-in typed factory inferring exact resource names/kinds and uniform value shapes from a literal spec. Added in 2.1.0.

typedElementKernel<const S extends ElementKernelSpec>(spec: S): TypedElementKernel<S>;

Parameters

NameTypeRequiredDefaultMeaning
specS extends ElementKernelSpecYes—Same runtime descriptor as elementKernel. Preserve literal kinds with inline fields or as const when stored separately.

Returns

TypedElementKernel<S> ElementKernel lifecycle with inferred run/encode call arguments.

Behavior & constraints

  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.
  • Every declared state/input/auxInputs name and Buffer kind is inferred. Uniform scalar/vector shapes follow KindOf, and declared uniforms are required. TypedElementKernelResources<S> and TypedElementKernelUniforms<S> expose the maps.
  • This opt-in interface does not tighten the original elementKernel or its broad Record calls, and does not type-check WGSL bodies. Runtime execution and validation reuse elementKernel.

Examples

20 typed PingPong steps with independent uniforms, count and auxInputs (2.1.0)
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++) {
  step.encode(
    batch.encoder,
    {
      next: state.other.value,
      previous: state.current.value,
      weights,
    },
    { delta: iteration + 1 },
    { count: 4, batch },
  );
  state.swap();
}
batch.submit();
console.log(Array.from(await state.current.value.read()));
// [211, 422, 633, 214, 0, 0]
step.destroy();
state.destroy();
weights.destroy();

Source reference: src/core/typed-kernel.ts

TypedElementKerneltype alias

ElementKernel controller with spec-inferred resource/uniform arguments. DispatchArguments is an internal conditional tuple: declared uniforms are required; otherwise they may be omitted. Added in 2.1.0.

export type TypedElementKernel<S extends ElementKernelSpec> = Omit<
  ElementKernel,
  'run' | 'encode'
> & {
  run(...args: DispatchArguments<S, ElementKernelDispatchOptions>): Promise<void>;
  encode(
    encoder: GPUCommandEncoder,
    ...args: DispatchArguments<S, ElementKernelEncodeOptions>
  ): void;
};

Behavior & constraints

  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.
  • Native path without options.batch: one nonzero encode per instance per submission, followed by endSubmit(). With options.batch, pass batch.encoder and submit only through batch.submit(); every encode has an independent uniform snapshot, repeated calls are supported, and the native guard is unchanged.

Source reference: src/core/typed-kernel.ts

TypedElementKernelResourcestype alias

ResourceFields<S> internally merges state, inputs and auxInputs. The public map preserves those names and Buffer kinds. Added in 2.1.0.

export type TypedElementKernelResources<S extends ElementKernelSpec> = {
  readonly [K in keyof ResourceFields<S>]: Buffer<ResourceFields<S>[K] & ScalarKind>;
};

Behavior & constraints

  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Source reference: src/core/typed-kernel.ts

TypedElementKernelUniformstype alias

Map spec.uniforms to scalar numbers or Vec2/Vec3/Vec4 objects. Fields is an internal declaration helper. Does not type-check WGSL bodies. Added in 2.1.0.

export type TypedElementKernelUniforms<S extends ElementKernelSpec> = {
  readonly [K in keyof Fields<S, 'uniforms'>]: KindOf<
    Fields<S, 'uniforms'>[K] & ScalarKind
  >;
};

Behavior & constraints

  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Source reference: src/core/typed-kernel.ts

ElementKernelEncodeOptionsinterface

Encode-only options: optional count plus a managed batch. run() retains ElementKernelDispatchOptions and accepts no batch. Added in 2.1.0.

export interface ElementKernelEncodeOptions extends ElementKernelDispatchOptions {
  batch?: ComputeBatch;
}

Behavior & constraints

  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.
  • Native path without options.batch: one nonzero encode per instance per submission, followed by endSubmit(). With options.batch, pass batch.encoder and submit only through batch.submit(); every encode has an independent uniform snapshot, repeated calls are supported, and the native guard is unchanged.
  • The batch owns encoder completion and submission: never call encoder.finish() or device.queue.submit() for batch.encoder yourself. Append native passes only while open, and call managed helpers outside any active pass.

Fields & related types

NameTypeRequiredDefaultMeaning
countnumberNoFirst state/input buffer lengthInteger 0..0xffffffff. Limits invocation indices to [0, count); every state/input capacity must be at least count. Auxiliary arrays have independent bounds.
batchComputeBatchNo—Open managed scope; use its encoder and submit() method. Supports repeated dispatches without touching the native guard.

Source reference: src/core/kernel.ts

PingPongclass

Two same-shaped buffer sets with explicit current/other ownership.

export class PingPong<K extends string, F extends Record<K, ScalarKind> = Record<K, ScalarKind>>

Behavior & constraints

  • Typing enhancement in 2.1.0: literal create({ value: 'f32' }, count) preserves Buffer<'f32'> on current/other and clone(). Existing PingPong<K> annotations and explicit create<'value'> calls remain supported; these broader forms retain broad kinds.

Fields & related types

NameTypeRequiredDefaultMeaning
current{ [P in K]: Buffer<F[P]> } (readonly property)——Current read/render side.
other{ [P in K]: Buffer<F[P]> } (readonly property)——Other write side.
namesreadonly K[]——Field names in creation order.

createmethod

Allocate both sides. The internal CreateResult helper preserves Buffer kinds from an inferred literal kind map; the field-name overload preserves explicit string type arguments and generic wrappers. Typing enhancement in 2.1.0.

static create<const F extends string | Record<string, ScalarKind>>(
  kinds: Exclude<F, string>,
  length: number,
): Promise<CreateResult<F>>;
static create<K extends string>(
  kinds: Record<K, ScalarKind>,
  length: number,
): Promise<PingPong<K>>;

Parameters

NameTypeRequiredDefaultMeaning
kindsRecord<K, ScalarKind>Yes—Non-empty field-name to element-kind map.
lengthnumberYes—Positive integer number of elements, not scalar components or bytes.

Returns

Promise<PingPong<K>> New two-sided buffer group.

Errors & failure cases

  • Empty kinds throws plain Error("PingPong requires at least one field"); Buffer.create validation applies to each field.

Examples

Example
import { PingPong, elementKernel } from 'wgpu-kit';
const pp = await PingPong.create({ value: 'f32' }, 4);
pp.current.value.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { out: 'f32' },
  inputs: { input: 'f32' },
  code: 'fn userFn(i:u32){out[i]=input[i]+1.0;}',
});
await pp.runWith((write, read) => k.run({ out: write.value, input: read.value }));
console.log(await pp.current.value.read());
k.destroy();
pp.destroy();

swapmethod

Exchange current and other by changing the active side; no GPU copy.

swap(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { PingPong, elementKernel } from 'wgpu-kit';
const pp = await PingPong.create({ value: 'f32' }, 4);
pp.current.value.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { out: 'f32' },
  inputs: { input: 'f32' },
  code: 'fn userFn(i:u32){out[i]=input[i]+1.0;}',
});
await pp.runWith((write, read) => k.run({ out: write.value, input: read.value }));
console.log(await pp.current.value.read());
k.destroy();
pp.destroy();

runWithmethod

Await fn(other,current), then swap only after it resolves successfully.

runWith(
  fn: (
    write: { [P in K]: Buffer<F[P]> },
    read: { [P in K]: Buffer<F[P]> },
  ) => Promise<void>,
): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
fn(write: { [P in K]: Buffer<F[P]> }, read: { [P in K]: Buffer<F[P]> }) => Promise<void>Yes—Callback receives write=other and read=current in that order.

Returns

Promise<void> Callback completion followed by swap.

Errors & failure cases

  • A rejected callback propagates and does not swap sides.

Examples

Example
import { PingPong, elementKernel } from 'wgpu-kit';
const pp = await PingPong.create({ value: 'f32' }, 4);
pp.current.value.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { out: 'f32' },
  inputs: { input: 'f32' },
  code: 'fn userFn(i:u32){out[i]=input[i]+1.0;}',
});
await pp.runWith((write, read) => k.run({ out: write.value, input: read.value }));
console.log(await pp.current.value.read());
k.destroy();
pp.destroy();

encodeWithmethod

Synchronously encode with typed write/read sides, then flip the logical current side. Participating side selections are restored if the unsubmitted batch is cancelled.

encodeWith(
  batch: ComputeBatch,
  fn: (
    write: { [P in K]: Buffer<F[P]> },
    read: { [P in K]: Buffer<F[P]> },
  ) => undefined,
): void;

Parameters

NameTypeRequiredDefaultMeaning
batchComputeBatchYes—Open batch; encode through its encoder and pass this batch to kernel encode options.
fn(write: { [P in K]: Buffer<F[P]> }, read: { [P in K]: Buffer<F[P]> }) => undefinedYes—Receives write=other and read=current. Must return undefined synchronously; async callbacks are rejected by TypeScript. Encode only; submit or cancel outside the callback.

Returns

void A successful callback is followed immediately by a side flip; no submission or GPU completion wait.

Behavior & constraints

  • Added in 2.2.0.
  • Prepare kernels before calling. Each callback receives per-field Buffer<F[P]> sides. Return undefined synchronously; a returned Promise or thenable is also rejected at runtime.
  • The first helper call per PingPong per batch records its initial side and reserves the instance until the batch settles. A successful callback swaps even if it records no work. Skip encodeWith() when the dispatch count is zero. A named callback can declare an undefined return type.
  • A reserved PingPong cannot join another open batch or re-enter its own helper. Manual swap() and runWith() are rejected while reserved. An in-flight legacy runWith() also prevents this helper from starting.
  • Call batch.submit() or batch.cancel() outside the callback. The callback should only encode into batch.encoder, including { batch } for managed kernels; it must not finish or submit the encoder itself.
  • batch.cancel() restores all participating PingPongs to their first helper call baseline. A callback exception cancels the entire batch, restores every participant, and propagates the original error; this includes rejected asynchronous callback use.
  • A synchronous encoder.finish() or queue.submit() exception in batch.submit() cancels the batch and restores participating sides. Successful submission releases ownership and keeps final directions; a later GPU completion failure does not roll back already-submitted directions.
  • Restoration changes only helper-managed side selection. It does not undo submitted GPU commands, CPU buffer writes or manual swaps outside the helper. Unreserved swap() and runWith() retain their legacy behavior; runWith() does not gain batch cancellation restoration.

Errors & failure cases

  • UsageError for a closed/invalid batch, conflicting PingPong ownership or re-entry, or an in-flight legacy runWith(). These precondition failures do not invoke the callback.
  • Callback exceptions are rethrown after whole-batch cancellation. A returned Promise/thenable causes UsageError and the same cancellation/restoration.

Examples

Three steps in one submission
import { PingPong, createBatch, typedElementKernel } from 'wgpu-kit';
const pp = await PingPong.create({ value: 'f32' }, 4);
pp.current.value.write(new Float32Array([1, 2, 3, 4]));
const step = typedElementKernel({
  state: { next: 'f32' },
  inputs: { previous: 'f32' },
  code: 'fn userFn(i: u32) { next[i] = previous[i] + 1.0; }',
});
await step.prepare();
const batch = await createBatch();
for (let i = 0; i < 3; i++) {
  pp.encodeWith(batch, (write, read) => {
    step.encode(batch.encoder, { next: write.value, previous: read.value }, undefined, {
      batch,
    });
  });
}
batch.submit(); // Or cancel() instead, to restore the initial side.
console.log(Array.from(await pp.current.value.read())); // [4, 5, 6, 7]
step.destroy();
pp.destroy();

Source reference: src/core/pingpong.ts

clonemethod

Allocate a new group with the same kinds and length; values and active-side index are not copied.

clone(): Promise<PingPong<K, F>>;

Parameters

This call takes no arguments.

Returns

Promise<PingPong<K, F>> Fresh same-shaped group.

Examples

Example
import { PingPong } from 'wgpu-kit';
const a = await PingPong.create({ x: 'f32' }, 4);
const b = await a.clone();
a.destroy();
b.destroy();

destroymethod

Destroy every field on both sides.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { PingPong, elementKernel } from 'wgpu-kit';
const pp = await PingPong.create({ value: 'f32' }, 4);
pp.current.value.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { out: 'f32' },
  inputs: { input: 'f32' },
  code: 'fn userFn(i:u32){out[i]=input[i]+1.0;}',
});
await pp.runWith((write, read) => k.run({ out: write.value, input: read.value }));
console.log(await pp.current.value.read());
k.destroy();
pp.destroy();

Examples

Example
import { PingPong, elementKernel } from 'wgpu-kit';
const pp = await PingPong.create({ value: 'f32' }, 4);
pp.current.value.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { out: 'f32' },
  inputs: { input: 'f32' },
  code: 'fn userFn(i:u32){out[i]=input[i]+1.0;}',
});
await pp.runWith((write, read) => k.run({ out: write.value, input: read.value }));
console.log(await pp.current.value.read());
k.destroy();
pp.destroy();

Source reference: src/core/pingpong.ts

rawKernelfunction

Compile and dispatch complete caller-authored WGSL without generated bindings or bounds checks.

export declare function rawKernel(
  code: string,
  entryPoint?: string,
  label?: string,
): RawKernel;

Parameters

NameTypeRequiredDefaultMeaning
codestringYes—Complete non-empty WGSL module.
entryPointstringNomainCompute entrypoint name.
labelstringNorawKernelDiagnostic shader/kernel label.

Returns

RawKernel Inferred controller type; RawKernel is declared internally but is not a root named export.

Behavior & constraints

  • Uses only bind group 0 and dispatchWorkgroups(workgroups). No library encode-once guard exists; ownership of any mutable uniform/storage parameter buffers is the caller’s responsibility.

Errors & failure cases

  • ERR_USAGE for empty code, non-positive/non-integer workgroups or encode before prepare; CompileError for WGSL compilation errors. Native binding/pipeline/dispatch validation still applies.

preparemethod

Idempotently compile using the shared device.

prepare(): Promise<void>;

Parameters

This call takes no arguments.

Returns

Promise<void> Ready for encode.

Examples

Example
import { Buffer, rawKernel } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
const k = rawKernel(
  '@group(0) @binding(0) var<storage,read_write> values:array<u32>; @compute @workgroup_size(4) fn main(@builtin(global_invocation_id) id:vec3u){if(id.x<4u){values[id.x]=id.x;}}',
);
await k.run([{ binding: 0, resource: { buffer: values.gpuBuffer } }], 1);
console.log(await values.read());
k.destroy();
values.destroy();

encodemethod

Create the group-0 bind group and append one compute pass.

encode(
  encoder: GPUCommandEncoder,
  entries: GPUBindGroupEntry[],
  workgroups: number,
): void;

Parameters

NameTypeRequiredDefaultMeaning
encoderGPUCommandEncoderYes—Caller-owned encoder from the same device; this API records work without submitting it.
entriesGPUBindGroupEntry[]Yes—Native entries for bind group 0 matching the shader auto layout; resources must come from the shared device.
workgroupsnumberYes—Positive integer X workgroup count; Y and Z remain 1. Must fit device dispatch limits.

Returns

void No return value.

Examples

Example
import { Buffer, rawKernel } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
const k = rawKernel(
  '@group(0) @binding(0) var<storage,read_write> values:array<u32>; @compute @workgroup_size(4) fn main(@builtin(global_invocation_id) id:vec3u){if(id.x<4u){values[id.x]=id.x;}}',
);
await k.run([{ binding: 0, resource: { buffer: values.gpuBuffer } }], 1);
console.log(await values.read());
k.destroy();
values.destroy();

runmethod

Prepare, encode and submit once.

run(entries: GPUBindGroupEntry[], workgroups: number): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
entriesGPUBindGroupEntry[]Yes—Native entries for bind group 0 matching the shader auto layout; resources must come from the shared device.
workgroupsnumberYes—Positive integer X workgroup count; Y and Z remain 1. Must fit device dispatch limits.

Returns

Promise<void> CPU submission; not a GPU completion fence.

Examples

Example
import { Buffer, rawKernel } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
const k = rawKernel(
  '@group(0) @binding(0) var<storage,read_write> values:array<u32>; @compute @workgroup_size(4) fn main(@builtin(global_invocation_id) id:vec3u){if(id.x<4u){values[id.x]=id.x;}}',
);
await k.run([{ binding: 0, resource: { buffer: values.gpuBuffer } }], 1);
console.log(await values.read());
k.destroy();
values.destroy();

destroymethod

Drop the pipeline reference; native caller resources are not destroyed.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer, rawKernel } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
const k = rawKernel(
  '@group(0) @binding(0) var<storage,read_write> values:array<u32>; @compute @workgroup_size(4) fn main(@builtin(global_invocation_id) id:vec3u){if(id.x<4u){values[id.x]=id.x;}}',
);
await k.run([{ binding: 0, resource: { buffer: values.gpuBuffer } }], 1);
console.log(await values.read());
k.destroy();
values.destroy();

Examples

Example
import { Buffer, rawKernel } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
const k = rawKernel(
  '@group(0) @binding(0) var<storage,read_write> values:array<u32>; @compute @workgroup_size(4) fn main(@builtin(global_invocation_id) id:vec3u){if(id.x<4u){values[id.x]=id.x;}}',
);
await k.run([{ binding: 0, resource: { buffer: values.gpuBuffer } }], 1);
console.log(await values.read());
k.destroy();
values.destroy();

Source reference: dist/core/raw.js

defineSchemafunction

Declare field kinds once for TS row inference, WGSL struct generation and per-field buffers.

export declare function defineSchema<const F extends Record<string, ScalarKind>>(
  fields: F,
): Schema<F>;

Parameters

NameTypeRequiredDefaultMeaning
fieldsF extends Record<string, ScalarKind>Yes—Non-empty field map; insertion order determines generated WGSL member order.

Returns

Schema<F> Schema facade holding the same fields object.

Behavior & constraints

  • This is a structure-of-arrays buffer model: buffers() creates one buffer per field, not an interleaved struct array. Do not mutate fields after definition.
  • Field names/kinds are not comprehensively runtime-validated here. Use valid non-reserved WGSL names and avoid helper names raws/destroy in buffers().

Errors & failure cases

  • UsageError / ERR_USAGE if there are no fields.

Examples

Example
import { defineSchema } from 'wgpu-kit';
const S = defineSchema({ position: 'vec3f', mass: 'f32' });
console.log(S.wgslStruct('Body'));
const b = await S.buffers(2);
b.position.write([
  { x: 0, y: 1, z: 2 },
  { x: 3, y: 4, z: 5 },
]);
b.mass.write([1, 2]);
const resources = b.raws();
b.destroy();

Source reference: dist/core/schema.js

TypedBufferclass

Typed row/object interface over Buffer; scalar kinds use numbers and vector kinds use component objects.

export declare class TypedBuffer<K extends ScalarKind>

Fields & related types

NameTypeRequiredDefaultMeaning
rawreadonly Buffer<K>——Escape hatch for flat typed-array uploads/readback and gpuBuffer access.
kindreadonly K——Element kind.
lengthreadonly number——Number of rows.

createmethod

Create a row-oriented wrapper and its raw storage buffer.

static create<K extends ScalarKind>(kind: K, length: number): Promise<TypedBuffer<K>>;

Parameters

NameTypeRequiredDefaultMeaning
kindK extends ScalarKindYes—Element kind; selects WGSL type, scalar representation and storage stride.
lengthnumberYes—Positive integer number of elements, not scalar components or bytes.

Returns

Promise<TypedBuffer<K>> Typed row buffer.

Examples

Example
import { TypedBuffer } from 'wgpu-kit';
const b = await TypedBuffer.create('vec2f', 2);
b.write([
  { x: 1, y: 2 },
  { x: 3, y: 4 },
]);
console.log(await b.read());
b.destroy();

writemethod

Flatten rows into the appropriate typed array, validate finite numbers, then upload through raw.write.

write(rows: ReadonlyArray<KindOf<K>>): void;

Parameters

NameTypeRequiredDefaultMeaning
rowsReadonlyArray<KindOf<K>>Yes—Exactly length numeric rows or vector objects. Vector components required by kind must be finite numbers.

Returns

void No return value.

Errors & failure cases

  • ERR_BUFFER_WRITE for invalid row/component values or a resulting length mismatch. Integer kinds use typed-array coercion; there is no integer-range validation.

Examples

Example
import { TypedBuffer } from 'wgpu-kit';
const b = await TypedBuffer.create('vec2f', 2);
b.write([
  { x: 1, y: 2 },
  { x: 3, y: 4 },
]);
console.log(await b.read());
b.destroy();

readmethod

Read raw components and reconstruct numbers or vector objects.

read(): Promise<Array<KindOf<K>>>;

Parameters

This call takes no arguments.

Returns

Promise<Array<KindOf<K>>> New array of typed rows.

Examples

Example
import { TypedBuffer } from 'wgpu-kit';
const b = await TypedBuffer.create('vec2f', 2);
b.write([
  { x: 1, y: 2 },
  { x: 3, y: 4 },
]);
console.log(await b.read());
b.destroy();

destroymethod

Destroy the underlying raw buffer.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { TypedBuffer } from 'wgpu-kit';
const b = await TypedBuffer.create('vec2f', 2);
b.write([
  { x: 1, y: 2 },
  { x: 3, y: 4 },
]);
console.log(await b.read());
b.destroy();

Examples

Example
import { TypedBuffer } from 'wgpu-kit';
const b = await TypedBuffer.create('vec2f', 2);
b.write([
  { x: 1, y: 2 },
  { x: 3, y: 4 },
]);
console.log(await b.read());
b.destroy();

Source reference: dist/core/schema.js

Schemainterface

Return contract of defineSchema.

export interface Schema<F extends Record<string, ScalarKind>>

Fields & related types

NameTypeRequiredDefaultMeaning
FRecord<string, ScalarKind>——Generic field map.
fieldsreadonly F——Original declaration object; declaration order is preserved.

wgslStructmethod

Generate a WGSL struct; storage mode adds @size(16) for vec3f members.

wgslStruct(name: string, addressSpace?: 'storage' | 'uniform'): string;

Parameters

NameTypeRequiredDefaultMeaning
namestringYes—Struct identifier matching /^[A-Za-z][A-Za-z0-9_]*$/. WGSL reserved-word validity is left to compilation.
addressSpace'storage' | 'uniform'NostorageSelect storage-member padding or natural uniform member declarations.

Returns

string WGSL struct source.

Errors & failure cases

  • ERR_USAGE for a struct name failing the identifier regex.

Examples

Example
import { defineSchema } from 'wgpu-kit';
const S = defineSchema({ position: 'vec3f', mass: 'f32' });
console.log(S.wgslStruct('Body'));
const b = await S.buffers(2);
b.position.write([
  { x: 0, y: 1, z: 2 },
  { x: 3, y: 4, z: 5 },
]);
b.mass.write([1, 2]);
const resources = b.raws();
b.destroy();

buffersmethod

Allocate a TypedBuffer for every schema field.

buffers(count: number): Promise<SchemaBuffers<F>>;

Parameters

NameTypeRequiredDefaultMeaning
countnumberYes—Positive integer number of rows in every field.

Returns

Promise<SchemaBuffers<F>> Field buffers plus raws() and destroy().

Examples

Example
import { defineSchema } from 'wgpu-kit';
const S = defineSchema({ position: 'vec3f', mass: 'f32' });
console.log(S.wgslStruct('Body'));
const b = await S.buffers(2);
b.position.write([
  { x: 0, y: 1, z: 2 },
  { x: 3, y: 4, z: 5 },
]);
b.mass.write([1, 2]);
const resources = b.raws();
b.destroy();

Examples

Example
import { defineSchema } from 'wgpu-kit';
const S = defineSchema({ position: 'vec3f', mass: 'f32' });
console.log(S.wgslStruct('Body'));
const b = await S.buffers(2);
b.position.write([
  { x: 0, y: 1, z: 2 },
  { x: 3, y: 4, z: 5 },
]);
b.mass.write([1, 2]);
const resources = b.raws();
b.destroy();

Source reference: dist/core/schema.js

SchemaBufferstype

Mapped field buffers with collective helpers.

export type SchemaBuffers<F extends Record<string, ScalarKind>> = {
  readonly [K in keyof F]: TypedBuffer<F[K]>;
} & {
  raws(): {
    readonly [K in keyof F]: Buffer<F[K]>;
  };
  destroy(): void;
};

Fields & related types

NameTypeRequiredDefaultMeaning
[K in keyof F]readonly TypedBuffer<F[K]>——Each schema field is a typed row buffer.

rawsmethod

Return a new map of field names to their underlying raw Buffer handles.

raws(): { readonly [K in keyof F]: Buffer<F[K]> };

Parameters

This call takes no arguments.

Returns

{ readonly [K in keyof F]: Buffer<F[K]> } Suitable resources map for an elementKernel with matching names.

Examples

Example
import { defineSchema } from 'wgpu-kit';
const S = defineSchema({ position: 'vec3f', mass: 'f32' });
console.log(S.wgslStruct('Body'));
const b = await S.buffers(2);
b.position.write([
  { x: 0, y: 1, z: 2 },
  { x: 3, y: 4, z: 5 },
]);
b.mass.write([1, 2]);
const resources = b.raws();
b.destroy();

destroymethod

Destroy all generated field buffers.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { defineSchema } from 'wgpu-kit';
const S = defineSchema({ position: 'vec3f', mass: 'f32' });
console.log(S.wgslStruct('Body'));
const b = await S.buffers(2);
b.position.write([
  { x: 0, y: 1, z: 2 },
  { x: 3, y: 4, z: 5 },
]);
b.mass.write([1, 2]);
const resources = b.raws();
b.destroy();

Examples

Example
import { defineSchema } from 'wgpu-kit';
const S = defineSchema({ position: 'vec3f', mass: 'f32' });
console.log(S.wgslStruct('Body'));
const b = await S.buffers(2);
b.position.write([
  { x: 0, y: 1, z: 2 },
  { x: 3, y: 4, z: 5 },
]);
b.mass.write([1, 2]);
const resources = b.raws();
b.destroy();

Source reference: dist/core/schema.js

SchemaInfertype

Compile-time readonly row shape derived from a field map.

export type SchemaInfer<F extends Record<string, ScalarKind>> = {
  readonly [K in keyof F]: KindOf<F[K]>;
};

Fields & related types

NameTypeRequiredDefaultMeaning
FRecord<string, ScalarKind>——Input declaration map.
[K in keyof F]readonly KindOf<F[K]>——Preserves exact field names and maps kinds to JS scalar/vector shapes.

Examples

Example
import { defineSchema, type SchemaInfer } from 'wgpu-kit';
const S = defineSchema({ p: 'vec2f', id: 'u32' });
type Row = SchemaInfer<typeof S.fields>;
const row: Row = { p: { x: 1, y: 2 }, id: 7 };

Source reference: dist/core/schema.js

KindOftype

Compile-time mapping from ScalarKind to a numeric or vector row type.

export type KindOf<S extends ScalarKind> = S extends 'f32' | 'i32' | 'u32'
  ? number
  : S extends 'vec2f' | 'vec2i' | 'vec2u'
    ? Vec2
    : S extends 'vec3f'
      ? Vec3
      : S extends 'vec4f'
        ? Vec4
        : never;

Fields & related types

NameTypeRequiredDefaultMeaning
f32 | i32 | u32number——Scalar kinds.
vec2f | vec2i | vec2uVec2——Two numeric components.
vec3fVec3——Three numeric components.
vec4fVec4——Four numeric components.

Examples

Example
import type { KindOf } from 'wgpu-kit';
const p: KindOf<'vec3f'> = { x: 1, y: 2, z: 3 };

Source reference: dist/core/schema.js

Vec2interface

Object with 2 required numeric components.

export interface Vec2

Parameters

NameTypeRequiredDefaultMeaning
xnumberYes—x component.
ynumberYes—y component.

Examples

Example
import type { Vec2 } from 'wgpu-kit';
const v: Vec2 = { x: 1, y: 2 };

Source reference: dist/core/schema.js

Vec3interface

Object with 3 required numeric components.

export interface Vec3

Parameters

NameTypeRequiredDefaultMeaning
xnumberYes—x component.
ynumberYes—y component.
znumberYes—z component.

Examples

Example
import type { Vec3 } from 'wgpu-kit';
const v: Vec3 = { x: 1, y: 2, z: 3 };

Source reference: dist/core/schema.js

Vec4interface

Object with 4 required numeric components.

export interface Vec4

Parameters

NameTypeRequiredDefaultMeaning
xnumberYes—x component.
ynumberYes—y component.
znumberYes—z component.
wnumberYes—w component.

Examples

Example
import type { Vec4 } from 'wgpu-kit';
const v: Vec4 = { x: 1, y: 2, z: 3, w: 4 };

Source reference: dist/core/schema.js

definePackfunction

Validate a pack name/create function and preserve its generic type; returns the same object.

export declare function definePack<TConfig, TSim extends PackSim>(
  pack: WgpuKitPack<TConfig, TSim>,
): WgpuKitPack<TConfig, TSim>;

Parameters

NameTypeRequiredDefaultMeaning
packWgpuKitPack<TConfig, TSim>Yes—Definition with lowercase name and callable create. TSim extends PackSim.

Returns

WgpuKitPack<TConfig, TSim> The exact input definition, without wrapping or registration.

Behavior & constraints

  • Runtime validation checks only name and create function, not the lifecycle object returned later by create().

Errors & failure cases

  • ERR_USAGE unless name matches /^[a-z][a-z0-9-]*$/ and create is a function.

Examples

Example
import { definePack, registerPack, getPack, listPacks } from 'wgpu-kit';
const pack = definePack({
  name: 'counter-demo',
  description: 'A lifecycle example',
  async create(config?: { start?: number }) {
    let value = config?.start ?? 0;
    return {
      tick() {
        value++;
      },
      stats() {
        return { value };
      },
      destroy() {},
    };
  },
});
registerPack(pack);
const sim = await getPack<{ start?: number }>('counter-demo')!.create({ start: 3 });
sim.tick();
console.log(sim.stats?.(), listPacks());
sim.destroy();

Source reference: dist/core/pack.js

registerPackfunction

Register a user definition in the process/module registry.

export declare function registerPack<TConfig, TSim extends PackSim>(
  pack: WgpuKitPack<TConfig, TSim>,
): void;

Parameters

NameTypeRequiredDefaultMeaning
packWgpuKitPack<TConfig, TSim>Yes—Pack definition, preferably already checked with definePack.

Returns

void Definition becomes discoverable by listPacks/getPack.

Behavior & constraints

  • registerPack does not call definePack; it checks duplicate/reserved names only. There is no public unregister/overwrite API.

Errors & failure cases

  • ERR_USAGE for an already-registered name or the built-in reserved name particles.

Examples

Example
import { definePack, registerPack, getPack, listPacks } from 'wgpu-kit';
const pack = definePack({
  name: 'counter-demo',
  description: 'A lifecycle example',
  async create(config?: { start?: number }) {
    let value = config?.start ?? 0;
    return {
      tick() {
        value++;
      },
      stats() {
        return { value };
      },
      destroy() {},
    };
  },
});
registerPack(pack);
const sim = await getPack<{ start?: number }>('counter-demo')!.create({ start: 3 });
sim.tick();
console.log(sim.stats?.(), listPacks());
sim.destroy();

Source reference: dist/core/pack.js

PackSiminterface

Minimum lifecycle contract for pack simulations. tick and destroy are required; all other members are optional.

export interface PackSim

attachmethod

Optional rendering attachment hook.

attach?(canvas: HTMLCanvasElement): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
canvasHTMLCanvasElementYes—Canvas chosen by the caller.

Returns

Promise<void> Attachment completion, defined by the pack.

tickmethod

Advance one frame of computation and optional rendering.

tick(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

statsmethod

Optional lightweight statistics.

stats?(): Record<string, number | string>;

Parameters

This call takes no arguments.

Returns

Record<string, number | string> Pack-defined numeric/string metrics.

probemethod

Optional invariant/diagnostic probe.

probe?(): Promise<Record<string, number | string | boolean>>;

Parameters

This call takes no arguments.

Returns

Promise<Record<string, number | string | boolean>> Pack-defined self-check results.

destroymethod

Release resources owned by the simulation.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { definePack, registerPack, getPack, listPacks } from 'wgpu-kit';
const pack = definePack({
  name: 'counter-demo',
  description: 'A lifecycle example',
  async create(config?: { start?: number }) {
    let value = config?.start ?? 0;
    return {
      tick() {
        value++;
      },
      stats() {
        return { value };
      },
      destroy() {},
    };
  },
});
registerPack(pack);
const sim = await getPack<{ start?: number }>('counter-demo')!.create({ start: 3 });
sim.tick();
console.log(sim.stats?.(), listPacks());
sim.destroy();

Source reference: dist/core/pack.js

WgpuKitPackinterface

Generic factory metadata and lifecycle contract.

export interface WgpuKitPack<TConfig, TSim extends PackSim = PackSim>

Fields & related types

NameTypeRequiredDefaultMeaning
TConfiggeneric type parameter——Configuration type; required at type-definition use.
TSimextends PackSim = PackSim——Simulation type; defaults to PackSim.
namereadonly string——Registry namespace name.
descriptionreadonly string | undefined——Optional human-readable description; not defaulted by the interface.

createmethod

Create a simulation; concrete configuration/defaults are defined by that pack.

create(config?: TConfig): Promise<TSim>;

Parameters

NameTypeRequiredDefaultMeaning
configTConfigNo—Optional pack-specific configuration; no default imposed by this interface.

Returns

Promise<TSim> Pack-specific simulation implementing PackSim.

Examples

Example
import { definePack, registerPack, getPack, listPacks } from 'wgpu-kit';
const pack = definePack({
  name: 'counter-demo',
  description: 'A lifecycle example',
  async create(config?: { start?: number }) {
    let value = config?.start ?? 0;
    return {
      tick() {
        value++;
      },
      stats() {
        return { value };
      },
      destroy() {},
    };
  },
});
registerPack(pack);
const sim = await getPack<{ start?: number }>('counter-demo')!.create({ start: 3 });
sim.tick();
console.log(sim.stats?.(), listPacks());
sim.destroy();

Source reference: dist/core/pack.js

createScanfunction

Create a lazy u32 prefix-scan controller; no arguments.

export declare function createScan(): Scan;

Parameters

This call takes no arguments.

Returns

Scan Controller for exclusive or inclusive prefix sums.

Behavior & constraints

  • u32 only, with modulo-2^32 overflow. Use distinct source/destination storage buffers of at least count*4 bytes; JS does not validate Buffer.kind or capacity.
  • count=0 encodes no work and does not arm the guard. The implementation cap is 8192*65535 = 536862720 values; allocation/binding/device limits may be lower.
  • Native path without a batch: one encode/sumInto per instance per submit, followed by endSubmit(). Managed batch calls use independent uniforms/scratch, support repeated encoding, do not consume or reset the native guard, and need no endSubmit(). resetEncodeGuard() only disables the native check and does not fix shared-uniform overwrite hazards.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Examples

Example
import { Buffer, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.run(src, dst, 4);
console.log(await dst.read()); // [0,3,4,8]
scan.destroy();
src.destroy();
dst.destroy();
Example
import { Buffer, GpuContext, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
scan.encode(enc, src.gpuBuffer, dst.gpuBuffer, 4, false);
device.queue.submit([enc.finish()]);
scan.endSubmit();
console.log(await dst.read()); // [3,4,8,10]
scan.destroy();
src.destroy();
dst.destroy();

Source reference: src/primitives/scan.ts

Scaninterface

Prefix-scan lifecycle and composition contract.

export interface Scan

Behavior & constraints

  • u32 only, with modulo-2^32 overflow. Use distinct source/destination storage buffers of at least count*4 bytes; JS does not validate Buffer.kind or capacity.
  • count=0 encodes no work and does not arm the guard. The implementation cap is 8192*65535 = 536862720 values; allocation/binding/device limits may be lower.
  • Native path without a batch: one encode/sumInto per instance per submit, followed by endSubmit(). Managed batch calls use independent uniforms/scratch, support repeated encoding, do not consume or reset the native guard, and need no endSubmit(). resetEncodeGuard() only disables the native check and does not fix shared-uniform overwrite hazards.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

preparemethod

Idempotently create the scan pipelines and parameter buffers.

prepare(): Promise<void>;

Parameters

This call takes no arguments.

Returns

Promise<void> Ready to encode.

Examples

Example
import { Buffer, GpuContext, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
scan.encode(enc, src.gpuBuffer, dst.gpuBuffer, 4, false);
device.queue.submit([enc.finish()]);
scan.endSubmit();
console.log(await dst.read()); // [3,4,8,10]
scan.destroy();
src.destroy();
dst.destroy();

encodemethod

Encode one or three compute passes depending on count; no submit/readback.

encode(
  encoder: GPUCommandEncoder,
  src: GPUBuffer,
  dst: GPUBuffer,
  count: number,
  exclusive?: boolean,
  batch?: ComputeBatch,
): void;

Parameters

NameTypeRequiredDefaultMeaning
encoderGPUCommandEncoderYes—Caller-owned encoder from the same device; this API records work without submitting it.
srcGPUBufferYes—Read-only u32 storage input.
dstGPUBufferYes—Separate writable u32 storage output.
countnumberYes—Non-negative integer number of u32 values to process; must not exceed source/destination capacity where applicable.
exclusivebooleanNotruetrue: dst[i]=sum(src[0..i)); false: dst[i]=sum(src[0..i]).
batchComputeBatchNo—Optional managed scope; encoder must equal batch.encoder. Independent per-call uniforms/scratch support repeated calls without endSubmit(). The batch owns submission.

Returns

void No return value.

Behavior & constraints

  • Managed encoding does not snapshot caller-owned output buffers. Consume a shared destination before a later dispatch overwrites it.

Errors & failure cases

  • ERR_USAGE before prepare(), for a repeated guarded encode, invalid count, or count above 536862720. Primitive shader errors use UsageError with code ERR_COMPILE; native WebGPU validation may also fail.
  • UsageError for a closed batch or an encoder that does not belong to it.

Examples

Example
import { Buffer, GpuContext, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
scan.encode(enc, src.gpuBuffer, dst.gpuBuffer, 4, false);
device.queue.submit([enc.finish()]);
scan.endSubmit();
console.log(await dst.read()); // [3,4,8,10]
scan.destroy();
src.destroy();
dst.destroy();

runmethod

Prepare, encode and submit; automatically clear the guard.

run(src: Buffer, dst: Buffer, count: number, exclusive?: boolean): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
srcBufferYes—Source Buffer; caller must supply kind u32.
dstBufferYes—Separate destination Buffer; caller must supply kind u32.
countnumberYes—Non-negative integer number of u32 values to process; must not exceed source/destination capacity where applicable.
exclusivebooleanNotruetrue: dst[i]=sum(src[0..i)); false: dst[i]=sum(src[0..i]).

Returns

Promise<void> CPU submission; await dst.read() or context.sync() for completion.

Errors & failure cases

  • ERR_USAGE before prepare(), for a repeated guarded encode, invalid count, or count above 536862720. Primitive shader errors use UsageError with code ERR_COMPILE; native WebGPU validation may also fail.

Examples

Example
import { Buffer, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.run(src, dst, 4);
console.log(await dst.read()); // [0,3,4,8]
scan.destroy();
src.destroy();
dst.destroy();

endSubmitmethod

Reset the native encode-once guard after the caller submits. Managed batch calls do not use or reset this guard.

endSubmit(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer, GpuContext, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
scan.encode(enc, src.gpuBuffer, dst.gpuBuffer, 4, false);
device.queue.submit([enc.finish()]);
scan.endSubmit();
console.log(await dst.read()); // [3,4,8,10]
scan.destroy();
src.destroy();
dst.destroy();

resetEncodeGuardmethod

Permanently disable the native guard; this does not provide independent uniforms. Use a managed batch for repeatable parameter snapshots.

resetEncodeGuard(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Native path without a batch: one encode/sumInto per instance per submit, followed by endSubmit(). Managed batch calls use independent uniforms/scratch, support repeated encoding, do not consume or reset the native guard, and need no endSubmit(). resetEncodeGuard() only disables the native check and does not fix shared-uniform overwrite hazards.

Examples

Example
import { createScan } from 'wgpu-kit';
const scan = createScan();
scan.resetEncodeGuard(); // advanced: caller owns uniform hazards
scan.destroy();

destroymethod

Release internal block sums/parameter buffers and pipeline references. Does not destroy src/dst.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.run(src, dst, 4);
console.log(await dst.read()); // [0,3,4,8]
scan.destroy();
src.destroy();
dst.destroy();

Examples

Example
import { Buffer, createScan } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 4);
src.write(new Uint32Array([3, 1, 4, 2]));
const scan = createScan();
await scan.run(src, dst, 4);
console.log(await dst.read()); // [0,3,4,8]
scan.destroy();
src.destroy();
dst.destroy();

Source reference: src/primitives/scan.ts

createReducefunction

Create a lazy u32 sum-reduction controller; no arguments.

export declare function createReduce(): Reduce;

Parameters

This call takes no arguments.

Returns

Reduce GPU-output and CPU-readback sum controller.

Behavior & constraints

  • Inputs/results use u32 modulo-2^32 arithmetic. sumInto overwrites dst[0] by first clearing it; count=0 produces zero.
  • Source requires count*4 bytes and destination at least 4 writable STORAGE bytes. Caller must ensure kind/capacity; JS does not check them. Keep input/output separate.
  • Maximum count is 256*32*65535 = 536862720; device/binding/memory limits may impose a smaller usable maximum.
  • Native path without a batch: one encode/sumInto per instance per submit, followed by endSubmit(). Managed batch calls use independent uniforms/scratch, support repeated encoding, do not consume or reset the native guard, and need no endSubmit(). resetEncodeGuard() only disables the native check and does not fix shared-uniform overwrite hazards.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Examples

Example
import { Buffer, createReduce } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
values.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
console.log(await reduce.sum(values, 4)); // 10
reduce.destroy();
values.destroy();
Example
import { Buffer, GpuContext, createReduce } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 1);
src.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
await reduce.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
reduce.sumInto(enc, src.gpuBuffer, 4, dst.gpuBuffer);
device.queue.submit([enc.finish()]);
reduce.endSubmit();
console.log(await dst.read()); // [10]
reduce.destroy();
src.destroy();
dst.destroy();

Source reference: src/primitives/reduce.ts

Reduceinterface

Reduction lifecycle and composition contract.

export interface Reduce

Behavior & constraints

  • Inputs/results use u32 modulo-2^32 arithmetic. sumInto overwrites dst[0] by first clearing it; count=0 produces zero.
  • Source requires count*4 bytes and destination at least 4 writable STORAGE bytes. Caller must ensure kind/capacity; JS does not check them. Keep input/output separate.
  • Maximum count is 256*32*65535 = 536862720; device/binding/memory limits may impose a smaller usable maximum.
  • Native path without a batch: one encode/sumInto per instance per submit, followed by endSubmit(). Managed batch calls use independent uniforms/scratch, support repeated encoding, do not consume or reset the native guard, and need no endSubmit(). resetEncodeGuard() only disables the native check and does not fix shared-uniform overwrite hazards.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

preparemethod

Idempotently prepare clear/reduction pipelines and parameters.

prepare(): Promise<void>;

Parameters

This call takes no arguments.

Returns

Promise<void> Ready to encode.

Examples

Example
import { Buffer, GpuContext, createReduce } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 1);
src.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
await reduce.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
reduce.sumInto(enc, src.gpuBuffer, 4, dst.gpuBuffer);
device.queue.submit([enc.finish()]);
reduce.endSubmit();
console.log(await dst.read()); // [10]
reduce.destroy();
src.destroy();
dst.destroy();

sumIntomethod

Record clear/reduction passes; result stays on GPU in dst[0].

sumInto(
  encoder: GPUCommandEncoder,
  src: GPUBuffer,
  count: number,
  dst: GPUBuffer,
  batch?: ComputeBatch,
): void;

Parameters

NameTypeRequiredDefaultMeaning
encoderGPUCommandEncoderYes—Caller-owned encoder from the same device; this API records work without submitting it.
srcGPUBufferYes—Read-only u32 storage input.
countnumberYes—Non-negative integer number of u32 values to process; must not exceed source/destination capacity where applicable.
dstGPUBufferYes—Writable storage buffer whose first u32 is treated as atomic<u32> by the shader.
batchComputeBatchNo—Optional managed scope; encoder must equal batch.encoder. Independent per-call uniforms/scratch support repeated calls without endSubmit(). The batch owns submission.

Returns

void No return value.

Behavior & constraints

  • Managed encoding does not snapshot caller-owned output buffers. Consume a shared destination before a later dispatch overwrites it.

Errors & failure cases

  • ERR_USAGE before prepare(), repeated guarded sumInto(), invalid count or count beyond the dispatch cap. Shader compilation errors use UsageError / ERR_COMPILE. Readback/map failures may reject sum().
  • UsageError for a closed batch or an encoder that does not belong to it.

Examples

Example
import { Buffer, GpuContext, createReduce } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 1);
src.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
await reduce.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
reduce.sumInto(enc, src.gpuBuffer, 4, dst.gpuBuffer);
device.queue.submit([enc.finish()]);
reduce.endSubmit();
console.log(await dst.read()); // [10]
reduce.destroy();
src.destroy();
dst.destroy();

summethod

Prepare, encode, submit and read back one u32 using per-call temporary buffers.

sum(src: Buffer, count: number): Promise<number>;

Parameters

NameTypeRequiredDefaultMeaning
srcBufferYes—Source Buffer interpreted as u32.
countnumberYes—Non-negative integer number of u32 values to process; must not exceed source/destination capacity where applicable.

Returns

Promise<number> Unsigned sum after GPU work/readback; overflow wraps modulo 2^32.

Errors & failure cases

  • ERR_USAGE before prepare(), repeated guarded sumInto(), invalid count or count beyond the dispatch cap. Shader compilation errors use UsageError / ERR_COMPILE. Readback/map failures may reject sum().

Examples

Example
import { Buffer, createReduce } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
values.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
console.log(await reduce.sum(values, 4)); // 10
reduce.destroy();
values.destroy();

endSubmitmethod

Reset the native encode-once guard after the caller submits. Managed batch calls do not use or reset this guard.

endSubmit(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer, GpuContext, createReduce } from 'wgpu-kit';
const src = await Buffer.create('u32', 4),
  dst = await Buffer.create('u32', 1);
src.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
await reduce.prepare();
const { device } = await GpuContext.get();
const enc = device.createCommandEncoder();
reduce.sumInto(enc, src.gpuBuffer, 4, dst.gpuBuffer);
device.queue.submit([enc.finish()]);
reduce.endSubmit();
console.log(await dst.read()); // [10]
reduce.destroy();
src.destroy();
dst.destroy();

resetEncodeGuardmethod

Permanently disable the native guard; this does not provide independent uniforms. Use a managed batch for repeatable parameter snapshots.

resetEncodeGuard(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Native path without a batch: one encode/sumInto per instance per submit, followed by endSubmit(). Managed batch calls use independent uniforms/scratch, support repeated encoding, do not consume or reset the native guard, and need no endSubmit(). resetEncodeGuard() only disables the native check and does not fix shared-uniform overwrite hazards.

Examples

Example
import { createReduce } from 'wgpu-kit';
const reduce = createReduce();
reduce.resetEncodeGuard();
reduce.destroy();

destroymethod

Destroy internal parameters and release pipeline references; input/output buffers are caller-owned.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer, createReduce } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
values.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
console.log(await reduce.sum(values, 4)); // 10
reduce.destroy();
values.destroy();

Examples

Example
import { Buffer, createReduce } from 'wgpu-kit';
const values = await Buffer.create('u32', 4);
values.write(new Uint32Array([3, 1, 4, 2]));
const reduce = createReduce();
console.log(await reduce.sum(values, 4)); // 10
reduce.destroy();
values.destroy();

Source reference: src/primitives/reduce.ts

particlesfunction

Create and initialize a four-species GPU particle simulation.

particles(config?: ParticlesConfig): Promise<ParticlesSim>;

Parameters

NameTypeRequiredDefaultMeaning
configParticlesConfigNo{}Simulation, rendering, and initialization options; all fields are detailed under ParticlesConfig.

Returns

Promise<ParticlesSim> Initialized buffers and compute pipelines, without a render loop or attached canvas.

Behavior & constraints

  • World half-width is fixed by count: sqrt(count/16_000). Initial positions are seeded within ±0.8*worldHalf, velocities start at zero, and species indices are 0..3. No public worldHalf or species-count option exists.
  • The caller owns animation scheduling. tick works without attach for compute-only use. Attach a canvas once if built-in rendering is desired.
  • WebGPU and the shared GpuContext are required. No WebGL or CPU fallback is provided. Resource use depends on count, grid resolution, and device limits.

Errors & failure cases

  • Rejects UsageError(ERR_USAGE) for invalid count/mode and n2 count >32_000. An unknown string force name throws plain Error. Device acquisition, buffer allocation, shader compilation, or pipeline validation can reject.
  • Physical numeric options and custom force-matrix length/range are not comprehensively checked. Invalid numbers can reach GPU code; validate application input.

Examples

Initialize once, render on animation frames, and stop scheduling before destroying.
import { particles } from 'wgpu-kit/particles';
const canvas = document.querySelector<HTMLCanvasElement>('#canvas')!;
const sim = await particles({ count: 4096, mode: 'grid', seed: 'example' });
await sim.attach(canvas);
let raf = 0;
let stopped = false;
function frame() {
  if (stopped) return;
  sim.tick();
  raf = requestAnimationFrame(frame);
}
raf = requestAnimationFrame(frame);
function dispose() {
  stopped = true;
  cancelAnimationFrame(raf);
  sim.destroy();
}

ParticlesSiminterface

Simulation handle returned by particles(); root entry point also exports this type.

interface ParticlesSim

Fields & related types

NameTypeRequiredDefaultMeaning
ForcePresetName (supporting, not exported by this entry point)'cells' | 'snakes' | 'orbitals' | 'viruses'——Literal names accepted as force selections. FORCE_PRESETS itself is not a public root or /particles export.
ForceMatrix (supporting, not exported by this entry point)readonly [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number]——A flat 4×4 matrix; lookup is mySpecies*4+otherSpecies. Obtain this type without a private-path import using Exclude<NonNullable<ParticlesConfig["forces"]>, string>.
SimMode (supporting, not exported by this entry point)'n2' | 'tiled' | 'grid'——Obtain through NonNullable<ParticlesConfig["mode"]>.

configreadonly property

Resolved initialization config, with live force selection updates.

readonly config: ResolvedConfig;

Parameters

NameTypeRequiredDefaultMeaning
countnumberYes—Integer particle count in 1..1_000_000. n2 mode rejects counts above 32_000 (its error text recommends at most 20_000). Device memory limits may be lower.
forcesForceMatrixYes—Resolved 16-number force matrix, updated by setForces().
mode'n2' | 'tiled' | 'grid'Yes—Neighbor algorithm: all-pairs, workgroup-tiled all-pairs, or spatial grid. The declaration comment saying tiled is the default is stale; implementation defaults to grid.
color'species' | 'velocity'Yes—Canvas coloring by four species or speed magnitude. Used when the renderer is attached.
bounds'wrap' | 'clamp'Yes—How updated positions remain in the square world: wrap or clamp. Interaction distances/neighborhood searches do not wrap across opposite edges.
seedstringYes—String(seed), retained from initialization.
rMaxnumberYes—Maximum interaction radius in world units. Use a finite positive number. Also affects grid resolution.
betanumberYes—Piecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API.
forceFactornumberYes—Acceleration scale: summed interactions are multiplied by forceFactor*rMax before integration.
frictionHalfLifenumberYes—Damping time parameter used as exp(-effectiveDt/frictionHalfLife). Despite the name, implementation does not include ln(2), so this is an exponential decay time constant rather than a mathematical half-life. Use a positive finite value.
dtnumberYes—Base simulation time step per tick, multiplied by the tick argument. The animation callback elapsed time is not measured automatically.
pointSizenumberYes—Normalized point-quad half-size used by the attached renderer, approximately in clip coordinates after world scaling. It is not a literal pixel size; shader generation rounds the scaled value to four decimals.
maxNeighborsnumberYes—Grid-only candidate budget: ceil(maxNeighbors/9) candidates per each of up to 9 neighboring cells (self may count). Use a finite positive number.
forcesNamestringYes—Selected literal force name, or 'custom'; updated by setForces().
seedHashnumberYes—32-bit hash of the normalized seed string.
frictionnumberYes—Initial exp(-dt/frictionHalfLife); not a live value after setParams or tick multipliers.

Returns

ResolvedConfig Internal supporting type reachable through ParticlesSim["config"]. The property is readonly, not a deeply immutable snapshot.

Behavior & constraints

  • setParams changes a separate internal physics object, so config.rMax/beta/forceFactor/frictionHalfLife/dt/friction may remain initialization values. snapshot() reads the current physics values.

Fields & related types

NameTypeRequiredDefaultMeaning
ResolvedConfig (supporting, not exported by this entry point){ count: number; forces: ForceMatrix; forcesName: string; mode: SimMode; color: "species" | "velocity"; bounds: "wrap" | "clamp"; seed: string; seedHash: number; rMax: number; beta: number; forceFactor: number; friction: number; frictionHalfLife: number; dt: number; pointSize: number; maxNeighbors: number }——All fields are required on resolved output. Do not mutate config directly to control the simulation.

attachmethod

Configure built-in particle rendering on one canvas.

attach(canvas: HTMLCanvasElement): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
canvasHTMLCanvasElementYes—Canvas with positive CSS client dimensions, not already acquired by an incompatible drawing backend.

Returns

Promise<void> Resolves when the canvas renderer is ready.

Behavior & constraints

  • Sets backing width/height to max(1, floor(clientSize*min(devicePixelRatio||1,2))). Configures opaque WebGPU rendering. No automatic resize observer is installed.
  • Call once per simulation. A second call replaces the renderer reference without first destroying the previous renderer. attach does not start an animation loop.

Errors & failure cases

  • Rejects if canvas.getContext("webgpu") is null or rendering shader/pipeline initialization fails.

tickmethod

Advance one simulation step, optionally render it, and swap current state buffers.

tick(dtMultiplier?: number): void;

Parameters

NameTypeRequiredDefaultMeaning
dtMultipliernumberNo1Multiplier applied to current dt. 0 freezes physical evolution but still submits work/renders/swaps/counts a tick; fractional values slow simulation.

Returns

void No return value.

Behavior & constraints

  • Submits its own command encoder; this high-level API does not expose prepare/encode/endSubmit. Returns before GPU completion. Skip tick entirely to pause GPU work.
  • Integration uses effectiveDt=dt*dtMultiplier and damping exp(-effectiveDt/frictionHalfLife). It does not adapt to elapsed animation-frame time.

setForcesmethod

Replace the force matrix without recreating the simulation.

setForces(forces: ForcePresetName | 'random' | ForceMatrix): void;

Parameters

NameTypeRequiredDefaultMeaning
forcesForcePresetName | 'random' | ForceMatrixYes—Same force selection types as ParticlesConfig.forces. random reuses the original seed, so repeated calls produce the same matrix.

Returns

void No return value.

Behavior & constraints

  • Queues a write to the 16-f32 matrix buffer and updates config.forces/config.forcesName. It does not reset positions or velocities.

Errors & failure cases

  • Unknown force strings throw plain Error. Custom matrix component count/type issues may propagate from Buffer.write; do not pass arbitrary-length arrays.

setParamsmethod

Patch current physics parameters; omitted fields retain their current values.

setParams(params: {
  rMax?: number;
  beta?: number;
  forceFactor?: number;
  frictionHalfLife?: number;
  dt?: number;
}): void;

Parameters

NameTypeRequiredDefaultMeaning
params{ rMax?: number; beta?: number; forceFactor?: number; frictionHalfLife?: number; dt?: number }Yes—Partial physics update; all nested fields are optional.
params.rMaxnumberNounchanged when omittedMaximum interaction radius in world units. Use a finite positive number. Also affects grid resolution.
params.betanumberNounchanged when omittedPiecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API.
params.forceFactornumberNounchanged when omittedAcceleration scale: summed interactions are multiplied by forceFactor*rMax before integration.
params.frictionHalfLifenumberNounchanged when omittedDamping time parameter used as exp(-effectiveDt/frictionHalfLife). Despite the name, implementation does not include ln(2), so this is an exponential decay time constant rather than a mathematical half-life. Use a positive finite value.
params.dtnumberNounchanged when omittedBase simulation time step per tick, multiplied by the tick argument. The animation callback elapsed time is not measured automatically.

Returns

void No return value.

Behavior & constraints

  • No runtime numeric validation. Do not explicitly pass undefined for a field, because Object.assign would overwrite it.
  • If rMax changes grid resolution, an asynchronous rebuild starts; only the latest rebuild wins and old grid resources are replaced. No promise or completion callback is exposed; rebuild errors are not caught here.

snapshotmethod

Serialize selected current settings, not simulation state.

snapshot(): string;

Parameters

This call takes no arguments.

Returns

string JSON containing count, forces name, mode, color, bounds, seed, rMax, beta, forceFactor, frictionHalfLife, dt, pointSize.

Behavior & constraints

  • Omits particle buffers, maxNeighbors, and the values of custom force matrices. A custom matrix becomes forces:"custom", which particles() cannot resolve as a named matrix; this is not a complete round-trip checkpoint.

statsmethod

Read tick-frequency and uncaptured-error counters.

stats(): { fps: number; gpuErrors: number };

Parameters

This call takes no arguments.

Returns

{ fps: number; gpuErrors: number } fps starts at 0 and updates when accumulated wall time reaches about 500 ms. gpuErrors counts device uncapturederror events observed by this instance.

Fields & related types

NameTypeRequiredDefaultMeaning
fpsnumber——Ticks per elapsed wall-clock second, not GPU kernel duration or a benchmark score. Long pauses can affect the next sample.
gpuErrorsnumber——Shared-device uncaptured error count; events may originate from other work using that device.

debugGridoptional method

Expose grid-internal buffers for diagnostics only; undefined outside grid mode.

debugGrid?(): {
  partial: Buffer;
  start: Buffer;
  fill: Buffer;
  sortedPos: Buffer;
  sortedSp: Buffer;
  order: Buffer;
};

Parameters

This call takes no arguments.

Returns

{ partial: Buffer; start: Buffer; fill: Buffer; sortedPos: Buffer; sortedSp: Buffer; order: Buffer } Borrowed internal buffers, replaced by a later grid rebuild. Do not destroy them.

Fields & related types

NameTypeRequiredDefaultMeaning
partialBuffer (vec2f, count*9)——Per-particle per-neighbor-cell partial force contributions.
startBuffer (u32, cells)——Inclusive starting slot for each cell.
fillBuffer (u32, cells)——Exclusive end slot after scatter, not raw occupancy count.
sortedPosBuffer (vec2f, count)——Position copy grouped by cell.
sortedSpBuffer (u32, count)——Species indices grouped by cell.
orderBuffer (u32, count)——Original particle index at each sorted slot.

buffersmethod

Get borrowed buffers for the current simulation state.

buffers(): { pos: Buffer; vel: Buffer; species: Buffer };

Parameters

This call takes no arguments.

Returns

{ pos: Buffer; vel: Buffer; species: Buffer } pos/vel are count-element vec2f buffers; species is a count-element u32 buffer.

Behavior & constraints

  • pos and vel alternate after tick; call buffers() again for the latest side. CPU snapshots require await buffer.read(). The simulation owns these buffers.

Fields & related types

NameTypeRequiredDefaultMeaning
posBuffer (vec2f)——Current 2D world positions.
velBuffer (vec2f)——Current 2D velocities.
speciesBuffer (u32)——Species labels 0..3, independent of ping-pong state.

Examples

Obtain the current side after ticking, then read a snapshot.
import { particles } from 'wgpu-kit';
const sim = await particles({ count: 4, mode: 'n2' });
sim.tick();
const { pos, vel, species } = sim.buffers();
const positions = await pos.read();
console.log(positions);
sim.destroy();

destroymethod

Release the simulation-owned particle, matrix, uniform, grid, and renderer resources handled by this implementation.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Cancel your animation loop and stop using borrowed buffers first. No automatic RAF cancellation, canvas unconfiguration, disposed-state guard, or error-listener removal is provided.
  • Avoid destroying while an asynchronous setParams grid rebuild is pending: 2.0.0 does not expose a way to await or cancel that rebuild.

ElementKernelinterface

Controller returned by elementKernel.

export interface ElementKernel

Behavior & constraints

  • New in 2.1.0: auxInputs, options.count and ElementKernelDispatchOptions are documented from src/core/kernel.ts and src/index.ts; these additions extend the historical npm 2.0.0 audit baseline.
  • All declared state/input/auxInputs buffers must be present and have the declared kind, including statically unused fields. Bound resources must belong to the shared device. Extra resource/uniform keys are ignored.
  • Without options.count, state and inputs must have equal lengths and the first such buffer determines the invocation count. At least one state or inputs field is required; auxInputs do not determine the count.
  • An explicit count must be an integer in 0..0xffffffff. State/input lengths may differ, but every such buffer must contain at least count elements. In either mode, ceil(count / workgroupSize) must not exceed device.limits.maxComputeWorkgroupsPerDimension.
  • Auxiliary arrays are read-only and may have independent lengths. They do not participate in per-element capacity checks; auxiliary indexing bounds are the WGSL author's responsibility. Query their lengths with arrayLength(&weights).
  • count: 0 validates all resources, uniforms and options, then performs no encoding or submission. It neither consumes nor clears an existing encode-once guard.
  • Field names must be unique across state, inputs, auxInputs and uniforms. The uniform name count is reserved and automatically injected. Use valid WGSL identifiers; the compiler checks reserved words.
  • Do not read neighboring elements from a buffer being concurrently written in the same dispatch; use separate input/output buffers or PingPong. The library does not provide global synchronization inside a dispatch.
  • The generated source uses lexical resource-use analysis; shadowing a resource name with a local variable is a known analysis limitation.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Fields & related types

NameTypeRequiredDefaultMeaning
namereadonly string——Diagnostic name.
sourcereadonly string——Complete generated WGSL, including declarations and entrypoint.
uniformLayoutreadonly UniformLayout——Ordered fields with byte offsets and padded byte size. UniformLayout is reachable but not a root named export.
workgroupSizereadonly number——Chosen X workgroup size.

preparemethod

Idempotently resolve the shared context, compile the pipeline and allocate uniforms.

prepare(): Promise<void>;

Parameters

This call takes no arguments.

Returns

Promise<void> Ready for synchronous encode().

Errors & failure cases

  • Preparation/replacement: CompileError / ERR_COMPILE reports WGSL errors with line numbers mapped to user code. Other native WebGPU validation/device failures may occur.

Examples

Example
import { Buffer, GpuContext, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
const k = elementKernel({
  state: { values: 'f32' },
  code: 'fn userFn(i:u32){values[i]=f32(i);}',
});
await k.prepare();
const { device } = await GpuContext.get();
const encoder = device.createCommandEncoder();
k.encode(encoder, { values });
device.queue.submit([encoder.finish()]);
k.endSubmit();
console.log(await values.read());
k.destroy();
values.destroy();

runmethod

Convenience prepare → encode → queue.submit; resets the encode guard after a nonzero submission. Zero count validates the call and leaves the guard unchanged.

run(
  resources: Record<string, Buffer>,
  uniforms?: Record<string, UniformValue>,
  options?: ElementKernelDispatchOptions,
): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
resourcesRecord<string, Buffer>Yes—Map every declared state/input/auxInputs field to a Buffer of the declared kind on the shared device. Count and capacity rules are controlled by options.
uniformsRecord<string, UniformValue>No{}Values for all declared uniforms. Vectors are {x,y,z,w} objects with components required by their kind.
optionsElementKernelDispatchOptionsNo{}Optional invocation count. Without count, state/inputs must be equal-length. An explicit count permits different capacities of at least count; auxInputs are independent. Pass undefined for uniforms when none are declared.

Returns

Promise<void> After a nonzero call, work has been submitted on the CPU; it does not await GPU completion. Zero count resolves after validation without a submission.

Behavior & constraints

  • Without options.count, state and inputs must have equal lengths and the first such buffer determines the invocation count. At least one state or inputs field is required; auxInputs do not determine the count.
  • An explicit count must be an integer in 0..0xffffffff. State/input lengths may differ, but every such buffer must contain at least count elements. In either mode, ceil(count / workgroupSize) must not exceed device.limits.maxComputeWorkgroupsPerDimension.
  • Auxiliary arrays are read-only and may have independent lengths. They do not participate in per-element capacity checks; auxiliary indexing bounds are the WGSL author's responsibility. Query their lengths with arrayLength(&weights).
  • count: 0 validates all resources, uniforms and options, then performs no encoding or submission. It neither consumes nor clears an existing encode-once guard.

Errors & failure cases

  • ERR_USAGE before prepare(), for a repeated native encode before submission/reset, or for a closed/mismatched managed batch. ERR_RESOURCE_MISSING, ERR_RESOURCE_TYPE and ERR_RESOURCE_LENGTH identify bad resources. Uniform packing reports ERR_UNIFORM_FIELD/ERR_UNIFORM_UNSUPPORTED. Shared-device resource ownership is a caller precondition.
  • UsageError also rejects invalid counts, a count beyond the device dispatch limit, or insufficient state/input capacity. All declared resources and uniform values are checked even when count is zero.

Examples

Example
import { Buffer, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
values.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { values: 'f32' },
  uniforms: { gain: 'f32' },
  code: 'fn userFn(i:u32,gain:f32){values[i]*=gain;}',
});
await k.run({ values }, { gain: 3 });
console.log(await values.read());
k.destroy();
values.destroy();

encodemethod

Encode a nonzero dispatch without submitting. Without a batch, use the native shared-uniform guard. With a batch, capture an independent uniform snapshot. Zero count validates without encoding or changing the native guard.

encode(
  encoder: GPUCommandEncoder,
  resources: Record<string, Buffer>,
  uniforms?: Record<string, UniformValue>,
  options?: ElementKernelEncodeOptions,
): void;

Parameters

NameTypeRequiredDefaultMeaning
encoderGPUCommandEncoderYes—Unfinished encoder from the shared device with no active pass. With options.batch this must be batch.encoder; batch.submit() owns finishing/submission.
resourcesRecord<string, Buffer>Yes—Map every declared state/input/auxInputs field to a Buffer of the declared kind on the shared device. Count and capacity rules are controlled by options.
uniformsRecord<string, UniformValue>No{}Values for all declared uniforms. Vectors are {x,y,z,w} objects with components required by their kind.
optionsElementKernelEncodeOptionsNo{}Optional count and managed batch. Count follows run() capacity rules. A batch allows repeated dispatches with independent parameters and owns submission; run() itself accepts no batch option.

Returns

void No return value.

Behavior & constraints

  • Native path without options.batch: one nonzero encode per instance per submission, followed by endSubmit(). With options.batch, pass batch.encoder and submit only through batch.submit(); every encode has an independent uniform snapshot, repeated calls are supported, and the native guard is unchanged.
  • Without options.count, state and inputs must have equal lengths and the first such buffer determines the invocation count. At least one state or inputs field is required; auxInputs do not determine the count.
  • An explicit count must be an integer in 0..0xffffffff. State/input lengths may differ, but every such buffer must contain at least count elements. In either mode, ceil(count / workgroupSize) must not exceed device.limits.maxComputeWorkgroupsPerDimension.
  • Auxiliary arrays are read-only and may have independent lengths. They do not participate in per-element capacity checks; auxiliary indexing bounds are the WGSL author's responsibility. Query their lengths with arrayLength(&weights).
  • count: 0 validates all resources, uniforms and options, then performs no encoding or submission. It neither consumes nor clears an existing encode-once guard.

Errors & failure cases

  • ERR_USAGE before prepare(), for a repeated native encode before submission/reset, or for a closed/mismatched managed batch. ERR_RESOURCE_MISSING, ERR_RESOURCE_TYPE and ERR_RESOURCE_LENGTH identify bad resources. Uniform packing reports ERR_UNIFORM_FIELD/ERR_UNIFORM_UNSUPPORTED. Shared-device resource ownership is a caller precondition.
  • UsageError also rejects invalid counts, a count beyond the device dispatch limit, or insufficient state/input capacity. All declared resources and uniform values are checked even when count is zero.

Examples

Example
import { Buffer, GpuContext, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
const k = elementKernel({
  state: { values: 'f32' },
  code: 'fn userFn(i:u32){values[i]=f32(i);}',
});
await k.prepare();
const { device } = await GpuContext.get();
const encoder = device.createCommandEncoder();
k.encode(encoder, { values });
device.queue.submit([encoder.finish()]);
k.endSubmit();
console.log(await values.read());
k.destroy();
values.destroy();

endSubmitmethod

Clear the native encode-once guard after a caller-owned submission. Does not submit or wait. Managed encoding neither needs this call nor changes the guard.

endSubmit(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer, GpuContext, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
const k = elementKernel({
  state: { values: 'f32' },
  code: 'fn userFn(i:u32){values[i]=f32(i);}',
});
await k.prepare();
const { device } = await GpuContext.get();
const encoder = device.createCommandEncoder();
k.encode(encoder, { values });
device.queue.submit([encoder.finish()]);
k.endSubmit();
console.log(await values.read());
k.destroy();
values.destroy();

resetEncodeGuardmethod

Permanently disable the native guard on this instance; managed batch encoding is already repeatable without this escape hatch.

resetEncodeGuard(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Without a batch, repeated encodes still share a uniform buffer and may see overwritten values. No corresponding enable method exists.

Examples

Example
import { elementKernel } from 'wgpu-kit';
const k = elementKernel({ state: { x: 'f32' }, code: 'fn userFn(i:u32){x[i]=1.0;}' });
k.resetEncodeGuard(); // only after auditing shared-uniform semantics
k.destroy();

replacemethod

Replace only the WGSL function source using the original declarations. Compile failure leaves the old kernel active.

replace(code: string): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
codestringYes—New non-empty WGSL userFn/helper source, with the same resource/uniform contract.

Returns

Promise<void> Resolves after successful recompilation; does not dispatch.

Errors & failure cases

  • Construction: ERR_WORKGROUP_SIZE for an invalid workgroup size; ERR_RESOURCE_MISSING for no arrays; ERR_USAGE for empty code, duplicate names or reserved count uniform.
  • Preparation/replacement: CompileError / ERR_COMPILE reports WGSL errors with line numbers mapped to user code. Other native WebGPU validation/device failures may occur.

Examples

Example
import { elementKernel } from 'wgpu-kit';
const k = elementKernel({ state: { x: 'f32' }, code: 'fn userFn(i:u32){x[i]=1.0;}' });
await k.replace('fn userFn(i:u32){x[i]=2.0;}');
k.destroy();

destroymethod

Release internal uniform storage and cached binding groups; caller-owned resource buffers are not destroyed.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Examples

Example
import { Buffer, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
values.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { values: 'f32' },
  uniforms: { gain: 'f32' },
  code: 'fn userFn(i:u32,gain:f32){values[i]*=gain;}',
});
await k.run({ values }, { gain: 3 });
console.log(await values.read());
k.destroy();
values.destroy();

Examples

Example
import { Buffer, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
values.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { values: 'f32' },
  uniforms: { gain: 'f32' },
  code: 'fn userFn(i:u32,gain:f32){values[i]*=gain;}',
});
await k.run({ values }, { gain: 3 });
console.log(await values.read());
k.destroy();
values.destroy();
Example
import { Buffer, GpuContext, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
const k = elementKernel({
  state: { values: 'f32' },
  code: 'fn userFn(i:u32){values[i]=f32(i);}',
});
await k.prepare();
const { device } = await GpuContext.get();
const encoder = device.createCommandEncoder();
k.encode(encoder, { values });
device.queue.submit([encoder.finish()]);
k.endSubmit();
console.log(await values.read());
k.destroy();
values.destroy();
Independent auxiliary length and an explicit buffer prefix (new in 2.1.0)
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();

Source reference: src/core/kernel.ts

ElementKernelSpecinterface

Complete options accepted by elementKernel.

export interface ElementKernelSpec

Parameters

NameTypeRequiredDefaultMeaning
namestringNokernelDiagnostic kernel label.
stateRecord<string, ScalarKind>No{}Read-write storage arrays, accessed by their field names in WGSL.
inputsRecord<string, ScalarKind>No{}Read-only storage arrays. At least one state or inputs field is required overall.
auxInputsRecord<string, ScalarKind>No{}Read-only auxiliary storage arrays with independent lengths; do not determine dispatch count. Bounds must be handled in WGSL. Added in 2.1.0.
uniformsRecord<string, ScalarKind>No{}Uniform declarations; insertion order must match userFn parameters after the element index.
workgroupSizenumberNo64Integer 1..512 accepted by the library; actual device limits may be stricter.
codestringYes—Non-empty WGSL containing fn userFn(index:u32, ...uniform arguments). May include helper functions; do not supply the generated bindings/main entrypoint.

Behavior & constraints

  • New in 2.1.0: auxInputs, options.count and ElementKernelDispatchOptions are documented from src/core/kernel.ts and src/index.ts; these additions extend the historical npm 2.0.0 audit baseline.
  • All declared state/input/auxInputs buffers must be present and have the declared kind, including statically unused fields. Bound resources must belong to the shared device. Extra resource/uniform keys are ignored.
  • Without options.count, state and inputs must have equal lengths and the first such buffer determines the invocation count. At least one state or inputs field is required; auxInputs do not determine the count.
  • An explicit count must be an integer in 0..0xffffffff. State/input lengths may differ, but every such buffer must contain at least count elements. In either mode, ceil(count / workgroupSize) must not exceed device.limits.maxComputeWorkgroupsPerDimension.
  • Auxiliary arrays are read-only and may have independent lengths. They do not participate in per-element capacity checks; auxiliary indexing bounds are the WGSL author's responsibility. Query their lengths with arrayLength(&weights).
  • count: 0 validates all resources, uniforms and options, then performs no encoding or submission. It neither consumes nor clears an existing encode-once guard.
  • Field names must be unique across state, inputs, auxInputs and uniforms. The uniform name count is reserved and automatically injected. Use valid WGSL identifiers; the compiler checks reserved words.
  • Do not read neighboring elements from a buffer being concurrently written in the same dispatch; use separate input/output buffers or PingPong. The library does not provide global synchronization inside a dispatch.
  • The generated source uses lexical resource-use analysis; shadowing a resource name with a local variable is a known analysis limitation.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Examples

Example
import { Buffer, elementKernel } from 'wgpu-kit';
const values = await Buffer.create('f32', 4);
values.write(new Float32Array([1, 2, 3, 4]));
const k = elementKernel({
  state: { values: 'f32' },
  uniforms: { gain: 'f32' },
  code: 'fn userFn(i:u32,gain:f32){values[i]*=gain;}',
});
await k.run({ values }, { gain: 3 });
console.log(await values.read());
k.destroy();
values.destroy();
Independent auxiliary length and an explicit buffer prefix (new in 2.1.0)
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();

Source reference: src/core/kernel.ts

ElementKernelDispatchOptionsinterface

Optional invocation count accepted by run() and inherited by ElementKernelEncodeOptions for encode(). Added in 2.1.0; run() remains count-only.

export interface ElementKernelDispatchOptions {
  count?: number;
}

Behavior & constraints

  • New in 2.1.0: auxInputs, options.count and ElementKernelDispatchOptions are documented from src/core/kernel.ts and src/index.ts; these additions extend the historical npm 2.0.0 audit baseline.
  • Without options.count, state and inputs must have equal lengths and the first such buffer determines the invocation count. At least one state or inputs field is required; auxInputs do not determine the count.
  • An explicit count must be an integer in 0..0xffffffff. State/input lengths may differ, but every such buffer must contain at least count elements. In either mode, ceil(count / workgroupSize) must not exceed device.limits.maxComputeWorkgroupsPerDimension.
  • Auxiliary arrays are read-only and may have independent lengths. They do not participate in per-element capacity checks; auxiliary indexing bounds are the WGSL author's responsibility. Query their lengths with arrayLength(&weights).
  • count: 0 validates all resources, uniforms and options, then performs no encoding or submission. It neither consumes nor clears an existing encode-once guard.
  • New in 2.1.0: managed batches and typed kernel calls are documented from their src files; these additions extend the historical npm 2.0.0 audit baseline.

Fields & related types

NameTypeRequiredDefaultMeaning
countnumberNoFirst state/input buffer lengthInteger 0..0xffffffff. Limits invocation indices to [0, count); every state/input capacity must be at least count. Auxiliary arrays have independent bounds.

Examples

Independent auxiliary length and an explicit buffer prefix (new in 2.1.0)
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();

Source reference: src/core/kernel.ts

TYPESconstant

Runtime WGSL size, stride, alignment and typed-array metadata table.

TYPES: Record<ScalarKind, TypeDef>;

Behavior & constraints

  • TypeDef is a reachable declaration type, not a root named export. Do not mutate this shared runtime table.

Fields & related types

NameTypeRequiredDefaultMeaning
TypeDef.sizenumber——Logical byte size.
TypeDef.stridenumber——Storage-array byte stride.
TypeDef.alignnumber——Byte alignment.
TypeDef.compsnumber——Scalar component count.
TypeDef.typed'Float32Array' | 'Int32Array' | 'Uint32Array'——Expected typed-array constructor name.
TypeDef.wgslstring——WGSL type spelling.
f32{"size": 4, "stride": 4, "align": 4, "comps": 1, "typed": "Float32Array", "wgsl": "f32"}——Exact 2.0.0 table entry.
i32{"size": 4, "stride": 4, "align": 4, "comps": 1, "typed": "Int32Array", "wgsl": "i32"}——Exact 2.0.0 table entry.
u32{"size": 4, "stride": 4, "align": 4, "comps": 1, "typed": "Uint32Array", "wgsl": "u32"}——Exact 2.0.0 table entry.
vec2f{"size": 8, "stride": 8, "align": 8, "comps": 2, "typed": "Float32Array", "wgsl": "vec2f"}——Exact 2.0.0 table entry.
vec2i{"size": 8, "stride": 8, "align": 8, "comps": 2, "typed": "Int32Array", "wgsl": "vec2i"}——Exact 2.0.0 table entry.
vec2u{"size": 8, "stride": 8, "align": 8, "comps": 2, "typed": "Uint32Array", "wgsl": "vec2u"}——Exact 2.0.0 table entry.
vec3f{"size": 12, "stride": 16, "align": 16, "comps": 3, "typed": "Float32Array", "wgsl": "vec3f"}——Exact 2.0.0 table entry.
vec4f{"size": 16, "stride": 16, "align": 16, "comps": 4, "typed": "Float32Array", "wgsl": "vec4f"}——Exact 2.0.0 table entry.

Examples

Example
import { TYPES } from 'wgpu-kit';
console.log(TYPES.vec3f.size, TYPES.vec3f.stride); // 12, 16

Source reference: dist/core/layout.js

planUniformfunction

Compute ordered uniform offsets from WGSL alignment rules.

export declare function planUniform(
  entries: ReadonlyArray<readonly [string, ScalarKind]>,
): UniformLayout;

Parameters

NameTypeRequiredDefaultMeaning
entriesReadonlyArray<readonly [string, ScalarKind]>Yes—Ordered pairs of field name and kind. Empty input is valid; name/kind/duplicate validation is not performed here.

Returns

UniformLayout Field offsets and padded allocation size; not itself a root named export.

Errors & failure cases

  • An invalid runtime kind can cause a native TypeError because its TYPES entry is absent. Use the ScalarKind contract.

Fields & related types

NameTypeRequiredDefaultMeaning
fieldsreadonly UniformField[]——Ordered field metadata.
fields[].namestring——Field name.
fields[].kindScalarKind——Element kind.
fields[].offsetnumber——Byte offset aligned to the kind.
sizenumber——Total bytes rounded up to a multiple of 16; minimum 16.

Examples

Example
import { planUniform, packUniform, packUniformInto } from 'wgpu-kit';
const layout = planUniform([
  ['gain', 'f32'],
  ['origin', 'vec3f'],
]);
const values = { gain: 0.5, origin: { x: 1, y: 2, z: 3 } };
const bytes = packUniform(layout, values);
packUniformInto(bytes, layout, values);

Source reference: dist/core/layout.js

packUniformfunction

Allocate and pack an ArrayBuffer using little-endian scalar writes.

export declare function packUniform(
  layout: UniformLayout,
  values: Readonly<Record<string, UniformValue>>,
): ArrayBuffer;

Parameters

NameTypeRequiredDefaultMeaning
layoutUniformLayoutYes—Layout from planUniform or a compatible ordered field/offset/size object.
valuesReadonly<Record<string, UniformValue>>Yes—Values for every layout field. Extra keys are silently ignored; missing fields are errors.

Returns

ArrayBuffer New zero-initialized buffer of layout.size bytes with fields packed.

Errors & failure cases

  • ERR_UNIFORM_FIELD for missing values, non-finite scalar values or missing/invalid required vector components; ERR_UNIFORM_UNSUPPORTED for unsupported packing kinds.

Fields & related types

NameTypeRequiredDefaultMeaning
fieldsreadonly UniformField[]——Ordered field metadata.
fields[].namestring——Field name.
fields[].kindScalarKind——Element kind.
fields[].offsetnumber——Byte offset aligned to the kind.
sizenumber——Total bytes rounded up to a multiple of 16; minimum 16.

Examples

Example
import { planUniform, packUniform, packUniformInto } from 'wgpu-kit';
const layout = planUniform([
  ['gain', 'f32'],
  ['origin', 'vec3f'],
]);
const values = { gain: 0.5, origin: { x: 1, y: 2, z: 3 } };
const bytes = packUniform(layout, values);
packUniformInto(bytes, layout, values);

Source reference: dist/core/layout.js

packUniformIntofunction

Pack into caller-owned storage without allocating a new ArrayBuffer.

export declare function packUniformInto(
  target: ArrayBuffer,
  layout: UniformLayout,
  values: Readonly<
    Record<
      string,
      | number
      | Readonly<{
          x: number;
          y: number;
          z?: number;
          w?: number;
        }>
    >
  >,
): void;

Parameters

NameTypeRequiredDefaultMeaning
targetArrayBufferYes—Writable buffer large enough for every field write. Existing padding/unused bytes are not cleared.
layoutUniformLayoutYes—Layout from planUniform or a compatible ordered field/offset/size object.
valuesReadonly<Record<string, UniformValue>>Yes—Values for every layout field. Extra keys are silently ignored; missing fields are errors.

Returns

void Mutates target only.

Errors & failure cases

  • ERR_UNIFORM_FIELD for missing values, non-finite scalar values or missing/invalid required vector components; ERR_UNIFORM_UNSUPPORTED for unsupported packing kinds.
  • Native RangeError if a field write exceeds target capacity; target length is not prevalidated.

Examples

Example
import { planUniform, packUniform, packUniformInto } from 'wgpu-kit';
const layout = planUniform([
  ['gain', 'f32'],
  ['origin', 'vec3f'],
]);
const values = { gain: 0.5, origin: { x: 1, y: 2, z: 3 } };
const bytes = packUniform(layout, values);
packUniformInto(bytes, layout, values);

Source reference: dist/core/layout.js

ScalarKindtype

Supported scalar/vector storage and uniform kinds; name is historical and includes vectors.

export type ScalarKind =
  | 'f32'
  | 'i32'
  | 'u32'
  | 'vec2f'
  | 'vec2i'
  | 'vec2u'
  | 'vec3f'
  | 'vec4f';

Fields & related types

NameTypeRequiredDefaultMeaning
f32string literal——Supported kind.
i32string literal——Supported kind.
u32string literal——Supported kind.
vec2fstring literal——Supported kind.
vec2istring literal——Supported kind.
vec2ustring literal——Supported kind.
vec3fstring literal——Supported kind.
vec4fstring literal——Supported kind.

Examples

Example
import type { ScalarKind } from 'wgpu-kit';
const positionKind: ScalarKind = 'vec3f';

Source reference: dist/core/layout.js

UniformValuetype

Numeric scalar or component object used by uniform packing. z/w are optional at the TS union level but required when the selected kind needs them.

export type UniformValue =
  | number
  | Readonly<{
      x: number;
      y: number;
      z?: number;
      w?: number;
    }>;

Parameters

NameTypeRequiredDefaultMeaning
xnumberYes—Vector x component.
ynumberYes—Vector y component.
znumberNo—Required for vec3f/vec4f; otherwise ignored.
wnumberNo—Required for vec4f; otherwise ignored.

Behavior & constraints

  • Scalar numbers and required vector components must be finite. Integer packing uses DataView conversion rather than explicit range/integer validation.

Examples

Example
import type { UniformValue } from 'wgpu-kit';
const gain: UniformValue = 0.5;
const origin: UniformValue = { x: 1, y: 2, z: 3 };

Source reference: dist/core/layout.js

WgpuKitErrorclass

Base Error subclass with a stable machine-readable code.

export declare class WgpuKitError extends Error

Fields & related types

NameTypeRequiredDefaultMeaning
codereadonly ErrorCode——Stable string code. ErrorCode and ERR are not root named exports in 2.0.0; compare string literals.
namestring——Runtime subclass constructor name.
messagestring——Inherited Error message.
stackstring | undefined——Standard runtime Error stack, when available.
ERR_WGPU_UNAVAILABLEErrorCode string literal——Missing WebGPU or adapter.
ERR_COMPILEErrorCode string literal——WGSL compilation failure.
ERR_USAGEErrorCode string literal——Invalid usage/arguments.
ERR_UNIFORM_FIELDErrorCode string literal——Missing/invalid uniform field.
ERR_UNIFORM_UNSUPPORTEDErrorCode string literal——Unsupported uniform packing kind.
ERR_WORKGROUP_SIZEErrorCode string literal——Invalid workgroup size.
ERR_RESOURCE_MISSINGErrorCode string literal——Missing declared resource.
ERR_RESOURCE_TYPEErrorCode string literal——Resource kind mismatch.
ERR_RESOURCE_LENGTHErrorCode string literal——Resource lengths disagree.
ERR_BUFFER_CREATEErrorCode string literal——Invalid buffer kind/length.
ERR_BUFFER_WRITEErrorCode string literal——Invalid buffer data type/length.
ERR_MEDIAErrorCode string literal——Recording unavailable/failed.
ERR_TIMESTAMP_UNSUPPORTEDErrorCode string literal——timestamp-query unavailable.
ERR_GENERICErrorCode string literal——Other library error.

constructorconstructor

Create a coded library error.

new WgpuKitError(code: ErrorCode, message: string)

Parameters

NameTypeRequiredDefaultMeaning
code'ERR_WGPU_UNAVAILABLE' | 'ERR_COMPILE' | 'ERR_USAGE' | 'ERR_UNIFORM_FIELD' | 'ERR_UNIFORM_UNSUPPORTED' | 'ERR_WORKGROUP_SIZE' | 'ERR_RESOURCE_MISSING' | 'ERR_RESOURCE_TYPE' | 'ERR_RESOURCE_LENGTH' | 'ERR_BUFFER_CREATE' | 'ERR_BUFFER_WRITE' | 'ERR_MEDIA' | 'ERR_TIMESTAMP_UNSUPPORTED' | 'ERR_GENERIC'Yes—Stable code from the declaration union.
messagestringYes—Human-readable message.

Returns

WgpuKitError New error instance; constructing does not throw it automatically.

Examples

Example
import { WgpuKitError } from 'wgpu-kit';
const error = new WgpuKitError('ERR_USAGE', 'Invalid input');

Examples

Example
import { Buffer, WgpuKitError } from 'wgpu-kit';
try {
  await Buffer.create('f32', 0);
} catch (error) {
  if (error instanceof WgpuKitError) console.log(error.code, error.message);
}

Source reference: dist/core/errors.js

WebGPUUnavailableErrorclass

Unavailable-device error with code ERR_WGPU_UNAVAILABLE.

export declare class WebGPUUnavailableError extends WgpuKitError

Fields & related types

NameTypeRequiredDefaultMeaning
code'ERR_WGPU_UNAVAILABLE'——Inherited stable code.

constructorconstructor

Prefix the reason with WebGPU availability context and built-in diagnostic suggestions.

new WebGPUUnavailableError(reason: string)

Parameters

NameTypeRequiredDefaultMeaning
reasonstringYes—Specific missing capability or adapter/context reason.

Returns

WebGPUUnavailableError New error instance; constructing does not throw it automatically.

Examples

Example
import { WebGPUUnavailableError } from 'wgpu-kit';
const error = new WebGPUUnavailableError('No adapter');

Examples

Example
import { Buffer, WgpuKitError } from 'wgpu-kit';
try {
  await Buffer.create('f32', 0);
} catch (error) {
  if (error instanceof WgpuKitError) console.log(error.code, error.message);
}

Source reference: dist/core/errors.js

CompileErrorclass

WGSL compilation error with user-relative diagnostic lines and code ERR_COMPILE.

export declare class CompileError extends WgpuKitError

Fields & related types

NameTypeRequiredDefaultMeaning
code'ERR_COMPILE'——Inherited stable code.
messages[].linenumber——1-based shader line before subtracting userCodeOffset.
messages[].msgstring——Compiler message.

constructorconstructor

Format WGSL diagnostics and map generated lines back to user code.

new CompileError(
  kernelName: string,
  messages: readonly { line:number; msg:string }[],
  userCodeOffset: number
)

Parameters

NameTypeRequiredDefaultMeaning
kernelNamestringYes—Diagnostic kernel name.
messagesreadonly {line:number;msg:string}[]Yes—Compilation diagnostics; line is a 1-based generated-source line and msg is text.
userCodeOffsetnumberYes—Number of generated lines before user code. A mapped line <=0 is described as generated code. rawKernel uses 0.

Returns

CompileError New error instance; constructing does not throw it automatically.

Examples

Example
import { CompileError } from 'wgpu-kit';
const error = new CompileError('demo', [{ line: 14, msg: 'unknown identifier' }], 10);

Examples

Example
import { elementKernel, CompileError } from 'wgpu-kit';
const k = elementKernel({
  state: { x: 'f32' },
  code: 'fn userFn(i:u32){x[i]=missing;}',
});
try {
  await k.prepare();
} catch (error) {
  if (error instanceof CompileError) console.log(error.message);
}
k.destroy();

Source reference: dist/core/errors.js

UsageErrorclass

Coded caller-usage error. Constructor accepts any ErrorCode in the declared union.

export declare class UsageError extends WgpuKitError

Fields & related types

NameTypeRequiredDefaultMeaning
codereadonly ErrorCode——Supplied stable code.

constructorconstructor

Create an error retaining the supplied code/message.

new UsageError(code: ErrorCode, message: string)

Parameters

NameTypeRequiredDefaultMeaning
code'ERR_WGPU_UNAVAILABLE' | 'ERR_COMPILE' | 'ERR_USAGE' | 'ERR_UNIFORM_FIELD' | 'ERR_UNIFORM_UNSUPPORTED' | 'ERR_WORKGROUP_SIZE' | 'ERR_RESOURCE_MISSING' | 'ERR_RESOURCE_TYPE' | 'ERR_RESOURCE_LENGTH' | 'ERR_BUFFER_CREATE' | 'ERR_BUFFER_WRITE' | 'ERR_MEDIA' | 'ERR_TIMESTAMP_UNSUPPORTED' | 'ERR_GENERIC'Yes—Stable error-code literal.
messagestringYes—Specific usage problem.

Returns

UsageError New error instance; constructing does not throw it automatically.

Examples

Example
import { UsageError } from 'wgpu-kit';
const error = new UsageError('ERR_RESOURCE_LENGTH', 'Buffers must have equal length');

Examples

Example
import { Buffer, WgpuKitError } from 'wgpu-kit';
try {
  await Buffer.create('f32', 0);
} catch (error) {
  if (error instanceof WgpuKitError) console.log(error.code, error.message);
}

Source reference: dist/core/errors.js

listPacksfunction

Enumerate built-in definitions followed by user registrations.

export declare function listPacks(): Array<{
  name: string;
  description: string;
}>;

Parameters

This call takes no arguments.

Returns

Array<{name:string;description:string}> Metadata only; missing descriptions become empty strings.

Behavior & constraints

  • The 2.0.0 built-in registry contains particles. Listing does not create simulations or allocate GPU resources.

Examples

Example
import { listPacks } from 'wgpu-kit';
console.log(listPacks());

Source reference: dist/index.js

getPackfunction

Look up a built-in first, then the user registry.

export declare function getPack<TConfig = unknown>(
  name: string,
): WgpuKitPack<TConfig, PackSim> | undefined;

Parameters

NameTypeRequiredDefaultMeaning
namestringYes—Exact, case-sensitive registered name.

Returns

WgpuKitPack<TConfig, PackSim> | undefined Definition if found, otherwise undefined. TConfig defaults to unknown at compile time.

Behavior & constraints

  • The generic is a caller-supplied type assertion; lookup does not validate configuration or create the simulation.

Examples

Example
import { definePack, registerPack, getPack, listPacks } from 'wgpu-kit';
const pack = definePack({
  name: 'counter-demo',
  description: 'A lifecycle example',
  async create(config?: { start?: number }) {
    let value = config?.start ?? 0;
    return {
      tick() {
        value++;
      },
      stats() {
        return { value };
      },
      destroy() {},
    };
  },
});
registerPack(pack);
const sim = await getPack<{ start?: number }>('counter-demo')!.create({ start: 3 });
sim.tick();
console.log(sim.stats?.(), listPacks());
sim.destroy();

Source reference: dist/index.js

Search concepts, APIs, and examples