FERRETGame engine over Babylon.js
Ferret

@ferret/crowd

68 exports · source in packages/crowd/src

Classes

CrowdAgent class

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: number0..1, where in the loop the agent is at time 0
rate: numberplayback 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): voidswitch clip by name (the loop keeps its phase)
get footSpeed(): numberthe speed in m/s at which the current clip's feet do not slide

packages/crowd/src/agent.ts:30

CrowdModel class

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 | nullthe measured thresholds the ladder was made from (null: the default ladder)
time: numberthe 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] }): Representationthe vertex-animation representation of an agent
vatLowRep(node: BABYLON.TransformNode, agent: ClipState & { tint?: [number, number, number] }): Representation | nullthe coarser vertex-animation representation (null when the model has none)
fullRep(node: BABYLON.TransformNode, agent: ClipState): Representationthe full-detail representation of an agent: takes a pooled instance while shown, gives it back when off
impostorFrame(agent: ClipState): numberthe impostor frame (index into the atlas) of an agent now
get fullInUse(): numberfor stats: full instances in use / ready
get fullPool(): number
dispose(): void

packages/crowd/src/model.ts:86

CrowdPath class

class CrowdPath extends Component<CrowdPathParams>

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

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

packages/crowd/src/agent.ts:127

CrowdRng class

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

packages/crowd/src/agent.ts:6

CrowdService class

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(): voidCalled 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

packages/crowd/src/crowd.ts:11

CrowdWander class

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)

packages/crowd/src/agent.ts:75

Rig class

class Rig

the figure's bones as transform nodes: poses are read from and written to them, the skeleton follows them

readonly nodes: BABYLON.TransformNode[]
readonly rest: Pose
readonly bones: Map<string, TransformNode>
readonly mesh: BABYLON.Mesh
readonly skeleton: BABYLON.Skeleton
constructor(readonly root: BABYLON.TransformNode, readonly groups: Record<string, BABYLON.AnimationGroup>)
read(): Pose
write(p: Pose)
duration(name: string): number
sample(name: string, t: number): Posethe pose of a clip at t seconds (clamped to its length)
finish()
blend(a: Pose, b: Pose, k: number): Posea blend of two poses: positions and scalings by lerp, rotations by normalised lerp (what the animation groups' own weighted blend does)
world()
hip(): BABYLON.Vector3
matrices(): number[]bone matrices of the pose now, mesh space, (bones + 1) * 16 floats
turn(bone: string, ax: 'pitch' | 'yaw' | 'roll', rad: number)a small turn of a bone about its own axis (what NearCrowd.applyMicro does every frame)
relax(seed: number, t: number)the hands at rest as a living man's (the same as NearCrowd.relaxHands): the arms a little in toward the body, the fingers each curled its own way; t: the clock of the curl

packages/crowd/src/person-bake.ts:38

VatSet class

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: numberthe crowd's time for the frames (set by the model each frame)
readonly triangles: numbertriangles of one instance after the decimation
readonly cell: numberthe 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] }): Representationa representation of one agent at this rung
get active(): number
dispose(): void

packages/crowd/src/vat.ts:278

Functions

bakeFits function

function bakeFits(bytes: Uint8Array, bones: number): VatBake | null

the bytes are a bake of that many bones (the cheap check before a whole bake is trusted)

packages/crowd/src/shipped-bake.ts:36

bakePersonRig function

function bakePersonRig(rig: Rig, opts: PersonBakeOptions): VatBake

everything a figure's clips need, baked into one texture of bone matrices

packages/crowd/src/person-bake.ts:156

bakeVat function

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.

packages/crowd/src/vat.ts:56

clipTime function

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

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

packages/crowd/src/clock.ts:31

crowdFrame function

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

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

packages/crowd/src/clock.ts:39

crowdModelFromLibrary function

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').

packages/crowd/src/library.ts:24

crowdSourceFromLibrary function

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.

packages/crowd/src/library.ts:10

decimateForCrowd function

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.

packages/crowd/src/vat.ts:110

defaultCrowdLadder function

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.

packages/crowd/src/model.ts:70

ladderOf function

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.

packages/crowd/src/model.ts:56

libraryBakeSource function

function libraryBakeSource(lib: VatBakeLibrary, id: string): VatBakeSource

the bake shipped in the package of the library character id: used when its recipe, clips and bones are the ones asked

packages/crowd/src/shipped-bake.ts:64

measureCrowdLadder function

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

packages/crowd/src/measure.ts:33

packVat function

function packVat(b: VatBake): Uint8Array

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

packages/crowd/src/vat.ts:91

personBakeKey function

function personBakeKey: (rig: Rig, clips?: readonly string[]) => string

the cache key / shipped name of a bake: the recipe, the rig's signature, the clips' lengths

packages/crowd/src/person-bake.ts:237

personClipsKey function

