# @ferret/morph: API

Geometric and colour morphing: banks of states from clip frames or hinged parts, objects blended by programs of the motion language, one-draw-call GPU batches, far colour morphs, retopology, morph.* commands.

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

## Classes

### ConformError

*class* · `packages/morph/src/conform.ts:53`

```ts
class ConformError extends Error
```

- `constructor(message: string, readonly report: ConformReport)`

### CpuMorphView

*class* · `packages/morph/src/view.ts:130`

```ts
class CpuMorphView
```

one object drawn by the CPU path

- `readonly mesh: BABYLON.Mesh`
- `readonly material: BABYLON.ShaderMaterial`
- `updates: number` — how many times the vertex arrays were rewritten (a morph that has arrived costs nothing: this stops growing)
- `look: MorphLook`
- `constructor(readonly scene: BABYLON.Scene, readonly bank: MorphBank, readonly object: MorphObject, name = `morph:${object.name}`)`
- `refresh(force = false): void` — call once per frame (the node is the mesh itself: parent it or move it)
- `arrays(): BlendOut` — the blended arrays now (for tests and the comparison with the GPU path)
- `dispose(): void`

### FarMorph

*class* · `packages/morph/src/far.ts:13`

```ts
class FarMorph
```

- `constructor(readonly object: MorphObject, readonly reps: ReadonlyMap<number, Representation>)`
- `stand(i: number): number` — the baked state that stands in for state `i`
- `pair(): { a: number; b: number; mix: number }` — the two impostors to draw and the mix between them, from the object's blend now
- `apply(rung: RepState, rungMix: number): void` — Draw the far rung. `rung` is the ladder's own state for this object (`on`, `in`, `out`, `off`) and `rungMix` its cross-fade with the neighbouring rung; the two cross-fades are laid over each other: state B shows with its share of the mix, state A with the rest.

### GpuMorphBatch

*class* · `packages/morph/src/view.ts:171`

```ts
class GpuMorphBatch
```

the objects of one bank drawn by the GPU path: one mesh, one draw call, thin instances

