# @ferret/animation: API

Animation graphs: state machines, blend spaces, layers, notifies, retargeting and a stand-in puppet.

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

## Classes

### Animator

*class* · `packages/animation/src/animator.ts:33`

```ts
class Animator extends Component<AnimatorParams>
```

Plays an animation graph on an entity. Parameters come from the entity's motion source (or from game code through
`graph.set` / `graph.trigger`), the pose is applied once per rendered frame (the world hands over dt scaled by the entity's time dilation).
Notifies are emitted on the world's event bus as `anim:notify` { entity, name, clip }.

- `graph: AnimGraph`
- `backend: GroupBackend`
- `rootDelta: RootDelta` — root motion of the last frame, in the entity's own space (zero without `rootMotion`)
- `poseGate: (() => boolean) | null` — Asked once per rendered frame: false skips applying the pose to the skeleton this frame (the graph still runs, so states, notifies, montages and the clock are exactly as without a gate; the root motion of the skipped frames comes with the next applied one). `@ferret/perspective` sets it so a far object poses its bones less often. Null (the default) poses every frame.
- `onAttach()`
- `onFixedUpdate()`
- `onUpdate(dt: number)`
- `playMontage(def: MontageDef)` — Play a one-shot clip over the base animation (a gesture, an attack, a pick-up).
- `onDetach()`

### AnimGraph

*class* · `packages/animation/src/graph.ts:265`

```ts
class AnimGraph
```

Runtime of one graph on one character.

- `readonly values: Record<string, number>`
- `notifyThreshold: number` — a clip whose weight in the output is at least this fires its notifies
- `constructor(readonly def: GraphDef, readonly clips: ClipLibrary, readonly events: GraphEvents = {})`
- `get state(): string`
- `get phase(): number` — how far the current state is through its cycle, 0..1 (for what follows the gait: a hop's arc, footsteps)
- `get activeMontages(): readonly Montage[]`
- `set(param: string, value: number | boolean)`
- `get(param: string): number`
- `trigger(name: string)`
- `playMontage(def: MontageDef): Montage`
- `stopMontage(m: Montage)`
- `update(dt: number): Pose` — Advance by dt seconds (already multiplied by the entity's time dilation).

### ClipEditError

*class* · `packages/animation/src/clip.ts:250`

```ts
class ClipEditError extends Error
```

### ClipEditor

*class* · `packages/animation/src/clip.ts:274`

```ts
class ClipEditor
```

- `readonly rest: Rest`
- `constructor(clip: ClipJson, private readonly o: ClipEditorOptions)`
- `static create(o: ClipEditorOptions & { skeleton: string; name: string; duration?: number; base?: string; loop?: boolean; fps?: number }): ClipEditor` — A new clip: empty (the rest pose), or a copy of a library clip.
- `get json(): ClipJson`
- `get canUndo()`
- `get canRedo()`
- `history(): string[]`
- `undo(): boolean`
- `redo(): boolean`
- `setKey(a: { bone: string; time: number; rotation?: Quat; euler?: Vec3; position?: Vec3; interp?: Interp; absolute?: boolean }): void` — Set a key of a bone at a time (replaces the key there). `rotation` (quaternion) or `euler` (degrees) is the change from rest; with `absolute` it is the bone's own rotation (the change is worked out from the rest pose). `position` is the offset from the rest position (root and pelvis only).
- `removeKey(a: { bone: string; time: number; channel?: 'rotation' | 'position' | 'scale' }): number` — Remove the key of a bone at a time (`channel` limits it to `rotation`, `position` or `scale`). Returns how many were removed.
- `copyKey(a: { from: number; to: number; bone?: string }): number` — Copy the keys at a time to another time: of one bone, or of every bone that has one (a pose). The values are what the clip is at `from` (held keys, or sampled between).
- `mirror(a: { time?: number } = {}): number` — Mirror left and right (partners are found by the `_l` / `_r` ending of the bone name; bones on the middle line are mirrored in place). With `time`, only the pose at that time is mirrored (the keys there); without, the whole clip.
- `ik(a: { chain: [string, string, string]; target: Vec3 | { bone: string; offset?: Vec3 }; pole?: Vec3 | { bone: string; offset?: Vec3 }; time: number; endRotation?: Quat; weight?: number; interp?: Interp }): { error: number; stretched: boolean }` — Set keys by solving a limb to a target at a time: `chain` is [root bone, middle bone, end bone] (shoulder, elbow, hand), `target` a point in the skeleton frame or a point on another bone (`{bone, offset}`, the offset in that bone's frame: a grip on the sword is an offset of the right hand), `pole` the same for the point the elbow or knee bends toward. The chain's three bones get rotation keys at `time`; the end bone keeps its rotation in the world unless `endRotation` (a rotation in the skeleton frame) is given. Returns how far the end is from the target afterwards (a limb too short stretches).
- `hold(a: { time: number; side?: 'r' | 'l'; grip: Grip; position: Vec3; direction: Vec3; roll?: number | 'auto'; both?: boolean; poleMain?: Vec3; poleOff?: Vec3; wrapToward?: Vec3; edge?: Vec3; edgeWeight?: number; interp?: Interp }): ReturnType<typeof holdWeapon>` — Put a weapon in the hands at a time (see `holdWeapon`): the grip's middle at `position`, the blade along `direction`, both hands if the grip has a spacing. The arms, the hands' turn and the fingers get rotation keys at `time`; returns the solve's errors.
- `holdRun(holds: Parameters<ClipEditor['hold']>[0][], o: { loop?: boolean; step?: number } = {}): ReturnType<typeof holdWeapon>[]` — Hold a weapon at many times at once (frames of a move, in any order): the turns of the hands about the blade left as `'auto'` (or absent) are chosen for the whole run together (`holdRolls`: wrists least bent, hands moving least between the times; `loop` joins the last to the first), then each is set as `hold` does. The poses the run is solved on are the clip's at those times before the hands are set. One undo step per time. Returns one result per hold, in the order given.
- `setNotify(a: { name: string; time: number }): void`
- `removeNotify(a: { name: string; time?: number }): number`
- `retime(a: { scale?: number; curve?: [number, number][] }): void` — Change the length: `scale` multiplies every time, or `curve` maps old times to new ones with straight lines between the pairs (first pair 0 -> 0 added if missing).
- `setInfo(a: { duration?: number; loop?: boolean; fps?: number; name?: string }): void`
- `validate(): { ok: boolean; issues: ClipIssue[]; skipped: string[] }` — Checks of the clip: what a hand-made clip gets wrong. Errors are what cannot play; warnings are joints bent past their limit (`limits`), sudden jumps between keys (pops), a loop whose end does not meet its start, and tracks for bones the skeleton lacks. Foot sliding and ground penetration need the bodies' bones in space and are not checked here (`skipped`).

### GroupBackend

*class* · `packages/animation/src/backend.ts:67`

```ts
class GroupBackend
```

Applies a pose request to Babylon animation groups without Babylon's own animation clock: every targeted animation is
sampled at the requested time (`Animation.evaluate`), the samples of one property are blended by weight (vectors and
floats linearly, rotations by normalised lerp) and written to the target. A masked item (a montage on the upper body)
counts only for targets under its bones, and takes its weight from the base clips there. Targets the pose does not
mention keep their value, and a property whose weights sum to less than 1 keeps the rest of its current value.
The groups are plain containers of animations: never started, so they cost nothing between frames.

- `constructor(readonly groups: Record<string, BABYLON.AnimationGroup>, readonly rootMotion?: RootMotionOptions)`
- `apply(pose: Pose, rootOnly = false): RootDelta` — Apply a pose; returns the root motion the clips made this call (all zero without `rootMotion`). With `rootOnly` nothing is written to the skeleton: only the root motion is measured (and each clip's clock noted), so an object that does not pose its bones still moves exactly as one that does.
- `dispose()`

### IkRig

*class* · `packages/animation/src/ik-babylon.ts:88`

```ts
class IkRig
```

IK for one body. Add parts (`limb`, `lookAt`, `footPlacement`), then `attach()` to run it after each frame's animation (or call `update(dt)` yourself).
Parts run in the order: feet, look-at, limbs (so a hand that follows a sword held by an animated hand sees the body as placed).

- `readonly frame: Node`
- `readonly rest: Rest`
- `readonly state: { pelvisDrop: number; footOffsets: number[]; limbError: Record<string, number> }` — what the last update did, for tests and the inspector
- `constructor(readonly scene: BABYLON.Scene, readonly bones: Record<string, Node>, o: IkRigOptions = {})`
- `limb(spec: LimbSpec): this`
- `lookAt(spec: LookAtSpec): this`
- `footPlacement(spec: FootPlacementSpec): this`
- `attach(): this` — run after the scene's animations every frame
- `dispose()`
- `frameT(n: Node): { p: Vec3; q: Quat }` — frame position and rotation of a node, from the local values of it and its parents up to the frame
- `axisOf(bone: string, worldDir: BABYLON.Vector3): Vec3` — a world direction as an axis of a bone's own frame, with the skeleton as it is now (for `lookAt.forward`: build the rig with the body at rest, facing `worldDir`)
- `update(dt: number): void`

### Legged

*class* · `packages/animation/src/legged.ts:115`

```ts
class Legged extends Component<LeggedParams>
```

Ground, slope, lean, rock, hop and head for a legged body (see the file's comment). Add it to an entity that has an `Animator` playing a `leggedGraph`; the
entity's node stays where the nav mesh keeps it. Exposes `state` for tests and the inspector.

- `schema: { readonly model: { readonly type: "object"; readonly required: true; }; readonly pivot: { readonly type: "object"; readonly required: true; }; readonly legs: { readonly type: "object"; readonly required: true; }; readonly pelvis: { readonly type: "string"; readonly required: true; }; readonly gaits: { readonly type: "array"; readonly required: true; }; readonly groundAt: { readonly type: "function"; readonly required: true; }; readonly head: { readonly type: "object"; }; readonly sway: { readonly type: "number"; readonly min: 0; }; readonly lean: { readonly type: "number"; readonly min: 0; }; readonly maxLean: { readonly type: "number"; readonly min: 0; }; readonly range: { readonly type: "number"; readonly min: 1; }; readonly smooth: { readonly type: "number"; readonly min: 0.1; }; readonly headForward: { readonly type: "array"; }; readonly climb: { readonly type: "boolean"; }; }`
- `readonly state: { pitch: number; roll: number; lift: number; bank: number; rock: number; near: boolean; footWeight: number; gait: string; wheelbase: number; track: number; }` — what the last frame did
- `onAttach()`
- `onUpdate(dt: number)`
- `onDetach()`

### Montage

*class* · `packages/animation/src/graph.ts:118`

```ts
class Montage
```

- `time: number`
- `weight: number`
- `stopping: boolean`
- `finished: boolean`
- `constructor(readonly def: MontageDef, readonly id: number)`

## Functions

### airState

*function* · `packages/animation/src/gait.ts:59`

```ts
function airState: (g: string | GaitSpec) => string
```

### alignFrames

*function* · `packages/animation/src/hold.ts:31`

```ts
function alignFrames(la: Vec3, lb: Vec3, wa: Vec3, wb: Vec3): Quat
```

The rotation that turns the orthonormal frame made of (la, lb) onto the one made of (wa, wb): `la` onto `wa` exactly, `lb` as near to `wb` as it can be.

### analyseAnimal

*function* · `packages/animation/src/anatomy.ts:221`

```ts
function analyseAnimal(scene: BABYLON.Scene, model: Node, o: AnalyseOptions): AnimalPlan
```

Make the plan of an animal from its skeleton and clips. The model must be at rest (no clip played) and may be turned by `plan.yaw` afterwards; the measures are
valid for the turned body.

### analyseFoot

*function* · `packages/animation/src/gait.ts:163`

```ts
function analyseFoot(track: FootTrack, duration: number, band = 0.2): FootGait
```

Stance of one foot: the samples within `band` (default a fifth of the foot's own height range) of its lowest point are on the ground; over the longest run
of them the foot moves back along the body at the speed the ground goes by under it. `duration` is the clip's length, seconds.

### applyClipPose

*function* · `packages/animation/src/clip-babylon.ts:145`

```ts
function applyClipPose(bones: Record<string, Node>, rest: Rest, pose: Record<string, { q?: Quat; p?: Vec3; s?: Vec3 }>): void
```

Put the pose of a clip at a time on a body's nodes (rest where the clip has no key): for scrubbing in a panel, without an animation group.

### bindClips

*function* · `packages/animation/src/character.ts:26`

```ts
function bindClips(scene: BABYLON.Scene, bodyRoot: BABYLON.TransformNode, source: Record<string, BABYLON.AnimationGroup>, map: Record<string, string>, o: BindClipsOptions = {}): BoundClips
```

Puts the clips of a skeleton on a body made of parts: `source` is the animation groups of a loaded clips file (by their names in the file),
`map` says which of them each name of the animation graph is (`{ idle: 'Idle', walk: 'Walk_Fwd' }`), `bodyRoot` is the loaded character.
Every bound clip is a copy of the source targeting the body's bones by name, so one clips file serves any number of bodies.
A character made by tools/ue-export/characters.mjs has the bone names of its clips; a body with other names passes a bone map in `retarget`.

### bonesOf

*function* · `packages/animation/src/clip-babylon.ts:12`

```ts
function bonesOf(root: Node, bones?: Iterable<string>): Record<string, Node>
```

The bones of a model by name: the transform nodes below a root (a body made by the library has them named `<model>/<bone>`).

### boneTracks

*function* · `packages/animation/src/legged.ts:44`

```ts
function boneTracks(scene: BABYLON.Scene, groups: Record<string, BABYLON.AnimationGroup>, model: Node, frame: Node, boneNames: string[], clip: string, duration: number, samples = 48): BABYLON.Vector3[][]
```

The places of some bones over one pass of a clip, in the frame of `frame` (the body's own: up is y), `samples` equal steps of the cycle. The skeleton is returned to the pose it
had before.

### buildPuppet

*function* · `packages/animation/src/puppet.ts:49`

```ts
function buildPuppet(scene: BABYLON.Scene, opts: PuppetOptions = {}): Puppet
```

### chain2Pose

*function* · `packages/animation/src/ik.ts:40`

```ts
function chain2Pose(c: Chain2): Chain2Pose
```

### classifyClips

*function* · `packages/animation/src/anatomy.ts:22`

```ts
function classifyClips(names: string[]): ClipRoles
```

Sort a skeleton's clips by what their names say: the ones it rests in, the ones it feeds in, the ones it moves in. Names carry the species and a `_anim` tail, which is ignored.

### clipFromJson

*function* · `packages/animation/src/clip-babylon.ts:71`

```ts
function clipFromJson(scene: BABYLON.Scene, clip: ClipJson, bones: Record<string, Node>, rest: Rest, o: { name?: string } = {}): BuiltClip
```

Make an AnimationGroup of a clip for a body: one animation per bone that has keys, targeting that bone's node. `bones` are the body's nodes by bone name and
`rest` its rest pose (`restOf`). Bones the body lacks are listed in `missing` and skipped. The group has the clip's name (or `name`) and is not started.

### clipInfo

*function* · `packages/animation/src/backend.ts:5`

```ts
function clipInfo(group: BABYLON.AnimationGroup, opts: { loop?: boolean; notifies?: Notify[] } = {}): ClipInfo
```

The length and frame rate of an AnimationGroup, as a graph clip.

### clipLibrary

*function* · `packages/animation/src/backend.ts:9`

```ts
function clipLibrary(groups: Record<string, BABYLON.AnimationGroup>, extra: Record<string, { loop?: boolean; notifies?: Notify[] }> = {}): ClipLibrary
```

### clipToJson

*function* · `packages/animation/src/clip-babylon.ts:108`

```ts
function clipToJson(group: BABYLON.AnimationGroup, rest: Rest, o: { name?: string; skeleton: string; loop?: boolean; fps?: number; positionBones?: (b: string) => boolean; scales?: boolean }): { clip: ClipJson; skipped: string[] }
```

The clip file of any AnimationGroup of a body, with the skeleton's `rest` (the library's clips are such groups): every animation of a bone's rotation and
position becomes keys at the animation's own frames, as the change from rest (linear between keys, as Babylon plays them). Tracks of other properties and of
nodes that are not bones are left out and named in `skipped`. With `scales`, a scaling track that leaves the rest scale is taken too, as factors on it (a track
with a zero in it is a broken export and is left out, as `retargetGroup` leaves it).

### findAnatomy

*function* · `packages/animation/src/anatomy.ts:76`

```ts
function findAnatomy(model: Node, frame: Node): Anatomy | null
```

Find a body's legs. A limb is a run of bones that hangs off the body at a joint where the skeleton branches into more than one part of real size, goes down to the
ground, and has a partner on the other side (a tail, a neck and a head are alone). The leg chain is the two longest consecutive segments of the limb (thigh and shin),
the sole is its lowest bone. Reads the nodes as they stand: call it before any clip has played.

### findHead

*function* · `packages/animation/src/anatomy.ts:148`

```ts
function findHead(model: Node, frame: Node, anatomy: Anatomy, yaw: number): Anatomy['head']
```

The head chain for a body facing +z: the foremost bone that is not in a limb, climbed to the first bone with some size to it, and the two bones above.

### gaitAt

*function* · `packages/animation/src/gait.ts:112`

```ts
function gaitAt(spec: Pick<LeggedGraphSpec, 'gaits' | 'startAt' | 'stopAt' | 'hysteresis'>, speed: number, current = -1): number
```

The gait a speed asks for, with the same hysteresis as the graph (`current` = the gait now; none = rest). Index into `spec.gaits`, or -1 for rest.

### gaitState

*function* · `packages/animation/src/gait.ts:58`

```ts
function gaitState: (g: string | GaitSpec) => string
```

### holdCost

*function* · `packages/animation/src/hold.ts:122`

```ts
function holdCost(a: HoldArgs, r: HoldResult, near = false): number
```

How awkward a hold leaves the arms: the wrists' bend counts in full, the turn of the forearm they carry much less, the elbows and shoulders less; a hand off its
place or a joint past its range costs much more. With `near`, also how far the hands moved from where `a.pose` has them.

### holdRolls

*function* · `packages/animation/src/hold.ts:142`

```ts
function holdRolls(holds: HoldArgs[], o: { step?: number; smooth?: number; loop?: boolean } = {}): number[]
```

The turns of the hands about the blade for a whole run of holds (one per frame of a clip, in time order): the run that is least awkward over all its frames and
whose hands move least between frames (each frame tries every turn in `step` degrees, the best path through them is found at once, then each is refined by a
degree). `loop`: the last frame joins the first. Returns one turn per hold, degrees, to pass as `roll`.

### holdWeapon

*function* · `packages/animation/src/hold.ts:107`

```ts
function holdWeapon(a: HoldArgs): HoldResult
```

Put a weapon in the hands: the grip's middle at `position`, the blade along `direction`, the main hand's frame turned so the weapon sits as its socket places it, the second hand
mirrored on the grip `spacing` toward the pommel, the arms solved to them (two-bone IK on the pose, elbows toward the poles), and the fingers closed round the grip.
The thumb is left as it is (it rests on the grip in the library's hands).

### hopLift

*function* · `packages/animation/src/gait.ts:194`

```ts
function hopLift(h: HopSpec, phase: number): number
```

The height of a hop at a cycle fraction, 0..1 of `height`: a parabola between lift-off and touch-down (the window may wrap past the end of the cycle).

### hopPitch

*function* · `packages/animation/src/gait.ts:202`

```ts
function hopPitch(h: HopSpec, phase: number): number
```

How far the nose is tipped at a cycle fraction, degrees, + up: leaving the ground it is up, at the top level, landing down.

### hopWindowOf

*function* · `packages/animation/src/gait.ts:215`

```ts
function hopWindowOf(legs: Partial<Record<LegRole, FootGait>>, min = 0.25): [number, number] | null
```

The window of a hop in a clip's cycle, from the stances of its feet: the body is off the ground from the hind feet's push-off to the front feet's touch-down
(a rabbit bounds so: its hind legs drive, its fore legs take the landing). Cycle fractions [lift-off, touch-down]; null when the clip has no such pair of feet.
A window shorter than `min` of the cycle is stretched about its middle so the hop is seen.

### leggedGraph

*function* · `packages/animation/src/gait.ts:65`

```ts
function leggedGraph(spec: LeggedGraphSpec): GraphDef
```

The animation graph of a walker. Parameters it reads: `speed` (m/s, fed by the Animator from the motion source) and `turnRate` (rad/s, when it has a `turn`).
States: `rest` (random player), `gait:<name>` per gait, `turn`. Gait changes keep the phase, so the feet stay in step across them.

### legShifts

*function* · `packages/animation/src/gait.ts:127`

```ts
function legShifts(native: Partial<Record<LegRole, number>>, pattern: Partial<Record<LegRole, number>>): Partial<Record<LegRole, number>>
```

The phases that put a clip's legs in a gait's footfall pattern. `native` is the cycle fraction at which each leg of the clip touches down (`touchDown`);
`pattern` the fractions the gait wants (trot: diagonals together: fl 0, hr 0, fr 0.5, hl 0.5). A leg's shift is the wanted fraction less its own, so
every leg runs the clip's own swing and stance, only at another time.

### locomotionGraph

*function* · `packages/animation/src/puppet.ts:166`

```ts
function locomotionGraph(opts: { walkSpeed?: number; runSpeed?: number; points?: { at: number; clip: string }[]; crouch?: boolean; swim?: { at: number; clip: string }[]; swim2d?: { x: number; y: number; clip: string }[] } = {})
```

A ready-made locomotion graph for a puppet (or any character with the same clip names): a blend of idle and gaits by speed, jump, fall,
and with `crouch` a crouch state (the clips `crouch` and `crouchWalk`) entered while the `crouching` parameter is true.
`swim` (blend1d points on the speed, e.g. Swim_Idle and Swim_Fwd) adds a swim state entered while the `swimming` parameter is true (CharacterMovement in a dense medium) and left when it is false.
`swim2d` (blend2d points on `swimX` = m/s to the right and `swimY` = m/s forward, e.g. Swim_Idle at 0,0, Swim_Fwd 0,3, Swim_Bwd 0,-3, Swim_Left -3,0, Swim_Right 3,0) replaces the speed blend of the swim state; the Animator feeds both from the motion source.
`points` replaces the idle/walk/run blend: `[{ at: 0, clip: 'idle' }, { at: 2, clip: 'walk' }, { at: 3.5, clip: 'jog' }, { at: 6, clip: 'sprint' }]`.

### measureClip

*function* · `packages/animation/src/legged.ts:63`

```ts
function measureClip(scene: BABYLON.Scene, groups: Record<string, BABYLON.AnimationGroup>, model: Node, frame: Node, legs: LegMap, clip: string, duration: number, o: { samples?: number; forward?: Vec3 } = {}): ClipFeet
```

Plays a clip through its cycle on the skeleton and watches the feet: the body's own frame is `frame` (up is y, forward is z unless `forward` says otherwise).
Without `forward` it is taken from the legs (the way the fore feet are from the hind feet). The skeleton is left as it was.

### mirrorName

*function* · `packages/animation/src/clip.ts:224`

```ts
function mirrorName(name: string): string | null
```

`upperarm_l` -> `upperarm_r` and back (case kept: `Wing_01_L` -> `Wing_01_R`); null for a bone on the middle line

### mirrorPosition

*function* · `packages/animation/src/clip.ts:243`

```ts
function mirrorPosition(p: Vec3, from: BoneRest, to: BoneRest): Vec3
```

### mirrorRotation

*function* · `packages/animation/src/clip.ts:236`

```ts
function mirrorRotation(q: Quat, from: BoneRest, to: BoneRest): Quat
```

The mirror of a rotation change of a bone as the change of its partner, for a skeleton that is symmetric about the plane x = 0 in its own frame: the change
is taken into the skeleton frame with the bone's rest rotation, reflected (the axis of a rotation keeps its component along the plane's normal and flips the
others), and taken into the partner's frame. A bone on the middle line is its own partner.

### motionClips

*function* · `packages/animation/src/graph.ts:164`

```ts
function motionClips(m: Motion): string[]
```

### poseFk

*function* · `packages/animation/src/clip.ts:160`

```ts
function poseFk(rest: Rest, pose: Record<string, { q?: Quat; p?: Vec3 }>, bone: string): { p: Vec3; q: Quat }
```

The frame position and rotation of a bone in a pose of the clip (the change from rest per bone, as `samplePose` gives), the skeleton frame being the top bone's parent.

### qAngle

*function* · `packages/animation/src/clip.ts:74`

```ts
function qAngle(q: Quat): number
```

the angle of a rotation in degrees, 0 to 180

### qDistance

*function* · `packages/animation/src/clip.ts:76`

```ts
function qDistance: (a: Quat, b: Quat) => number
```

angle between two rotations in degrees

### qFromEuler

*function* · `packages/animation/src/clip.ts:99`

```ts
function qFromEuler(deg: Vec3): Quat
```

Euler angles in degrees, rotating about x, then y, then z of the parent frame's axes taken in the XYZ order of three.js (q = qx * qy * qz).

### qIdentity

*function* · `packages/animation/src/clip.ts:61`

```ts
function qIdentity: () => Quat
```

### qInv

*function* · `packages/animation/src/clip.ts:70`

```ts
function qInv: (q: Quat) => Quat
```

### qMul

*function* · `packages/animation/src/clip.ts:62`

```ts
function qMul(a: Quat, b: Quat): Quat
```

### qNorm

*function* · `packages/animation/src/clip.ts:71`

```ts
function qNorm(q: Quat): Quat
```

### qRotate

*function* · `packages/animation/src/clip.ts:72`

```ts
function qRotate(q: Quat, v: Vec3): Vec3
```

### qSlerp

*function* · `packages/animation/src/clip.ts:90`

```ts
function qSlerp(a: Quat, b: Quat, t: number): Quat
```

### qToEuler

*function* · `packages/animation/src/clip.ts:104`

```ts
function qToEuler(q: Quat): Vec3
```

### restOf

*function* · `packages/animation/src/clip-babylon.ts:26`

```ts
function restOf(bones: Record<string, Node>): Rest
```

The rest pose of a skeleton as the editor wants it: local position and rotation of every bone, and the rest rotations in the skeleton's frame (every parent
multiplied in; the loader's mirror above the skeleton is not part of it). Read from the nodes as they are: call it before any clip has played, or with the
skeleton returned to rest.

### retargetGroup

*function* · `packages/animation/src/retarget.ts:31`

```ts
function retargetGroup(scene: BABYLON.Scene, source: BABYLON.AnimationGroup, targetRoot: BABYLON.TransformNode, opts: RetargetOptions = {}): RetargetResult
```

Copy an animation group from one skeleton onto another with different bone names, proportions and rest pose.
Targets are found by name below `targetRoot`. Rotations keep their change from the rest pose
(target = targetRest * inverse(sourceRest) * source); positions are scaled.

### samplePose

*function* · `packages/animation/src/clip.ts:147`

```ts
function samplePose(clip: ClipJson, t: number): Record<string, { q?: Quat; p?: Vec3; s?: Vec3 }>
```

A pose of the clip at a time: per bone the change from rest. Bones without keys are not in it.

### samplePosition

*function* · `packages/animation/src/clip.ts:130`

```ts
function samplePosition(keys: PosKey[], t: number): Vec3
```

### sampleRotation

*function* · `packages/animation/src/clip.ts:124`

```ts
function sampleRotation(keys: RotKey[], t: number): Quat
```

The rotation key track at a time (held before the first and after the last key).

### sampleScale

*function* · `packages/animation/src/clip.ts:138`

```ts
function sampleScale(keys: ScaleKey[], t: number): Vec3
```

### solveLookAt

*function* · `packages/animation/src/ik.ts:108`

```ts
function solveLookAt(bones: LookBone[], forward: Vec3, toward: Vec3, o: { maxAngle?: number; weight?: number } = {}): Quat[]
```

Turn a chain of bones (root-ward first, the head last) so the axis `forward` of the last bone (in its own frame) points along `toward`, within `maxAngle` degrees
of where it points now. Every bone takes its share of the turn; the last one takes what is left so the whole comes out exact. Parents' rotations are taken from
`parentQ` of the first bone and the bones above each other.

### solveTwoBone

*function* · `packages/animation/src/ik.ts:62`

```ts
function solveTwoBone(c: Chain2, target: Vec3, o: TwoBoneOptions = {}): TwoBoneResult
```

Solve a two-bone chain so its end is at `target` (law of cosines), bending toward `pole`. The bone lengths are kept.

### strideSpeed

*function* · `packages/animation/src/gait.ts:187`

```ts
function strideSpeed(feet: FootTrack[], duration: number): number
```

The ground speed of a gait from the stances of its feet (the median of the feet that stand: one slow foot does not set it).

### swing

*function* · `packages/animation/src/ik.ts:16`

```ts
function swing(a: Vec3, b: Vec3): Quat
```

The shortest rotation taking direction `a` to direction `b` (any lengths).

### swingTwist

*function* · `packages/animation/src/clip.ts:78`

```ts
function swingTwist(q: Quat, axis: Vec3): { swing: number; twist: number; twistQ: Quat }
```

Split a rotation into a turn about `axis` (twist, signed degrees) and the rest (swing, degrees): q = swing * twist.

### twistAxis

*function* · `packages/animation/src/clip.ts:89`

```ts
function twistAxis(rest: Rest, bone: string): Vec3
```

The axis a bone twists about, in its own frame: the line from its parent's joint to its own (its rest offset seen from itself).

### validateClipJson

*function* · `packages/animation/src/clip.ts:180`

```ts
function validateClipJson(clip: unknown): ClipIssue[]
```

The problems of a clip file (JSON path and message). Empty when it can be played.

### validateGraphDef

*function* · `packages/animation/src/graph.ts:177`

```ts
function validateGraphDef(def: unknown): { path: string; message: string }[]
```

Check a graph definition without any clips: the initial state exists, transitions join existing states, every condition names a
declared parameter of the right kind, motions have clips and sensible numbers. Returns the problems with their paths (relative to
the graph); an empty list means `new AnimGraph` will accept it as long as the clips exist.

## Interfaces

### AnalyseOptions

*interface* · `packages/animation/src/anatomy.ts:208`

```ts
interface AnalyseOptions
```

- `clips: Record<string, number>` — the clips by name, with their lengths in seconds
- `groups: Record<string, BABYLON.AnimationGroup>` — the groups to play
- `frame: Node` — the frame the body's measures are taken in

### Anatomy

*interface* · `packages/animation/src/anatomy.ts:58`

```ts
interface Anatomy
```

- `limbs: Limb[]`
- `pelvis: string` — the bone all the legs hang from together: the body is lowered by it
- `head?: { bones: { bone: string; share: number }[] }` — neck and head, rootward first
- `rest: Record<string, [number, number, number]>` — bone positions at rest, in the body's frame (before any turn of the model)
- `height: number` — overall height of the skeleton at rest and the height of the hip over the sole, metres
- `legHeight: number`

### AnimalPlan

*interface* · `packages/animation/src/anatomy.ts:173`

```ts
interface AnimalPlan
```

- `kind: 'walker' | 'swimmer' | 'glider' | 'flier' | 'crawler'` — what its body is: walks on legs, or swims, glides, flies, crawls without feet to measure
- `legs: LegMap`
- `pelvis: string`
- `head?: Anatomy['head']`
- `gaits: GaitSpec[]`
- `air: GaitSpec[]`
- `graph: GraphDef`
- `paces: { speed: number; weight?: number; minDistance?: number }[]` — the paces of a trip, m/s, as `Roam` chooses among them
- `turnFirst: number` — radians of heading error that stop it before it sets off, and how fast it turns, rad/s
- `turnRate: number`
- `sway: number` — degrees the body rocks as it walks
- `yaw: number` — the turn of the model about the vertical that puts the way it goes along +z, radians; apply it to the model's node
- `per: Record<string, number>` — ground speed of each gait's clip, m/s
- `size: { length: number; width: number; legHeight: number; sprawl: number }` — the body's length, width and leg height, metres, and how far its legs sprawl (track over leg height)
- `climb: boolean` — the body climbs with its path (it swims or flies)
- `notes: string[]`
- `feet: Record<string, ClipFeet>` — what the feet of each move clip did, when it has feet

### AnimatorParams

*interface* · `packages/animation/src/animator.ts:11`

```ts
interface AnimatorParams
```

- `graph: GraphDef`
- `groups: Record<string, BABYLON.AnimationGroup>` — one AnimationGroup per clip name used by the graph
- `notifies?: Record<string, Notify[]>` — notifies per clip, and clips that do not loop (default: all loop)
- `loops?: Record<string, boolean>`
- `fromMovement?: boolean` — Feed `speed`, `verticalSpeed`, `grounded`, `crouching` from the entity's motion source (a component with `motionState()`: CharacterMovement, NavAgent) and the `jump` trigger from `character:jump` (default true)
- `rootMotion?: RootMotionOptions & { apply?: 'node' | 'none' }` — Take the movement the clips author on a bone off the skeleton (see `RootMotionOptions`). Each frame it is reported as `Animator.rootDelta` and the `anim:rootmotion` event { entity, x, y, z, yaw } in the entity's own space. `apply: 'node'` also moves and turns the entity's node by it (for entities nothing else drives: a prop, a cutscene actor); the default `'none'` leaves that to the game, e.g. to feed a character controller.

### BindClipsOptions

*interface* · `packages/animation/src/character.ts:4`

```ts
interface BindClipsOptions
```

- `retarget?: RetargetOptions` — `retargetGroup` options (the bones are matched by name; `restRotation` re-bases the rotations when the two rest poses differ)
- `oneShot?: string[]` — clip names (the keys of `map`) that do not loop (default: all loop)

### BoneRest

*interface* · `packages/animation/src/clip.ts:44`

```ts
interface BoneRest
```

What the editor must know about one bone of the skeleton: its rest pose (local), and the rest rotations in the skeleton frame for mirroring.

- `p: Vec3`
- `q: Quat`
- `s?: Vec3` — the local rest scale (absent: 1, 1, 1)
- `wq?: Quat` — the bone's rest rotation in the skeleton's frame (all parents multiplied in); needed to mirror left to right
- `pwq?: Quat` — the same for its parent (identity at the root)
- `parent?: string` — the parent bone's name (absent at the top of the skeleton); needed to work in space (ik)

### BoundClips

*interface* · `packages/animation/src/character.ts:11`

```ts
interface BoundClips
```

- `groups: Record<string, BABYLON.AnimationGroup>` — one AnimationGroup per graph clip name, targeting this body's bones: what `Animator` takes as `groups`
- `loops: Record<string, boolean>`
- `missingClips: string[]` — graph clip names whose source clip does not exist, and the source bones without a bone on the body (per clip, once)
- `missingBones: string[]`

### BuiltClip

*interface* · `packages/animation/src/clip-babylon.ts:65`

```ts
interface BuiltClip
```

- `group: BABYLON.AnimationGroup`
- `info: ClipInfo`
- `missing: string[]`

### Chain2

*interface* · `packages/animation/src/ik.ts:29`

```ts
interface Chain2
```

A two-bone chain a -> b -> c: the local rotations and positions of the three bones, and the rotation of a's parent in the frame the target is given in.

- `pa: Quat` — world (frame) rotation of the parent of `a`, and the frame position of `a`
- `posA: Vec3`
- `qa: Quat`
- `pb: Vec3` — local position of b in a, and of c in b
- `pc: Vec3`
- `qb: Quat`
- `qc: Quat`

### Chain2Pose

*interface* · `packages/animation/src/ik.ts:38`

```ts
interface Chain2Pose
```

- `A: Vec3`
- `B: Vec3`
- `C: Vec3`
- `wa: Quat`
- `wb: Quat`
- `wc: Quat`

### ClipBone

*interface* · `packages/animation/src/clip.ts:21`

```ts
interface ClipBone
```

- `rotation?: RotKey[]`
- `position?: PosKey[]`
- `scale?: ScaleKey[]`

### ClipEditorOptions

*interface* · `packages/animation/src/clip.ts:252`

```ts
interface ClipEditorOptions
```

- `rest: Rest`
- `positionBones?: (bone: string) => boolean` — which bones may carry position keys (default: the root and the pelvis)
- `library?: (name: string) => ClipJson | undefined` — a clip of the library by name, for `base` (its keys are copied)
- `limits?: [RegExp, number][]` — largest change from rest, in degrees, per bone matcher; the first match counts (default: a table for a human)
- `twistLimits?: [RegExp, number][]` — bones whose turn about their own length is checked apart (degrees): for these `limits` holds the bend (the swing) and this the twist; the default: the hands, which turn with the forearm (from a T-pose, palm down, a forearm turns some 170 degrees, a wrist bends no more than 90)

### ClipFeet

*interface* · `packages/animation/src/legged.ts:26`

```ts
interface ClipFeet
```

- `speed: number` — ground speed at which the clip does not slide, m/s (0 for a clip whose feet never stand)
- `legs: Record<string, FootGait>` — per leg: when it touches down and leaves, how long it stands, the stride it makes
- `duration: number`

### ClipInfo

*interface* · `packages/animation/src/graph.ts:8`

```ts
interface ClipInfo
```

- `duration: number`
- `loop?: boolean`
- `notifies?: Notify[]`

### ClipIssue

*interface* · `packages/animation/src/clip.ts:58`

```ts
interface ClipIssue
```

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

### ClipJson

*interface* · `packages/animation/src/clip.ts:24`

```ts
interface ClipJson
```

- `format: 1`
- `name: string`
- `skeleton: string` — skeleton id of the library (`gw-68`, `viking-73`, `dragon-62`)
- `duration: number` — seconds
- `loop?: boolean`
- `fps?: number` — frame rate the clip is played and sampled at when it becomes an animation group (default 30)
- `base?: string` — the library clip this one was made from (its keys were copied in; informational)
- `additive?: boolean` — an additive clip (UE's additive animations): its keys are the change itself (rotation from identity, position from zero), to be put on top of another pose, not relative to rest
- `bones: Record<string, ClipBone>`
- `notifies?: ClipNotify[]`

### ClipNotify

*interface* · `packages/animation/src/clip.ts:22`

```ts
interface ClipNotify
```

- `name: string`
- `time: number`

### ClipRoles

*interface* · `packages/animation/src/anatomy.ts:17`

```ts
interface ClipRoles
```

- `idle: string[]`
- `graze: string[]`
- `moves: MoveClip[]`

### FootGait

*interface* · `packages/animation/src/gait.ts:147`

```ts
interface FootGait
```

- `speed: number` — the ground speed that makes the stance still (m/s); 0 when the foot never stands
- `touch: number` — cycle fraction at which the foot touches down and leaves the ground
- `lift: number`
- `duty: number` — fraction of the cycle the foot is on the ground
- `stride: number` — distance the foot travels back along the body while it stands, metres

### FootPlacementSpec

*interface* · `packages/animation/src/ik-babylon.ts:58`

```ts
interface FootPlacementSpec
```

- `feet: FootSpec[]`
- `pelvis?: string` — the bone that carries the body and is lowered when a foot finds the ground lower (default `pelvis`)
- `isGround?: (mesh: BABYLON.AbstractMesh) => boolean` — which meshes are ground (rays are cast at them)
- `groundAt?: (world: BABYLON.Vector3) => { y: number; normal?: BABYLON.Vector3 } | null` — or: the ground's height (and, if known, its normal) under a world point, from the game's own query (a nav mesh, a height field); no ray is cast then. Null: no ground there.
- `probeUp?: number` — how far above the foot the probe starts and how far below it ends, in metres (default 0.6 and 1.0)
- `probeDown?: number`
- `smooth?: number` — how quickly the offsets follow the ground, 1/s (default 14)
- `maxDrop?: number` — the largest the body is lowered, in metres (default 0.45)
- `tilt?: number` — tilt the foot to the ground normal, up to this many degrees (default 25; 0 leaves it)
- `weight?: Live<number>`

### FootSpec

*interface* · `packages/animation/src/ik-babylon.ts:52`

```ts
interface FootSpec
```

- `chain: [string, string, string]` — [thigh, calf, foot]
- `sole?: string` — the bone that stands on the ground when the chain's end is not the sole (a hoof's ball below the chain's last bone): the ground is probed under it, so it, not the chain's end, lands

### FootTrack

*interface* · `packages/animation/src/gait.ts:145`

```ts
interface FootTrack
```

one foot over one cycle: samples at equal steps of the cycle, `x` forward along the body, `y` up, metres, in the frame of the body (the ground's frame)

- `x: number[]`
- `y: number[]`

### GaitSpec

*interface* · `packages/animation/src/gait.ts:21`

```ts
interface GaitSpec
```

- `name: string`
- `clip: string`
- `per: number` — the ground speed, m/s, at which the clip as authored does not slide (`strideSpeed`, `measureGait`)
- `from: number` — the body speed from which this gait is used, m/s (the first gait is used from `startAt`)
- `legs?: { mask: string[]; phase: number }[]` — legs in other phases than the clip has them: bone names under each leg and the shift in cycles
- `minRate?: number` — the playback rate may be bent this far (defaults 0.5 and 2)
- `maxRate?: number`
- `hop?: HopSpec`

### GraphDef

*interface* · `packages/animation/src/graph.ts:79`

```ts
interface GraphDef
```

- `params?: Record<string, 'float' | 'bool' | 'trigger'>`
- `states: Record<string, StateDef>`
- `initial: string`
- `transitions?: TransitionDef[]`
- `seed?: number` — seed of the random players, so a run can be repeated (default: not seeded)

### GraphEvents

*interface* · `packages/animation/src/graph.ts:111`

```ts
interface GraphEvents
```

- `notify?(name: string, clip: string): void`
- `stateEnter?(state: string): void`
- `stateExit?(state: string): void`
- `montageEnd?(handle: Montage): void`

### Grip

*interface* · `packages/animation/src/hold.ts:19`

```ts
interface Grip
```

A grip of a weapon in the frame of the bone that holds it (the socket's bone): `point` is the middle of the grip, `axis` runs along it toward the blade.

- `point: Vec3`
- `axis: Vec3`
- `radius: number` — radius of the grip, metres
- `spacing?: number` — distance from the hand on the grip to the second hand, toward the pommel (metres; 0 or absent: one hand)
- `edge?: Vec3` — for a blade: the way its edge faces, across `axis` (a two-edged blade cuts along it either way)