function personClipsKey: (rig: Rig, clips?: readonly string[]) => string

the lengths of the clips baked: a changed clip is another key

packages/crowd/src/person-bake.ts:235

personSignature function

function personSignature(rig: Rig): string

the bake is valid for another figure when its skeleton and mesh frame are the same numbers: a hash of the bones' names and inverse binds and the mesh's frame

packages/crowd/src/person-bake.ts:227

resolveVatBake function

async function resolveVatBake(o: ResolveVatOptions): Promise<ResolvedVat>

the bake for a key: from the cache, else shipped (and then cached), else computed here (and then cached)

packages/crowd/src/shipped-bake.ts:98

rigidAsSkinned function

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.

packages/crowd/src/vat.ts:197

shippedBakeName function

function shippedBakeName: (key: string) => string

the file name of a bake: its key with only safe characters

packages/crowd/src/shipped-bake.ts:13

skinnedMeshes function

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

the skinned meshes of a model and their skeleton

packages/crowd/src/vat.ts:36

spawnCrowdAgent function

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.

packages/crowd/src/crowd.ts:66

splitBakeKey function

function splitBakeKey(key: string): { recipe: string; signature: string; clips: string }

vat-crowd:v1:87:673c6b4e:11.933,... (recipe, version, the rig's signature bones:hash, the clips' lengths) -> the recipe vat-crowd:v1 and the clips key

packages/crowd/src/shipped-bake.ts:30

unpackVat function

function unpackVat(bytes: Uint8Array): VatBake | null

packages/crowd/src/vat.ts:97

urlBakeSource function

function urlBakeSource(o: { base?: string | URL | (() => string | URL | undefined); dir?: string; fetch?: typeof fetch } = {}): VatBakeSource

the files a game ships beside its page: <dir><name>.vat relative to base (default: the page's own address)

packages/crowd/src/shipped-bake.ts:41

vatParts function

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)

packages/crowd/src/vat.ts:231

vatSettings function

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.

packages/crowd/src/clock.ts:48

vertexColourMaterial function

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)

packages/crowd/src/vat.ts:375

Interfaces

BakeCache interface

interface BakeCache
get(key: string): Promise<Uint8Array | null | undefined>
put(key: string, bytes: Uint8Array): Promise<void>

packages/crowd/src/shipped-bake.ts:78

ClipState interface

interface ClipState

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

clip: number
phase: number0..1, where in the loop the agent is at time 0
rate: numberplayback rate (1: as baked)

packages/crowd/src/clock.ts:22

CrowdAgentParams interface

interface CrowdAgentParams
clip?: stringthe crowd model's name of the clip to play (index into its clips by name, resolved at attach)
phase?: number0..1, where in the loop the agent starts
rate?: numberplayback 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

packages/crowd/src/agent.ts:13

CrowdClip interface

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: numberfirst baked frame (row of the vertex-animation texture)
frames: numberbaked frames of the loop
duration: numberseconds of one loop at rate 1
speed: numbertravel speed in m/s at rate 1 (0: in place); an agent moving at speed * rate has feet that do not slide

packages/crowd/src/clock.ts:9

CrowdClipSpec interface

interface CrowdClipSpec
name: string
fps?: numberbaked frames per second of the vertex animation (default 30)
impostorFrames?: numberframes of this clip in the animated impostor (default 12 for a moving clip, 4 in place)
speed?: numberm/s at rate 1; default measured (see bakeVat)

packages/crowd/src/model.ts:16

CrowdMeasureInput interface

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 | nullthe coarser VAT set (its threshold comes from its cell too)
full: { root: BABYLON.TransformNode; meshes: BABYLON.AbstractMesh[]; rep: Representation; pose(frame01: number): void } | nulla full instance (posed by pose) or null when the model has no full rung
atlas: Uint8Array | null
impostorFrame(frame01: number): numberatlas 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?: numberpixels a merged cell of the VAT rungs may cover (default 1)

packages/crowd/src/measure.ts:11

CrowdModelOptions interface

interface CrowdModelOptions
key: stringnames 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: CrowdSourcethe 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?: numberfull instances kept ready (the budget of the full rung; default 8)
impostor?: ImpostorBakeOptions | falseimpostor bake options (default flat, upper hemisphere, 8 views of 96 px); false: no impostor rung
cache?: CacheBackendthe persistent cache for the bakes (@ferret/assets)
vatTriangles?: numbertriangles of the vertex-animation rung per agent (the mid source is simplified down to it; default 6000)
vatLowTriangles?: numbertriangles of the coarser vertex-animation rung (default 1200; 0: none)
measure?: booleanmeasure the ladder in the scene (default true; cached by key); false: defaultCrowdLadder
tolerance?: numberthe 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

packages/crowd/src/model.ts:26

CrowdPathParams interface

interface CrowdPathParams
points: [number, number][]points (x, z) walked in order, looping
walk: string
from?: numberstart at this point index
turnRate?: number

