wgpu-kit/particles
Four-species particle simulation API; configuration and lifecycle, without preset marketing.
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 ↗ 3 ↗ 4 ↗ 5 ↗ 6 ↗
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();
}ParticlesConfiginterface
All options are optional; defaults below come from the installed 2.0.0 implementation.
interface ParticlesConfigParameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
count | number | No | 8192 | 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 | ForcePresetName | 'random' | ForceMatrix | No | 'cells' | One of cells/snakes/orbitals/viruses, seeded random, or a readonly 16-number tuple. Four species use matrix[mySpecies*4+otherSpecies]; custom arrays are not length/range-validated here. |
mode | 'n2' | 'tiled' | 'grid' | No | 'grid' | 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' | No | 'species' | Canvas coloring by four species or speed magnitude. Used when the renderer is attached. |
bounds | 'wrap' | 'clamp' | No | 'wrap' | How updated positions remain in the square world: wrap or clamp. Interaction distances/neighborhood searches do not wrap across opposite edges. |
seed | string | number | No | 'wgpu-kit' | Converted to String(seed), then hashed; initializes positions/species and the random force matrix deterministically. |
rMax | number | No | 0.12 | Maximum interaction radius in world units. Use a finite positive number. Also affects grid resolution. |
beta | number | No | 0.3 | Piecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API. |
forceFactor | number | No | 10 | Acceleration scale: summed interactions are multiplied by forceFactor*rMax before integration. |
frictionHalfLife | number | No | 0.04 | 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 | No | 0.02 | Base simulation time step per tick, multiplied by the tick argument. The animation callback elapsed time is not measured automatically. |
pointSize | number | No | 0.004 | 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 | No | 8100 | Grid-only candidate budget: ceil(maxNeighbors/9) candidates per each of up to 9 neighboring cells (self may count). Use a finite positive number. |
Behavior & constraints
- maxNeighbors=Infinity does not disable the cap in 2.0.0 despite the declaration comment: DataView.setUint32 converts Infinity to 0, and the shader then processes no candidates. Use a sufficiently large finite budget when needed.
- No package export exists for the internal config/presets file paths. Use public ParticlesConfig and its indexed types, not wgpu-kit/dist/... imports.
Fields & 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"]>. |
Examples
import type { ParticlesConfig } from 'wgpu-kit/particles';
const options = {
count: 2048,
mode: 'grid',
color: 'velocity',
bounds: 'clamp',
seed: 42,
rMax: 0.12,
beta: 0.3,
forceFactor: 8,
frictionHalfLife: 0.04,
dt: 0.02,
pointSize: 0.004,
maxNeighbors: 8100,
forces: [0, 0.4, -0.2, 0, -0.3, 0, 0.4, 0, 0.2, -0.3, 0, 0.4, 0, 0.2, -0.3, 0],
} satisfies ParticlesConfig;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
sim.tick();
const { pos, vel, species } = sim.buffers();
const positions = await pos.read();
console.log(positions);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.
四物种粒子模拟 API,完整说明配置和生命周期,不将预设作为营销展示。
辅助输入、dispatch count、托管批次与类型化内核已随 2.1.0 发布。原 API 仍以 npm 2.0.0 声明与实现为历史核对基线;2.1.0 和 2.2.0 新增能力在对应 API 中注明并引用 src 文件,不代表整份 API 重新审计。只列出此入口实际导出的公开 API。
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();
}ParticlesConfiginterface
所有选项均可选;以下默认值来自已安装 2.0.0 的实现。
interface ParticlesConfig参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
count | number | 否 | 8192 | 粒子数量,整数范围 1..1_000_000。n2 模式拒绝超过 32_000 的数量(其错误文案建议不超过 20_000)。设备内存限制可能更低。 |
forces | ForcePresetName | 'random' | ForceMatrix | 否 | 'cells' | 可选 cells/snakes/orbitals/viruses、带种子的 random 或只读 16 数值元组。四个物种按 matrix[mySpecies*4+otherSpecies] 取值;此处不校验自定义数组长度/范围。 |
mode | 'n2' | 'tiled' | 'grid' | 否 | 'grid' | 邻域算法:全量两两计算、workgroup 分块两两计算或空间网格。声明中默认 tiled 的注释已过时;实现默认 grid。 |
color | 'species' | 'velocity' | 否 | 'species' | 画布按四种物种或速度大小着色,attach 渲染器时生效。 |
bounds | 'wrap' | 'clamp' | 否 | 'wrap' | 更新后位置如何保持在方形世界内:环绕或钳位。交互距离/邻域搜索不会跨相对边界环绕。 |
seed | string | number | 否 | 'wgpu-kit' | 转换为 String(seed) 后散列,确定性地初始化位置、物种和 random 力矩阵。 |
rMax | number | 否 | 0.12 | 世界单位下的最大交互半径,应使用有限正数,也影响网格分辨率。 |
beta | number | 否 | 0.3 | 归一化距离 d/rMax 下的分段力曲线分界点。合理值在 0 与 1 之间;API 不验证。 |
forceFactor | number | 否 | 10 | 加速度缩放;交互总和在积分前乘以 forceFactor*rMax。 |
frictionHalfLife | number | 否 | 0.04 | 阻尼时间参数,实际公式为 exp(-effectiveDt/frictionHalfLife)。虽然名称含 HalfLife,实现没有 ln(2),数学上是指数衰减时间常数,不是真正半衰期。应使用有限正数。 |
dt | number | 否 | 0.02 | 每次 tick 的基础模拟时间步,乘以 tick 参数;不会自动测量动画回调经过的时间。 |
pointSize | number | 否 | 0.004 | attach 渲染器使用的归一化点四边形半尺寸,经世界缩放后近似为裁剪空间坐标尺寸。它不是直接像素值;shader 生成时会把缩放后的值保留四位小数。 |
maxNeighbors | number | 否 | 8100 | 仅 grid 使用的候选预算:最多 9 个相邻格子,每格检查 ceil(maxNeighbors/9) 个候选(自身也可能计入)。应使用有限正数。 |
行为与约束
- 尽管声明注释这样描述,2.0.0 的 maxNeighbors=Infinity 并不会禁用上限:DataView.setUint32 将 Infinity 转为 0,shader 随后不处理任何候选。需要时应使用足够大的有限预算。
- 内部 config/presets 文件路径未在 package exports 中暴露。应使用公共 ParticlesConfig 及其索引类型,不要导入 wgpu-kit/dist/...。
字段与关联类型
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
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"]> 获取。 |
示例
import type { ParticlesConfig } from 'wgpu-kit/particles';
const options = {
count: 2048,
mode: 'grid',
color: 'velocity',
bounds: 'clamp',
seed: 42,
rMax: 0.12,
beta: 0.3,
forceFactor: 8,
frictionHalfLife: 0.04,
dt: 0.02,
pointSize: 0.004,
maxNeighbors: 8100,
forces: [0, 0.4, -0.2, 0, -0.3, 0, 0.4, 0, 0.2, -0.3, 0, 0.4, 0, 0.2, -0.3, 0],
} satisfies ParticlesConfig;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 的物种标签,独立于双缓冲状态。 |
示例
sim.tick();
const { pos, vel, species } = sim.buffers();
const positions = await pos.read();
console.log(positions);destroymethod
释放实现中负责清理的粒子、矩阵、uniform、网格和渲染器资源。
destroy(): void;参数
此调用不接收参数。
返回值
void 无返回值。
行为与约束
- 先取消动画循环并停止使用借用缓冲。不自动取消 RAF、不取消画布配置、不提供销毁状态防护,也不移除错误监听器。
- 避免在 setParams 异步重建网格期间销毁;2.0.0 不提供等待或取消该重建的方式。