- `readonly mesh: BABYLON.Mesh`
- `readonly material: BABYLON.ShaderMaterial`
- `readonly texture: BABYLON.RawTexture`
- `readonly layout: BankTexture`
- `uploads: number` — how many times the per-instance weight buffers were rewritten
- `look: MorphLook`
- `readonly lookup: VertexLookup`
- `constructor(readonly scene: BABYLON.Scene, readonly bank: MorphBank, name = 'morph:batch', lookup?: VertexLookup)`
- `add(object: MorphObject, node: BABYLON.TransformNode): void`
- `remove(object: MorphObject): void`
- `get count(): number`
- `refresh(): void` — every frame (it is also hooked to the scene's before-render): matrices always, the weight vectors of an object only when its blend changed
- `dispose(): void`

### MorphBank

*class* · `packages/morph/src/bank.ts:24`

```ts
class MorphBank
```

- `readonly states: MorphState[]`
- `source: string` — where the bank came from (a clip and a model, with their versions): a bank is re-baked when this changes
- `constructor(readonly vertexCount: number, readonly indices: Uint32Array)`
- `get count(): number`
- `has(name: string): boolean`
- `indexOf(name: string): number`
- `names(): string[]`
- `get(name: string): MorphState`
- `add(state: MorphState): number` — add a state (a name already used is replaced); the arrays are checked against the vertex count
- `remove(name: string): void`
- `hash(): string` — the content hash of every state and the index buffer
- `validate(): MorphIssue[]`
- `toJson(): unknown` — the bank as JSON: arrays become plain number lists, so a small bank can be read and diffed by eye
- `static fromJson(j: any): MorphBank`
- `toBinary(): Uint8Array` — The bank as one binary file (what a host loads and the GPU upload reads), little-endian: 'FMRB' u32 version=1 u32 vertexCount u32 indexCount u32 stateCount u32 sourceLength source (utf8, padded to 4) indices u32[indexCount] per state: u32 nameLength name (utf8, padded to 4) u32 flags (1 normals, 2 colors) f32 scale f32 pivot[3] f32 positions[3n] (f32 normals[3n]) (f32 colors[4n])
- `static fromBinary(bytes: Uint8Array): MorphBank`

### MorphHost

*class* · `packages/morph/src/host.ts:22`

```ts
class MorphHost implements Service
```

- `readonly name: "morph"`
- `readonly service: MorphService`
- `readonly rt: MotionRuntime`
- `readonly bridge: MotionBridge`
- `constructor(readonly opts: MorphHostOptions)`
- `init(world: World): void`
- `fixedUpdate(dt: number): void` — the world's fixed step: the programs first (they say what to do), then the objects advance

### MorphObject

*class* · `packages/morph/src/sim.ts:25`

```ts
class MorphObject
```

- `time: number`
- `version: number` — bumped whenever the blend or the tint can have changed, so a view redraws only then
- `constructor(readonly name: string, readonly bank: MorphBank, initial?: string)`
- `set(state: string): void` — jump to a state at once
- `to(state: string, seconds: number, curve = 'smooth'): MorphWait` — move to `state` over `seconds` along the ease `curve`, from the blend as it is now. A move already running is replaced and its waiters end.
- `stop(): void` — freeze the move where it is
- `hold(state: string, w: number): void` — lay `state` over the result with weight `w` (0..1) until `release`; a state held twice has the last weight
- `release(state: string): void`
- `pin(a: string, b: string, w: number): void` — hold the object at exactly `a` mixed with `b` by `w` (a hand on the slider) until `unpin`; moves are ignored meanwhile
- `unpin(): void`
- `tintTo(color: Color3, seconds = 0, curve = 'smooth'): MorphWait` — the colour factor, now or over `seconds`
- `step(dt: number): void`
- `progress(): number` — progress of the running move, eased, 0..1 (1 when none runs)
- `moving(): boolean`
- `weights(): Weights` — the weights of the states now: at most four, summing to 1, the largest first
- `dominant(): string` — the name of the state with the largest weight
- `weightOf(state: string): number` — the weight of one state in the blend now
- `tint(): Color3`
- `snapshot(): MorphSnapshot`
- `restore(s: MorphSnapshot): void`

### MorphService

*class* · `packages/morph/src/service.ts:15`

```ts
class MorphService
```

- `addBank(name: string, bank: MorphBank): void`
- `bank(name: string): MorphBank`
- `bankNames(): string[]`
- `addModel(name: string, model: SkinnedModel): void` — data the commands bake from: a skinned model, a clip, a mesh of another topology
- `addClip(name: string, clip: ClipJson): void`
- `addMesh(name: string, mesh: MeshData): void`
- `fromClip(bank: string, model: string, clip: string, opts: FromClipOptions = {}): MorphBank` — a bank from frames of a clip of a registered model (the clip path of fromclip.ts)
- `conform(bank: string, state: string, mesh: string, opts: ConformOptions = {}): unknown` — a state of a bank's topology that looks like a registered mesh
- `spawn(name: string, bank: string, initial?: string): MorphObject` — make an object that wears a bank's states
- `object(name: string): MorphObject`
- `has(name: string): boolean`
- `objectNames(): string[]`
- `remove(name: string): void`
- `step(dt: number): void` — every fixed step
- `describe(name: string): unknown` — state of one object, as the commands answer it
- `register(reg: RegisterFn): void`

## Functions

### add3

*function* · `packages/morph/src/math.ts:10`

```ts
function add3: (a: Vec3, b: Vec3) => Vec3
```

### appliedPositions

*function* · `packages/morph/src/blend.ts:17`

```ts
function appliedPositions(state: MorphState): Float32Array
```

the positions of a state with its scale and pivot applied

### averageColors

*function* · `packages/morph/src/babylon.ts:28`

```ts
async function averageColors(root: BABYLON.TransformNode): Promise<(m: BABYLON.AbstractMesh) => [number, number, number, number]>
```

The average colour of the base-colour texture of every material below `root` (a light figure has one colour per vertex, so a textured part takes the mean of its texture;
a material without a texture keeps its colour factor). The answer is a function for `modelArrays` and `bankFromGroups`.

### bankBytes

*function* · `packages/morph/src/budget.ts:36`

```ts
function bankBytes(bank: MorphBank): { texture: number; arrays: number }
```

bytes of the bank in the texture and in the arrays, for `morph.state`

### bankFromClip

*function* · `packages/morph/src/fromclip.ts:77`

```ts
function bankFromClip(model: SkinnedModel, clip: ClipJson, opts: FromClipOptions = {}): MorphBank
```

a bank of the frames of `clip`, one state per chosen time

### bankFromGroups

*function* · `packages/morph/src/babylon.ts:73`

```ts
function bankFromGroups(root: BABYLON.TransformNode, groups: BABYLON.AnimationGroup[], opts: FromClipOptions = {}, colorOf?: (m: BABYLON.AbstractMesh) => [number, number, number, number]): { bank: MorphBank; arrays: ModelArrays }
```

The frames of animation groups of a model as a bank. The model must be in the scene at its rest pose. For every group and chosen time (see `FromClipOptions`) the group is put
at that time, the bones are brought up to date and the vertices are skinned (rigid parts follow their node). The states are named `${group}@${seconds}`.

### bankFromMesh

*function* · `packages/morph/src/source.ts:112`

```ts
function bankFromMesh(name: string, positions: ArrayLike<number>, indices: ArrayLike<number>, colors?: ArrayLike<number>): MorphBank
```

a bank from the arrays of one mesh: its first state is the mesh itself, named `name`

### bankIsCurrent

*function* · `packages/morph/src/fromclip.ts:126`

```ts
function bankIsCurrent(bank: MorphBank, model: SkinnedModel, clip: ClipJson): boolean
```

is the bank still what the clip and the model would bake now? (if not, bake it again)

### bankSource

*function* · `packages/morph/src/fromclip.ts:119`

```ts
function bankSource(model: SkinnedModel, clip: ClipJson): string
```

names the clip and the model by their content

### blendImages

*function* · `packages/morph/src/far.ts:53`

```ts
function blendImages(a: ArrayLike<number>, b: ArrayLike<number>, w: number, out?: Float32Array): Float32Array
```

the colour blend of two baked pictures, texel by texel (RGBA8 or float, the same size): the reference of the far rung, also used for the dots on the horizon

### blendInto

*function* · `packages/morph/src/blend.ts:61`

```ts
function blendInto(bank: MorphBank, weights: Weights, out: BlendOut, tint: readonly [number, number, number] = [1, 1, 1]): BlendOut
```

mix `weights` (they are normalised here) into `out`; `tint` multiplies the colours

### boneFrames

*function* · `packages/morph/src/fromclip.ts:69`

```ts
function boneFrames(model: SkinnedModel, clip: ClipJson | null, t: number): Bone[]
```

the model-space frames of every bone of the model at a time of the clip

### captureState

*function* · `packages/morph/src/source.ts:12`

```ts
function captureState(bank: MorphBank, name: string, positions: ArrayLike<number>, colors?: ArrayLike<number>, normals?: ArrayLike<number>): MorphState
```

copy the arrays of a mesh as a state (with normals computed from its triangles when none are given)

### chooseViews

*function* · `packages/morph/src/budget.ts:25`

```ts
function chooseViews(objects: Candidate[], budget: MorphBudget = defaultBudget()): Map<string, ViewKind>
```

which view each object gets: the nearest moving objects take the CPU path while the budget lasts, the rest go to the GPU (or, with no GPU, all stay CPU and over-budget ones simply update less often)

### clamp

*function* · `packages/morph/src/math.ts:6`

```ts
function clamp: (v: number, lo: number, hi: number) => number
```

### closestOnTriangle

*function* · `packages/morph/src/conform.ts:64`

```ts
function closestOnTriangle(p: Vec3, a: Vec3, b: Vec3, c: Vec3): { point: Vec3; u: number; v: number; w: number }
```

closest point on triangle (a, b, c) to p, with its barycentric coordinates (Ericson, Real-Time Collision Detection)

### colorState

*function* · `packages/morph/src/source.ts:34`

```ts
function colorState(bank: MorphBank, name: string, base: string, fn: (i: number, p: Vec3) => Color3 | [number, number, number, number]): MorphState
```

a state of the same shape as `base` with colours from a function of the vertex: `fn(i, position) -> [r, g, b, a?]`

### computeNormals

*function* · `packages/morph/src/blend.ts:26`

```ts
function computeNormals(positions: ArrayLike<number>, indices: ArrayLike<number>, out?: Float32Array): Float32Array
```

area-weighted vertex normals of a triangle list

### conform

*function* · `packages/morph/src/conform.ts:118`

```ts
function conform(bank: MorphBank, name: string, target: MeshData, opts: ConformOptions = {}): ConformReport
```

Make a state called `name` in `bank` that looks like `target`. Returns the report; throws a ConformError when the result is not good enough (unless `check: false`),
in which case no state is added.

### cross3

*function* · `packages/morph/src/math.ts:13`

```ts
function cross3: (a: Vec3, b: Vec3) => Vec3
```

### defaultBudget

*function* · `packages/morph/src/budget.ts:20`

```ts
function defaultBudget: () => MorphBudget
```

### defaultLook

*function* · `packages/morph/src/view.ts:22`

```ts
function defaultLook: () => MorphLook
```

### dot3

*function* · `packages/morph/src/math.ts:12`

```ts
function dot3: (a: Vec3, b: Vec3) => number
```

### hashFloats

*function* · `packages/morph/src/math.ts:18`

```ts
function hashFloats(parts: ArrayLike<number>[]): string
```

32-bit FNV-1a of float data: the content hash of a bank (the same bytes give the same hash on every machine)

### installMorphOps

*function* · `packages/morph/src/ops.ts:34`

```ts
function installMorphOps(service: MorphService, bridge: MorphBridgeLike): void
```

### len3

*function* · `packages/morph/src/math.ts:14`

```ts
function len3: (a: Vec3) => number
```

### lerp

*function* · `packages/morph/src/math.ts:7`

```ts
function lerp: (a: number, b: number, t: number) => number
```

### lerp3

*function* · `packages/morph/src/math.ts:8`

```ts
function lerp3: (a: Vec3, b: Vec3, t: number) => Vec3
```

### materialColor

*function* · `packages/morph/src/babylon.ts:18`

```ts
function materialColor(m: BABYLON.Material | null): [number, number, number, number]
```

the colour of a material for a vertex colour: the PBR albedo, the standard diffuse, else white

### mergeBanks

*function* · `packages/morph/src/source.ts:100`

```ts
function mergeBanks(banks: MorphBank[]): MorphBank
```

the states of several banks of one topology in one bank (the first bank's index buffer; the topologies must agree)

### mirroredState

*function* · `packages/morph/src/source.ts:49`

```ts
function mirroredState(bank: MorphBank, name: string, base: string, partner: ArrayLike<number>, axis: 0 | 1 | 2 = 0): MorphState
```

a state mirrored across the plane `axis = 0` (x by default), using a vertex pairing `partner[i]` = the vertex at the mirrored place

### mirrorPairs

*function* · `packages/morph/src/source.ts:62`

```ts
function mirrorPairs(positions: ArrayLike<number>, axis: 0 | 1 | 2 = 0, tolerance = 1e-4): Int32Array
```

pair each vertex with the vertex at its mirror image across `axis = 0` (nearest within `tolerance`), or throw naming the first vertex without one

### modelArrays

*function* · `packages/morph/src/babylon.ts:49`

```ts
function modelArrays(root: BABYLON.TransformNode, colorOf: (m: BABYLON.AbstractMesh) => [number, number, number, number] = m => materialColor(m.material)): ModelArrays
```

every mesh below `root` as one mesh in the space of the scene (their world matrices applied), vertex colours from their materials (or from their own vertex colours)

### newBlendOut

*function* · `packages/morph/src/blend.ts:12`

```ts
function newBlendOut(vertexCount: number): BlendOut
```

### nodeHandle

*function* · `packages/morph/src/view.ts:245`

```ts
function nodeHandle(node: BABYLON.TransformNode, forward: [number, number, number] = [0, 0, 1]): NodeHandle
```

A scene node as the handle the language's node operations (`move-along`, `turn-to`) move. `forward` is the node's own axis that points where it faces (Ferret's is +z; a model
made with its nose along +x says `[1, 0, 0]`); a placement turns the node so that axis points along the asked direction, with no roll (the upright aim of a vehicle or a person).

### norm3

*function* · `packages/morph/src/math.ts:15`

```ts
function norm3: (a: Vec3) => Vec3
```

### packBank

*function* · `packages/morph/src/layout.ts:22`

```ts
function packBank(bank: MorphBank, width = TEXTURE_WIDTH): BankTexture
```

### partBounds

*function* · `packages/morph/src/source.ts:93`

```ts
function partBounds(bank: MorphBank, state: string, part: { first: number; count: number }): { min: Vec3; max: Vec3 }
```

the bounds of a part of a state: the corners of its box

### prepare

*function* · `packages/morph/src/blend.ts:47`

```ts
function prepare(bank: MorphBank, i: number): Prepared
```

applied positions, normals (stored or computed) and colours of state `i`, cached until the state is replaced

### proceduralState

*function* · `packages/morph/src/source.ts:22`

```ts
function proceduralState(bank: MorphBank, name: string, base: string, fn: (i: number, p: Vec3) => Vec3): MorphState
```

a state from a function of the vertex: `fn(i, position of the base state) -> new position`

### rotatedPartState

*function* · `packages/morph/src/source.ts:79`

```ts
function rotatedPartState(bank: MorphBank, name: string, base: string, part: { first: number; count: number }, point: Vec3, axis: Vec3, angle: number): MorphState
```

A state in which the vertices `first .. first + count - 1` (one part of a model: a flap, a propeller, a door) are turned by `angle` radians about the line through `point` along
`axis`, the rest of the model unchanged. This is how a part on a hinge takes a pose without a clip; `hingeOf` finds a hinge from the part's own bounds.

### scale3

*function* · `packages/morph/src/math.ts:11`

```ts
function scale3: (a: Vec3, k: number) => Vec3
```

### selectKeyTimes

*function* · `packages/morph/src/fromclip.ts:104`

```ts
function selectKeyTimes(candidates: number[], poseAt: (t: number) => Float32Array, count: number): number[]
```

The `count` most different times of `candidates`: the first, then each time whose pose is farthest (largest minimum vertex distance) from those chosen. Returned in time order.

### shadeAll

*function* · `packages/morph/src/layout.ts:65`

```ts
function shadeAll(t: BankTexture, idx: ArrayLike<number>, w: ArrayLike<number>, tint: readonly [number, number, number], out: BlendOut): BlendOut
```

the whole mesh through the shader's arithmetic

### shadeVertex

*function* · `packages/morph/src/layout.ts:50`

```ts
function shadeVertex(t: BankTexture, v: number, idx: ArrayLike<number>, w: ArrayLike<number>, tint: readonly [number, number, number]): { position: [number, number, number]; normal: [number, number, number]; color: [number, number, number, number] }
```

What the vertex shader computes for one vertex of one object: up to four states (`idx`) with their weights (`w`), normalised here as in the shader, and the tint. This is the
function the GPU result is compared with in the tests (and the CPU path is its loop over all vertices).

### skinVertices

*function* · `packages/morph/src/fromclip.ts:50`

```ts
function skinVertices(model: SkinnedModel, bind: Bone[], pose: Bone[], out?: Float32Array): Float32Array
```

the vertices skinned by the bone frames `pose` (model space) against the rest frames `bind`

### slots

*function* · `packages/morph/src/layout.ts:74`

```ts
function slots(weights: ReadonlyArray<readonly [number, number]>): { idx: [number, number, number, number]; w: [number, number, number, number] }
```

the weights of an object as the four-slot vectors the per-instance buffers carry (unused slots: state 0, weight 0)

### sub3

*function* · `packages/morph/src/math.ts:9`

```ts
function sub3: (a: Vec3, b: Vec3) => Vec3
```

### texel

*function* · `packages/morph/src/layout.ts:41`

```ts
function texel(t: BankTexture, state: number, kind: number, v: number): [number, number, number, number]
```

the texel of (state, kind, vertex) as the shader's `texelFetch(tex, ivec2(col, row), 0)` finds it

### tintedState

*function* · `packages/morph/src/source.ts:46`

```ts
function tintedState(bank: MorphBank, name: string, base: string, color: Color3): MorphState
```

a flat colour over a whole state (a livery)

### vertexIndexChannel

*function* · `packages/morph/src/layout.ts:82`

```ts
function vertexIndexChannel(vertexCount: number): Float32Array
```

the UV values of the baked vertex index: the vertex number as a float (exact below 2^24 vertices), one value per vertex, written by the content import for meshes without a vertex id

## Interfaces

### BankTexture

*interface* · `packages/morph/src/layout.ts:14`

```ts
interface BankTexture
```

- `width: number`
- `height: number`
- `rowsPer: number`
- `states: number`
- `vertexCount: number`
- `data: Float32Array` — RGBA32F, width * height * 4
- `hash: string` — the hash of the bank this texture was made from

### BlendOut

*interface* · `packages/morph/src/blend.ts:10`

```ts
interface BlendOut
```

- `positions: Float32Array`
- `normals: Float32Array`
- `colors: Float32Array`

### Candidate

*interface* · `packages/morph/src/budget.ts:22`

```ts
interface Candidate
```

- `name: string`
- `vertices: number`
- `distance: number`
- `moving: boolean`

### ConformOptions

*interface* · `packages/morph/src/conform.ts:21`

```ts
interface ConformOptions
```

- `align?: 'bbox' | 'landmarks' | 'none'` — how B is put over A: 'bbox' (centres and the diagonal match; default), 'landmarks' (centroid and spread of the landmarks), 'none'
- `landmarks?: Landmark[]`
- `collapse?: Array<{ a: number; to: Vec3 }>` — vertices of A that have no counterpart in B: each goes to a point (in B's own frame) and is held there
- `smooth?: number` — 0..1, how far a vertex moves toward the mean offset of its neighbours per pass (default 0.5)
- `iterations?: number` — passes of smoothing (default 4)
- `normalWeight?: number` — weight of the normal agreement in the choice of the closest point (default 0.5); 0 is the plain closest point
- `base?: string` — the state of A whose normals and edges are used (default: its first state)
- `maxResidual?: number` — fail with a ConformError if the residual (max) is above this fraction of B's bounding diagonal (default 0.05) or any triangle folds (default 0 allowed)
- `maxFolds?: number`
- `check?: boolean` — do not fail, only report

### ConformReport

*interface* · `packages/morph/src/conform.ts:42`

```ts
interface ConformReport
```

- `meanResidual: number` — mean and maximum distance of the result's vertices from B's surface, in the units of A and as a fraction of B's diagonal
- `maxResidual: number`
- `relativeMax: number`
- `folded: number[]` — triangles of A whose normal turned over or that became a point
- `unused: number[]` — vertices of A that no triangle uses, plus the collapsed ones
- `collapsed: number[]`
- `alignment: { scale: number; centreA: Vec3; centreB: Vec3 }` — the alignment that was applied: B' = scale * (B - centreB) + centreA

### FarSlot

*interface* · `packages/morph/src/far.ts:11`

```ts
interface FarSlot
```

The far rung of a morphing object. A baked impostor is a picture, so it cannot change shape; it morphs by colour. The impostors of the key states are
baked (one `Representation` per state, from the perspective module's own bake) and the object shows the two states of largest weight, the one fading out while the other
fades in with mix = the weight of the second: the same cross-fade the ladder uses between rungs, so state changes and rung changes run together and a program cannot tell which
rung is drawn. A state with no baked impostor is replaced by the nearest baked one (by name order along the bank), so a bank can be baked at a few key states only.

- `state: number`
- `rep: Representation`

### FromClipOptions

*interface* · `packages/morph/src/fromclip.ts:27`

```ts
interface FromClipOptions
```

- `times?: number[]` — the times (seconds) to pose at; or:
- `every?: number` — every n-th frame of the clip at its fps; or:
- `keyPoses?: number` — the `n` most different poses of the clip, found automatically (farthest-point choice over the skinned vertices, always including the first frame)
- `prefix?: string` — name of the states: `${prefix}@${seconds}`, default the clip's name
- `inPlace?: boolean` — take the root's travel out of every frame (default true)

### Landmark

*interface* · `packages/morph/src/conform.ts:14`

```ts
interface Landmark
```

- `a: number` — a vertex of A
- `b: Vec3` — where it must land, in B's own frame (before the alignment is applied)

### MeshData

*interface* · `packages/morph/src/conform.ts:12`

```ts
interface MeshData
```

Retopology: a state of A's topology that looks like a mesh B of another topology. B is aligned to A, every vertex of A takes the closest point on B's
surface (the normals of both break ties, so a vertex does not jump through a thin part to the far side), the field of offsets is smoothed so neighbours stay neighbours,
colours are sampled at the same points, and the result is *measured*: the residual distance from B and the folded triangles. A failed conform is an error, not a silent result.
Cost is O(vertices of A x triangles of B), which is small for light figures.

- `positions: ArrayLike<number>`
- `indices: ArrayLike<number>`
- `colors?: ArrayLike<number>`

### ModelArrays

*interface* · `packages/morph/src/babylon.ts:11`

```ts
interface ModelArrays extends MeshData
```

Reading models the engine holds: the arrays of a model's meshes as a mesh, and the frames of its animation groups as a bank. The skinning is the
engine's own (the bone matrices Babylon computes, applied to the vertices on the CPU), so the states are what the engine would draw at those times. A model made of rigid
parts (an aeroplane whose flap is a node) is the same case with one bone per part: its animation group moves the nodes and the part's vertices follow them.

- `positions: Float32Array`
- `indices: Uint32Array`
- `colors: Float32Array`
- `parts: Array<{ name: string; first: number; count: number }>` — per mesh: first vertex, vertex count, name

### MorphBridgeLike

*interface* · `packages/morph/src/ops.ts:19`

```ts
interface MorphBridgeLike
```

- `define(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => unknown): unknown`
- `lasting(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => { done(): boolean; result?: unknown }): unknown`
- `action(name: string, sig: { args: string[]; min?: number; rest?: string }, spec: { start(ctx: any, args: any[]): { step?(args: any[], ctx: any): void; stop?(): void } | void }): unknown`

### MorphBudget

*interface* · `packages/morph/src/budget.ts:11`

```ts
interface MorphBudget
```

- `maxCpu: number` — at most this many objects drawn by the CPU path (default 8)
- `cpuVertices: number` — vertices the CPU path may blend in one frame over all its objects (default 200000)
- `gpu: boolean` — the device has no vertex texture fetch (or GPU views are off): everything is CPU

### MorphHostOptions

*interface* · `packages/morph/src/host.ts:14`

```ts
interface MorphHostOptions
```

The two modules in one service: the morph service and the motion language's runtime stepped together in the world's fixed step, with
the morph operations and the node-moving operations (`move-along`, `turn-to`) registered on the same bridge, and the commands `morph.*` and `morph.run`. A program that morphs a
plane and flies it is one program: `(par (move-along route 80) (morph-to gear-up 4s) (tint-to #203040 20s))`.

The host knows no engine: the game says how a node name becomes a `NodeHandle` (`node`), and the programs' `target` names both the morph object and the node.

- `seed?: number`
- `node: (name: string) => NodeHandle | undefined` — a node of the scene by name, as the handle the node operations move
- `budget?: number` — reductions a program may do per step (the language's budget)

### MorphIssue

*interface* · `packages/morph/src/bank.ts:22`

```ts
interface MorphIssue
```

- `level: 'error' | 'warning'`
- `path: string`
- `message: string`

### MorphLook

*interface* · `packages/morph/src/view.ts:15`

```ts
interface MorphLook
```

Drawing the blend. Two views of the same `MorphObject`:
  `CpuMorphView`  one mesh whose vertex arrays are rewritten when the blend changes (and not otherwise): the reference, exact for any bank, for the few important objects;
  `GpuMorphBatch` one mesh and one draw call for all the objects of a bank: the states are in a float texture (see layout.ts), the vertex shader mixes up to four of them per
                  instance, and the CPU writes only a small vector per object per frame (four state numbers, four weights, a tint).
Both are lit by the same fragment shader (`MorphLook`), so a picture of one equals a picture of the other (the test of M4 compares them pixel by pixel).

- `sun: [number, number, number]` — the direction the sun shines along
- `sunColor: [number, number, number]`
- `ambientUp: [number, number, number]`
- `ambientDown: [number, number, number]`

### MorphSnapshot

*interface* · `packages/morph/src/sim.ts:15`

```ts
interface MorphSnapshot
```

- `v: 1`
- `time: number`
- `base: Array<[number, number]>`
- `tr: { to: number; t0: number; dur: number; ease: string; id: number } | null`
- `holds: Array<[number, number]>`
- `pinned: { a: number; b: number; w: number } | null`
- `nextId: number`
- `activeId: number`
- `tint: { from: Color3; to: Color3; t0: number; dur: number; ease: string }`

### MorphState

*interface* · `packages/morph/src/bank.ts:8`

```ts
interface MorphState
```

The bank: the states of one topology. A state is a full set of per-vertex data (positions, optionally normals and colours) and a scale and pivot;
the index buffer is held once. States are named. The bank is plain typed arrays and JSON/binary files, so the same bank is read by the browser and by the UE build.

- `name: string`
- `positions: Float32Array` — xyz per vertex
- `normals?: Float32Array` — xyz per vertex, unit length; recomputed from the positions when absent
- `colors?: Float32Array` — rgba per vertex, 0..1; absent: white
- `scale?: number` — one scale of the whole state (a folded wing is shorter than an open one)
- `pivot?: [number, number, number]` — the point the scale is about

### MorphWait

*interface* · `packages/morph/src/sim.ts:23`

```ts
interface MorphWait
```

a lasting move: the program waits on it; it is done when it has arrived or has been replaced by another move

- `readonly id: number`
- `done(): boolean`

### SkinnedModel

*interface* · `packages/morph/src/fromclip.ts:12`

```ts
interface SkinnedModel
```

States from the frames of a clip. A skinned model, posed at chosen times of a clip, is skinned on the CPU and the result is stored
as a state of the model's topology. The model's vertices are in the rest pose of the skeleton the clip is made for (as a skinned mesh is bound). Root motion is taken out of
every frame (the figure stays where it was at the first frame), as in the VAT bake. The bank carries a `source` that names the clip and the model by content, so a bank is
re-baked when either changes (`bankIsCurrent`).

- `name: string` — the model's name, for the bank's source
- `positions: Float32Array` — xyz per vertex in the bind pose
- `indices: Uint32Array`
- `joints: ArrayLike<number>` — four bone indices per vertex (into `boneNames`) and four weights
- `weights: ArrayLike<number>`
- `boneNames: string[]`
- `rest: Rest`
- `colors?: Float32Array` — rgba per vertex, 0..1, kept in every state (optional)

## Types

### Color3

*type* · `packages/morph/src/math.ts:4`

```ts
type Color3 = [number, number, number]
```

### RegisterFn

*type* · `packages/morph/src/service.ts:13`

```ts
type RegisterFn = (name: string, description: string, fn: (args: any) => unknown) => void
```

The morph service: the banks and the objects of a world, stepped once per fixed step, and the `morph.*` commands. It is host-agnostic: the game passes
`world.commands.register`, a test passes a function that fills a Map. Everything the commands take and return is plain JSON.

### Vec3

*type* · `packages/morph/src/math.ts:3`

```ts
type Vec3 = [number, number, number]
```

### VertexLookup

*type* · `packages/morph/src/view.ts:105`

```ts
type VertexLookup = 'vertex-id' | 'uv-index'
```

how the shader finds a vertex in the bank texture: by the vertex id the draw gives (`vertex-id`, WebGL2), or by the vertex's baked index in an attribute (`uv-index`)

### ViewKind

*type* · `packages/morph/src/budget.ts:9`

```ts
type ViewKind = 'cpu' | 'gpu'
```

The choice between the CPU view and the GPU view, in the spirit of the perspective governor. A few objects near the camera may be drawn by the
CPU path (any function can change the mesh, normals are exact); many, or any object whose blend changes every frame in a crowd, go to the GPU path (one draw call for all,
cost per frame is the number of objects). Both read the same `MorphObject`, so an object can move from one to the other at any step.

### Weights

*type* · `packages/morph/src/blend.ts:8`

```ts
type Weights = ReadonlyArray<readonly [index: number, weight: number]>
```

The blend: up to four weighted states of one bank mixed into positions, normals and colours.
A state's scale and pivot are applied first (`appliedPositions`), so the blend is a plain weighted sum and the GPU can read the same applied numbers from its texture.

## Constants

### KINDS

*const* · `packages/morph/src/layout.ts:12`

```ts
const KINDS: 3
```

### MAX_STATES

*const* · `packages/morph/src/sim.ts:12`

```ts
const MAX_STATES: 4
```

The deterministic part: what blend one object is in, as a function of the fixed step and the commands it was given. Pure numbers, no engine; the
same on every peer and every tier. The object holds up to four weighted states: a transition from the current blend to a state is `base * (1 - u) + target * u` with `u` the
eased progress, a new transition starts from the blend as it is at that moment (never from a jump), and held weights (`hold`) are laid over the result.

### TEXTURE_WIDTH

*const* · `packages/morph/src/layout.ts:11`

```ts
const TEXTURE_WIDTH: 2048
```

The layout of a bank in a float texture and the reference of what the vertex shader does with it. The texture is RGBA32F, `width` texels
wide; one row block of `rowsPer = ceil(vertexCount / width)` rows per (state, kind), the kinds being 0 position (xyz, w = 1), 1 normal (xyz), 2 colour (rgba). Vertex `v` of
state `s`, kind `k` is at column `v % width`, row `(s * 3 + k) * rowsPer + floor(v / width)`. A shader reads the same texture with the same
arithmetic, by the vertex id or by the baked index of the vertex in an attribute (`vertexIndexChannel`), so both lookups give the same texel.