packages/crowd/src/agent.ts:117

CrowdSource interface

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?(): voiddispose the instance (the model calls it for pooled full instances it drops)

packages/crowd/src/model.ts:9

CrowdWanderParams interface

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

packages/crowd/src/agent.ts:58

PersonBakeOptions interface

interface PersonBakeOptions

everything a figure's clips need, baked into one texture of bone matrices

profile: MicroProfilethe micro-motion profile the standing, talking, sitting and crouching loops are recorded with (a MicroProfile of the game's people)
clips?: readonly string[]the clips baked (default PERSON_CLIPS); every name must be in the rig's animation groups

packages/crowd/src/person-bake.ts:148

ResolvedVat interface

interface ResolvedVat
bake: VatBake
bytes: Uint8Array
from: stringwhere it came from: cache, the name of the source that shipped it, or computed

packages/crowd/src/shipped-bake.ts:90

ResolveVatOptions interface

interface ResolveVatOptions
key: string
bones: number
cache?: BakeCache
sources?: readonly VatBakeSource[]the shipped places, tried in order after the cache
compute: () => Promise<{ bake: VatBake; bytes: Uint8Array }> | { bake: VatBake; bytes: Uint8Array }the fallback: bake it here (slow) and give the bake with its packed bytes

packages/crowd/src/shipped-bake.ts:80

ShippedVatEntry interface

interface ShippedVatEntry

what a library figure's vat entry says (the VatBakeEntry of @ferret/assets, as far as the loader reads it)

recipe: string
clips: string
bones: number
signature?: string

packages/crowd/src/shipped-bake.ts:59

SpawnAgentOptions interface

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

packages/crowd/src/crowd.ts:51

VatBake interface

interface VatBake
bones: number
frames: numbertotal baked frames (rows)
data: Float32Array(bones + 1) * 16 floats per frame
clips: CrowdClip[]

packages/crowd/src/vat.ts:24

VatBakeLibrary interface

interface VatBakeLibrary

the part of the asset library the loader needs (AssetLibrary.vatBake)

vatBake(id: string): Promise<{ entry: ShippedVatEntry; bytes: Uint8Array } | null>

packages/crowd/src/shipped-bake.ts:61

VatBakeSource interface

interface VatBakeSource

a place bakes are shipped: gives the packed bytes of the bake for key, or null when it has none that fits

readonly name: string
get(expect: VatExpect): Promise<Uint8Array | null>

packages/crowd/src/shipped-bake.ts:24

VatClipSource interface

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?: numberbaked frames per second (default 30)
maxFrames?: numberat most this many frames of the loop (default 48): a long clip is sampled more sparsely
speed?: numbertravel speed in m/s at rate 1; default: measured from the clip's root motion, or from the feet when it is in place

packages/crowd/src/vat.ts:13

VatExpect interface

interface VatExpect

what a bake must be to be used for a figure

bones: numberthe bones of the figure's skeleton
key: stringthe bake's key: <recipe>:<signature>:<clips>; the recipe is the part before the signature

packages/crowd/src/shipped-bake.ts:16

Types

CrowdThresholds type

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).

packages/crowd/src/model.ts:53

Constants

FPS const

const FPS: 15

packages/crowd/src/person-bake.ts:23

LOOP_MIN const

const LOOP_MIN: 8

a loop of a standing/talking clip is at least this long, s

packages/crowd/src/person-bake.ts:31

LOW_VARIANTS const

const LOW_VARIANTS: 3

variants of the micro-motion of a sitting or crouching man

packages/crowd/src/person-bake.ts:25

PAIRS const

const PAIRS: [string, string][]

packages/crowd/src/person-bake.ts:32

PERSON_BAKE_VERSION const

const PERSON_BAKE_VERSION: "v1"

the recipe's version: a changed recipe is a new key, so shipped and cached bakes of an older one are not used

packages/crowd/src/person-bake.ts:20

PERSON_CLIPS const

const PERSON_CLIPS: string[]

the clips of the library's Customizer set a crowd of people uses

packages/crowd/src/person-bake.ts:22

STIR_FROM const

const STIR_FROM: 0.82

packages/crowd/src/person-bake.ts:29

STIR_RATE const

const STIR_RATE: 1.6

a lying man's stir: its pace, rad/s, and how far back into Death_Backward it reaches

packages/crowd/src/person-bake.ts:29

STOP_PHASES const

const STOP_PHASES: 4

packages/crowd/src/person-bake.ts:27

TRANS_N const

const TRANS_N: 20

frames of a posture blend, of a walk start/stop blend (at WALK_FPS)

packages/crowd/src/person-bake.ts:27

WALK_FPS const

const WALK_FPS: 24

packages/crowd/src/person-bake.ts:27

WALK_N const

const WALK_N: 8

packages/crowd/src/person-bake.ts:27