API REFERENCE · 2.2.0

wgpu-kit/grid

Reusable 2D GPU spatial indexing with caller-controlled command submission.

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.

Source reference: 1 ↗ 2 ↗

createNeighborGridfunction

Allocate and prepare a two-dimensional count/sort neighbor-grid index.

createNeighborGrid(config: NeighborGridConfig): Promise<NeighborGrid>;

Parameters

NameTypeRequiredDefaultMeaning
configNeighborGridConfigYes—Grid dimensions and entity count; every field is specified below.

Returns

Promise<NeighborGrid> Ready grid with owned u32 index buffers. The input position buffer remains caller-owned.

Behavior & constraints

  • Factory already prepares the internal scan and pipelines. Explicit prepare() is idempotent and useful in generic composed workflows.
  • Positions outside the square are assigned to edge cells by clamping. This is not a toroidal/wrapping neighbor index. Cell order is sorted; order within a cell is not promised stable.
  • Do not assume a 3×3 neighborhood covers your radius: ceil-based subdivision can make cells smaller than cellSize. Compute the search radius in cells from actual width.
  • 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

  • Throws plain Error for non-positive/non-integer count or cellSize not greater than zero. Allocation/context errors and CompileError can reject. worldHalf/workgroupSize and buffer/device-size feasibility are not fully validated.

Examples

Build a grid in a caller-owned command encoder and read its index.
import { Buffer, GpuContext } from 'wgpu-kit';
import { createNeighborGrid } from 'wgpu-kit/grid';
const pos = await Buffer.create('vec2f', 3);
pos.write(new Float32Array([-0.5, 0, 0, 0, 0.5, 0]));
const grid = await createNeighborGrid({ count: 3, worldHalf: 1, cellSize: 0.25 });
await grid.prepare();
const ctx = await GpuContext.get();
const encoder = ctx.device.createCommandEncoder();
grid.encode(encoder, pos);
// Encode downstream consumers of grid.cellStart/cellFill/order here.
ctx.device.queue.submit([encoder.finish()]);
grid.endSubmit();
const starts = await grid.cellStart.read();
const ends = await grid.cellFill.read();
const order = await grid.order.read();
console.log(starts, ends, order);
grid.destroy();
pos.destroy();

Source reference: src/packs/grid/index.ts

NeighborGridConfiginterface

Configuration accepted by createNeighborGrid.

interface NeighborGridConfig {
  count: number;
  worldHalf: number;
  cellSize: number;
  workgroupSize?: number;
}

Parameters

NameTypeRequiredDefaultMeaning
countnumberYes—Positive integer entity count. The supplied position buffer must contain this many vec2f elements.
worldHalfnumberYes—Half-width of the square world on each axis, nominally [-worldHalf, worldHalf]. Use a finite positive value; 2.0.0 does not validate it.
cellSizenumberYes—Requested cell size. gridSize=max(1, ceil(2*worldHalf/cellSize)), so actual cell width is 2*worldHalf/gridSize and can be smaller.
workgroupSizenumberNo64Declared configuration option but ignored by 2.0.0 implementation; shader and dispatch both use the fixed value 64.

NeighborGridinterface

Owned grid buffers and operations; destroy them when finished.

interface NeighborGrid

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.
  • cellStart, cellFill and order are shared public output buffers. Consume them in downstream passes before another build overwrites them. Managed scratch isolation does not preserve old grid outputs.

gridSizereadonly property

Number of cells on each axis: max(1, ceil(2*worldHalf/cellSize)).

readonly gridSize: number;

Returns

number Fixed at creation.

cellsreadonly property

Total cell count, gridSize × gridSize.

readonly cells: number;

Returns

number Length of cellStart and cellFill.

cellStartproperty

Owned u32 buffer of exclusive starting slots per cell.

cellStart: Buffer;

Returns

Buffer cells elements; use cellStart[c] as the inclusive start in order.

cellFillproperty

Owned u32 buffer of exclusive ending slots after scatter.

cellFill: Buffer;

Returns

Buffer cells elements. Members of cell c occupy order[cellStart[c]..cellFill[c]); this value is not the occupancy count.

orderproperty

Owned u32 entity-index buffer, grouped by cell.

order: Buffer;

Returns

Buffer count elements; order[slot] is the original entity index.

preparemethod

Idempotently prepare the internal scan.

prepare(): Promise<void>;

Parameters

This call takes no arguments.

Returns

Promise<void> Resolves when encoding dependencies are ready.

encodemethod

Append counts → scan → post → scatter passes to the caller encoder.

encode(encoder: GPUCommandEncoder, pos: Buffer, batch?: ComputeBatch): void;

Parameters

NameTypeRequiredDefaultMeaning
encoderGPUCommandEncoderYes—Unfinished encoder from the shared device. No active pass may lock it. The method does not submit or finish it.
posBufferYes—Caller-owned vec2f storage buffer with count positions on the same device. No dedicated kind/length validation is performed here.
batchComputeBatchNo—Optional managed scope from wgpu-kit. Encoder must equal batch.encoder; call batch.submit() rather than submitting it yourself.

Returns

void No return value.

Behavior & constraints

  • Without batch, one encode per grid instance per submission, followed by endSubmit(). With batch, repeated builds use independent internal parameters/scratch and need no endSubmit(); the native guard is unchanged.
  • cellStart, cellFill and order are shared public output buffers. Consume them in downstream passes before another build overwrites them. Managed scratch isolation does not preserve old grid outputs.
  • On a failed native repeated call, the counts pass may already be encoded before the internal scan guard rejects it. Discard that native encoder. Batch lifecycle is validated before grid work is recorded.
  • 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

  • Propagates UsageError for repeated native encoding, closed/mismatched batches, and WebGPU validation/device errors for incompatible resources or encoder state. Buffer device ownership is a caller precondition.

Examples

Managed grid build
import { Buffer, createBatch } from 'wgpu-kit';
import { createNeighborGrid } from 'wgpu-kit/grid';
const pos = await Buffer.create('vec2f', 2);
pos.write(new Float32Array([-0.2, 0, 0.2, 0]));
const grid = await createNeighborGrid({ count: 2, worldHalf: 1, cellSize: 0.25 });
await grid.prepare();
const batch = await createBatch();
grid.encode(batch.encoder, pos, batch);
// Append a consumer of cellStart/cellFill/order before another build.
batch.submit();
console.log(await grid.order.read());
grid.destroy();
pos.destroy();

endSubmitmethod

Reset the internal scan native encode-once guard after a caller-owned submission. Managed batch encoding neither needs nor changes this guard.

endSubmit(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Does not submit or wait for completion. Calling early bypasses the intended lifecycle and can produce incorrect shared-buffer use.

updatemethod

Convenience build with an internal encoder and queue submission.

update(pos: Buffer): void;

Parameters

NameTypeRequiredDefaultMeaning
posBufferYes—Same vec2f/count/device requirements as encode(pos).

Returns

void No return value.

Behavior & constraints

  • Automatically calls endSubmit after submitting. Returns before GPU execution completes; queue ordering or Buffer.read() synchronizes dependent work.

destroymethod

Destroy grid-owned index, count, uniform, and scan resources.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Does not destroy the caller position buffer. Stop encoding/updating before disposal; do not use grid buffers after destruction.

Source reference: src/packs/grid/index.ts

Search concepts, APIs, and examples