# @ferret/vfx: API

Special effects: fire and smoke, explosions and weapons, water, steam and dust, energy. Effects are JSON definitions with parameters and expressions, drawn on a ladder of volume, GPU particles, impostors and dots, fed by the physics events or placed by hand, with their sound, and acting on sight, light and fire spread.

353 exports. Generated from the source (`packages/vfx/src`), so it matches the code.

## Classes

### BakedVolumePlayer

*class* · `packages/vfx/src/volume.ts:159`

```ts
class BakedVolumePlayer implements VolumeSource
```

a baked sequence played at the instance's time, the two nearest frames blended

- `readonly n: number` — voxels along each side of the texture
- `readonly size: number` — metres along each side of the box the volume fills
- `readonly scale: number` — a point of the box at uvw in 0..1 reads the texture at uvw * scale + bias
- `readonly bias: number`
- `readonly data: Uint8Array` — two bytes per voxel: density, heat
- `readonly densityMax: number`
- `readonly heatMax: number` — the temperature a full heat byte means, and the air's (a zero one), kelvin
- `readonly ambient: number`
- `version: number` — changes whenever `data` does, so the view uploads only what is new
- `constructor(private readonly src: BakedVolumeData, private readonly def: VolumeRender)`
- `origin(inst: Instance, out: [number, number, number]): void` — the lowest corner of the box in the world
- `update(inst: Instance, _dt: number): boolean` — advances to the time of the instance; true when `data` changed

### BatchData

*class* · `packages/vfx/src/gather.ts:11`

```ts
class BatchData
```

the arrays of one batch of billboards, streaks or ribbon segments (four floats each, ready for the instance buffers)

- `n: number`
- `cap: number`
- `pos: Float32Array` — x, y, z (relative to the batch origin) and size; a ribbon segment: its start and the width there
- `col: Float32Array` — r, g, b, alpha
- `misc: Float32Array` — rotation (radians), the position in the flipbook 0..1, glow multiplier, soft-fade distance (streak: length in metres)
- `vel: Float32Array` — velocity (streak) or the end point and the width there (ribbon segment)
- `keys: Float32Array` — the sort key, larger drawn first
- `constructor(cap = 256)`
- `grow(cap: number)`
- `next(): number` — a free slot (the arrays grow by doubling)
- `clear()`

### DecalScheduler

*class* · `packages/vfx/src/parts.ts:127`

```ts
class DecalScheduler
```

decides when the decals of instances appear: once each, at `start`, at a number of seconds, or at `end` (stopped or ended)

