# @ferret/crowd: API

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

## Classes

### CrowdAgent

*class* · `packages/crowd/src/agent.ts:30`

```ts
class CrowdAgent extends Component<CrowdAgentParams> implements ClipState
```

The crowd state of an agent: which clip, where in its loop, how fast. It is simulation state (fixed step); the rungs read it to draw. A behaviour
(`CrowdWander`, `CrowdPath`, or the game's own) moves the entity and sets `clip` / `rate`.

- `clip: number`
- `clipName: string`
- `phase: number` — 0..1, where in the loop the agent is at time 0
- `rate: number` — playback rate (1: as baked)
- `tint: [number, number, number]`
- `clipNames: string[]` — the clip names of the model (set by the model when the agent is spawned)
- `clipSpeeds: number[]` — travel speed of each clip at rate 1, m/s
- `onAttach()`
- `play(name: string): void` — switch clip by name (the loop keeps its phase)
- `get footSpeed(): number` — the speed in m/s at which the current clip's feet do not slide

### CrowdModel

*class* · `packages/crowd/src/model.ts:86`

```ts
class CrowdModel
```

Everything the rungs of a crowd need for one character, made once: the vertex-animation set (from `mid`), the animated impostor atlas (all
clips side by side, from `mid` too), the point colour and size, and a pool of full instances. Agents of the model share all of it.

- `readonly clips: CrowdClip[]`
- `readonly impostorFrames: [number, number][]` — frames of each clip in the impostor atlas: [start, frames] by clip index
- `ladder: PerspectiveLevel[]`
- `thresholds: CrowdThresholds | null` — the measured thresholds the ladder was made from (null: the default ladder)
- `time: number` — the crowd time the rungs show (the world's simulated time; set by the crowd every frame)
- `get key(): string`
- `get clipNames(): string[]`
- `get radius(): number`
- `get centre(): [number, number, number]`
- `get look(): { color: [number, number, number]; fill: number }`
- `static async prepare(scene: BABYLON.Scene, o: CrowdModelOptions): Promise<CrowdModel>`
- `vatRep(node: BABYLON.TransformNode, agent: ClipState & { tint?: [number, number, number] }): Representation` — the vertex-animation representation of an agent
- `vatLowRep(node: BABYLON.TransformNode, agent: ClipState & { tint?: [number, number, number] }): Representation | null` — the coarser vertex-animation representation (null when the model has none)
- `fullRep(node: BABYLON.TransformNode, agent: ClipState): Representation` — the full-detail representation of an agent: takes a pooled instance while shown, gives it back when off
- `impostorFrame(agent: ClipState): number` — the impostor frame (index into the atlas) of an agent now
- `get fullInUse(): number` — for stats: full instances in use / ready
- `get fullPool(): number`
- `dispose(): void`

### CrowdPath

*class* · `packages/crowd/src/agent.ts:127`

```ts
class CrowdPath extends Component<CrowdPathParams>
```

Walks a closed path of points at the walk clip's foot speed.

- `heading: number`
- `onAttach()`
- `onFixedUpdate(dt: number)`

### CrowdRng

*class* · `packages/crowd/src/agent.ts:6`

```ts
class CrowdRng
```

A seeded generator (the same seed gives the same crowd on every machine).

- `constructor(seed: number)`
- `next(): number`
- `range(a: number, b: number): number`

### CrowdService

*class* · `packages/crowd/src/crowd.ts:11`

```ts
class CrowdService implements Service
```

The crowd service: the models, their agents, the time the rungs show. It owns nothing of the simulation (agents are entities with components that
move in the fixed step); in `update` it gives every model the world's simulated time, so every rung of every agent shows the same moment.

- `readonly name: "crowd"`
- `readonly models: Map<string, CrowdModel>`
- `readonly agents: Map<string, { entity: Entity; model: CrowdModel; }>`
- `constructor(readonly backend: BabylonBackend)`
- `init(world: World): void`
- `addModel(model: CrowdModel): CrowdModel`
- `update(): void` — Called once per rendered frame.
- `stats(): { agents: number; byRung: Record<string, number>; models: { key: string; agents: number; vat: number; full: string }[] }` — agents per rung of the ladder, per model, and the draw cost of the shared rungs
- `dispose(): void`

### CrowdWander

*class* · `packages/crowd/src/agent.ts:75`

```ts
class CrowdWander extends Component<CrowdWanderParams>
```

Walks between random points of a region at the walk clip's foot speed, turning smoothly, pausing (idle clip) at each goal. Deterministic: the
goals come from the seed, the movement from the fixed step.

- `heading: number`
- `onAttach()`
- `onFixedUpdate(dt: number)`

### VatSet

*class* · `packages/crowd/src/vat.ts:278`

```ts
class VatSet
```

Every agent of one crowd model at the vertex-animation rung. `template` is an instance of the model's mid-detail source kept at the origin and
hidden; its skinned meshes become the instanced meshes. Materials that are not PBR or standard (a custom shader) are replaced by `fallback(mesh)`
(default a PBR material of the mesh's vertex colours), because the baked skinning lives in Babylon's own shaders.

- `readonly meshes: BABYLON.Mesh[]`
- `readonly manager: BABYLON.BakedVertexAnimationManager`
- `readonly texture: BABYLON.RawTexture`
- `time: number` — the crowd's time for the frames (set by the model each frame)
- `readonly triangles: number` — triangles of one instance after the decimation
- `readonly cell: number` — the grid cell the solid meshes were merged on, metres (0: not simplified): the geometric error of this rung
- `static async create(scene: BABYLON.Scene, template: BABYLON.TransformNode, bake: VatBake, o: { fallback?: (m: BABYLON.Mesh) => BABYLON.Material; targetTriangles?: number; parts?: BABYLON.Mesh[]; share?: VatSet } = {}): Promise<VatSet>` — a VAT set, its meshes simplified first (asynchronous: the simplifier works in steps)
- `add(node: BABYLON.TransformNode, agent: ClipState & { tint?: [number, number, number] }): Representation` — a representation of one agent at this rung
- `get active(): number`
- `dispose(): void`

## Functions

### bakeVat

*function* · `packages/crowd/src/vat.ts:56`

```ts
function bakeVat(root: BABYLON.TransformNode, clips: VatClipSource[]): VatBake
```

Bake the clips of a skinned model (an instance in the scene, at the origin). Root motion is taken out of every frame (the agent's node moves
instead) and measured as the clip's speed; a clip made in place gets its speed from the stance of its feet.

### clipTime

*function* · `packages/crowd/src/clock.ts:31`

```ts
function clipTime(clip: CrowdClip, s: ClipState, t: number): number
```

Seconds into the agent's loop at time `t` (0 <= result < duration).

### crowdFrame

*function* · `packages/crowd/src/clock.ts:39`

```ts
function crowdFrame(clip: CrowdClip, s: ClipState, t: number): number
```

The baked frame (fractional, within the clip: 0 <= f < frames) at time `t`.

### crowdModelFromLibrary

*function* · `packages/crowd/src/library.ts:24`

```ts
async function crowdModelFromLibrary(scene: BABYLON.Scene, lib: AssetLibrary, id: string, clips: Record<string, string>, o: Partial<Omit<CrowdModelOptions, 'mid' | 'full' | 'clips'>> & { mid?: LibraryTier; full?: LibraryTier | false } = {}): Promise<CrowdModel>
```

A crowd model of a library character: the vertex animation and the impostor from tier `mid` (default 'low'), full instances from `full` (default 'desktop').

### crowdSourceFromLibrary

*function* · `packages/crowd/src/library.ts:10`

```ts
async function crowdSourceFromLibrary(lib: AssetLibrary, id: string, clips: Record<string, string>, o: { tier?: LibraryTier; name?: string } = {}): Promise<CrowdSource>
```

A crowd source from the asset library: an instance of character `id` at `tier` with its clips bound. `clips` maps the agent's clip names to the
library's clip ids (`{ walk: 'cc-clips/Walk_Fwd', idle: 'cc-clips/Idle' }`); the character's compatible clip sets are searched.

### decimateForCrowd

*function* · `packages/crowd/src/vat.ts:110`

```ts
async function decimateForCrowd(meshes: BABYLON.Mesh[], target: number): Promise<{ meshes: BABYLON.Mesh[]; triangles: number; cell: number }>
```

Fewer triangles for the middle rung, whatever the source: vertices are merged per cell of a grid (the first vertex of a cell stands for it, with its
normal, uvs and skin weights), triangles that collapse are dropped. Every mesh of the model shares the cell size, chosen as the smallest that brings
the whole model under `target` triangles. Returns the triangles after.

### defaultCrowdLadder

*function* · `packages/crowd/src/model.ts:70`

```ts
function defaultCrowdLadder(o: { full?: boolean; impostor?: boolean; low?: boolean } = {}): PerspectiveLevel[]
```

A default ladder for a person-sized model (projected size of the bounding sphere in pixels). Measure your own with tools/perspective/thresholds.mjs.

### ladderOf

*function* · `packages/crowd/src/model.ts:56`

```ts
function ladderOf(t: CrowdThresholds, has: { full: boolean; impostor: boolean; low?: boolean }): PerspectiveLevel[]
```

The ladder from measured thresholds: full above `mesh`, the vertex animation above `impostor`, the impostor above `point`, the point above `none`; each rung a little below the one before.

### measureCrowdLadder

*function* · `packages/crowd/src/measure.ts:33`

```ts
async function measureCrowdLadder(inp: CrowdMeasureInput): Promise<MeasuredThresholds & { vatLow?: number; curves?: Record<string, [number, number][]> }>
```

### packVat

*function* · `packages/crowd/src/vat.ts:91`

```ts
function packVat(b: VatBake): Uint8Array
```

bytes of a bake, for a cache (version, bones, frames, clips json, floats)

### rigidAsSkinned

*function* · `packages/crowd/src/vat.ts:197`

```ts
function rigidAsSkinned(root: BABYLON.TransformNode, skeleton: BABYLON.Skeleton, skinned: BABYLON.Mesh): BABYLON.Mesh[]
```

Parts that ride a bone as child nodes (a hat, a weapon in a socket, strand hair) become meshes skinned to that one bone, in the frame of the
skinned meshes, so the baked animation moves them too. The model is put in its rest pose first.

### skinnedMeshes

*function* · `packages/crowd/src/vat.ts:36`

```ts
function skinnedMeshes(root: BABYLON.Node): { meshes: BABYLON.Mesh[]; skeleton: BABYLON.Skeleton }
```

the skinned meshes of a model and their skeleton

### spawnCrowdAgent

*function* · `packages/crowd/src/crowd.ts:66`

```ts
async function spawnCrowdAgent(world: World, model: CrowdModel, o: SpawnAgentOptions): Promise<Entity>
```

An agent of `model`: an entity with a ladder of every rung the model has, the agent state and an optional behaviour.

### unpackVat

*function* · `packages/crowd/src/vat.ts:97`

```ts
function unpackVat(bytes: Uint8Array): VatBake | null
```

### vatParts

*function* · `packages/crowd/src/vat.ts:231`

```ts
function vatParts(template: BABYLON.TransformNode): BABYLON.Mesh[]
```

the parts a VAT set is made of: the skinned meshes and the rigid parts on bones made skinned (made once per model, shared by its sets)

### vatSettings

*function* · `packages/crowd/src/clock.ts:48`

```ts
function vatSettings(clip: CrowdClip, s: ClipState, t: number): [number, number, number, number]
```

The per-instance settings of Babylon's baked vertex animation for this agent at time `t`: (start frame, end frame, offset, speed). The speed is 0 and
the offset is the frame itself, so the shader shows exactly `start + floor(crowdFrame)` (its own time formula skips frame 0 after the first loop);
the crowd writes these every frame with the instance matrices, so every rung shows the same frame.

### vertexColourMaterial

*function* · `packages/crowd/src/vat.ts:375`

```ts
function vertexColourMaterial(scene: BABYLON.Scene, m: BABYLON.Mesh): BABYLON.PBRMaterial
```

a PBR material of the mesh's vertex colours (for meshes drawn by a custom shader, such as strand hair)

## Interfaces

### ClipState

*interface* · `packages/crowd/src/clock.ts:22`

```ts
interface ClipState
```

The part of an agent's state the clocks need.

- `clip: number`
- `phase: number` — 0..1, where in the loop the agent is at time 0
- `rate: number` — playback rate (1: as baked)

### CrowdAgentParams

*interface* · `packages/crowd/src/agent.ts:13`

```ts
interface CrowdAgentParams
```

- `clip?: string` — the crowd model's name of the clip to play (index into its clips by name, resolved at attach)
- `phase?: number` — 0..1, where in the loop the agent starts
- `rate?: number` — playback rate (also scales the travel speed of a walking behaviour, so the feet keep their place)
- `tint?: [number, number, number]` — a colour multiplied into the model at every rung (linear rgb, default white)
- `clips?: { name: string; speed: number }[]` — the model's clips (names and foot speeds), given by `spawnCrowdAgent`

### CrowdClip

*interface* · `packages/crowd/src/clock.ts:9`

```ts
interface CrowdClip
```

One clip as baked into a crowd model: where its frames start in the baked texture, how many, at what rate.

- `name: string`
- `start: number` — first baked frame (row of the vertex-animation texture)
- `frames: number` — baked frames of the loop
- `duration: number` — seconds of one loop at rate 1
- `speed: number` — travel speed in m/s at rate 1 (0: in place); an agent moving at `speed * rate` has feet that do not slide

### CrowdClipSpec

*interface* · `packages/crowd/src/model.ts:16`

```ts
interface CrowdClipSpec
```

- `name: string`
- `fps?: number` — baked frames per second of the vertex animation (default 30)
- `impostorFrames?: number` — frames of this clip in the animated impostor (default 12 for a moving clip, 4 in place)
- `speed?: number` — m/s at rate 1; default measured (see bakeVat)

### CrowdMeasureInput

*interface* · `packages/crowd/src/measure.ts:11`

```ts
interface CrowdMeasureInput
```

The thresholds of a crowd model's ladder, measured in the scene it lives in: one sample of each rung (the full figure, the
vertex-animation instance, the impostor, the point) drawn alone into a render target at the same moment of the first clip, from four sides,
at a ladder of sizes; a cheaper rung takes over at the smallest size where its picture is within `tolerance` of the richer one
(`blurError`, as `@ferret/perspective` measures its models). Runs before any agent exists, so nothing else is in the pictures.

- `scene: BABYLON.Scene`
- `vat: VatSet`
- `vatLow?: VatSet | null` — the coarser VAT set (its threshold comes from its cell too)
- `full: { root: BABYLON.TransformNode; meshes: BABYLON.AbstractMesh[]; rep: Representation; pose(frame01: number): void } | null` — a full instance (posed by `pose`) or null when the model has no full rung
- `atlas: Uint8Array | null`
- `impostorFrame(frame01: number): number` — atlas frame of the first clip's moment `frame01`
- `centre: [number, number, number]`
- `radius: number`
- `color: [number, number, number]`
- `fill: number`
- `tolerance?: number`
- `maxPx?: number`
- `errorPx?: number` — pixels a merged cell of the VAT rungs may cover (default 1)

### CrowdModelOptions

*interface* · `packages/crowd/src/model.ts:26`

```ts
interface CrowdModelOptions
```

- `key: string` — names the model and its content with a version (cache key of the bakes, and agents of one key share one atlas and one VAT)
- `clips: (string | CrowdClipSpec)[]`
- `mid: CrowdSource` — the lighter instance the vertex animation and the impostor are made from (stays hidden at the origin)
- `full?: () => Promise<CrowdSource>` — makes one more full-detail instance for an agent near the camera (pooled: at most `maxFull`)
- `maxFull?: number` — full instances kept ready (the budget of the full rung; default 8)
- `impostor?: ImpostorBakeOptions | false` — impostor bake options (default flat, upper hemisphere, 8 views of 96 px); false: no impostor rung
- `cache?: CacheBackend` — the persistent cache for the bakes (@ferret/assets)
- `vatTriangles?: number` — triangles of the vertex-animation rung per agent (the mid source is simplified down to it; default 6000)
- `vatLowTriangles?: number` — triangles of the coarser vertex-animation rung (default 1200; 0: none)
- `measure?: boolean` — measure the ladder in the scene (default true; cached by key); false: `defaultCrowdLadder`
- `tolerance?: number` — the error a cheaper rung may have against the richer one (default 0.05)
- `ladder?: PerspectiveLevel[]` — the ladder of every agent of this model; given, nothing is measured

### CrowdPathParams

*interface* · `packages/crowd/src/agent.ts:117`

```ts
interface CrowdPathParams
```

- `points: [number, number][]` — points (x, z) walked in order, looping
- `walk: string`
- `from?: number` — start at this point index
- `turnRate?: number`

### CrowdSource

*interface* · `packages/crowd/src/model.ts:9`

```ts
interface CrowdSource
```

A loaded instance of a character: its root (at the origin) and its animation groups by clip name, bound to that root.

- `root: BABYLON.TransformNode`
- `groups: Record<string, BABYLON.AnimationGroup>`
- `dispose?(): void` — dispose the instance (the model calls it for pooled full instances it drops)

### CrowdWanderParams

*interface* · `packages/crowd/src/agent.ts:58`

```ts
interface CrowdWanderParams
```

- `area: { x: number; z: number; halfX: number; halfZ: number }` — the region: centre x, z and half sizes
- `walk: string` — clip names: walking and standing
- `idle?: string`
- `pause?: [number, number]` — seconds of a pause at a goal (min, max); 0 never stops
- `turnRate?: number` — degrees per second the agent turns at most
- `seed?: number`

### SpawnAgentOptions

*interface* · `packages/crowd/src/crowd.ts:51`

```ts
interface SpawnAgentOptions
```

- `name?: string`
- `position: [number, number, number]`
- `heading?: number` — radians about +Y; 0 faces +Z
- `clip?: string`
- `phase?: number`
- `rate?: number`
- `tint?: [number, number, number]`
- `wander?: CrowdWanderParams` — a built-in behaviour (or none: the game moves the entity and sets the agent's clip)
- `path?: CrowdPathParams`

### VatBake

*interface* · `packages/crowd/src/vat.ts:24`

```ts
interface VatBake
```

- `bones: number`
- `frames: number` — total baked frames (rows)
- `data: Float32Array` — (bones + 1) * 16 floats per frame
- `clips: CrowdClip[]`

### VatClipSource

*interface* · `packages/crowd/src/vat.ts:13`

```ts
interface VatClipSource
```

The vertex-animation rung of a crowd. A skinned model's bone matrices are baked for every frame of the chosen clips into one float
texture in the layout of Babylon's `BakedVertexAnimationManager` ((bones + 1) x 4 texels per frame row); the model's own meshes and materials
then draw every agent as a thin instance, skinned on the GPU from the texture. One draw call per mesh of the model for all its agents; the CPU
writes one matrix, one frame number, a fade and a tint per agent per frame.

- `name: string`
- `group: BABYLON.AnimationGroup`
- `fps?: number` — baked frames per second (default 30)
- `maxFrames?: number` — at most this many frames of the loop (default 48): a long clip is sampled more sparsely
- `speed?: number` — travel speed in m/s at rate 1; default: measured from the clip's root motion, or from the feet when it is in place

## Types

### CrowdThresholds

*type* · `packages/crowd/src/model.ts:53`

```ts
type CrowdThresholds = MeasuredThresholds & { vatLow?: number; curves?: Record<string, [number, number][]> }
```

Measured thresholds of a crowd model: the perspective's, and `vatLow` (below it the coarser VAT rung is within the tolerance of the full figure).

