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 GpuContextBehavior & 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
device | readonly GPUDevice | — | — | Native shared device. |
adapterInfo | readonly string | — | — | Diagnostic vendor/architecture/description string; adopted device may use "adopted device". |
lost | readonly 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
device | GPUDevice | Yes | — | 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
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
import { GpuContext } from 'wgpu-kit';
GpuContext.resetForTests(); // isolated test/recovery setup onlysyncmethod
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
kind | readonly K | — | — | Chosen element kind. |
length | readonly number | — | — | Number of elements. |
gpuBuffer | readonly GPUBuffer | — | — | Native handle with STORAGE | COPY_SRC | COPY_DST usage only. |
NumArray | Float32Array<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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
kind | K extends ScalarKind | Yes | — | Element kind; selects WGSL type, scalar representation and storage stride. |
length | number | Yes | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
data | Float32Array<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
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
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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
spec | ElementKernelSpec | Yes | — | 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
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();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();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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
encoder | GPUCommandEncoder | Yes | — | Readonly encoder owned by this scope; append work while open. |
status | 'open' | 'submitted' | 'cancelled' | Yes | open | Readonly 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
spec | S extends ElementKernelSpec | Yes | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
count | number | No | First state/input buffer length | Integer 0..0xffffffff. Limits invocation indices to [0, count); every state/input capacity must be at least count. Auxiliary arrays have independent bounds. |
batch | ComputeBatch | No | — | 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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. |
names | readonly 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
kinds | Record<K, ScalarKind> | Yes | — | Non-empty field-name to element-kind map. |
length | number | Yes | — | 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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
batch | ComputeBatch | Yes | — | 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]> }) => undefined | Yes | — | 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
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
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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
code | string | Yes | — | Complete non-empty WGSL module. |
entryPoint | string | No | main | Compute entrypoint name. |
label | string | No | rawKernel | Diagnostic 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
encoder | GPUCommandEncoder | Yes | — | Caller-owned encoder from the same device; this API records work without submitting it. |
entries | GPUBindGroupEntry[] | Yes | — | Native entries for bind group 0 matching the shader auto layout; resources must come from the shared device. |
workgroups | number | Yes | — | Positive integer X workgroup count; Y and Z remain 1. Must fit device dispatch limits. |
Returns
void No return value.
Examples
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
entries | GPUBindGroupEntry[] | Yes | — | Native entries for bind group 0 matching the shader auto layout; resources must come from the shared device. |
workgroups | number | Yes | — | 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
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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
fields | F 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
raw | readonly Buffer<K> | — | — | Escape hatch for flat typed-array uploads/readback and gpuBuffer access. |
kind | readonly K | — | — | Element kind. |
length | readonly 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
kind | K extends ScalarKind | Yes | — | Element kind; selects WGSL type, scalar representation and storage stride. |
length | number | Yes | — | Positive integer number of elements, not scalar components or bytes. |
Returns
Promise<TypedBuffer<K>> Typed row buffer.
Examples
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
rows | ReadonlyArray<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
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
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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
F | Record<string, ScalarKind> | — | — | Generic field map. |
fields | readonly 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
name | string | Yes | — | Struct identifier matching /^[A-Za-z][A-Za-z0-9_]*$/. WGSL reserved-word validity is left to compilation. |
addressSpace | 'storage' | 'uniform' | No | storage | Select 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
count | number | Yes | — | Positive integer number of rows in every field. |
Returns
Promise<SchemaBuffers<F>> Field buffers plus raws() and destroy().
Examples
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
[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
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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
F | Record<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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
f32 | i32 | u32 | number | — | — | Scalar kinds. |
vec2f | vec2i | vec2u | Vec2 | — | — | Two numeric components. |
vec3f | Vec3 | — | — | Three numeric components. |
vec4f | Vec4 | — | — | Four numeric components. |
Examples
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 Vec2Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
x | number | Yes | — | x component. |
y | number | Yes | — | y component. |
Examples
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 Vec3Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
x | number | Yes | — | x component. |
y | number | Yes | — | y component. |
z | number | Yes | — | z component. |
Examples
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 Vec4Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
x | number | Yes | — | x component. |
y | number | Yes | — | y component. |
z | number | Yes | — | z component. |
w | number | Yes | — | w component. |
Examples
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
pack | WgpuKitPack<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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
pack | WgpuKitPack<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
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 PackSimattachmethod
Optional rendering attachment hook.
attach?(canvas: HTMLCanvasElement): Promise<void>;Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
canvas | HTMLCanvasElement | Yes | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
TConfig | generic type parameter | — | — | Configuration type; required at type-definition use. |
TSim | extends PackSim = PackSim | — | — | Simulation type; defaults to PackSim. |
name | readonly string | — | — | Registry namespace name. |
description | readonly 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
config | TConfig | No | — | Optional pack-specific configuration; no default imposed by this interface. |
Returns
Promise<TSim> Pack-specific simulation implementing PackSim.
Examples
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
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();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 ScanBehavior & 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
encoder | GPUCommandEncoder | Yes | — | Caller-owned encoder from the same device; this API records work without submitting it. |
src | GPUBuffer | Yes | — | Read-only u32 storage input. |
dst | GPUBuffer | Yes | — | Separate writable u32 storage output. |
count | number | Yes | — | Non-negative integer number of u32 values to process; must not exceed source/destination capacity where applicable. |
exclusive | boolean | No | true | true: dst[i]=sum(src[0..i)); false: dst[i]=sum(src[0..i]). |
batch | ComputeBatch | No | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
src | Buffer | Yes | — | Source Buffer; caller must supply kind u32. |
dst | Buffer | Yes | — | Separate destination Buffer; caller must supply kind u32. |
count | number | Yes | — | Non-negative integer number of u32 values to process; must not exceed source/destination capacity where applicable. |
exclusive | boolean | No | true | true: 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
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
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
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
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
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
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();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 ReduceBehavior & 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
encoder | GPUCommandEncoder | Yes | — | Caller-owned encoder from the same device; this API records work without submitting it. |
src | GPUBuffer | Yes | — | Read-only u32 storage input. |
count | number | Yes | — | Non-negative integer number of u32 values to process; must not exceed source/destination capacity where applicable. |
dst | GPUBuffer | Yes | — | Writable storage buffer whose first u32 is treated as atomic<u32> by the shader. |
batch | ComputeBatch | No | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
src | Buffer | Yes | — | Source Buffer interpreted as u32. |
count | number | Yes | — | 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
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
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
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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
config | ParticlesConfig | No | {} | 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
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 ParticlesSimFields & related types
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
count | number | Yes | — | 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. |
forces | ForceMatrix | Yes | — | 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. |
seed | string | Yes | — | String(seed), retained from initialization. |
rMax | number | Yes | — | Maximum interaction radius in world units. Use a finite positive number. Also affects grid resolution. |
beta | number | Yes | — | Piecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API. |
forceFactor | number | Yes | — | Acceleration scale: summed interactions are multiplied by forceFactor*rMax before integration. |
frictionHalfLife | number | Yes | — | 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. |
dt | number | Yes | — | Base simulation time step per tick, multiplied by the tick argument. The animation callback elapsed time is not measured automatically. |
pointSize | number | Yes | — | 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. |
maxNeighbors | number | Yes | — | Grid-only candidate budget: ceil(maxNeighbors/9) candidates per each of up to 9 neighboring cells (self may count). Use a finite positive number. |
forcesName | string | Yes | — | Selected literal force name, or 'custom'; updated by setForces(). |
seedHash | number | Yes | — | 32-bit hash of the normalized seed string. |
friction | number | Yes | — | 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
canvas | HTMLCanvasElement | Yes | — | 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
dtMultiplier | number | No | 1 | Multiplier 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
forces | ForcePresetName | 'random' | ForceMatrix | Yes | — | 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
params | { rMax?: number; beta?: number; forceFactor?: number; frictionHalfLife?: number; dt?: number } | Yes | — | Partial physics update; all nested fields are optional. |
params.rMax | number | No | unchanged when omitted | Maximum interaction radius in world units. Use a finite positive number. Also affects grid resolution. |
params.beta | number | No | unchanged when omitted | Piecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API. |
params.forceFactor | number | No | unchanged when omitted | Acceleration scale: summed interactions are multiplied by forceFactor*rMax before integration. |
params.frictionHalfLife | number | No | unchanged when omitted | 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. |
params.dt | number | No | unchanged when omitted | Base 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
fps | number | — | — | Ticks per elapsed wall-clock second, not GPU kernel duration or a benchmark score. Long pauses can affect the next sample. |
gpuErrors | number | — | — | 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
partial | Buffer (vec2f, count*9) | — | — | Per-particle per-neighbor-cell partial force contributions. |
start | Buffer (u32, cells) | — | — | Inclusive starting slot for each cell. |
fill | Buffer (u32, cells) | — | — | Exclusive end slot after scatter, not raw occupancy count. |
sortedPos | Buffer (vec2f, count) | — | — | Position copy grouped by cell. |
sortedSp | Buffer (u32, count) | — | — | Species indices grouped by cell. |
order | Buffer (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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
pos | Buffer (vec2f) | — | — | Current 2D world positions. |
vel | Buffer (vec2f) | — | — | Current 2D velocities. |
species | Buffer (u32) | — | — | Species labels 0..3, independent of ping-pong state. |
Examples
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 ElementKernelBehavior & 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
name | readonly string | — | — | Diagnostic name. |
source | readonly string | — | — | Complete generated WGSL, including declarations and entrypoint. |
uniformLayout | readonly UniformLayout | — | — | Ordered fields with byte offsets and padded byte size. UniformLayout is reachable but not a root named export. |
workgroupSize | readonly 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
resources | Record<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. |
uniforms | Record<string, UniformValue> | No | {} | Values for all declared uniforms. Vectors are {x,y,z,w} objects with components required by their kind. |
options | ElementKernelDispatchOptions | No | {} | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
encoder | GPUCommandEncoder | Yes | — | Unfinished encoder from the shared device with no active pass. With options.batch this must be batch.encoder; batch.submit() owns finishing/submission. |
resources | Record<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. |
uniforms | Record<string, UniformValue> | No | {} | Values for all declared uniforms. Vectors are {x,y,z,w} objects with components required by their kind. |
options | ElementKernelEncodeOptions | No | {} | 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
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
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
code | string | Yes | — | 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
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
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
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();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();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 ElementKernelSpecParameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
name | string | No | kernel | Diagnostic kernel label. |
state | Record<string, ScalarKind> | No | {} | Read-write storage arrays, accessed by their field names in WGSL. |
inputs | Record<string, ScalarKind> | No | {} | Read-only storage arrays. At least one state or inputs field is required overall. |
auxInputs | Record<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. |
uniforms | Record<string, ScalarKind> | No | {} | Uniform declarations; insertion order must match userFn parameters after the element index. |
workgroupSize | number | No | 64 | Integer 1..512 accepted by the library; actual device limits may be stricter. |
code | string | Yes | — | 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
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();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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
count | number | No | First state/input buffer length | Integer 0..0xffffffff. Limits invocation indices to [0, count); every state/input capacity must be at least count. Auxiliary arrays have independent bounds. |
Examples
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
TypeDef.size | number | — | — | Logical byte size. |
TypeDef.stride | number | — | — | Storage-array byte stride. |
TypeDef.align | number | — | — | Byte alignment. |
TypeDef.comps | number | — | — | Scalar component count. |
TypeDef.typed | 'Float32Array' | 'Int32Array' | 'Uint32Array' | — | — | Expected typed-array constructor name. |
TypeDef.wgsl | string | — | — | 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
import { TYPES } from 'wgpu-kit';
console.log(TYPES.vec3f.size, TYPES.vec3f.stride); // 12, 16Source 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
entries | ReadonlyArray<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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
fields | readonly UniformField[] | — | — | Ordered field metadata. |
fields[].name | string | — | — | Field name. |
fields[].kind | ScalarKind | — | — | Element kind. |
fields[].offset | number | — | — | Byte offset aligned to the kind. |
size | number | — | — | Total bytes rounded up to a multiple of 16; minimum 16. |
Examples
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
layout | UniformLayout | Yes | — | Layout from planUniform or a compatible ordered field/offset/size object. |
values | Readonly<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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
fields | readonly UniformField[] | — | — | Ordered field metadata. |
fields[].name | string | — | — | Field name. |
fields[].kind | ScalarKind | — | — | Element kind. |
fields[].offset | number | — | — | Byte offset aligned to the kind. |
size | number | — | — | Total bytes rounded up to a multiple of 16; minimum 16. |
Examples
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
target | ArrayBuffer | Yes | — | Writable buffer large enough for every field write. Existing padding/unused bytes are not cleared. |
layout | UniformLayout | Yes | — | Layout from planUniform or a compatible ordered field/offset/size object. |
values | Readonly<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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
f32 | string literal | — | — | Supported kind. |
i32 | string literal | — | — | Supported kind. |
u32 | string literal | — | — | Supported kind. |
vec2f | string literal | — | — | Supported kind. |
vec2i | string literal | — | — | Supported kind. |
vec2u | string literal | — | — | Supported kind. |
vec3f | string literal | — | — | Supported kind. |
vec4f | string literal | — | — | Supported kind. |
Examples
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
x | number | Yes | — | Vector x component. |
y | number | Yes | — | Vector y component. |
z | number | No | — | Required for vec3f/vec4f; otherwise ignored. |
w | number | No | — | 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
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 ErrorFields & related types
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
code | readonly ErrorCode | — | — | Stable string code. ErrorCode and ERR are not root named exports in 2.0.0; compare string literals. |
name | string | — | — | Runtime subclass constructor name. |
message | string | — | — | Inherited Error message. |
stack | string | undefined | — | — | Standard runtime Error stack, when available. |
ERR_WGPU_UNAVAILABLE | ErrorCode string literal | — | — | Missing WebGPU or adapter. |
ERR_COMPILE | ErrorCode string literal | — | — | WGSL compilation failure. |
ERR_USAGE | ErrorCode string literal | — | — | Invalid usage/arguments. |
ERR_UNIFORM_FIELD | ErrorCode string literal | — | — | Missing/invalid uniform field. |
ERR_UNIFORM_UNSUPPORTED | ErrorCode string literal | — | — | Unsupported uniform packing kind. |
ERR_WORKGROUP_SIZE | ErrorCode string literal | — | — | Invalid workgroup size. |
ERR_RESOURCE_MISSING | ErrorCode string literal | — | — | Missing declared resource. |
ERR_RESOURCE_TYPE | ErrorCode string literal | — | — | Resource kind mismatch. |
ERR_RESOURCE_LENGTH | ErrorCode string literal | — | — | Resource lengths disagree. |
ERR_BUFFER_CREATE | ErrorCode string literal | — | — | Invalid buffer kind/length. |
ERR_BUFFER_WRITE | ErrorCode string literal | — | — | Invalid buffer data type/length. |
ERR_MEDIA | ErrorCode string literal | — | — | Recording unavailable/failed. |
ERR_TIMESTAMP_UNSUPPORTED | ErrorCode string literal | — | — | timestamp-query unavailable. |
ERR_GENERIC | ErrorCode string literal | — | — | Other library error. |
constructorconstructor
Create a coded library error.
new WgpuKitError(code: ErrorCode, message: string)Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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. |
message | string | Yes | — | Human-readable message. |
Returns
WgpuKitError New error instance; constructing does not throw it automatically.
Examples
import { WgpuKitError } from 'wgpu-kit';
const error = new WgpuKitError('ERR_USAGE', 'Invalid input');Examples
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 WgpuKitErrorFields & related types
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
code | 'ERR_COMPILE' | — | — | Inherited stable code. |
messages[].line | number | — | — | 1-based shader line before subtracting userCodeOffset. |
messages[].msg | string | — | — | 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
kernelName | string | Yes | — | Diagnostic kernel name. |
messages | readonly {line:number;msg:string}[] | Yes | — | Compilation diagnostics; line is a 1-based generated-source line and msg is text. |
userCodeOffset | number | Yes | — | 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
import { CompileError } from 'wgpu-kit';
const error = new CompileError('demo', [{ line: 14, msg: 'unknown identifier' }], 10);Examples
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 WgpuKitErrorFields & related types
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
code | readonly ErrorCode | — | — | Supplied stable code. |
constructorconstructor
Create an error retaining the supplied code/message.
new UsageError(code: ErrorCode, message: string)Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
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. |
message | string | Yes | — | Specific usage problem. |
Returns
UsageError New error instance; constructing does not throw it automatically.
Examples
import { UsageError } from 'wgpu-kit';
const error = new UsageError('ERR_RESOURCE_LENGTH', 'Buffers must have equal length');Examples
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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
name | string | Yes | — | 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
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
计算、缓冲区、组合执行、类型化 schema、扩展包契约与诊断。
辅助输入、dispatch count、托管批次与类型化内核已随 2.1.0 发布。原 API 仍以 npm 2.0.0 声明与实现为历史核对基线;2.1.0 和 2.2.0 新增能力在对应 API 中注明并引用 src 文件,不代表整份 API 重新审计。只列出此入口实际导出的公开 API。
GpuContextclass
共享且延迟创建的 WebGPU 设备上下文。通过 get() 或 adopt() 获取;构造函数为私有。
export declare class GpuContext行为与约束
- get() 优先请求高性能适配器;只有首次返回 null 才请求回退适配器。它请求受支持的存储限制,并在可用时启用 timestamp-query。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
device | readonly GPUDevice | — | — | 原生共享设备。 |
adapterInfo | readonly string | — | — | 诊断用厂商、架构、描述字符串;接管设备时可能为 "adopted device"。 |
lost | readonly Promise<GPUDeviceLostInfo> | — | — | 直接返回 device.lost;设备丢失时兑现并给出信息,声明注释中所写的 reject 不准确。 |
getmethod
获取或创建库的单例。创建失败会清除缓存,允许之后重试。
static get(): Promise<GpuContext>;参数
此调用不接收参数。
返回值
Promise<GpuContext> 共享上下文。
错误与失败情况
- 缺少 navigator.gpu 或无法获取适配器时抛出 WebGPUUnavailableError / ERR_WGPU_UNAVAILABLE;适配器或设备请求失败也可能导致拒绝。
示例
import { GpuContext } from 'wgpu-kit';
const ctx = await GpuContext.get();
await ctx.sync();adoptmethod
在任何 get() 调用之前,将已有设备设为共享上下文。
static adopt(device: GPUDevice): GpuContext;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
device | GPUDevice | 是 | — | 所有库资源使用的已有设备。 |
返回值
GpuContext 包装同一设备的上下文,不复制设备。
错误与失败情况
- 单例已存在(包括尚未完成的 get())时抛出 WebGPUUnavailableError。
示例
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
只清除单例引用;用于测试或设备恢复集成。
static resetForTests(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 不会销毁旧设备,也不会迁移已有资源;不要用它切换正在使用的资源图。
示例
import { GpuContext } from 'wgpu-kit';
GpuContext.resetForTests(); // isolated test/recovery setup onlysyncmethod
等待队列中已提交的工作完成。
sync(): Promise<void>;参数
此调用不接收参数。
返回值
Promise<void> 在 device.queue.onSubmittedWorkDone() 完成后兑现。
示例
import { GpuContext } from 'wgpu-kit';
await (await GpuContext.get()).sync();源码参考: dist/core/context.js
Bufferclass
带上传校验与 staging 读回的类型化存储缓冲区封装。
export declare class Buffer<K extends ScalarKind = ScalarKind>行为与约束
- 不会添加 VERTEX、INDEX、UNIFORM 或 MAP 用途。无读回渲染可在原生渲染着色器中将 gpuBuffer 作为 storage 读取。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
kind | readonly K | — | — | 选定的元素类型。 |
length | readonly number | — | — | 元素数量。 |
gpuBuffer | readonly GPUBuffer | — | — | 原生句柄,仅包含 STORAGE | COPY_SRC | COPY_DST 用途。 |
NumArray | Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | — | — | 签名关联类型,不是根入口具名导出。浮点类型使用 Float32Array,有符号整数使用 Int32Array,无符号整数使用 Uint32Array。 |
createmethod
在共享设备上分配 length × TYPES[kind].stride 字节。
static create<K extends ScalarKind>(kind: K, length: number): Promise<Buffer<K>>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
kind | K extends ScalarKind | 是 | — | 元素类型,决定 WGSL 类型、标量表示与存储步长。 |
length | number | 是 | — | 正整数元素数量,不是标量分量数或字节数。 |
返回值
Promise<Buffer<K>> 新的类型化 GPU 缓冲区。
错误与失败情况
- 未知 kind、非正数或非整数 length 会抛出 UsageError / ERR_BUFFER_CREATE;设备限制也可能导致 GPU 分配失败。
示例
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
上传整个缓冲区。vec3f 输入为紧密排列,内部自动补齐为 16 字节存储步长。
write(data: NumArray): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
data | Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | 是 | — | 匹配类型的 TypedArray,必须恰好包含 length × 分量数个值;无 offset 或局部写入重载。 |
返回值
void 无返回值。
错误与失败情况
- TypedArray 构造类型或分量数错误时抛出 UsageError / ERR_BUFFER_WRITE;Buffer.write 不检查浮点内容是否有限。
示例
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
复制到缓存的 staging 缓冲区、映射并复制到新的 TypedArray 后解除映射;去除 vec3f 填充。并发 read 共享进行中的读回。
read(): Promise<NumArray>;参数
此调用不接收参数。
返回值
Promise<Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer>> CPU 拥有的紧密排列标量分量。
示例
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
销毁存储缓冲区及已分配的 staging 缓冲区。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();源码参考: dist/core/buffer.js
elementKernelfunction
生成并管理每元素一次调用的计算内核。创建本身同步;GPU 准备延迟进行。
export declare function elementKernel(spec: ElementKernelSpec): ElementKernel;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
spec | ElementKernelSpec | 是 | — | 内核资源声明、uniform 与 WGSL 函数。 |
返回值
ElementKernel 可延迟准备的内核控制器。
行为与约束
- 2.1.0 新增:auxInputs、options.count 与 ElementKernelDispatchOptions 依据 src/core/kernel.ts 和 src/index.ts 记录,在 npm 2.0.0 历史审计基线之上扩展。
- 所有声明的 state/input/auxInputs 缓冲必须存在且类型匹配,包括静态未使用的字段。参与绑定的资源须属于共享设备。额外资源/uniform 键被忽略。
- 省略 options.count 时,state 与 inputs 必须等长,调用数量取首个此类缓冲长度。至少需要一个 state 或 inputs 字段;auxInputs 不参与数量推导。
- 显式 count 须为 0..0xffffffff 内的整数。state/input 可不同长,但每个缓冲都必须至少容纳 count 个元素。两种模式下,ceil(count / workgroupSize) 均不得超过 device.limits.maxComputeWorkgroupsPerDimension。
- 辅助数组只读且长度独立,不参与逐元素容量校验;辅助索引边界由 WGSL 作者负责。可用 arrayLength(&weights) 查询长度。
- count: 0 完整校验全部资源、uniform 与选项后,不编码、不提交,也不消耗或清除已有的 encode-once 检查状态。
- 字段名在 state、inputs、auxInputs、uniforms 之间必须唯一。uniform 名 count 为保留名称,由库自动注入。应使用有效 WGSL 标识符,保留字由编译器检查。
- 不要在同一 dispatch 中读取正在被并行写入的缓冲区邻居元素;应使用分离的输入/输出或 PingPong。库不提供 dispatch 内的全局同步。
- 生成源码使用词法资源使用分析;局部变量遮蔽资源名是已知分析限制。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
错误与失败情况
- 构造时:非法工作组大小为 ERR_WORKGROUP_SIZE;无数组为 ERR_RESOURCE_MISSING;空代码、重名或保留 count uniform 为 ERR_USAGE。
- 准备/替换时:CompileError / ERR_COMPILE 报告映射到用户代码行号的 WGSL 错误;也可能发生原生 WebGPU 校验或设备错误。
示例
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();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();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();源码参考: src/core/kernel.ts
createBatchfunction
创建 open 的托管计算提交作用域。2.1.0 新增。
createBatch(): Promise<ComputeBatch>;参数
此调用不接收参数。
返回值
Promise<ComputeBatch> 共享设备上的新批次,具有只读 encoder 与 status;不会替你准备内核。
行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
- 批次拥有 encoder 的结束与提交权:请勿自行对 batch.encoder 调用 finish() 或 device.queue.submit()。仅在 open 时追加原生 pass,且托管助手须在没有打开 pass 时调用。
- 每次托管 dispatch 获得独立对齐参数区间及所需私有 scratch。资源按设备池化,保留内存有上限;已提交分配仅在 GPU 完成后回收。调用方 storage 输出仍共享。
- 取消丢弃已编码命令与托管分配,不回滚外部 CPU 写入、此前提交或 PingPong.swap()。
示例
import { createBatch } from 'wgpu-kit';
const batch = await createBatch();
console.log(batch.status); // 'open'
batch.cancel();
batch.cancel(); // idempotent
console.log(batch.status); // 'cancelled'源码参考: src/core/batch.ts
ComputeBatchinterface
createBatch() 返回的托管提交生命周期。2.1.0 新增。
export interface ComputeBatch {
readonly encoder: GPUCommandEncoder;
readonly status: 'open' | 'submitted' | 'cancelled';
submit(): void;
cancel(): void;
}行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
- 批次拥有 encoder 的结束与提交权:请勿自行对 batch.encoder 调用 finish() 或 device.queue.submit()。仅在 open 时追加原生 pass,且托管助手须在没有打开 pass 时调用。
- submit/cancel 后继续编码或提交抛 UsageError;对已提交批次调用 cancel() 抛 UsageError;对已取消批次重复 cancel() 幂等。
- 取消丢弃已编码命令与托管分配,不回滚外部 CPU 写入、此前提交或 PingPong.swap()。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
encoder | GPUCommandEncoder | 是 | — | 此作用域拥有的只读 encoder;open 时追加任务。 |
status | 'open' | 'submitted' | 'cancelled' | 是 | open | 只读状态;初始 open,经 submit/cancel 后永久关闭。 |
submitmethod
结束并提交 open 批次一次;返回时不保证 GPU 已完成。
submit(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 批次拥有 encoder 的结束与提交权:请勿自行对 batch.encoder 调用 finish() 或 device.queue.submit()。仅在 open 时追加原生 pass,且托管助手须在没有打开 pass 时调用。
- 每次托管 dispatch 获得独立对齐参数区间及所需私有 scratch。资源按设备池化,保留内存有上限;已提交分配仅在 GPU 完成后回收。调用方 storage 输出仍共享。
错误与失败情况
- submit/cancel 后继续编码或提交抛 UsageError;对已提交批次调用 cancel() 抛 UsageError;对已取消批次重复 cancel() 幂等。
cancelmethod
丢弃 open 批次;重复取消幂等。
cancel(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 取消丢弃已编码命令与托管分配,不回滚外部 CPU 写入、此前提交或 PingPong.swap()。
错误与失败情况
- submit/cancel 后继续编码或提交抛 UsageError;对已提交批次调用 cancel() 抛 UsageError;对已取消批次重复 cancel() 幂等。
源码参考: src/core/batch.ts
typedElementKernelfunction
可选类型化工厂,从字面量 spec 推导精确资源名/kind 与 uniform 值。2.1.0 新增。
typedElementKernel<const S extends ElementKernelSpec>(spec: S): TypedElementKernel<S>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
spec | S extends ElementKernelSpec | 是 | — | 运行时描述符与 elementKernel 相同;内联字段或单独保存时用 as const 保留 kind 字面量。 |
返回值
TypedElementKernel<S> 保留 ElementKernel 生命周期,并推导 run/encode 调用参数。
行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
- 推导所有 state/input/auxInputs 名称与 Buffer kind;uniform 标量/向量遵循 KindOf,声明了 uniform 时调用必须提供。TypedElementKernelResources<S> 与 TypedElementKernelUniforms<S> 暴露映射。
- 此可选接口不收紧原 elementKernel 或宽泛 Record 调用,也不检查 WGSL 函数体。运行与校验复用 elementKernel。
示例
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();源码参考: src/core/typed-kernel.ts
TypedElementKerneltype alias
从 spec 推导资源/uniform 调用参数的 ElementKernel 控制器。DispatchArguments 是内部条件元组:声明 uniform 时必传,否则可省略。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;
};行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
- 省略 options.batch 的原生路径:每实例每次提交只能进行一次非零 encode,提交后调用 endSubmit()。使用 options.batch 时传入 batch.encoder,且只能通过 batch.submit() 提交;每次编码都有独立 uniform 快照,支持重复调用,原生闸状态保持不变。
源码参考: src/core/typed-kernel.ts
TypedElementKernelResourcestype alias
内部 ResourceFields<S> 合并 state、inputs、auxInputs;此公开映射保留资源名与 Buffer kind。2.1.0 新增。
export type TypedElementKernelResources<S extends ElementKernelSpec> = {
readonly [K in keyof ResourceFields<S>]: Buffer<ResourceFields<S>[K] & ScalarKind>;
};行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
源码参考: src/core/typed-kernel.ts
TypedElementKernelUniformstype alias
将 spec.uniforms 映射为标量 number 或 Vec2/Vec3/Vec4 对象。Fields 是内部声明助手,不检查 WGSL 函数体。2.1.0 新增。
export type TypedElementKernelUniforms<S extends ElementKernelSpec> = {
readonly [K in keyof Fields<S, 'uniforms'>]: KindOf<
Fields<S, 'uniforms'>[K] & ScalarKind
>;
};行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
源码参考: src/core/typed-kernel.ts
ElementKernelEncodeOptionsinterface
仅 encode 接收的选项:可选 count 与托管 batch。run() 保留 ElementKernelDispatchOptions,不接收 batch。2.1.0 新增。
export interface ElementKernelEncodeOptions extends ElementKernelDispatchOptions {
batch?: ComputeBatch;
}行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
- 省略 options.batch 的原生路径:每实例每次提交只能进行一次非零 encode,提交后调用 endSubmit()。使用 options.batch 时传入 batch.encoder,且只能通过 batch.submit() 提交;每次编码都有独立 uniform 快照,支持重复调用,原生闸状态保持不变。
- 批次拥有 encoder 的结束与提交权:请勿自行对 batch.encoder 调用 finish() 或 device.queue.submit()。仅在 open 时追加原生 pass,且托管助手须在没有打开 pass 时调用。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
count | number | 否 | 首个 state/input 缓冲长度 | 0..0xffffffff 内整数。调用索引范围为 [0, count),所有 state/input 容量须至少为 count。辅助数组具有独立边界。 |
batch | ComputeBatch | 否 | — | open 的托管作用域;使用其 encoder 与 submit()。支持重复 dispatch,不改变原生闸。 |
源码参考: src/core/kernel.ts
PingPongclass
两个形状一致的缓冲区集合,显式区分 current 与 other。
export class PingPong<K extends string, F extends Record<K, ScalarKind> = Record<K, ScalarKind>>行为与约束
- 2.1.0 类型增强:字面量 create({ value: 'f32' }, count) 在 current/other 与 clone() 中保留 Buffer<'f32'>。现有 PingPong<K> 标注及显式 create<'value'> 调用仍兼容,这些宽泛形式保留宽泛 kind。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
current | { [P in K]: Buffer<F[P]> } (readonly property) | — | — | 当前读/渲染侧。 |
other | { [P in K]: Buffer<F[P]> } (readonly property) | — | — | 另一写侧。 |
names | readonly K[] | — | — | 按创建顺序排列的字段名。 |
createmethod
分配两侧。内部 CreateResult 助手使推导的字面量 kind 表保留 Buffer kind;字段名重载兼容显式字符串类型参数与泛型包装器。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>>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
kinds | Record<K, ScalarKind> | 是 | — | 非空的字段名到元素类型映射。 |
length | number | 是 | — | 正整数元素数量,不是标量分量数或字节数。 |
返回值
Promise<PingPong<K>> 新的双侧缓冲区组。
错误与失败情况
- 空 kinds 抛出普通 Error("PingPong requires at least one field");各字段也适用 Buffer.create 校验。
示例
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
切换活动侧以交换 current 和 other;不复制 GPU 数据。
swap(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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
等待 fn(other,current);仅成功兑现后交换两侧。
runWith(
fn: (
write: { [P in K]: Buffer<F[P]> },
read: { [P in K]: Buffer<F[P]> },
) => Promise<void>,
): Promise<void>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
fn | (write: { [P in K]: Buffer<F[P]> }, read: { [P in K]: Buffer<F[P]> }) => Promise<void> | 是 | — | 回调按顺序接收写侧 other 和读侧 current。 |
返回值
Promise<void> 回调完成后交换。
错误与失败情况
- 回调拒绝会向上传播,且不交换两侧。
示例
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
以保留字段 kind 的写/读侧同步编码,随后翻转逻辑当前侧。未提交批次取消时,恢复参与者的侧选择。
encodeWith(
batch: ComputeBatch,
fn: (
write: { [P in K]: Buffer<F[P]> },
read: { [P in K]: Buffer<F[P]> },
) => undefined,
): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
batch | ComputeBatch | 是 | — | open 批次;通过其 encoder 编码,并向内核编码选项传入此 batch。 |
fn | (write: { [P in K]: Buffer<F[P]> }, read: { [P in K]: Buffer<F[P]> }) => undefined | 是 | — | 接收 write=other、read=current。须同步返回 undefined,TypeScript 拒绝 async 回调。仅编码,提交或取消放在回调之外。 |
返回值
void 回调成功后立即换边,不提交或等待 GPU 完成。
行为与约束
- 自 2.2.0 起可用。
- 调用前准备内核。回调两侧各字段均为 Buffer<F[P]>。须同步返回 undefined,运行时也拒绝返回的 Promise 或 thenable。
- 每个 PingPong 在该批首次调用 helper 时记录初始方向,并占用到批次结束。回调正常返回后会换边,即使没有编码工作。dispatch count 为零时跳过 encodeWith(),独立声明回调时可标注 undefined 返回类型。
- 被占用的 PingPong 不能加入另一 open 批次或重入自身 helper;占用期间拒绝手动 swap() 与 runWith()。原 runWith() 尚在执行时,也不能开始此 helper。
- 在回调之外调用 batch.submit() 或 batch.cancel()。回调只向 batch.encoder 编码,托管内核须传 { batch },不得自行 finish 或提交 encoder。
- batch.cancel() 恢复本批所有参与 PingPong 到首次 helper 调用的方向。回调抛错会取消整个批次,恢复所有参与者,并传播原错误;违规异步回调也包含在内。
- batch.submit() 中 encoder.finish() 或 queue.submit() 同步抛错会取消批次并恢复参与者方向。成功提交即释放占用且保留最终方向;随后 GPU 完成失败不回滚已提交方向。
- 恢复仅改变 helper 管理的侧选择,不撤销已提交 GPU 命令、CPU 缓冲写入或 helper 外的手动 swap。未被占用的 swap() 与 runWith() 保留原行为;runWith() 不新增批次取消恢复。
错误与失败情况
- 批次无效/已关闭、PingPong 占用冲突或重入、原 runWith() 尚在执行时抛 UsageError;这些前置失败不执行回调。
- 回调错误在整批取消后重新抛出。返回 Promise/thenable 时抛 UsageError,并执行相同取消与恢复。
示例
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();源码参考: src/core/pingpong.ts
clonemethod
分配具有相同类型和长度的新组;不会复制数据或活动侧索引。
clone(): Promise<PingPong<K, F>>;参数
此调用不接收参数。
返回值
Promise<PingPong<K, F>> 新的同形组。
示例
import { PingPong } from 'wgpu-kit';
const a = await PingPong.create({ x: 'f32' }, 4);
const b = await a.clone();
a.destroy();
b.destroy();destroymethod
销毁两侧的全部字段。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();源码参考: src/core/pingpong.ts
rawKernelfunction
编译并派发调用方完整 WGSL,不生成绑定或越界保护。
export declare function rawKernel(
code: string,
entryPoint?: string,
label?: string,
): RawKernel;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
code | string | 是 | — | 完整、非空 WGSL 模块。 |
entryPoint | string | 否 | main | 计算入口名称。 |
label | string | 否 | rawKernel | 诊断用着色器/内核标签。 |
返回值
RawKernel 可推导的控制器类型;RawKernel 在内部声明,但不是根入口具名导出。
行为与约束
- 仅使用第 0 绑定组和 dispatchWorkgroups(workgroups)。没有库级单次编码检查;可变 uniform/storage 参数缓冲区的所有权由调用方负责。
错误与失败情况
- 空代码、非正数/非整数 workgroups、prepare 前 encode 会产生 ERR_USAGE;WGSL 编译错误产生 CompileError;仍须遵守原生绑定/管线/dispatch 校验。
preparemethod
使用共享设备幂等编译。
prepare(): Promise<void>;参数
此调用不接收参数。
返回值
Promise<void> 可编码。
示例
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
创建第 0 绑定组并追加一个计算 pass。
encode(
encoder: GPUCommandEncoder,
entries: GPUBindGroupEntry[],
workgroups: number,
): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
encoder | GPUCommandEncoder | 是 | — | 来自同一设备的调用方编码器;此 API 只记录工作,不提交。 |
entries | GPUBindGroupEntry[] | 是 | — | 与着色器自动布局匹配的第 0 绑定组原生条目;资源须来自共享设备。 |
workgroups | number | 是 | — | 正整数 X 维工作组数量;Y、Z 为 1,须符合设备 dispatch 限制。 |
返回值
void 无返回值。
示例
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
准备、编码并提交一次。
run(entries: GPUBindGroupEntry[], workgroups: number): Promise<void>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
entries | GPUBindGroupEntry[] | 是 | — | 与着色器自动布局匹配的第 0 绑定组原生条目;资源须来自共享设备。 |
workgroups | number | 是 | — | 正整数 X 维工作组数量;Y、Z 为 1,须符合设备 dispatch 限制。 |
返回值
Promise<void> CPU 提交完成,不是 GPU 完成栅栏。
示例
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
丢弃管线引用,不销毁调用方原生资源。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();源码参考: dist/core/raw.js
defineSchemafunction
一次声明字段类型,用于 TS 行类型推导、WGSL 结构体生成及逐字段缓冲区。
export declare function defineSchema<const F extends Record<string, ScalarKind>>(
fields: F,
): Schema<F>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
fields | F extends Record<string, ScalarKind> | 是 | — | 非空字段映射;插入顺序决定生成的 WGSL 成员顺序。 |
返回值
Schema<F> 持有同一 fields 对象的 schema 接口。
行为与约束
- 缓冲区采用 SoA 模型:buffers() 为每个字段创建一个缓冲区,而非交错结构体数组。定义后不要修改 fields。
- 这里不全面校验字段名/类型;应使用有效、非保留的 WGSL 名称,并避免 buffers() 辅助名称 raws/destroy。
错误与失败情况
- 无字段时抛出 UsageError / ERR_USAGE。
示例
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();源码参考: dist/core/schema.js
TypedBufferclass
Buffer 上的类型化行/对象接口;标量使用 number,向量使用分量对象。
export declare class TypedBuffer<K extends ScalarKind>字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
raw | readonly Buffer<K> | — | — | 用于紧密 TypedArray 上传/读回及 gpuBuffer 访问的底层接口。 |
kind | readonly K | — | — | 元素类型。 |
length | readonly number | — | — | 行数量。 |
createmethod
创建面向行的封装及底层存储缓冲区。
static create<K extends ScalarKind>(kind: K, length: number): Promise<TypedBuffer<K>>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
kind | K extends ScalarKind | 是 | — | 元素类型,决定 WGSL 类型、标量表示与存储步长。 |
length | number | 是 | — | 正整数元素数量,不是标量分量数或字节数。 |
返回值
Promise<TypedBuffer<K>> 类型化行缓冲区。
示例
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
将行展平为相应 TypedArray,校验有限数值后通过 raw.write 上传。
write(rows: ReadonlyArray<KindOf<K>>): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
rows | ReadonlyArray<KindOf<K>> | 是 | — | 恰好 length 个数值行或向量对象;kind 所需的向量分量必须为有限数值。 |
返回值
void 无返回值。
错误与失败情况
- 非法行/分量或最终长度不匹配时为 ERR_BUFFER_WRITE。整数类型使用 TypedArray 转换,不另做整数范围校验。
示例
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
读回原始分量并重建 number 或向量对象。
read(): Promise<Array<KindOf<K>>>;参数
此调用不接收参数。
返回值
Promise<Array<KindOf<K>>> 新的类型化行数组。
示例
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
销毁底层 raw 缓冲区。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();源码参考: dist/core/schema.js
Schemainterface
defineSchema 的返回契约。
export interface Schema<F extends Record<string, ScalarKind>>字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
F | Record<string, ScalarKind> | — | — | 泛型字段映射。 |
fields | readonly F | — | — | 原始声明对象,保留声明顺序。 |
wgslStructmethod
生成 WGSL struct;storage 模式对 vec3f 成员添加 @size(16)。
wgslStruct(name: string, addressSpace?: 'storage' | 'uniform'): string;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
name | string | 是 | — | 匹配 /^[A-Za-z][A-Za-z0-9_]*$/ 的结构体名;WGSL 保留字有效性仍由编译检查。 |
addressSpace | 'storage' | 'uniform' | 否 | storage | 选择 storage 成员填充或自然 uniform 成员声明。 |
返回值
string WGSL 结构体源码。
错误与失败情况
- 结构体名称不满足标识符正则时为 ERR_USAGE。
示例
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
为每个 schema 字段分配 TypedBuffer。
buffers(count: number): Promise<SchemaBuffers<F>>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
count | number | 是 | — | 每个字段的正整数行数。 |
返回值
Promise<SchemaBuffers<F>> 字段缓冲区以及 raws()、destroy()。
示例
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();示例
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();源码参考: dist/core/schema.js
SchemaBufferstype
带集合辅助方法的映射字段缓冲区。
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;
};字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
[K in keyof F] | readonly TypedBuffer<F[K]> | — | — | 每个 schema 字段均为类型化行缓冲区。 |
rawsmethod
返回字段名到其底层 raw Buffer 句柄的新映射。
raws(): { readonly [K in keyof F]: Buffer<F[K]> };参数
此调用不接收参数。
返回值
{ readonly [K in keyof F]: Buffer<F[K]> } 可用作名称匹配的 elementKernel 资源映射。
示例
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(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();源码参考: dist/core/schema.js
SchemaInfertype
从字段映射推导出的编译期只读行形状。
export type SchemaInfer<F extends Record<string, ScalarKind>> = {
readonly [K in keyof F]: KindOf<F[K]>;
};字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
F | Record<string, ScalarKind> | — | — | 输入声明映射。 |
[K in keyof F] | readonly KindOf<F[K]> | — | — | 保留精确字段名,并将类型映射到 JS 标量/向量形状。 |
示例
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 };源码参考: dist/core/schema.js
KindOftype
从 ScalarKind 到数值或向量行类型的编译期映射。
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;字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
f32 | i32 | u32 | number | — | — | 标量类型。 |
vec2f | vec2i | vec2u | Vec2 | — | — | 两个数值分量。 |
vec3f | Vec3 | — | — | 三个数值分量。 |
vec4f | Vec4 | — | — | 四个数值分量。 |
示例
import type { KindOf } from 'wgpu-kit';
const p: KindOf<'vec3f'> = { x: 1, y: 2, z: 3 };源码参考: dist/core/schema.js
Vec2interface
包含 2 个必需数值分量的对象。
export interface Vec2参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
x | number | 是 | — | x 分量。 |
y | number | 是 | — | y 分量。 |
示例
import type { Vec2 } from 'wgpu-kit';
const v: Vec2 = { x: 1, y: 2 };源码参考: dist/core/schema.js
Vec3interface
包含 3 个必需数值分量的对象。
export interface Vec3参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
x | number | 是 | — | x 分量。 |
y | number | 是 | — | y 分量。 |
z | number | 是 | — | z 分量。 |
示例
import type { Vec3 } from 'wgpu-kit';
const v: Vec3 = { x: 1, y: 2, z: 3 };源码参考: dist/core/schema.js
Vec4interface
包含 4 个必需数值分量的对象。
export interface Vec4参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
x | number | 是 | — | x 分量。 |
y | number | 是 | — | y 分量。 |
z | number | 是 | — | z 分量。 |
w | number | 是 | — | w 分量。 |
示例
import type { Vec4 } from 'wgpu-kit';
const v: Vec4 = { x: 1, y: 2, z: 3, w: 4 };源码参考: dist/core/schema.js
definePackfunction
校验扩展包名称/create 函数并保留泛型类型;返回原对象。
export declare function definePack<TConfig, TSim extends PackSim>(
pack: WgpuKitPack<TConfig, TSim>,
): WgpuKitPack<TConfig, TSim>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
pack | WgpuKitPack<TConfig, TSim> | 是 | — | 具有小写名称与可调用 create 的定义;TSim 继承 PackSim。 |
返回值
WgpuKitPack<TConfig, TSim> 原始定义,不包装、不注册。
行为与约束
- 运行时仅校验名称和 create 函数,不校验之后 create() 返回对象的生命周期。
错误与失败情况
- 名称不匹配 /^[a-z][a-z0-9-]*$/ 或 create 不是函数时为 ERR_USAGE。
示例
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();源码参考: dist/core/pack.js
registerPackfunction
将用户定义注册到进程/模块注册表。
export declare function registerPack<TConfig, TSim extends PackSim>(
pack: WgpuKitPack<TConfig, TSim>,
): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
pack | WgpuKitPack<TConfig, TSim> | 是 | — | 扩展包定义,建议先通过 definePack 校验。 |
返回值
void 此定义可被 listPacks/getPack 查到。
行为与约束
- registerPack 不调用 definePack,只检查重名/保留名称。没有公开的注销或覆盖 API。
错误与失败情况
- 已注册名称或内置保留名称 particles 会产生 ERR_USAGE。
示例
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();源码参考: dist/core/pack.js
PackSiminterface
扩展包模拟的最小生命周期契约。tick、destroy 必需,其余成员可选。
export interface PackSimattachmethod
可选的渲染挂载钩子。
attach?(canvas: HTMLCanvasElement): Promise<void>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
canvas | HTMLCanvasElement | 是 | — | 调用方选择的画布。 |
返回值
Promise<void> 由扩展包定义的挂载完成。
tickmethod
推进一帧计算及可选渲染。
tick(): void;参数
此调用不接收参数。
返回值
void 无返回值。
statsmethod
可选的轻量统计。
stats?(): Record<string, number | string>;参数
此调用不接收参数。
返回值
Record<string, number | string> 扩展包定义的数值/字符串指标。
probemethod
可选的不变量/诊断探针。
probe?(): Promise<Record<string, number | string | boolean>>;参数
此调用不接收参数。
返回值
Promise<Record<string, number | string | boolean>> 扩展包定义的自检结果。
destroymethod
释放模拟持有的资源。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();源码参考: dist/core/pack.js
WgpuKitPackinterface
泛型工厂元数据与生命周期契约。
export interface WgpuKitPack<TConfig, TSim extends PackSim = PackSim>字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
TConfig | generic type parameter | — | — | 配置类型;使用该类型定义时须指定。 |
TSim | extends PackSim = PackSim | — | — | 模拟类型,默认 PackSim。 |
name | readonly string | — | — | 注册表命名空间名称。 |
description | readonly string | undefined | — | — | 可选的易读说明;接口不设置默认值。 |
createmethod
创建模拟;具体配置和默认值由该扩展包定义。
create(config?: TConfig): Promise<TSim>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
config | TConfig | 否 | — | 可选的扩展包专属配置;本接口不规定默认值。 |
返回值
Promise<TSim> 实现 PackSim 的扩展包专属模拟。
示例
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();源码参考: dist/core/pack.js
createScanfunction
创建延迟准备的 u32 前缀扫描控制器;无参数。
export declare function createScan(): Scan;参数
此调用不接收参数。
返回值
Scan 支持排他或包含式前缀和的控制器。
行为与约束
- 仅用于 u32,并按模 2^32 溢出。使用至少 count*4 字节、相互独立的输入/输出存储缓冲区;JS 不校验 Buffer.kind 或容量。
- count=0 不编码工作,也不启用检查锁。实现上限为 8192*65535 = 536862720 个值;分配/绑定/设备限制可能更低。
- 省略 batch 的原生路径:每个实例每次提交只能 encode/sumInto 一次,提交后调用 endSubmit()。托管批次使用独立 uniform/scratch,支持重复编码,不消耗或重置原生闸,也不需要 endSubmit()。resetEncodeGuard() 仅关闭原生检查,不能修复共享 uniform 覆盖风险。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
示例
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();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();源码参考: src/primitives/scan.ts
Scaninterface
前缀扫描生命周期与组合契约。
export interface Scan行为与约束
- 仅用于 u32,并按模 2^32 溢出。使用至少 count*4 字节、相互独立的输入/输出存储缓冲区;JS 不校验 Buffer.kind 或容量。
- count=0 不编码工作,也不启用检查锁。实现上限为 8192*65535 = 536862720 个值;分配/绑定/设备限制可能更低。
- 省略 batch 的原生路径:每个实例每次提交只能 encode/sumInto 一次,提交后调用 endSubmit()。托管批次使用独立 uniform/scratch,支持重复编码,不消耗或重置原生闸,也不需要 endSubmit()。resetEncodeGuard() 仅关闭原生检查,不能修复共享 uniform 覆盖风险。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
preparemethod
幂等创建扫描管线和参数缓冲区。
prepare(): Promise<void>;参数
此调用不接收参数。
返回值
Promise<void> 可编码。
示例
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
根据 count 编码一个或三个计算 pass;不提交、不读回。
encode(
encoder: GPUCommandEncoder,
src: GPUBuffer,
dst: GPUBuffer,
count: number,
exclusive?: boolean,
batch?: ComputeBatch,
): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
encoder | GPUCommandEncoder | 是 | — | 来自同一设备的调用方编码器;此 API 只记录工作,不提交。 |
src | GPUBuffer | 是 | — | 只读 u32 storage 输入。 |
dst | GPUBuffer | 是 | — | 独立的可写 u32 storage 输出。 |
count | number | 是 | — | 要处理的 u32 值数量,须为非负整数;在适用时不得超过输入/输出容量。 |
exclusive | boolean | 否 | true | true:dst[i]=sum(src[0..i));false:dst[i]=sum(src[0..i])。 |
batch | ComputeBatch | 否 | — | 可选托管作用域;encoder 须为 batch.encoder。每次调用参数/scratch 独立,支持重复调用且无需 endSubmit(),由批次拥有提交权。 |
返回值
void 无返回值。
行为与约束
- 托管编码不会为调用方输出缓冲创建快照;共享目标必须在后续 dispatch 覆盖前消费。
错误与失败情况
- prepare 前调用、重复受检查 encode、非法 count 或超过 536862720 时为 ERR_USAGE。原语着色器错误使用代码为 ERR_COMPILE 的 UsageError;原生 WebGPU 校验也可能失败。
- 批次已关闭或 encoder 不属于该批次时抛 UsageError。
示例
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
准备、编码并提交,自动清除检查锁。
run(src: Buffer, dst: Buffer, count: number, exclusive?: boolean): Promise<void>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
src | Buffer | 是 | — | 输入 Buffer;调用方须使用 u32 类型。 |
dst | Buffer | 是 | — | 独立输出 Buffer;调用方须使用 u32 类型。 |
count | number | 是 | — | 要处理的 u32 值数量,须为非负整数;在适用时不得超过输入/输出容量。 |
exclusive | boolean | 否 | true | true:dst[i]=sum(src[0..i));false:dst[i]=sum(src[0..i])。 |
返回值
Promise<void> CPU 提交;可等待 dst.read() 或 context.sync() 确认完成。
错误与失败情况
- prepare 前调用、重复受检查 encode、非法 count 或超过 536862720 时为 ERR_USAGE。原语着色器错误使用代码为 ERR_COMPILE 的 UsageError;原生 WebGPU 校验也可能失败。
示例
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
调用方原生提交后重置 encode-once 闸;托管批次不使用或重置该闸。
endSubmit(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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
永久关闭原生闸,不会获得独立 uniform;需要重复参数快照时可使用托管批次。
resetEncodeGuard(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 省略 batch 的原生路径:每个实例每次提交只能 encode/sumInto 一次,提交后调用 endSubmit()。托管批次使用独立 uniform/scratch,支持重复编码,不消耗或重置原生闸,也不需要 endSubmit()。resetEncodeGuard() 仅关闭原生检查,不能修复共享 uniform 覆盖风险。
示例
import { createScan } from 'wgpu-kit';
const scan = createScan();
scan.resetEncodeGuard(); // advanced: caller owns uniform hazards
scan.destroy();destroymethod
释放内部块和/参数缓冲区与管线引用,不销毁 src/dst。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();源码参考: src/primitives/scan.ts
createReducefunction
创建延迟准备的 u32 求和归约控制器;无参数。
export declare function createReduce(): Reduce;参数
此调用不接收参数。
返回值
Reduce 支持 GPU 输出与 CPU 读回的求和控制器。
行为与约束
- 输入/结果采用模 2^32 的 u32 算术。sumInto 先清零再覆盖 dst[0];count=0 结果为零。
- 输入须容纳 count*4 字节,输出至少有 4 字节可写 STORAGE。类型/容量由调用方保证,JS 不校验;输入与输出应独立。
- 最大 count 为 256*32*65535 = 536862720;设备/绑定/内存限制可能使实际最大值更小。
- 省略 batch 的原生路径:每个实例每次提交只能 encode/sumInto 一次,提交后调用 endSubmit()。托管批次使用独立 uniform/scratch,支持重复编码,不消耗或重置原生闸,也不需要 endSubmit()。resetEncodeGuard() 仅关闭原生检查,不能修复共享 uniform 覆盖风险。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
示例
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();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();源码参考: src/primitives/reduce.ts
Reduceinterface
归约生命周期与组合契约。
export interface Reduce行为与约束
- 输入/结果采用模 2^32 的 u32 算术。sumInto 先清零再覆盖 dst[0];count=0 结果为零。
- 输入须容纳 count*4 字节,输出至少有 4 字节可写 STORAGE。类型/容量由调用方保证,JS 不校验;输入与输出应独立。
- 最大 count 为 256*32*65535 = 536862720;设备/绑定/内存限制可能使实际最大值更小。
- 省略 batch 的原生路径:每个实例每次提交只能 encode/sumInto 一次,提交后调用 endSubmit()。托管批次使用独立 uniform/scratch,支持重复编码,不消耗或重置原生闸,也不需要 endSubmit()。resetEncodeGuard() 仅关闭原生检查,不能修复共享 uniform 覆盖风险。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
preparemethod
幂等准备清零/归约管线与参数。
prepare(): Promise<void>;参数
此调用不接收参数。
返回值
Promise<void> 可编码。
示例
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
记录清零/归约 pass;结果保留在 GPU 的 dst[0]。
sumInto(
encoder: GPUCommandEncoder,
src: GPUBuffer,
count: number,
dst: GPUBuffer,
batch?: ComputeBatch,
): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
encoder | GPUCommandEncoder | 是 | — | 来自同一设备的调用方编码器;此 API 只记录工作,不提交。 |
src | GPUBuffer | 是 | — | 只读 u32 storage 输入。 |
count | number | 是 | — | 要处理的 u32 值数量,须为非负整数;在适用时不得超过输入/输出容量。 |
dst | GPUBuffer | 是 | — | 可写存储缓冲区,其首个 u32 在着色器中作为 atomic<u32> 使用。 |
batch | ComputeBatch | 否 | — | 可选托管作用域;encoder 须为 batch.encoder。每次调用参数/scratch 独立,支持重复调用且无需 endSubmit(),由批次拥有提交权。 |
返回值
void 无返回值。
行为与约束
- 托管编码不会为调用方输出缓冲创建快照;共享目标必须在后续 dispatch 覆盖前消费。
错误与失败情况
- prepare 前调用、重复受检查 sumInto()、非法 count 或超出 dispatch 上限时为 ERR_USAGE。着色器编译错误为 UsageError / ERR_COMPILE。读回/映射失败可能拒绝 sum()。
- 批次已关闭或 encoder 不属于该批次时抛 UsageError。
示例
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
通过每次调用独立临时缓冲区准备、编码、提交并读回一个 u32。
sum(src: Buffer, count: number): Promise<number>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
src | Buffer | 是 | — | 按 u32 解释的输入 Buffer。 |
count | number | 是 | — | 要处理的 u32 值数量,须为非负整数;在适用时不得超过输入/输出容量。 |
返回值
Promise<number> GPU 工作/读回后的无符号和,溢出按模 2^32 回绕。
错误与失败情况
- prepare 前调用、重复受检查 sumInto()、非法 count 或超出 dispatch 上限时为 ERR_USAGE。着色器编译错误为 UsageError / ERR_COMPILE。读回/映射失败可能拒绝 sum()。
示例
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
调用方原生提交后重置 encode-once 闸;托管批次不使用或重置该闸。
endSubmit(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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
永久关闭原生闸,不会获得独立 uniform;需要重复参数快照时可使用托管批次。
resetEncodeGuard(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 省略 batch 的原生路径:每个实例每次提交只能 encode/sumInto 一次,提交后调用 endSubmit()。托管批次使用独立 uniform/scratch,支持重复编码,不消耗或重置原生闸,也不需要 endSubmit()。resetEncodeGuard() 仅关闭原生检查,不能修复共享 uniform 覆盖风险。
示例
import { createReduce } from 'wgpu-kit';
const reduce = createReduce();
reduce.resetEncodeGuard();
reduce.destroy();destroymethod
销毁内部参数并释放管线引用;输入/输出缓冲区归调用方所有。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();源码参考: src/primitives/reduce.ts
particlesfunction
创建并初始化四物种 GPU 粒子模拟。
particles(config?: ParticlesConfig): Promise<ParticlesSim>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
config | ParticlesConfig | 否 | {} | 模拟、渲染和初始化选项;所有字段详见 ParticlesConfig。 |
返回值
Promise<ParticlesSim> 已初始化的缓冲和计算管线,尚无渲染循环,也未绑定画布。
行为与约束
- 世界半宽由 count 决定:sqrt(count/16_000)。初始位置位于 ±0.8*worldHalf,速度为零,物种编号为 0..3。不提供 worldHalf 或物种数公共选项。
- 动画调度由调用者负责。无需 attach 也能 tick,支持纯计算。需要内置渲染时只 attach 一次画布。
- 需要 WebGPU 和共享 GpuContext。不提供 WebGL 或 CPU 回退。资源用量取决于数量、网格分辨率和设备限制。
错误与失败情况
- count/mode 无效或 n2 数量 >32_000 时拒绝,错误为 UsageError(ERR_USAGE)。未知字符串力名称抛普通 Error。设备获取、缓冲分配、shader 编译或管线校验也可能失败。
- 不会全面校验物理数值选项或自定义力矩阵长度/范围。无效数值可能直接进入 GPU 代码,应由应用验证输入。
示例
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
particles() 返回的模拟句柄;根入口也导出此类型。
interface ParticlesSim字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
ForcePresetName (supporting, not exported by this entry point) | 'cells' | 'snakes' | 'orbitals' | 'viruses' | — | — | 作为力配置接受的字面量名称。FORCE_PRESETS 本身不是根入口或 /particles 的公共导出。 |
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] | — | — | 扁平 4×4 矩阵,下标为 mySpecies*4+otherSpecies。无需私有路径导入,可用 Exclude<NonNullable<ParticlesConfig["forces"]>, string> 获取此类型。 |
SimMode (supporting, not exported by this entry point) | 'n2' | 'tiled' | 'grid' | — | — | 可通过 NonNullable<ParticlesConfig["mode"]> 获取。 |
configreadonly property
解析后的初始化配置,力配置会实时更新。
readonly config: ResolvedConfig;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
count | number | 是 | — | 粒子数量,整数范围 1..1_000_000。n2 模式拒绝超过 32_000 的数量(其错误文案建议不超过 20_000)。设备内存限制可能更低。 |
forces | ForceMatrix | 是 | — | 解析后的 16 数值力矩阵,由 setForces() 更新。 |
mode | 'n2' | 'tiled' | 'grid' | 是 | — | 邻域算法:全量两两计算、workgroup 分块两两计算或空间网格。声明中默认 tiled 的注释已过时;实现默认 grid。 |
color | 'species' | 'velocity' | 是 | — | 画布按四种物种或速度大小着色,attach 渲染器时生效。 |
bounds | 'wrap' | 'clamp' | 是 | — | 更新后位置如何保持在方形世界内:环绕或钳位。交互距离/邻域搜索不会跨相对边界环绕。 |
seed | string | 是 | — | 初始化时保存的 String(seed)。 |
rMax | number | 是 | — | 世界单位下的最大交互半径,应使用有限正数,也影响网格分辨率。 |
beta | number | 是 | — | 归一化距离 d/rMax 下的分段力曲线分界点。合理值在 0 与 1 之间;API 不验证。 |
forceFactor | number | 是 | — | 加速度缩放;交互总和在积分前乘以 forceFactor*rMax。 |
frictionHalfLife | number | 是 | — | 阻尼时间参数,实际公式为 exp(-effectiveDt/frictionHalfLife)。虽然名称含 HalfLife,实现没有 ln(2),数学上是指数衰减时间常数,不是真正半衰期。应使用有限正数。 |
dt | number | 是 | — | 每次 tick 的基础模拟时间步,乘以 tick 参数;不会自动测量动画回调经过的时间。 |
pointSize | number | 是 | — | attach 渲染器使用的归一化点四边形半尺寸,经世界缩放后近似为裁剪空间坐标尺寸。它不是直接像素值;shader 生成时会把缩放后的值保留四位小数。 |
maxNeighbors | number | 是 | — | 仅 grid 使用的候选预算:最多 9 个相邻格子,每格检查 ceil(maxNeighbors/9) 个候选(自身也可能计入)。应使用有限正数。 |
forcesName | string | 是 | — | 选中的字面量力名称,或 'custom';由 setForces() 更新。 |
seedHash | number | 是 | — | 归一化种子字符串的 32 位散列。 |
friction | number | 是 | — | 初始 exp(-dt/frictionHalfLife);setParams 或 tick 倍率变化后不会变成实时值。 |
返回值
ResolvedConfig 可通过 ParticlesSim["config"] 取得的内部关联类型。属性 readonly 不等于深层不可变快照。
行为与约束
- setParams 修改另一个内部物理对象,因此 config.rMax/beta/forceFactor/frictionHalfLife/dt/friction 可能仍为初始化值。snapshot() 读取当前物理值。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
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 } | — | — | 解析结果中所有字段均必有;不要直接修改 config 来控制模拟。 |
attachmethod
在一个画布上配置内置粒子渲染。
attach(canvas: HTMLCanvasElement): Promise<void>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
canvas | HTMLCanvasElement | 是 | — | 具有有效 CSS 客户区尺寸的画布,不应已被不兼容绘制后端占用。 |
返回值
Promise<void> 画布渲染器就绪时完成。
行为与约束
- 像素宽高设为 max(1, floor(clientSize*min(devicePixelRatio||1,2))),配置不透明 WebGPU 渲染。不自动安装 resize observer。
- 每个模拟只调用一次。再次调用会替换渲染器引用,但不会先销毁旧渲染器。attach 不启动动画循环。
错误与失败情况
- canvas.getContext("webgpu") 返回 null 或渲染 shader/管线初始化失败时拒绝。
tickmethod
推进一步模拟,按需渲染,并切换当前状态缓冲。
tick(dtMultiplier?: number): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
dtMultiplier | number | 否 | 1 | 当前 dt 的倍率。0 停止物理推进,但仍提交工作、渲染、交换缓冲并计一次 tick;小数可减慢模拟。 |
返回值
void 无返回值。
行为与约束
- 自行提交 command encoder;此高层 API 不暴露 prepare/encode/endSubmit。返回时 GPU 不一定已完成。若要暂停 GPU 工作,应完全跳过 tick。
- 积分使用 effectiveDt=dt*dtMultiplier,阻尼为 exp(-effectiveDt/frictionHalfLife)。不会根据动画帧实际间隔自动调整。
setForcesmethod
无需重建模拟,替换力矩阵。
setForces(forces: ForcePresetName | 'random' | ForceMatrix): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
forces | ForcePresetName | 'random' | ForceMatrix | 是 | — | 与 ParticlesConfig.forces 相同的力配置类型。random 复用原始种子,因此重复调用得到同一矩阵。 |
返回值
void 无返回值。
行为与约束
- 向 16 个 f32 的矩阵缓冲排队写入,并更新 config.forces/config.forcesName;不重置位置或速度。
错误与失败情况
- 未知力名称抛普通 Error。自定义矩阵分量数/类型问题可能从 Buffer.write 传播;不要传任意长度数组。
setParamsmethod
局部更新当前物理参数;省略字段保留当前值。
setParams(params: {
rMax?: number;
beta?: number;
forceFactor?: number;
frictionHalfLife?: number;
dt?: number;
}): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
params | { rMax?: number; beta?: number; forceFactor?: number; frictionHalfLife?: number; dt?: number } | 是 | — | 物理参数的部分更新;嵌套字段均可省略。 |
params.rMax | number | 否 | unchanged when omitted | 世界单位下的最大交互半径,应使用有限正数,也影响网格分辨率。 |
params.beta | number | 否 | unchanged when omitted | 归一化距离 d/rMax 下的分段力曲线分界点。合理值在 0 与 1 之间;API 不验证。 |
params.forceFactor | number | 否 | unchanged when omitted | 加速度缩放;交互总和在积分前乘以 forceFactor*rMax。 |
params.frictionHalfLife | number | 否 | unchanged when omitted | 阻尼时间参数,实际公式为 exp(-effectiveDt/frictionHalfLife)。虽然名称含 HalfLife,实现没有 ln(2),数学上是指数衰减时间常数,不是真正半衰期。应使用有限正数。 |
params.dt | number | 否 | unchanged when omitted | 每次 tick 的基础模拟时间步,乘以 tick 参数;不会自动测量动画回调经过的时间。 |
返回值
void 无返回值。
行为与约束
- 没有运行时数值验证。不要显式把某字段设为 undefined,因为 Object.assign 会覆盖原值。
- 若 rMax 改变网格分辨率,会启动异步重建;仅最后一次重建生效并替换旧网格资源。不提供 Promise 或完成回调;此处不捕获重建错误。
snapshotmethod
序列化选定的当前配置,不保存模拟状态。
snapshot(): string;参数
此调用不接收参数。
返回值
string JSON 字符串,含 count、forces 名称、mode、color、bounds、seed、rMax、beta、forceFactor、frictionHalfLife、dt、pointSize。
行为与约束
- 省略粒子缓冲、maxNeighbors 和自定义力矩阵数值。自定义矩阵变为 forces:"custom",particles() 无法按名称解析它;此方法不是完整可恢复检查点。
statsmethod
读取 tick 频率和未捕获错误计数。
stats(): { fps: number; gpuErrors: number };参数
此调用不接收参数。
返回值
{ fps: number; gpuErrors: number } fps 初始为 0,在累计墙钟时间达到约 500 ms 时更新。gpuErrors 统计此实例监听到的设备 uncapturederror 事件。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
fps | number | — | — | 每墙钟秒的 tick 数,不是 GPU kernel 耗时或性能基准分数。长暂停会影响下一次样本。 |
gpuErrors | number | — | — | 共享设备的未捕获错误数量;事件可能来自使用同一设备的其他工作。 |
debugGridoptional method
仅用于诊断,暴露 grid 内部缓冲;非 grid 模式为 undefined。
debugGrid?(): {
partial: Buffer;
start: Buffer;
fill: Buffer;
sortedPos: Buffer;
sortedSp: Buffer;
order: Buffer;
};参数
此调用不接收参数。
返回值
{ partial: Buffer; start: Buffer; fill: Buffer; sortedPos: Buffer; sortedSp: Buffer; order: Buffer } 借用的内部缓冲,后续网格重建会替换它们。不要自行销毁。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
partial | Buffer (vec2f, count*9) | — | — | 每粒子、每邻格的部分力贡献。 |
start | Buffer (u32, cells) | — | — | 各格子的包含式起始槽位。 |
fill | Buffer (u32, cells) | — | — | scatter 后排他终止槽位,不是原始格内数量。 |
sortedPos | Buffer (vec2f, count) | — | — | 按格子分组的位置副本。 |
sortedSp | Buffer (u32, count) | — | — | 按格子分组的物种下标。 |
order | Buffer (u32, count) | — | — | 每个排序槽位对应的原始粒子下标。 |
buffersmethod
获取当前模拟状态的借用缓冲。
buffers(): { pos: Buffer; vel: Buffer; species: Buffer };参数
此调用不接收参数。
返回值
{ pos: Buffer; vel: Buffer; species: Buffer } pos/vel 为 count 个 vec2f 元素的缓冲,species 为 count 个 u32 元素的缓冲。
行为与约束
- tick 后 pos 和 vel 交替,获取最新侧须再次调用 buffers()。CPU 快照需要 await buffer.read()。这些缓冲由模拟拥有。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
pos | Buffer (vec2f) | — | — | 当前二维世界位置。 |
vel | Buffer (vec2f) | — | — | 当前二维速度。 |
species | Buffer (u32) | — | — | 0..3 的物种标签,独立于双缓冲状态。 |
示例
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
释放实现中负责清理的粒子、矩阵、uniform、网格和渲染器资源。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 先取消动画循环并停止使用借用缓冲。不自动取消 RAF、不取消画布配置、不提供销毁状态防护,也不移除错误监听器。
- 避免在 setParams 异步重建网格期间销毁;2.0.0 不提供等待或取消该重建的方式。
ElementKernelinterface
elementKernel 返回的控制器。
export interface ElementKernel行为与约束
- 2.1.0 新增:auxInputs、options.count 与 ElementKernelDispatchOptions 依据 src/core/kernel.ts 和 src/index.ts 记录,在 npm 2.0.0 历史审计基线之上扩展。
- 所有声明的 state/input/auxInputs 缓冲必须存在且类型匹配,包括静态未使用的字段。参与绑定的资源须属于共享设备。额外资源/uniform 键被忽略。
- 省略 options.count 时,state 与 inputs 必须等长,调用数量取首个此类缓冲长度。至少需要一个 state 或 inputs 字段;auxInputs 不参与数量推导。
- 显式 count 须为 0..0xffffffff 内的整数。state/input 可不同长,但每个缓冲都必须至少容纳 count 个元素。两种模式下,ceil(count / workgroupSize) 均不得超过 device.limits.maxComputeWorkgroupsPerDimension。
- 辅助数组只读且长度独立,不参与逐元素容量校验;辅助索引边界由 WGSL 作者负责。可用 arrayLength(&weights) 查询长度。
- count: 0 完整校验全部资源、uniform 与选项后,不编码、不提交,也不消耗或清除已有的 encode-once 检查状态。
- 字段名在 state、inputs、auxInputs、uniforms 之间必须唯一。uniform 名 count 为保留名称,由库自动注入。应使用有效 WGSL 标识符,保留字由编译器检查。
- 不要在同一 dispatch 中读取正在被并行写入的缓冲区邻居元素;应使用分离的输入/输出或 PingPong。库不提供 dispatch 内的全局同步。
- 生成源码使用词法资源使用分析;局部变量遮蔽资源名是已知分析限制。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
name | readonly string | — | — | 诊断名称。 |
source | readonly string | — | — | 完整生成 WGSL,含声明和入口。 |
uniformLayout | readonly UniformLayout | — | — | 有序字段、字节偏移与填充后大小。UniformLayout 为关联类型,不是根入口具名导出。 |
workgroupSize | readonly number | — | — | 选定的 X 维工作组大小。 |
preparemethod
幂等地获取共享上下文、编译管线并分配 uniform。
prepare(): Promise<void>;参数
此调用不接收参数。
返回值
Promise<void> 可进行同步 encode()。
错误与失败情况
- 准备/替换时:CompileError / ERR_COMPILE 报告映射到用户代码行号的 WGSL 错误;也可能发生原生 WebGPU 校验或设备错误。
示例
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
便捷执行 prepare → encode → queue.submit;非零提交后重置 encode 检查。零 count 完整校验调用并保留原检查状态。
run(
resources: Record<string, Buffer>,
uniforms?: Record<string, UniformValue>,
options?: ElementKernelDispatchOptions,
): Promise<void>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
resources | Record<string, Buffer> | 是 | — | 将每个声明的 state/input/auxInputs 字段映射到类型匹配且属于共享设备的 Buffer。数量与容量规则由 options 控制。 |
uniforms | Record<string, UniformValue> | 否 | {} | 全部已声明 uniform 的值。向量使用 {x,y,z,w} 对象,须包含类型所要求的分量。 |
options | ElementKernelDispatchOptions | 否 | {} | 可选调用数量。省略 count 时 state/inputs 须等长;显式 count 允许不同容量,但均须至少容纳 count 个元素。auxInputs 长度独立。无 uniform 声明时第二个参数传 undefined。 |
返回值
Promise<void> 非零调用在 CPU 侧提交后兑现,不等待 GPU 完成。零 count 在校验后兑现,不提交。
行为与约束
- 省略 options.count 时,state 与 inputs 必须等长,调用数量取首个此类缓冲长度。至少需要一个 state 或 inputs 字段;auxInputs 不参与数量推导。
- 显式 count 须为 0..0xffffffff 内的整数。state/input 可不同长,但每个缓冲都必须至少容纳 count 个元素。两种模式下,ceil(count / workgroupSize) 均不得超过 device.limits.maxComputeWorkgroupsPerDimension。
- 辅助数组只读且长度独立,不参与逐元素容量校验;辅助索引边界由 WGSL 作者负责。可用 arrayLength(&weights) 查询长度。
- count: 0 完整校验全部资源、uniform 与选项后,不编码、不提交,也不消耗或清除已有的 encode-once 检查状态。
错误与失败情况
- 未 prepare()、原生路径提交/重置前重复编码,或托管批次已关闭/不匹配时为 ERR_USAGE。资源错误对应 ERR_RESOURCE_MISSING、ERR_RESOURCE_TYPE、ERR_RESOURCE_LENGTH;uniform 打包报告 ERR_UNIFORM_FIELD/ERR_UNIFORM_UNSUPPORTED。资源须属于共享设备是调用方前提。
- count 非法、超出设备 dispatch 上限或 state/input 容量不足时也抛出 UsageError。count 为零仍校验全部声明资源与 uniform 值。
示例
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
编码非零 dispatch,不提交。省略 batch 时使用原生共享 uniform 闸;传入 batch 时保存独立 uniform 快照。零 count 仅校验,不编码或改变原生闸。
encode(
encoder: GPUCommandEncoder,
resources: Record<string, Buffer>,
uniforms?: Record<string, UniformValue>,
options?: ElementKernelEncodeOptions,
): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
encoder | GPUCommandEncoder | 是 | — | 来自共享设备、没有打开 pass 的未完成 encoder。传入 options.batch 时须为 batch.encoder,由 batch.submit() 结束并提交。 |
resources | Record<string, Buffer> | 是 | — | 将每个声明的 state/input/auxInputs 字段映射到类型匹配且属于共享设备的 Buffer。数量与容量规则由 options 控制。 |
uniforms | Record<string, UniformValue> | 否 | {} | 全部已声明 uniform 的值。向量使用 {x,y,z,w} 对象,须包含类型所要求的分量。 |
options | ElementKernelEncodeOptions | 否 | {} | 可选 count 与托管 batch。count 遵循 run() 容量规则;batch 提供独立参数以支持重复 dispatch,并拥有提交权;run() 自身不接收 batch 选项。 |
返回值
void 无返回值。
行为与约束
- 省略 options.batch 的原生路径:每实例每次提交只能进行一次非零 encode,提交后调用 endSubmit()。使用 options.batch 时传入 batch.encoder,且只能通过 batch.submit() 提交;每次编码都有独立 uniform 快照,支持重复调用,原生闸状态保持不变。
- 省略 options.count 时,state 与 inputs 必须等长,调用数量取首个此类缓冲长度。至少需要一个 state 或 inputs 字段;auxInputs 不参与数量推导。
- 显式 count 须为 0..0xffffffff 内的整数。state/input 可不同长,但每个缓冲都必须至少容纳 count 个元素。两种模式下,ceil(count / workgroupSize) 均不得超过 device.limits.maxComputeWorkgroupsPerDimension。
- 辅助数组只读且长度独立,不参与逐元素容量校验;辅助索引边界由 WGSL 作者负责。可用 arrayLength(&weights) 查询长度。
- count: 0 完整校验全部资源、uniform 与选项后,不编码、不提交,也不消耗或清除已有的 encode-once 检查状态。
错误与失败情况
- 未 prepare()、原生路径提交/重置前重复编码,或托管批次已关闭/不匹配时为 ERR_USAGE。资源错误对应 ERR_RESOURCE_MISSING、ERR_RESOURCE_TYPE、ERR_RESOURCE_LENGTH;uniform 打包报告 ERR_UNIFORM_FIELD/ERR_UNIFORM_UNSUPPORTED。资源须属于共享设备是调用方前提。
- count 非法、超出设备 dispatch 上限或 state/input 容量不足时也抛出 UsageError。count 为零仍校验全部声明资源与 uniform 值。
示例
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
调用方原生提交后清除 encode-once 闸;不提交,也不等待。托管编码无需调用,也不会改变该闸。
endSubmit(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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
永久关闭该实例的原生闸;托管批次本身已支持重复编码,无需此逃生接口。
resetEncodeGuard(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 省略 batch 时,重复编码仍共享 uniform,可能读取被覆盖的值;没有对应的重新启用方法。
示例
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
只替换 WGSL 函数源码,保留原声明。编译失败时旧内核继续有效。
replace(code: string): Promise<void>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
code | string | 是 | — | 新的非空 WGSL userFn/辅助函数源码,资源和 uniform 契约不变。 |
返回值
Promise<void> 成功重新编译后兑现;不进行 dispatch。
错误与失败情况
- 构造时:非法工作组大小为 ERR_WORKGROUP_SIZE;无数组为 ERR_RESOURCE_MISSING;空代码、重名或保留 count uniform 为 ERR_USAGE。
- 准备/替换时:CompileError / ERR_COMPILE 报告映射到用户代码行号的 WGSL 错误;也可能发生原生 WebGPU 校验或设备错误。
示例
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
释放内部 uniform 存储与缓存绑定组,不销毁调用方资源缓冲区。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
示例
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();示例
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();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();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();源码参考: src/core/kernel.ts
ElementKernelSpecinterface
elementKernel 接受的完整配置。
export interface ElementKernelSpec参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
name | string | 否 | kernel | 诊断用内核名称。 |
state | Record<string, ScalarKind> | 否 | {} | 可读写 storage 数组;在 WGSL 中按字段名访问。 |
inputs | Record<string, ScalarKind> | 否 | {} | 只读 storage 数组;state 与 inputs 合计至少一个字段。 |
auxInputs | Record<string, ScalarKind> | 否 | {} | 长度独立的只读辅助 storage 数组,不决定 dispatch 数量;索引边界由 WGSL 处理。2.1.0 新增。 |
uniforms | Record<string, ScalarKind> | 否 | {} | uniform 声明;插入顺序须匹配 userFn 中元素索引之后的参数。 |
workgroupSize | number | 否 | 64 | 库接受 1..512 整数;实际设备限制可能更严格。 |
code | string | 是 | — | 非空 WGSL,包含 fn userFn(index:u32, ...uniform 参数);可含辅助函数,不应重复提供生成的绑定或 main 入口。 |
行为与约束
- 2.1.0 新增:auxInputs、options.count 与 ElementKernelDispatchOptions 依据 src/core/kernel.ts 和 src/index.ts 记录,在 npm 2.0.0 历史审计基线之上扩展。
- 所有声明的 state/input/auxInputs 缓冲必须存在且类型匹配,包括静态未使用的字段。参与绑定的资源须属于共享设备。额外资源/uniform 键被忽略。
- 省略 options.count 时,state 与 inputs 必须等长,调用数量取首个此类缓冲长度。至少需要一个 state 或 inputs 字段;auxInputs 不参与数量推导。
- 显式 count 须为 0..0xffffffff 内的整数。state/input 可不同长,但每个缓冲都必须至少容纳 count 个元素。两种模式下,ceil(count / workgroupSize) 均不得超过 device.limits.maxComputeWorkgroupsPerDimension。
- 辅助数组只读且长度独立,不参与逐元素容量校验;辅助索引边界由 WGSL 作者负责。可用 arrayLength(&weights) 查询长度。
- count: 0 完整校验全部资源、uniform 与选项后,不编码、不提交,也不消耗或清除已有的 encode-once 检查状态。
- 字段名在 state、inputs、auxInputs、uniforms 之间必须唯一。uniform 名 count 为保留名称,由库自动注入。应使用有效 WGSL 标识符,保留字由编译器检查。
- 不要在同一 dispatch 中读取正在被并行写入的缓冲区邻居元素;应使用分离的输入/输出或 PingPong。库不提供 dispatch 内的全局同步。
- 生成源码使用词法资源使用分析;局部变量遮蔽资源名是已知分析限制。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
示例
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();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();源码参考: src/core/kernel.ts
ElementKernelDispatchOptionsinterface
run() 接收的可选调用数量,并由 encode() 的 ElementKernelEncodeOptions 继承。2.1.0 新增;run() 仍只接收 count。
export interface ElementKernelDispatchOptions {
count?: number;
}行为与约束
- 2.1.0 新增:auxInputs、options.count 与 ElementKernelDispatchOptions 依据 src/core/kernel.ts 和 src/index.ts 记录,在 npm 2.0.0 历史审计基线之上扩展。
- 省略 options.count 时,state 与 inputs 必须等长,调用数量取首个此类缓冲长度。至少需要一个 state 或 inputs 字段;auxInputs 不参与数量推导。
- 显式 count 须为 0..0xffffffff 内的整数。state/input 可不同长,但每个缓冲都必须至少容纳 count 个元素。两种模式下,ceil(count / workgroupSize) 均不得超过 device.limits.maxComputeWorkgroupsPerDimension。
- 辅助数组只读且长度独立,不参与逐元素容量校验;辅助索引边界由 WGSL 作者负责。可用 arrayLength(&weights) 查询长度。
- count: 0 完整校验全部资源、uniform 与选项后,不编码、不提交,也不消耗或清除已有的 encode-once 检查状态。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
count | number | 否 | 首个 state/input 缓冲长度 | 0..0xffffffff 内整数。调用索引范围为 [0, count),所有 state/input 容量须至少为 count。辅助数组具有独立边界。 |
示例
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();源码参考: src/core/kernel.ts
TYPESconstant
运行时 WGSL 大小、步长、对齐和 TypedArray 元数据表。
TYPES: Record<ScalarKind, TypeDef>;行为与约束
- TypeDef 是关联声明类型,不是根入口具名导出。不要修改此共享运行时表。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
TypeDef.size | number | — | — | 逻辑字节大小。 |
TypeDef.stride | number | — | — | storage 数组字节步长。 |
TypeDef.align | number | — | — | 字节对齐。 |
TypeDef.comps | number | — | — | 标量分量数。 |
TypeDef.typed | 'Float32Array' | 'Int32Array' | 'Uint32Array' | — | — | 预期 TypedArray 构造名称。 |
TypeDef.wgsl | string | — | — | WGSL 类型拼写。 |
f32 | {"size": 4, "stride": 4, "align": 4, "comps": 1, "typed": "Float32Array", "wgsl": "f32"} | — | — | 2.0.0 的精确表项。 |
i32 | {"size": 4, "stride": 4, "align": 4, "comps": 1, "typed": "Int32Array", "wgsl": "i32"} | — | — | 2.0.0 的精确表项。 |
u32 | {"size": 4, "stride": 4, "align": 4, "comps": 1, "typed": "Uint32Array", "wgsl": "u32"} | — | — | 2.0.0 的精确表项。 |
vec2f | {"size": 8, "stride": 8, "align": 8, "comps": 2, "typed": "Float32Array", "wgsl": "vec2f"} | — | — | 2.0.0 的精确表项。 |
vec2i | {"size": 8, "stride": 8, "align": 8, "comps": 2, "typed": "Int32Array", "wgsl": "vec2i"} | — | — | 2.0.0 的精确表项。 |
vec2u | {"size": 8, "stride": 8, "align": 8, "comps": 2, "typed": "Uint32Array", "wgsl": "vec2u"} | — | — | 2.0.0 的精确表项。 |
vec3f | {"size": 12, "stride": 16, "align": 16, "comps": 3, "typed": "Float32Array", "wgsl": "vec3f"} | — | — | 2.0.0 的精确表项。 |
vec4f | {"size": 16, "stride": 16, "align": 16, "comps": 4, "typed": "Float32Array", "wgsl": "vec4f"} | — | — | 2.0.0 的精确表项。 |
示例
import { TYPES } from 'wgpu-kit';
console.log(TYPES.vec3f.size, TYPES.vec3f.stride); // 12, 16源码参考: dist/core/layout.js
planUniformfunction
根据 WGSL 对齐规则计算有序 uniform 偏移。
export declare function planUniform(
entries: ReadonlyArray<readonly [string, ScalarKind]>,
): UniformLayout;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
entries | ReadonlyArray<readonly [string, ScalarKind]> | 是 | — | 有序字段名与类型对。允许空输入;此处不校验名称、类型有效性或重复项。 |
返回值
UniformLayout 字段偏移和填充后分配大小;该类型本身不是根入口具名导出。
错误与失败情况
- 运行时非法 kind 缺少 TYPES 项,可导致原生 TypeError;应遵循 ScalarKind 契约。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
fields | readonly UniformField[] | — | — | 有序字段元数据。 |
fields[].name | string | — | — | 字段名。 |
fields[].kind | ScalarKind | — | — | 元素类型。 |
fields[].offset | number | — | — | 按类型对齐的字节偏移。 |
size | number | — | — | 总字节数向上对齐到 16 的倍数,最小 16。 |
示例
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);源码参考: dist/core/layout.js
packUniformfunction
分配 ArrayBuffer 并以小端标量写入打包。
export declare function packUniform(
layout: UniformLayout,
values: Readonly<Record<string, UniformValue>>,
): ArrayBuffer;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
layout | UniformLayout | 是 | — | planUniform 返回的布局,或兼容的有序字段/偏移/大小对象。 |
values | Readonly<Record<string, UniformValue>> | 是 | — | 每个布局字段的值。额外键静默忽略,缺少字段为错误。 |
返回值
ArrayBuffer 新的零初始化 layout.size 字节缓冲区,写入各字段。
错误与失败情况
- 缺值、非有限标量、缺少或非法必需向量分量为 ERR_UNIFORM_FIELD;不支持的打包类型为 ERR_UNIFORM_UNSUPPORTED。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
fields | readonly UniformField[] | — | — | 有序字段元数据。 |
fields[].name | string | — | — | 字段名。 |
fields[].kind | ScalarKind | — | — | 元素类型。 |
fields[].offset | number | — | — | 按类型对齐的字节偏移。 |
size | number | — | — | 总字节数向上对齐到 16 的倍数,最小 16。 |
示例
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);源码参考: dist/core/layout.js
packUniformIntofunction
在调用方存储中打包,不分配新的 ArrayBuffer。
export declare function packUniformInto(
target: ArrayBuffer,
layout: UniformLayout,
values: Readonly<
Record<
string,
| number
| Readonly<{
x: number;
y: number;
z?: number;
w?: number;
}>
>
>,
): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
target | ArrayBuffer | 是 | — | 足以容纳所有字段写入的缓冲区。不会清空已有填充/未用字节。 |
layout | UniformLayout | 是 | — | planUniform 返回的布局,或兼容的有序字段/偏移/大小对象。 |
values | Readonly<Record<string, UniformValue>> | 是 | — | 每个布局字段的值。额外键静默忽略,缺少字段为错误。 |
返回值
void 仅修改 target。
错误与失败情况
- 缺值、非有限标量、缺少或非法必需向量分量为 ERR_UNIFORM_FIELD;不支持的打包类型为 ERR_UNIFORM_UNSUPPORTED。
- 字段写入超出 target 容量时产生原生 RangeError;不预先校验 target 长度。
示例
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);源码参考: dist/core/layout.js
ScalarKindtype
支持的标量/向量存储及 uniform 类型;名称沿用历史,但包含向量。
export type ScalarKind =
| 'f32'
| 'i32'
| 'u32'
| 'vec2f'
| 'vec2i'
| 'vec2u'
| 'vec3f'
| 'vec4f';字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
f32 | string literal | — | — | 支持的类型。 |
i32 | string literal | — | — | 支持的类型。 |
u32 | string literal | — | — | 支持的类型。 |
vec2f | string literal | — | — | 支持的类型。 |
vec2i | string literal | — | — | 支持的类型。 |
vec2u | string literal | — | — | 支持的类型。 |
vec3f | string literal | — | — | 支持的类型。 |
vec4f | string literal | — | — | 支持的类型。 |
示例
import type { ScalarKind } from 'wgpu-kit';
const positionKind: ScalarKind = 'vec3f';源码参考: dist/core/layout.js
UniformValuetype
uniform 打包使用的数值标量或分量对象。z/w 在 TS 联合类型中可选,但选定类型需要时必须提供。
export type UniformValue =
| number
| Readonly<{
x: number;
y: number;
z?: number;
w?: number;
}>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
x | number | 是 | — | 向量 x 分量。 |
y | number | 是 | — | 向量 y 分量。 |
z | number | 否 | — | vec3f/vec4f 必需,否则忽略。 |
w | number | 否 | — | vec4f 必需,否则忽略。 |
行为与约束
- 标量和必需向量分量必须有限。整数打包使用 DataView 转换,不显式校验整数性/范围。
示例
import type { UniformValue } from 'wgpu-kit';
const gain: UniformValue = 0.5;
const origin: UniformValue = { x: 1, y: 2, z: 3 };源码参考: dist/core/layout.js
WgpuKitErrorclass
带稳定机器可读代码的 Error 基类。
export declare class WgpuKitError extends Error字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
code | readonly ErrorCode | — | — | 稳定字符串代码。2.0.0 的根入口不导出 ErrorCode 或 ERR;可比较字符串字面量。 |
name | string | — | — | 运行时子类构造函数名称。 |
message | string | — | — | 继承的 Error 消息。 |
stack | string | undefined | — | — | 运行时可用时的标准 Error 堆栈。 |
ERR_WGPU_UNAVAILABLE | ErrorCode string literal | — | — | 缺少 WebGPU 或适配器。 |
ERR_COMPILE | ErrorCode string literal | — | — | WGSL 编译失败。 |
ERR_USAGE | ErrorCode string literal | — | — | 用法/参数错误。 |
ERR_UNIFORM_FIELD | ErrorCode string literal | — | — | uniform 字段缺失/非法。 |
ERR_UNIFORM_UNSUPPORTED | ErrorCode string literal | — | — | 不支持的 uniform 打包类型。 |
ERR_WORKGROUP_SIZE | ErrorCode string literal | — | — | 工作组大小非法。 |
ERR_RESOURCE_MISSING | ErrorCode string literal | — | — | 缺少声明资源。 |
ERR_RESOURCE_TYPE | ErrorCode string literal | — | — | 资源类型不匹配。 |
ERR_RESOURCE_LENGTH | ErrorCode string literal | — | — | 资源长度不一致。 |
ERR_BUFFER_CREATE | ErrorCode string literal | — | — | 缓冲区类型/长度非法。 |
ERR_BUFFER_WRITE | ErrorCode string literal | — | — | 缓冲区数据类型/长度非法。 |
ERR_MEDIA | ErrorCode string literal | — | — | 录制不可用/失败。 |
ERR_TIMESTAMP_UNSUPPORTED | ErrorCode string literal | — | — | timestamp-query 不可用。 |
ERR_GENERIC | ErrorCode string literal | — | — | 其他库错误。 |
constructorconstructor
创建带代码的库错误。
new WgpuKitError(code: ErrorCode, message: string)参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
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' | 是 | — | 声明联合类型中的稳定代码。 |
message | string | 是 | — | 可读错误消息。 |
返回值
WgpuKitError 新的错误实例;构造不会自动抛出。
示例
import { WgpuKitError } from 'wgpu-kit';
const error = new WgpuKitError('ERR_USAGE', 'Invalid input');示例
import { Buffer, WgpuKitError } from 'wgpu-kit';
try {
await Buffer.create('f32', 0);
} catch (error) {
if (error instanceof WgpuKitError) console.log(error.code, error.message);
}源码参考: dist/core/errors.js
CompileErrorclass
带用户相对诊断行号的 WGSL 编译错误,代码为 ERR_COMPILE。
export declare class CompileError extends WgpuKitError字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
code | 'ERR_COMPILE' | — | — | 继承的稳定代码。 |
messages[].line | number | — | — | 减去 userCodeOffset 之前从 1 开始的着色器行号。 |
messages[].msg | string | — | — | 编译器消息。 |
constructorconstructor
格式化 WGSL 诊断,并将生成代码行映射回用户代码。
new CompileError(
kernelName: string,
messages: readonly { line:number; msg:string }[],
userCodeOffset: number
)参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
kernelName | string | 是 | — | 诊断内核名称。 |
messages | readonly {line:number;msg:string}[] | 是 | — | 编译诊断;line 为从 1 开始的生成源码行号,msg 为文本。 |
userCodeOffset | number | 是 | — | 用户代码之前的生成行数。映射后 <=0 的行描述为生成代码;rawKernel 使用 0。 |
返回值
CompileError 新的错误实例;构造不会自动抛出。
示例
import { CompileError } from 'wgpu-kit';
const error = new CompileError('demo', [{ line: 14, msg: 'unknown identifier' }], 10);示例
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();源码参考: dist/core/errors.js
UsageErrorclass
带代码的调用方用法错误;构造函数接受声明联合类型中的任意 ErrorCode。
export declare class UsageError extends WgpuKitError字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
code | readonly ErrorCode | — | — | 给定的稳定代码。 |
constructorconstructor
创建保留给定代码/消息的错误。
new UsageError(code: ErrorCode, message: string)参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
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' | 是 | — | 稳定错误代码字面量。 |
message | string | 是 | — | 具体用法问题。 |
返回值
UsageError 新的错误实例;构造不会自动抛出。
示例
import { UsageError } from 'wgpu-kit';
const error = new UsageError('ERR_RESOURCE_LENGTH', 'Buffers must have equal length');示例
import { Buffer, WgpuKitError } from 'wgpu-kit';
try {
await Buffer.create('f32', 0);
} catch (error) {
if (error instanceof WgpuKitError) console.log(error.code, error.message);
}源码参考: dist/core/errors.js
listPacksfunction
依次枚举内置定义与用户注册项。
export declare function listPacks(): Array<{
name: string;
description: string;
}>;参数
此调用不接收参数。
返回值
Array<{name:string;description:string}> 仅含元数据;缺省 description 变为空字符串。
行为与约束
- 2.0.0 的内置注册表包含 particles。枚举不会创建模拟或分配 GPU 资源。
示例
import { listPacks } from 'wgpu-kit';
console.log(listPacks());源码参考: dist/index.js
getPackfunction
先查内置定义,再查用户注册表。
export declare function getPack<TConfig = unknown>(
name: string,
): WgpuKitPack<TConfig, PackSim> | undefined;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
name | string | 是 | — | 精确、区分大小写的注册名称。 |
返回值
WgpuKitPack<TConfig, PackSim> | undefined 找到时返回定义,否则 undefined。编译期 TConfig 默认 unknown。
行为与约束
- 泛型属于调用方提供的类型断言;查找不会校验配置,也不会创建模拟。
示例
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();源码参考: dist/index.js