- `due(inst: Instance): DecalSpec[]` — the decals due now for this instance (their positions are the instance's, the view puts them on the ground)
- `forget(live: ReadonlySet<number>): void`

### DropletPool

*class* · `packages/vfx/src/droplets.ts:183`

```ts
class DropletPool
```

- `readonly capacity: number`
- `readonly parcels: Float32Array`
- `readonly emitterData: Float32Array`
- `readonly impacts: Float32Array`
- `impactCount: number`
- `head: number`
- `time: number`
- `readonly liquid: LiquidProps`
- `readonly diffusivity: number`
- `readonly cloud0: number`
- `readonly maxImpacts: number`
- `readonly seed: number`
- `alive: number` — parcels alive after the last step
- `constructor(o: DropletPoolOptions)`
- `plan(emitters: readonly DropletEmitter[], dt: number): number` — pack this step's emission: the number of new parcels; the GPU execution uses the same packing
- `advance(total: number): void` — advance the head after `total` parcels were emitted (the ring)
- `step(emitters: readonly DropletEmitter[], dt: number, air: DropletAir, surface: SurfaceGrid | null): void` — one step on the CPU: emit, move, break up, land

### DropletView

*class* · `packages/vfx/src/droplets-view.ts:90`

```ts
class DropletView
```

- `readonly gpu: boolean`
- `readonly capacity: number`
- `readonly mesh: BABYLON.Mesh`
- `readonly material: BABYLON.ShaderMaterial`
- `impacts: Float32Array` — impacts on water of the last step that came back: x z diameter speed, `impactCount` of them
- `impactCount: number`
- `get alive(): number` — parcels alive (the CPU path counts them; the GPU path does not read them back: -1)
- `constructor(readonly scene: BABYLON.Scene, readonly o: DropletViewOptions = {})`
- `step(emitters: readonly DropletEmitter[], dt: number, air: DropletAir, surface: SurfaceGrid | null): void` — one step: the emitters shed parcels, all parcels move in the air and land; on WebGPU this only records compute passes
- `dispose(): void`

### Exposure

*class* · `packages/vfx/src/spread.ts:290`

```ts
class Exposure
```

a target that accumulates heating over time: the share of its time to ignition it has used (exposure adds as dt over the ignition time at that flux)

- `constructor(readonly material: Combustible, readonly T0 = 293.15)`
- `add(flux: number, dt: number): boolean` — adds dt seconds at the given flux; true once the surface has reached its ignition temperature
- `get fraction()`
- `reset()`

### ExprError

*class* · `packages/vfx/src/expr.ts:6`

```ts
class ExprError extends Error
```

- `constructor(message: string, readonly at: number)`

### FireBridge

*class* · `packages/vfx/src/spread-bridge.ts:25`

```ts
class FireBridge
```

- `constructor(private sim: VfxSim, readonly spread: FireSpread | null, private o: BridgeOptions = {})`
- `addTarget(t: Target)`
- `apply(events: SpreadEvent[])` — puts the model's events in the world: call after `spread.step(t)` with what it returned
- `adopt(events: SpreadEvent[], find: (def: string, seed: number) => VfxHandle | undefined, cellEffect = this.o.cellEffect ?? 'fire.grass')` — After a late join: the cells that burn now already have their effects (they came in the simulation's snapshot); this finds them again by (effect, seed) so `apply` can stop them when the cell goes out. `events` are what the front's replay gave; `find` looks up a live effect by its definition name and seed.
- `heat(fires: Array<{ at: Vec3; power: number }>, dt: number)` — the heat the fires of the scene deliver to the targets in dt seconds; targets that reach ignition catch (`vfx:ignite` with cause `heat`)
- `burning(): Array<{ at: Vec3; power: number }>` — the fire effects burning now, as (position, power) for `heat`
- `water(targetId: number, flow: number, efficiency = 1): boolean` — water of mass flow `flow` (kg/s) reaches the burning target : its power falls by the energy balance (a rate against a rate), and at zero it is out (`vfx:out`, cause `water`)

### FireSpread

*class* · `packages/vfx/src/spread.ts:172`

```ts
class FireSpread
```

A fire front on a grid of fuel cells. A cell burns from its arrival for the residence time of its fuel. The arrival at a neighbour is the arrival here plus the
distance over the speed along that edge, taken from the ellipse of a point fire under the wind and slope at the moment the source cell ignites; the earliest
arrival wins. Time is advanced by `step(t)`; everything is a function of the inputs, so the same inputs give the same fire.

- `readonly cells: Cell[]`
- `constructor(readonly grid: SpreadGrid, private env: SpreadEnv, private o: SpreadOptions = {})`
- `index(ix: number, iz: number)`
- `cellAt(x: number, z: number): number`
- `centre(i: number): [number, number]`
- `setFuel(i: number, bed: FuelBed | null, moisture?: number)`
- `setMoisture(i: number, m: number)`
- `wet(i: number, moisture: number, t: number, events?: SpreadEvent[])` — rain or water on a cell wets its fuel; a wet enough cell cannot burn and one that is burning is put out
- `ignite(i: number, t: number, from?: number): boolean` — lights a cell at time t; false if it cannot burn
- `get burningCells(): ReadonlySet<number>`
- `get spots()`
- `step(t: number): SpreadEvent[]` — advances the fire to time t; returns what happened since the last call, in time order

### FluidGrid

*class* · `packages/vfx/src/grid.ts:40`

```ts
class FluidGrid
```

a cubic grid of cells with a solid one-cell wall around (the floor and the sides), velocity, density and temperature

- `readonly nx: number`
- `readonly ny: number`
- `readonly nz: number`
- `readonly u: Float32Array`
- `readonly v: Float32Array`
- `readonly w: Float32Array`
- `readonly d: Float32Array`
- `readonly t: Float32Array`
- `readonly o: GridOptions`
- `time: number`
- `constructor(nx: number, ny: number, nz: number, readonly seed: number, o: Partial<GridOptions> = {})`
- `get size(): number`
- `idx(x: number, y: number, z: number): number`
- `addSphere(cx: number, cy: number, cz: number, r: number, s: { density?: number; temperature?: number; up?: number; out?: number; set?: boolean }): void` — adds a soft sphere of density, heat and an outward + upward velocity; (cx, cy, cz) and `r` are in cells
- `step(dt: number): void` — one step of `dt` seconds
- `project(): void` — subtracts the gradient of the pressure that makes the velocity divergence-free
- `sample(f: Float32Array, x: number, y: number, z: number): number` — trilinear sample of a field at a position in cells (clamped inside the grid)
- `divergence(): number` — the divergence of the velocity, summed in absolute value (for tests)
- `mass(): number` — total density (for tests)

### Governor

*class* · `packages/vfx/src/governor.ts:41`

```ts
class Governor
```

- `level: number`
- `constructor(readonly o: GovernorOptions)`
- `get step(): GovernorStep`
- `update(frameMs: number, particles = 0): boolean` — feed one frame: the time effects took and the number of live particles; returns true if the level changed
- `apply(sys: VfxSystem)` — puts the current step on a simulation (the rung cap is read by the view from `step.cap`)
- `reset()`

### LibraryTextures

*class* · `packages/vfx/src/textures.ts:80`

```ts
class LibraryTextures implements TextureProvider
```

The library's flipbooks (baked in F2) under the ids the definitions already use. `preload` brings the images from the library and decodes them; until an id is
loaded, or when the library does not have it, `get` falls back to the provider it was given (the generated one), so an effect never waits and never fails to draw.

- `constructor(private load: (id: string) => Promise<LibraryFlipbook>, private fallback: TextureProvider = new ProceduralTextures())`
- `async preload(ids: string[], scene: BABYLON.Scene): Promise<string[]>` — loads these ids into the scene; an id the library lacks is skipped (and reported in the returned list)
- `put(id: string, lf: LibraryFlipbook, scene: BABYLON.Scene): boolean` — uses these images for the id at once (a flipbook just baked, or one the caller loaded itself); replaces any earlier one; false if there is no color image
- `get(id: string | undefined, scene: BABYLON.Scene): Flipbook`
- `dispose(): void`

### LightBudget

*class* · `packages/vfx/src/parts.ts:76`

```ts
class LightBudget
```

Which lights the frame can afford. The score is the light's contribution at the camera, intensity x range^2 / (distance^2 + 1); the best `max` win, the ones that were
lit last frame get a bonus so two close scores do not swap every frame, and a light fades in and out over `fade` seconds so none pops.

- `constructor(public max: number, readonly fade = 0.3, readonly bonus = 1.3)`
- `update(cands: ReadonlyArray<LightState>, cam: readonly [number, number, number], dt: number): Array<{ light: LightState; weight: number }>` — returns the lights to show with their fade weight (0..1); `dt` seconds since the last call
- `get lit(): number` — lights that are lit or fading now

### LiveVolume

*class* · `packages/vfx/src/volume.ts:45`

```ts
class LiveVolume implements VolumeSource
```

a live grid, fed by particles

- `readonly n: number` — voxels along each side of the texture
- `readonly size: number` — metres along each side of the box the volume fills
- `readonly scale: number` — a point of the box at uvw in 0..1 reads the texture at uvw * scale + bias
- `readonly bias: number`
- `readonly data: Uint8Array` — two bytes per voxel: density, heat
- `readonly densityMax: number`
- `readonly heatMax: number` — the temperature a full heat byte means, and the air's (a zero one), kelvin
- `readonly ambient: 300`
- `version: number` — changes whenever `data` does, so the view uploads only what is new
- `readonly grid: FluidGrid`
- `constructor(private readonly def: VolumeRender, o: LiveOptions = {})`
- `origin(inst: Instance, out: [number, number, number]): void` — the lowest corner of the box in the world
- `update(inst: Instance, dt: number): boolean` — advances to the time of the instance; true when `data` changed

### PartsLayer

*class* · `packages/vfx/src/parts-view.ts:149`

```ts
class PartsLayer
```

- `stats: { lights: number; strips: number; dots: number; decals: number; glows: number; }`
- `constructor(private readonly scene: BABYLON.Scene, private readonly o: PartsViewOptions = {})`
- `get maxLights(): number`
- `begin(): void`
- `setLights(chosen: ReadonlyArray<{ light: LightState; weight: number }>): void` — the lights the budget chose, with their fade weight
- `addStrip(foot: readonly [number, number, number], s: StripShape, fade: number): void` — a distant plume: a strip standing on `foot` (camera-relative); `fade` is the cross-fade weight of the rung
- `addDot(at: readonly [number, number, number], d: DotLook, fade: number): void` — a dot: `at` camera-relative, sized in the world to be a few pixels across
- `addGlow(at: readonly [number, number, number], rgb: readonly [number, number, number], radius: number, alpha: number): void` — the cheap glow of a light that did not fit the budget: a soft additive disc, `radius` metres, `alpha` by distance
- `placeDecal(spec: DecalSpec): void` — puts a decal on the ground (or on the first mesh below it) and keeps it for its life
- `dropDecals(owners: ReadonlySet<number>): void` — removes the decals of effects that were taken away by hand (an editor's remove or undo)
- `drawDecals(dt: number, cam: readonly [number, number, number]): void` — advances the clock and writes the live decals; `cam` is the camera's position
- `end(): void`
- `bind(view: BABYLON.Matrix, proj: BABYLON.Matrix, light: BABYLON.Vector3): void` — `light` is the scene's light on things that do not glow (the covering strips and smudges take it; fire glow does not)
- `get decalCount(): number`
- `dispose(): void`

### Pool

*class* · `packages/vfx/src/sim.ts:31`

```ts
class Pool
```

the structure of arrays that holds the live particles of one emitter of one instance; views read it directly

- `n: number`
- `cap: number`
- `px: Float64Array`
- `py: Float64Array`
- `pz: Float64Array`
- `vx: Float32Array`
- `vy: Float32Array`
- `vz: Float32Array`
- `age: Float32Array`
- `life: Float32Array`
- `size0: Float32Array`
- `size: Float32Array`
- `rot: Float32Array`
- `spin: Float32Array`
- `temp: Float32Array`
- `rnd: Float32Array`
- `id: Uint32Array` — the spawn index of the particle in its emitter: stable, and ascending with age
- `constructor(readonly max: number)`
- `push(): number` — a free slot, or -1 when the pool is at its maximum
- `remove(i: number)` — removes slot i by moving the last particle into it (the order of slots is not the order of age: sort by `id` when order matters)
- `clear()`
- `toJSON()`
- `static fromJSON(max: number, j: { n: number } & Record<string, number[]>): Pool`

### ProceduralTextures

*class* · `packages/vfx/src/textures.ts:47`

```ts
class ProceduralTextures implements TextureProvider
```

makes the generated flipbooks on demand, once per scene and id; an id it does not know gets the soft disc

- `get(id: string | undefined, scene: BABYLON.Scene): Flipbook`
- `dispose()`

### RungTracker

*class* · `packages/vfx/src/select.ts:47`

```ts
class RungTracker
```

the rung of one effect over time, with its cross-fade

- `rung: Rung`
- `from: Rung | null`
- `fade: number` — 0..1, how far the cross-fade from `from` to `rung` has gone (1 when there is no cross-fade)
- `pixels: number`
- `constructor(readonly def: Pick<VfxDef, 'emitters' | 'volume' | 'impostor' | 'dot' | 'rungs'>, readonly fadeTime = 0.25)`
- `update(pixels: number, tier: VfxTier, dt: number, cap: Rung = 'volume'): RungState`
- `get state(): RungState`

### SmokeSight

*class* · `packages/vfx/src/sight.ts:59`

```ts
class SmokeSight implements VfxSight
```

the smoke of a simulation as a sight contract; `at` is a hook for extra volumes of the host (a room full of smoke)

- `constructor(private sim: VfxSystem)`
- `addSphere(c: Vec3, r: number, extinction: number): number` — a volume of the host's own: the sphere of a room, an area of fog; returns an id to remove it by
- `remove(id: number)`
- `volumeOf(inst: Instance): { shape: 'sphere' | 'column' | 'slab'; c: Vec3; r: number; y0: number; h: number; K: number } | null` — the smoke volumes of one instance now: shape, centre, radius, height and extinction
- `opticalDepth(a: Vec3, b: Vec3): number` — the optical depth (integral of extinction, dimensionless) along the segment a..b through every smoke in the sim
- `transmittance(a: Vec3, b: Vec3): number` — exp(-opticalDepth): the share of light that gets through, 1 clear .. 0 hidden
- `visible(a: Vec3, b: Vec3, minContrast = 0.02): boolean` — can an eye at `a` see a thing at `b` through the smoke (contrast left of at least 2 %, or the `minContrast` given)

### SurfaceGrid

*class* · `packages/vfx/src/droplets.ts:128`

```ts
class SurfaceGrid
```

The surface the parcels fall onto round a moving centre: per cell the ground height and the water level (NaN-free: no water is -1e9). Cells are asked of
the game only when they come into the window (the window scrolls in whole cells), so a costly height query runs for one row at a time.

- `readonly data: Float32Array`
- `originX: number`
- `originZ: number`
- `constructor(readonly n: number, readonly cell: number, readonly query: (x: number, z: number) => { ground: number; water: number })`
- `follow(x: number, z: number): boolean` — centre the window on x, z; returns true when cells changed
- `at(x: number, z: number): { y: number; water: boolean }` — the surface under x, z: the higher of ground and water, and whether it is water; outside the window: no surface

### VfxBabylonView

*class* · `packages/vfx/src/view.ts:157`

```ts
class VfxBabylonView implements VfxView
```

- `readonly budget: { particles: number; lights: number; overdraw: number; }` — the budget the governor holds the view to: particles drawn, lights, and the share of overdraw
- `readonly stats: VfxViewStats`
- `cap: Rung` — the richest rung the governor allows now
- `readonly textures: TextureProvider`
- `constructor(readonly scene: BABYLON.Scene, readonly sys: VfxSystem, readonly camera: BABYLON.Camera, readonly o: VfxBabylonViewOptions = {})`
- `draw(frame: ViewFrame): void`
- `partsStats(): { lights: number; strips: number; dots: number; decals: number; glows: number }` — what the lights, decals and far rungs drew in the last frame
- `rungOf(h: VfxHandle): RungState | undefined`
- `dispose(): void`

### VfxReplica

*class* · `packages/vfx/src/vfx-net.ts:53`

```ts
class VfxReplica
```

- `late: number` — commands that arrived after their time
- `applied: number` — commands applied
- `synced: boolean` — true once the state of an answering peer has been taken (a peer that is the first in the room never gets one and is `alone` after a while: the game decides). A peer that has just joined should wait for it before it gives commands: those it gives before are dropped by the sync
- `constructor(readonly sys: VfxSystem, private o: ReplicaOptions)`
- `spawn(def: string, o: { at: Vec3; dir?: Vec3; params?: Record<string, number>; seed?: number; attach?: { entity: number; node?: string } }): string` — starts an effect everywhere; returns its network id. The seed is chosen from the id, so every peer makes the same particles
- `stop(net: string, immediate = false): void`
- `setParam(net: string, name: string, value: number): void`
- `ignite(cell: number): void`
- `wet(cell: number, moisture: number): void`
- `receive(m: VfxMsg): void` — a command from another peer
- `hello(from: string): void` — a peer says hello (it has just joined): answer it with the state
- `sync(): VfxSync`
- `join(): void` — says hello to the others: call when this peer has joined
- `adopt(s: VfxSync): void` — the state of an answering peer: restore it (the commands queued before it are dropped: the snapshot already has their effect)
- `step(dt: number): void` — one fixed step: applies the commands whose time has come, advances the simulation by dt, and the fire front to the new time
- `asSim(): VfxSim` — A `VfxSim` whose spawns, stops and parameters go through the replica, for `driveFromPhysics(bus, replica.asSim(), ...)` on the peer that owns the physics: the effects its events start then appear on every peer. (If every peer runs the physics, drive the plain sim on each instead and do not replicate: the same events make the same effects everywhere.) Handles are local numbers for the network ids it started.
- `handleOf(net: string): { id: number } | undefined` — the local handle of an effect by its network id

### VfxService

*class* · `packages/vfx/src/vfx-commands.ts:271`

```ts
class VfxService
```

The service a game adds to its world (`world.addService(new VfxService(session))`): it registers the commands, steps the simulation in the fixed step (through
the replica when there is one, so the network's order holds) and takes the level's `vfx` block while the level is loaded (the level loader finds it as the
service named `vfx`, as it finds `physics.host`). Structural, so it needs no import of the engine core.

- `readonly name: "vfx"`
- `constructor(readonly session: VfxSession, readonly o: { replica?: { step(dt: number): void }; view?: { cap: Rung } } = {})`
- `qualityKnobs(): { id: string; label: string; load: 'both'; steps: number; visibility: (l: number) => number; apply(l: number): void }[]` — a knob for the quality regulator (`QualityService` finds it): the governor's steps, richest first (no volume, fewer spawns, shorter lives)
- `init(world: { commands?: CommandHost }): void`
- `fixedUpdate(dt: number): void`
- `beginLevel(block: VfxBlock): string[]`
- `endLevel(): void`
- `dispose(): void`

### VfxSession

*class* · `packages/vfx/src/vfx-commands.ts:85`

```ts
class VfxSession
```

- `readonly placed: Map<string, VfxPlacement & { handle: number; }>` — what an author placed in the level, in order
- `constructor(readonly sys: VfxSystem, readonly o: { sight?: SmokeSight; depth?: number } = {})`
- `get canUndo(): boolean`
- `get canRedo(): boolean`
- `undo(): string | null`
- `redo(): string | null`
- `spawn(def: string, o: { at: Vec3; dir?: Vec3; params?: Record<string, number>; seed?: number; attach?: { entity: number; node?: string }; delay?: number }): number` — starts an effect; undo removes it, redo puts back the same effect
- `stop(id: number, immediate = false): boolean`
- `remove(id: number): boolean`
- `setParam(id: number, name: string, value: number): number`
- `attach(id: number, attach: { entity: number; node?: string } | null): boolean`
- `place(p: VfxPlacement): number`
- `unplace(id: string): boolean`
- `manifest(): VfxBlock` — the `vfx` block that holds what has been placed and the definitions the session made
- `defCreate(def: VfxDef): void` — registers a definition (or replaces the one of that name); throws with every problem listed; undo puts the old one back
- `defPatch(name: string, ops: PatchOp[]): VfxDef`
- `defRemove(name: string): boolean`
- `validate(def: unknown): Issue[]`
- `beginLevel(block: VfxBlock): string[]` — registers the level's definitions and starts its placements; returns warnings (a bad entry is skipped, the rest is made)
- `endLevel(): void` — the level goes: its placements are removed and its definitions forgotten

### VfxSoundPlayer

*class* · `packages/vfx/src/sound-play.ts:36`

```ts
class VfxSoundPlayer
```

- `constructor(private o: SoundPlayerOptions)`
- `spawned(id: number, defName: string, at: Vec3, params: Record<string, number> = {}): void` — an effect started at `at` with `params` (the ones set for it; the rest are the definition's defaults)
- `setParam(id: number, name: string, value: number): void` — a parameter of a running effect changed: the loops follow it
- `stopped(id: number, fade = 0.8): void` — an effect ended: its loops fade out
- `update(): void` — every frame (or a few times a second): loops start inside the audible radius and stop outside it (the distance law itself is the audio service's panner: inverse from a thirtieth of the radius to the radius, as `loudnessAt`; the lowpass is set when a sound starts)
- `get count(): number` — the number of effects whose sound is being tracked
- `dispose(): void`

### VfxSystem

*class* · `packages/vfx/src/sim.ts:134`

```ts
class VfxSystem implements VfxSim
```

- `readonly defs: Map<string, CompiledDef>`
- `host: VfxHost`
- `quality: { spawn: number; life: number; }` — the share of spawns that go ahead (thinning, by particle index) and the share of life kept: set by the governor, 1 and 1 when nothing is given up
- `time: number`
- `register(def: VfxDef): void` — validates the definition (its parts are looked up when it is spawned) and makes it ready to run; throws with every problem listed
- `registerAll(defs: VfxDef[]): void` — registers a set together and checks the parts across them (that they exist, that their parameters exist, that no two include each other)
- `has(name: string)`
- `get(id: number): Instance | undefined`
- `instances(): IterableIterator<Instance>`
- `get count()`
- `get particles(): number` — live particles over all instances
- `spawn(name: string, o: SpawnOptions): VfxHandle`
- `stop(h: VfxHandle, o: StopOptions = {})`
- `setParam(h: VfxHandle, name: string, value: number)`
- `alive(h: VfxHandle): boolean` — the effect's own time and whether it still has anything to show
- `step(dt: number)` — advance by one fixed step, seconds
- `snapshot(): VfxSnapshot`
- `restore(s: VfxSnapshot)`
- `exportEffect(id: number): InstJson[] | null` — the effect and its parts, as plain data (for an exact undo of a stop or a removal); null if there is no such effect
- `importEffect(parts: InstJson[]): void` — puts back what `exportEffect` took out (the definitions must still be registered)
- `readonly removedIds: number[]` — ids of the effects `remove` took away since the view last asked (the view drops their decals)
- `takeRemoved(): number[]` — the ids removed by hand since the last call, and forgets them
- `remove(h: VfxHandle): boolean` — removes an effect and its parts at once, without letting the particles finish; false if it is not there
- `defOf(name: string): VfxDef | undefined` — the definition as registered, or undefined
- `names(): string[]` — the names of the registered definitions
- `unregister(name: string): boolean` — forgets a definition (the effects that run from it go on until they end); false if it was not registered
- `setAttach(h: VfxHandle, attach: { entity: number; node?: string } | null): boolean` — moves an effect to follow an entity (and a node of it), or lets it go (`null`)

### VolumeLayer

*class* · `packages/vfx/src/volume-view.ts:114`

```ts
class VolumeLayer
```

- `stats: { volumes: number; steps: number; }`
- `constructor(private readonly scene: BABYLON.Scene, private readonly o: VolumeLayerOptions)`
- `begin(): void` — a new frame: nothing is drawn unless `show` is called for it
- `show(inst: Instance, src: VolumeSource, def: VolumeRender, alpha: number, cam: readonly [number, number, number], dt: number): void` — draws the volume of an instance this frame at `alpha` (0..1); `cam` is the camera's position in the world
- `end(): void` — the frame is over: boxes that were not shown are hidden, and dropped after a while
- `bind(proj: BABYLON.Matrix, viewRot: BABYLON.Matrix, fwd: BABYLON.Vector3, res: BABYLON.Vector2): void` — per camera, just before it renders
- `dispose(): void`

## Functions

### absorptionCutoff

*function* · `packages/vfx/src/sound-fx.ts:34`

```ts
function absorptionCutoff(distance: number, a: AirState = {}, medium: 'air' | 'water' = 'air'): number
```

The frequency above which a sound that has crossed `distance` metres of air has lost more than 3 dB to absorption: the cutoff of the lowpass a far sound is
played through. Clamped to 150 Hz .. 20 kHz; in water absorption is small and the cutoff stays high.

### airAbsorption

*function* · `packages/vfx/src/sound-fx.ts:18`

```ts
function airAbsorption(freq: number, a: AirState = {}): number
```

the absorption of sound in air, dB per metre, at `freq` Hz (ISO 9613-1, the pure-tone formula); humidity is relative, percent

### airAt

*function* · `packages/vfx/src/droplets.ts:253`

```ts
function airAt(air: DropletAir, x: number, y: number, z: number, ground: number): [number, number, number]
```

the air at a point: the grid's horizontal velocity blended by height above the surface, plus the wind

### arrival

*function* · `packages/vfx/src/sound-fx.ts:57`

```ts
function arrival(s: { radius: number; gain?: number; at?: number; medium?: 'air' | 'water'; delayBySpeed?: boolean }, distance: number, air: AirState = {}): SoundArrival
```

what a listener `distance` metres away hears of a sound block with its numbers worked out (`gain`, `radius`, `at` already evaluated)

### availableRungs

*function* · `packages/vfx/src/select.ts:17`

```ts
function availableRungs(def: Pick<VfxDef, 'emitters' | 'volume' | 'impostor' | 'dot'>): Available
```

which rungs an effect has: particles if it has emitters, volume, impostor and dot if it declares them

### bake

*function* · `packages/vfx/src/bake.ts:162`

```ts
function bake(r: BakeRecipe): BakedFlipbook
```

runs a recipe: warms the solver up, then renders every frame (and keeps the voxels, when the recipe asks for them)

### bakeSoftDisc

*function* · `packages/vfx/src/bake.ts:197`

```ts
function bakeSoftDisc(size = 64): BakedFlipbook
```

a soft round blob

### bakeSpark

*function* · `packages/vfx/src/bake.ts:202`

```ts
function bakeSpark(size = 32): BakedFlipbook
```

a spark: a bright point with a short falling tail

### blackbody

*function* · `packages/vfx/src/color.ts:6`

```ts
function blackbody(T: number): [number, number, number]
```

Colour of a black body at T kelvin (Tanner Helland's fit of the Planck locus; within a few percent from 1000 K to 40000 K), 0..1.

### blastDef

*function* · `packages/vfx/src/catalog-blast.ts:256`

```ts
function blastDef: (name: string) => VfxDef | undefined
```

### breakupTime

*function* · `packages/vfx/src/droplets.ts:54`

```ts
function breakupTime(w: number, d: number, liquid: LiquidProps = WATER): number
```

the time a drop takes to break (Pilch and Erdman: about 5 characteristic times d/w sqrt(rho_l/rho_a) near the critical Weber number)

### breathVisible

*function* · `packages/vfx/src/world-fx.ts:27`

```ts
function breathVisible: (tempC: number) => number
```

how much of a breath is visible as a cloud at an air temperature (C): none above 10 C and all below -5 C, in between by a ramp (an art ramp of the physical fact that the breath, saturated at body temperature, condenses when the air is cold)

### byramFlameLength

*function* · `packages/vfx/src/plume.ts:72`

```ts
function byramFlameLength: (I_kWm: number) => number
```

Byram's flame length of a fire front (grass, ground, crown fires): L = 0.0775 I^0.46, I the fireline intensity in kW per metre of front, L in metres

### chooseRung

*function* · `packages/vfx/src/select.ts:33`

```ts
function chooseRung(pixels: number, tier: VfxTier, ladder: ResolvedLadder, avail: Available, o: ChooseOptions = {}): Rung
```

### chordColumn

*function* · `packages/vfx/src/sight.ts:39`

```ts
function chordColumn(a: Vec3, b: Vec3, c: Vec3, r: number, y0: number, h: number): number
```

the length of the segment a..b inside a vertical cylinder of radius r from y0 to y0 + h with its axis through c (x, z)

### chordSphere

*function* · `packages/vfx/src/sight.ts:27`

```ts
function chordSphere(a: Vec3, b: Vec3, c: Vec3, r: number): number
```

the length of the segment a..b that lies inside a sphere

### clampParam

*function* · `packages/vfx/src/params.ts:29`

```ts
function clampParam(def: Pick<VfxDef, 'params'>, name: string, value: number): number
```

clamp one value to the limits of a parameter of the definition (the value itself if the parameter has no limits or does not exist)

### cloudRadius

*function* · `packages/vfx/src/droplets.ts:60`

```ts
function cloudRadius(age: number, r0: number, k: number): number
```

the radius of a parcel's cloud of drops at an age: it starts as `r0` and spreads by the air's turbulence, sqrt(r0^2 + 2 K age)

### columnHeight

*function* · `packages/vfx/src/blast-fx.ts:38`

```ts
function columnHeight: (tnt: number) => number
```

### compile

*function* · `packages/vfx/src/expr.ts:177`

```ts
function compile(source: string): Compiled
```

parse and compile; throws ExprError with the position of the problem

### compiled

*function* · `packages/vfx/src/expr.ts:186`

```ts
function compiled(e: number | string): Compiled
```

a number is itself; a string is compiled (cached by text)

### compileDef

*function* · `packages/vfx/src/compile.ts:100`

```ts
function compileDef(def: VfxDef): CompiledDef
```

compile a definition that already passed validateDef

### composeMatrix

*function* · `packages/vfx/src/gather.ts:161`

```ts
function composeMatrix(out: Float32Array, o: number, x: number, y: number, z: number, scale: number, yaw: number, tilt: number): void
```

the matrix of a mesh particle (Babylon's row-major layout, row vectors): uniform scale, a turn about y by `yaw` and a tilt about x by `tilt`, then the position

### coreShape

*function* · `packages/vfx/src/parts.ts:184`

```ts
function coreShape(inst: Instance, spec: ImpostorRender, flame: { height: number; width: number } | null): StripShape | null
```

The glow of the flames of an effect as a strip: the height and width of its additive particles, in the colour of the fire's own temperature, as bright as the share
of the plume that is flame. Null for an effect with no additive emitter or one that asks for no core.

### cr

*function* · `packages/vfx/src/compile.ts:14`

```ts
function cr: (v: Range) => CRange
```

### criticalFlux

*function* · `packages/vfx/src/spread.ts:281`

```ts
function criticalFlux: (m: Combustible, T0?: number, h?: number) => number
```

the least flux that can ever ignite a surface (below it the surface loses as much as it gains before it gets hot enough): q_cr = h (T_ig - T0), h the film coefficient, W/m^2 K

### curl3

*function* · `packages/vfx/src/rng.ts:43`

```ts
function curl3(seed: number, x: number, y: number, z: number, out: [number, number, number]): void
```

The curl of a vector potential made of three noise fields: a divergence-free swirl (smoke curls and never piles up or thins out). Central differences
at a fifth of the noise cell. Writes the unit-scale swirl into `out`.

### curlLookup

*function* · `packages/vfx/src/rng.ts:85`

```ts
function curlLookup(x: number, y: number, z: number, out: [number, number, number]): void
```

the swirl at a point of noise space (period 16): the same divergence-free field as curl3, read from the grid; writes into `out`

### curlOffset

*function* · `packages/vfx/src/rng.ts:102`

```ts
function curlOffset(seed: number, out: [number, number, number]): void
```

the offset of an instance in the field, from its seed: three numbers in 0..16

### cx

*function* · `packages/vfx/src/compile.ts:12`

```ts
function cx: (v: string | number) => CExpr
```

### cxOpt

*function* · `packages/vfx/src/compile.ts:13`

```ts
function cxOpt: (v: string | number | undefined) => CExpr | undefined
```

### decalAlpha

*function* · `packages/vfx/src/parts.ts:118`

```ts
function decalAlpha(d: Pick<DecalSpec, 'life' | 'fade'>, age: number): number
```

the opacity of a decal `age` seconds old: 0 at birth growing in over a moment, 1 through its life, then fading to 0

### decalEnd

*function* · `packages/vfx/src/parts.ts:124`

```ts
function decalEnd: (d: Pick<DecalSpec, "life" | "fade">) => number
```

### densityAt

*function* · `packages/vfx/src/volume.ts:202`

```ts
function densityAt(v: VolumeSource, origin: readonly [number, number, number], x: number, y: number, z: number): number
```

the density of a source at a point of the world (for tests and for what reads a volume): trilinear over the bytes, in density units

### detailNoise

*function* · `packages/vfx/src/volume.ts:134`

```ts
function detailNoise(n = 32, seed = 7): Uint8Array
```

a tileable 3D noise (three octaves of value noise on a periodic lattice), one byte per voxel, n x n x n: the fine detail the raymarch erodes smoke with

### digest

*function* · `packages/vfx/src/bake.ts:269`

```ts
function digest(...parts: Uint8Array[]): string
```

a stable digest of the arrays (FNV-1a over the bytes), for tests and for the item's record of what it holds

### dotLook

*function* · `packages/vfx/src/parts.ts:203`

```ts
function dotLook(inst: Instance, spec: DotRender, distance: number, fov: number, heightPx: number, projectedPx: number, night: number): DotLook
```

A dot: a point of light or a smudge never smaller than a pixel and a half on screen, so a distant fire does not wink out as it shrinks, and fading out below that
only by getting dimmer in proportion to its real size, so it goes quietly.

### dragAcceleration

*function* · `packages/vfx/src/droplets.ts:32`

```ts
function dragAcceleration(w: number, d: number, liquid: LiquidProps = WATER): number
```

the acceleration the air gives a drop of diameter d moving at relative velocity w (m/s), along -w: 3/4 (rho_a/rho_l) Cd |w|^2 / d

### dragCoefficient

*function* · `packages/vfx/src/droplets.ts:29`

```ts
function dragCoefficient(re: number): number
```

drag coefficient of a sphere at Reynolds number `re` (Schiller-Naumann below 1000, Newton's 0.44 above)

### driveFromPhysics

*function* · `packages/vfx/src/drive.ts:36`

```ts
function driveFromPhysics(bus: EventSource, sim: VfxSim, o: DriveOptions = {}): () => void
```

subscribes the simulation to the physics events; returns the function that stops it

### dropletRand

*function* · `packages/vfx/src/droplets.ts:73`

```ts
function dropletRand(seed: number, k: number): number
```

a number in [0, 1) from a seed and a stream index

### dustPuffPixels

*function* · `packages/vfx/src/pixels.ts:97`

```ts
function dustPuffPixels(cols = 4, rows = 4, tile = 96): FlipbookPixels
```

a dry-mud / dust puff: like smoke but flatter and browner in its shading; the tint comes from the particle colour

### effectiveWind

*function* · `packages/vfx/src/spread.ts:97`

```ts
function effectiveWind(bed: FuelBed, factor: number): number
```

the effective wind speed (m/s) at which the wind factor alone would equal `factor`: the inverse of the wind factor

### effectTemperature

*function* · `packages/vfx/src/parts.ts:15`

```ts
function effectTemperature(def: VfxDef, vars: Readonly<Record<string, number>>): number
```

the hottest initial temperature an emitter of the effect gives (kelvin), which is what a light or a dot "of temperature" is: the effect's own fire, not a constant

### ellipse

*function* · `packages/vfx/src/spread.ts:105`

```ts
function ellipse(effWind: number): { Z: number; e: number }
```

the ellipse of a fire from a point under an effective wind (m/s): length-to-width Z = 1 + 0.25 U_E (U_E in mi/h), eccentricity e = sqrt(Z^2 - 1) / Z

### emitOne

*function* · `packages/vfx/src/droplets.ts:233`

```ts
function emitOne(p: Float32Array, em: Float32Array, count: number, head: number, capacity: number, k: number, seed: number, time: number): void
```

the k-th new parcel of this step, written at the ring position head + k (WGSL `emit` does the same)

### energyDef

*function* · `packages/vfx/src/catalog-energy.ts:186`

```ts
function energyDef: (name: string) => VfxDef | undefined
```

### evaluate

*function* · `packages/vfx/src/expr.ts:194`

```ts
function evaluate: (e: string | number, vars?: Readonly<Record<string, number>>) => number
```

one-shot evaluation of a number or an expression

### extinguishingFlow

*function* · `packages/vfx/src/spread.ts:319`

```ts
function extinguishingFlow: (power: number, efficiency?: number, T?: number) => number
```

the smallest water flow (kg/s) that puts a fire of `power` out at the given efficiency

### fireDef

*function* · `packages/vfx/src/catalog-fire.ts:294`

```ts
function fireDef: (name: string) => VfxDef | undefined
```

### firelineIntensity

*function* · `packages/vfx/src/plume.ts:75`

```ts
function firelineIntensity: (heatKJkg: number, fuelKgM2: number, spreadMs: number) => number
```

fireline intensity, kW/m (Byram): I = H w r, heat of combustion of the fuel (kJ/kg) x fuel consumed (kg/m^2) x rate of spread (m/s)

### flameHeight

*function* · `packages/vfx/src/plume.ts:11`

```ts
function flameHeight(Q: number, D: number): number
```

mean flame height above the fuel, metres: L = 0.235 Q^(2/5) - 1.02 D (Q in kW). Never below a fifth of the diameter: a small fire still has a flame.

### flamePixels

*function* · `packages/vfx/src/pixels.ts:72`

```ts
function flamePixels(cols = 4, rows = 4, tile = 96, seed = 3): FlipbookPixels
```

Flame: a licking teardrop, hot white-yellow at the core and orange-red at the edge; meant for additive blending

### flameTipTemperature

*function* · `packages/vfx/src/plume.ts:40`

```ts
function flameTipTemperature: (Q: number, D: number) => number
```

the temperature of the gas at the flame tip, kelvin (the plume above it is cooler)

### flashoverPower

*function* · `packages/vfx/src/spread.ts:304`

```ts
function flashoverPower(hk: number, wallArea: number, openingArea: number, openingHeight: number): number
```

the heat release of a compartment fire at flashover, W (McCaffrey, Quintiere, Harkleroad): Q = 610 (h_k A_T A_o sqrt(H_o))^(1/2) kW, h_k the wall's effective conductance W/m^2 K, A_T the bounding surface area less the opening, A_o and H_o the opening's area and height

### fountainHeight

*function* · `packages/vfx/src/world-fx.ts:13`

```ts
function fountainHeight: (gaugePressure: number) => number
```

the height a jet of water reaches, m: Bernoulli, p / (rho g) for a gauge pressure p (Pa) at the nozzle; Torricelli, v^2 / (2 g), for a speed v

### fuelFireballDiameter

*function* · `packages/vfx/src/blast-fx.ts:25`

```ts
function fuelFireballDiameter: (fuelKg: number) => number
```

the largest diameter of the fireball of `fuelKg` kg of fuel burning in a ball (CCPS): 5.8 M^(1/3), m

### fuelFireballDuration

*function* · `packages/vfx/src/blast-fx.ts:27`

```ts
function fuelFireballDuration: (fuelKg: number) => number
```

its duration, s: 0.45 M^(1/3) up to 30 t, 2.6 M^(1/6) above

### gatherEmitter

*function* · `packages/vfx/src/gather.ts:101`

```ts
function gatherEmitter(batch: BatchData, inst: Instance, c: CEmitter, p: Pool, g: Gather): void
```

Writes the live particles of one emitter into `batch`. Billboards and streaks: one entry each. Ribbons: one segment between each particle and the one spawned
right after it (the trail of a moving emitter), so the strip follows the path and breaks where particles were not spawned in sequence.

### generatedKind

*function* · `packages/vfx/src/textures.ts:33`

```ts
function generatedKind(id: string | undefined): string | undefined
```

the id of a flipbook that the generators make, or undefined

### glow

*function* · `packages/vfx/src/catalog-kit.ts:56`

```ts
function glow(o: GlowOpts): EmitterDef
```

additive glowing sprites: energy, plasma, magic, flares

### hash4

*function* · `packages/vfx/src/rng.ts:12`

```ts
function hash4(a: number, b: number, c: number, d: number): number
```

a 32-bit hash of four integers

### headFire

*function* · `packages/vfx/src/spread.ts:114`

```ts
function headFire(bed: FuelBed, moisture: number, wind: [number, number], slope: [number, number]): { rate: number; dir: number; e: number; Z: number }
```

the head fire of a fuel under a wind and over a slope: wind (m/s, midflame) and slope (tan, a vector pointing uphill) combine as vectors of their factors

### heFireballRadius

*function* · `packages/vfx/src/blast-fx.ts:19`

```ts
function heFireballRadius(tnt: number): number
```

The radius of the fireball of a detonation of `tnt` kg TNT, m: the products start in the charge's own volume at the Chapman-Jouguet pressure and expand
isentropically until they are at ambient pressure, r = r0 (P_CJ / P_atm)^(1/(3 gamma)) with r0 the radius of the charge. About 1.4 m for 1 kg. Scales as the cube
root of the mass.

