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.
createNeighborGridfunction
Allocate and prepare a two-dimensional count/sort neighbor-grid index.
createNeighborGrid(config: NeighborGridConfig): Promise<NeighborGrid>;Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
config | NeighborGridConfig | Yes | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
count | number | Yes | — | Positive integer entity count. The supplied position buffer must contain this many vec2f elements. |
worldHalf | number | Yes | — | Half-width of the square world on each axis, nominally [-worldHalf, worldHalf]. Use a finite positive value; 2.0.0 does not validate it. |
cellSize | number | Yes | — | Requested cell size. gridSize=max(1, ceil(2*worldHalf/cellSize)), so actual cell width is 2*worldHalf/gridSize and can be smaller. |
workgroupSize | number | No | 64 | Declared 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 NeighborGridBehavior & 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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
encoder | GPUCommandEncoder | Yes | — | Unfinished encoder from the shared device. No active pass may lock it. The method does not submit or finish it. |
pos | Buffer | Yes | — | Caller-owned vec2f storage buffer with count positions on the same device. No dedicated kind/length validation is performed here. |
batch | ComputeBatch | No | — | 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
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
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
pos | Buffer | Yes | — | 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
支持调用方控制命令提交的可复用二维 GPU 空间索引。
辅助输入、dispatch count、托管批次与类型化内核已随 2.1.0 发布。原 API 仍以 npm 2.0.0 声明与实现为历史核对基线;2.1.0 和 2.2.0 新增能力在对应 API 中注明并引用 src 文件,不代表整份 API 重新审计。只列出此入口实际导出的公开 API。
createNeighborGridfunction
分配并准备二维计数/排序邻域网格索引。
createNeighborGrid(config: NeighborGridConfig): Promise<NeighborGrid>;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
config | NeighborGridConfig | 是 | — | 网格尺寸和实体数量,各字段见下方。 |
返回值
Promise<NeighborGrid> 已就绪的网格,拥有自己的 u32 索引缓冲;输入位置缓冲仍由调用者拥有。
行为与约束
- 工厂已经准备内部 scan 和管线;显式 prepare() 幂等,可用于统一的组合工作流。
- 方形范围外的位置通过 clamp 归入边缘格子;这不是环绕世界的邻域索引。格子之间有序,但不保证格内实体顺序稳定。
- 不要直接假设 3×3 邻域覆盖交互半径:ceil 分格可能使实际格宽小于 cellSize,应根据实际格宽计算搜索格数。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
错误与失败情况
- count 非正整数或 cellSize 不大于 0 时抛出普通 Error。上下文/分配错误和 CompileError 也可能导致拒绝。不全面验证 worldHalf、workgroupSize 或缓冲/设备尺寸是否可行。
示例
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();源码参考: src/packs/grid/index.ts
NeighborGridConfiginterface
createNeighborGrid 的配置。
interface NeighborGridConfig {
count: number;
worldHalf: number;
cellSize: number;
workgroupSize?: number;
}参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
count | number | 是 | — | 实体数量,必须为正整数。输入位置缓冲应含这么多个 vec2f 元素。 |
worldHalf | number | 是 | — | 每轴方形世界的半宽,范围通常为 [-worldHalf, worldHalf]。应使用有限正数;2.0.0 不验证此值。 |
cellSize | number | 是 | — | 请求的格子尺寸。gridSize=max(1, ceil(2*worldHalf/cellSize)),因此实际格宽为 2*worldHalf/gridSize,可能比请求值小。 |
workgroupSize | number | 否 | 64 | 声明中的配置项,但 2.0.0 实现未使用它;shader 和 dispatch 都固定使用 64。 |
NeighborGridinterface
网格拥有的缓冲及操作;结束使用后销毁。
interface NeighborGrid行为与约束
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
- cellStart、cellFill、order 是共享公开输出缓冲。必须在下一次建格覆盖前通过后续 pass 消费;托管 scratch 独立不会保留旧网格输出。
gridSizereadonly property
每轴格子数:max(1, ceil(2*worldHalf/cellSize))。
readonly gridSize: number;返回值
number 创建时固定。
cellsreadonly property
总格子数,即 gridSize × gridSize。
readonly cells: number;返回值
number cellStart 和 cellFill 的长度。
cellStartproperty
各格子独占起始槽位,网格拥有的 u32 缓冲。
cellStart: Buffer;返回值
Buffer 含 cells 个元素;cellStart[c] 是 order 中的包含式起点。
cellFillproperty
scatter 后各格子的排他终止槽位,网格拥有的 u32 缓冲。
cellFill: Buffer;返回值
Buffer 含 cells 个元素。格子 c 的成员位于 order[cellStart[c]..cellFill[c]);此值不是格内数量。
orderproperty
按格子分组的实体下标,网格拥有的 u32 缓冲。
order: Buffer;返回值
Buffer 含 count 个元素;order[slot] 是原始实体下标。
preparemethod
幂等地准备内部 scan。
prepare(): Promise<void>;参数
此调用不接收参数。
返回值
Promise<void> 编码所需依赖就绪时完成。
encodemethod
向调用者 encoder 追加 counts → scan → post → scatter pass。
encode(encoder: GPUCommandEncoder, pos: Buffer, batch?: ComputeBatch): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
encoder | GPUCommandEncoder | 是 | — | 来自共享设备、尚未完成的 encoder。不能被未结束的 pass 占用;方法不会自动 finish 或提交。 |
pos | Buffer | 是 | — | 调用者拥有、同一设备上的 vec2f storage 缓冲,含 count 个位置。此处没有专门的 kind/length 校验。 |
batch | ComputeBatch | 否 | — | 可选托管作用域,从 wgpu-kit 导入;encoder 须为 batch.encoder,并通过 batch.submit() 提交。 |
返回值
void 无返回值。
行为与约束
- 省略 batch 时每个网格实例每次提交只能 encode 一次,提交后调用 endSubmit()。传入 batch 后内部参数/scratch 独立,可重复建格且无需 endSubmit(),原生闸不变。
- cellStart、cellFill、order 是共享公开输出缓冲。必须在下一次建格覆盖前通过后续 pass 消费;托管 scratch 独立不会保留旧网格输出。
- 原生路径违规重复调用失败时,内部 scan 闸拒绝前可能已写入 counts pass,应丢弃该原生 encoder。批次生命周期会在写入网格任务前校验。
- 2.1.0 新增:托管批次与类型化内核调用依据对应 src 文件记录,在 npm 2.0.0 历史审计基线之上扩展。
错误与失败情况
- 重复原生编码、批次关闭/不匹配时传播 UsageError;资源或 encoder 状态不兼容时产生 WebGPU 校验/设备错误。缓冲设备归属是调用方前提。
示例
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
调用方原生提交后重置内部 scan 的 encode-once 闸;托管批次不需要或改变此闸。
endSubmit(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 不提交,也不等待完成。提前调用会绕过预期生命周期,可能错误复用共享缓冲。
updatemethod
使用内部 encoder 和队列提交的便捷建格。
update(pos: Buffer): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
pos | Buffer | 是 | — | 与 encode(pos) 相同的 vec2f、count 和设备要求。 |
返回值
void 无返回值。
行为与约束
- 提交后自动调用 endSubmit。返回时 GPU 未必已完成;通过队列顺序或 Buffer.read() 同步依赖工作。
destroymethod
销毁网格拥有的索引、计数、uniform 和 scan 资源。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 不销毁调用者的位置缓冲。销毁前停止 encode/update;销毁后不要使用网格缓冲。
源码参考: src/packs/grid/index.ts