# fmdl/SPEC.md

Status: **draft for the owner's acceptance (stage M0 of `plans/PLAN-FMDL.md`)**, format 1. Field names and merge rules are proposals until accepted.
Words that decide behaviour: MUST, MUST NOT, MAY. Everything else is explanation.

A `.fmdl` is a `.ferret` package (see the `ferret-packages` skill) of kind `model`: a special case of `.ferret` with all its properties (zip or folder,
manifest, sha256 of every file, signature, encryption, catalogs, dependencies, cache). Nothing of `.ferret` is taken away or done differently. It holds
one model with everything a scene needs to use it: levels of quality and impostors, a description for people and for AI, motion programs, moving
parts, docks, physics and materials; it may extend one parent model and include other models as its parts. The format serves Ferret and its tools.

Machine-readable schemas (JSON Schema 2020-12) are in `schema/`; the example in `examples/chair/` validates against them.

## 1. Files

```
ferret.json                 manifest, kind "model" (section 2)
model.json                  the model (section 3)
description.json            the facts for people and AI (section 9)
description.md              the description in words: generated part + the author's text (section 9)
levels/<n>.glb              quality levels, glTF 2.0 binary, level 0 the richest (section 4); absent in an abstract model
nodes/*.glb                 node sources a child uses to edit the parent's geometry (section 4.3)
impostors/<name>.fpia       baked impostors (section 4.4)
clips/<set>.json            skeletal clips, the `ClipJson` of `@ferret/animation`
motions/<name>.fm           motion programs, the text form of `@ferret/motion` (section 7)
materials/                  maps of render materials (images), nothing else
placements/*.json           long lists of placements for includes (section 6.2)
previews/*.webp             pictures, 256 x 256 at least one
```

Paths are relative to the package root, use `/`, contain no `..`, and the names of files not listed above are free under their folder. Every file but
`ferret.json` is under the manifest's `files` hashes (a package that is not a project). A file nothing refers to is allowed and ignored.

Units: metres, kilograms, seconds, radians, SI everywhere. Axes: `up` is `+Y`; `forward` is declared in `model.json` (`+Z` default). Quaternions are
`[x, y, z, w]`. Colours are linear `[r, g, b]` in 0..1 unless a field says otherwise.

## 2. The manifest `ferret.json`

The `.ferret` manifest with `"kind": "model"`:

| Field | Rule |
|---|---|
| `format` | 1 (the package format) |
| `id` | the package id rule (`[a-z0-9][a-z0-9._-]*`); it IS the model's id, the name everything refers to |
| `name`, `version` | as in `.ferret`; `version` is semver; the model's version |
| `kind` | `"model"` |
| `dependencies` | MUST list the parent (`extends`) and every included model, id -> version range, and MAY list other packages the model refers to (`ferret://` maps) |
| `catalogs` | where the dependencies are looked up not yet open, as in `.ferret` |
| `files`, `signature`, `encryption` | as in `.ferret`; `ferret.json` is never encrypted |
| `entry`, `code`, `game`, `modules`, `provides.levels` ... | MUST NOT be present: a model holds no code and no levels |

File name: `<id>.fmdl`; a name ending in `.fmdl` MUST carry kind `model`, and a package of kind `model` is named `.fmdl` when packed to a file.

## 3. `model.json`

An object with these fields; unknown fields are refused except those starting with `x-` (the author's own, kept, never read by Ferret).

| Field | Type | Meaning |
|---|---|---|
| `fmdl` | 1 | the version of this specification the file follows; required |
| `id` | string | MUST equal the manifest `id` |
| `abstract` | boolean | no geometry: cannot be placed, only extended or included as a slot (section 8.2); default false |
| `extends` | `{ id, version }` | the parent: its package id and a version range; MUST also be in `dependencies` |
| `up`, `forward` | `"+Y"`; one of `+X -X +Z -Z` | the axes of the model; default `+Y`, `+Z` |
| `scale` | `{ drawn }` | scene metres per true metre; default 1. For models far from human size: the geometry is drawn at this scale and `physics` values stay true (section 5.5) |
| `levels` | array of level | the quality levels (section 4.1) |
| `levelEdits` | `{ "<index>": partial level or null }` | a child's change of the parent's levels by index (section 4.2) |
| `nodeEdits` | array of node edit | a child's change of the parent's geometry by node (section 4.3) |
| `impostors` | `{ name: impostor }` | baked far pictures (section 4.4) |
| `parts` | `{ name: part }` | the named things the model is made of (section 5.1) |
| `materials` | `{ name: material }` | render and physical materials in one entry (section 5.2) |
| `physics` | physics block | mass, collision, bodies, joints, module data (section 5.3) |
| `movingParts` | `{ name: moving part }` | hinges, sliders, rotors (section 5.4) |
| `docks` | `{ name: dock }` | places where something joins (section 6) |
| `includes` | `{ name: include }` | other models used as parts (section 6.2) |
| `clips` | `{ set: path }` | clip files, keyed by set name |
| `motions` | `{ name: motion }` | motion programs (section 7) |
| `requires` | `{ forms?, capabilities? }` | names the motions and the physics need: forms of the motion language, physics capabilities; a player that lacks one refuses the model before running it |
| `final` | array of JSON Pointer | values below these pointers in the resolved model that a child MUST NOT change (section 8.3) |
| `required` | array of JSON Pointer | values a concrete descendant MUST hold after resolution (section 8.3) |

Names (of parts, materials, moving parts, docks, includes, motions, impostors, clip sets) are keys of the objects above; they match
`[A-Za-z0-9][A-Za-z0-9._-]*` and are what a motion, a dock, a child and a description refer to.

## 4. Geometry

### 4.1 Quality levels

`levels` is an ordered list; index 0 is the full model. A level:

| Field | Meaning |
|---|---|
| `file` | path of the glTF 2.0 binary |
| `bytes`, `triangles`, `texCap`, `bones`, `drawCalls` | the cost, written by the packer (`texCap`: largest texture side) |
| `load` | `"cpu"`, `"gpu"` or `"both"`: which side of the frame the level mainly loads (the packer measures it) |
| `maxTier` | the finest device tier that may load this level: `desktop`, `mobile` or `low`; a device may load levels no finer than its tier's |
| `thresholds` | `{ px, tolerance, of }`: the size on screen in pixels below which the next level is within `tolerance` of this one; measured by the packer, never typed. `of` is the level key (section 4.5) of what it was measured from; `check` reports a threshold whose `of` is not the level's key now as stale |

Node names of the parts, moving parts, docks, collision and body parts MUST be the same in every level. The levels of a model that has includes are
those of the model alone: the includes are drawn on the level of the whole (the loader's rule, plan section 3).

### 4.2 A child's levels

A child gives `levels` (replaces the parent's list) or `levelEdits` (changes the parent's by index). A child giving both is refused.

`levelEdits` keys are indices of the parent's list. An entry for an index the list has is laid over that level, except that an entry with a `file`
brings its own costs: the old `bytes`, `triangles` and the rest are dropped, as they described another file. An entry for the next index after the last
adds a level and MUST have a `file`; an index further on is a gap and is refused. A `null` removes the level; removals are applied after the other
entries, so every index means the parent's level, and the later levels move up. A level removed takes with it the node edits made for it by the
earlier models of the chain: an edit that named only that level is dropped, the indices of the others move up. A child that gives `levels` replaces
the whole list, and the node edits of the earlier models, which were edits of levels now gone, are dropped.

### 4.3 Node edits

A child that keeps the parent's levels changes them by node. `nodeEdits` is a list applied in order, each to every level or to the levels in
`levels` (indices):

| `op` | Fields | Effect |
|---|---|---|
| `replace` | `node`, `from` | the node (and its children) is replaced by the node of the same name in `from` |
| `add` | `node`, `parent`, `from` | the node `node` of `from` is added under `parent` |
| `hide` | `node` | the node and its children are not drawn and not collided |
| `material` | `node`, `material` | the node's meshes take the material of that name |

`from` is a path to a glTF 2.0 binary, or an object `{ "<level index>": path }` when each level has its own file. A level whose file is missing for the
node edit is an error. Node edits are kept as a list in the resolved model, the earlier models' first; the loader applies them to each level when it
loads it. Names are tracked through the edits: `replace` swaps the node's descendants for the source's, `add` adds the node and its descendants,
`hide` removes the node and its descendants from the names a part, a moving part, a dock or a collision shape may refer to; a node is the named node and
the named nodes below it, an unnamed node in between does not break the line.

### 4.4 Impostors

`impostors` is `{ name: impostor }` with the entry of `ImpostorEntry` in `@ferret/assets`: `file` (`.fpia`), `bytes`, `tier`, `modelHash`, `views`,
`cell`, `mode`, `radius`, `bakeVersion`, `look`, and optional `hide`, `replace`, `anim`, `flat`, `thresholds`. `modelHash` is the resolved hash
(section 8.5) of the model it was baked from: a different hash means the impostor is stale. The one named `default` is the static far picture;
others are per pose or manoeuvre and are chosen by the loader or named by a program.

### 4.5 Choosing a level

A device of tier T may load the levels from the first one whose `maxTier` is T or coarser (a level with no `maxTier` counts as `desktop`); the levels below
that stay, they are what it draws far away (`levelsForTier`). The loader's ladder for a placed model is: those levels, richest first, each used from the size
at which the next takes over (`thresholds.px` of the level before it); then the impostor, taking over at `thresholds.px` of the last level (when
the last level has none, at the impostor's own `thresholds.impostor`); then the point and nothing at the impostor's `thresholds.point` and `thresholds.none`. A rung
that would take over at a size not below the one before it is left out. The thresholds are in screen pixels and a regulator moves only those between drawn
models, never the one to a point.

The **level key** of level i is the sha256 of: the text `level i`, the sha256 of the file of level i and of level i + 1, of every file a node edit brings,
and the resolved hashes of the included instances in order. It is what `thresholds.of` records: the same files and includes give the same key, so a changed
level, a changed edit source or a changed included model makes the thresholds of the levels it touches stale, and `check` says so.

## 5. What the model is made of

### 5.1 Parts

`parts[name] = { node, role?, description?, material?, optional? }`: `node` is a node name of the glTF; `role` a short word for what it is
(`aileron`, `piston`, `hand`); `description` one line for AI; `material` the name in `materials`. An abstract model's parts name the roles
(`aileron-l`) without a node; a child binds them by giving the node.

### 5.2 Materials

`materials[name] = { gltf?, render?, physical }`:

- `gltf`: the name of the material in the glTF this entry belongs to (default: the entry's own name);
- `render`: a `MaterialDef` of `@ferret/assets` laid over the glTF's (colours, maps as package paths, `alpha`, `uv`, `variants` for liveries and wear);
- `physical`: a `PhysicsMaterial` of `@ferret/physics` (numbers only: `density`, `friction`, `restitution`, `youngModulus`, `yieldStrength` ...), or the
  name of a material of the physics tables the game loaded.

Render and physical sides are in one entry so they cannot disagree. A concrete model MUST have `physical` for every material that a collision shape or
a part with mass uses.

### 5.3 Physics

```
physics: {
  mass: number | "computed",            // kg
  charge?: number | "computed",         // C
  bindingEnergy?: number,               // J: what holds the whole together; its mass is the sum less this over c^2
  centerOfMass?: [x,y,z],               // m, in the model
  inertia?: [Ixx, Iyy, Izz],            // kg m2, principal, about the centre of mass
  computed?: { hash, mass, charge?, centerOfMass, inertia, counted },   // written by the packer when "computed"
  collision: { name: { part?|node?, shape: box|sphere|cylinder|capsule|hull|mesh, size?, center?, material } },
  bodies?: { name: { parts: [part names], kind: static|dynamic|kinematic } },
  joints?: { name: { between: [body, body], kind: fixed|hinge|ball|slider, anchor, axis?, limits?, breakForce?, breakTorque? } },
  modules?: { "<module name>": { ... } },  // data a physics module reads: vessel, wing, engine ... named as the module is
  propulsors?: { name: { kind: ducted-fan|rotor|propeller|nozzle|exhaust, node?, position, axis, diameter?|exitArea?, medium?: air|water, actuator?, hoverShare?, temperature?, wash?: false|number } }
}
```

`mass: "computed"` and `charge: "computed"` mean the packer works them out and writes them into `computed` (`ferret fmdl pack`); the resolver reads
`computed`, never recomputes, and `ferret fmdl check` reports it missing or stale (`computed.hash` names what it was computed from: the level-0 file, the
densities, `scale`, the binding energy and every instance's totals and place). The sum:

- **parts**: for each part whose material has `physical: { density }` (an object of numbers; a name of the game's physics tables is not known to the packer
  and counts nothing), volume x density, the volume of the closed meshes under the part's node in level 0 after the node transforms, in true metres
  (lengths of the drawing divided by `scale.drawn`). A mesh belongs to the nearest part above it, so a part nested in another is counted once. A part
  with no density (a ring drawn for the eye) adds nothing; `computed.counted` lists the parts that were counted;
- **includes**: every instance's totals (its stated numbers, or its own `computed`; an included model that asks for `computed` and has none is refused,
  naming it), placed where it sits. Its centre of mass is moved by the placement, its inertia turned by it (a stated mass without `inertia` is a point
  mass about its centre of mass);
- **binding**: `bindingEnergy / c^2` is taken off the mass (helium-4: the masses of two protons, two neutrons and two electrons less 28.3 MeV, 0.75 %);
- **charge**: the sum of the instances' charges (the parts have none);
- **centre of mass and inertia**: of the sum, the inertia as the diagonal (Ixx, Iyy, Izz) about the centre of mass in the model's axes: principal when the model
  is symmetric about them.

A stated `mass` is the whole's, includes and binding in it; `charge: "computed"` alone leaves the mass as stated.

**The frame.** Positions, docks, nodes and placements of physics are in the frame the model is drawn in: the glTF's own frame mirrored in X (the loader
puts the glTF under Babylon's root that turns it to its left-handed frame); the placement rule is the drawing's (6.2). `physicsPlan` (`@ferret/assets`) gives
the bodies and joints of a whole with the includes counted: the whole's own bodies (`bodies`, else one body of everything); an include fused `"rigid"` merged
into the body that holds it (its shapes and mass); one fused `"body"` (the default) a body of its own, joined to the including body by a `fixed` joint at
its place. Each body holds the mass of what is in it and the masses of all add up to the whole's; a stated mass is shared by the bodies in proportion to
the mass of their parts (refused when none has a density). Shapes carry the matrix of their instance in the whole, in drawing units.

**Propulsors** (`physics.propulsors`, optional; `@ferret/physics-response`, PLAN-PHYSICS-RESPONSE 5.1). A propulsor is a fan, a rotor, a propeller, a nozzle or an exhaust that
throws a medium. `node` is the node it rides on (a gimbal turns the jet with it; the model's root when missing), `position` and `axis` are in the drawn frame and the
jet runs along `axis`; `diameter` (the disc or the exit) or `exitArea` sizes it; `medium` is `air` (default) or `water`; `actuator` names the physics actuator whose
force is the thrust; `hoverShare` is its share of the weight in hover (the fallback when the model's physics is not running, default 1 over the number of
propulsors); `temperature` is the excess at the exit, K; `wash: false` switches the wash of this one off, a number scales it. A model without the section
makes no wash. Materials may carry `response`: `false`, or `{ class, ...parameters }` with the class one of `rigid`, `elastic`, `membrane`, `granular`, `flake`,
`liquid-surface`, `bed`, `stone`, `floating`, `heat`; absent, the class and its parameters are derived from the material's physical side.

A body not listed in `bodies` is one body of the whole model. Collision `shape` values follow `ModelCollision`
and the shapes of `@ferret/physics-bodies`. The data under `modules` is defined by the module that reads it and listed in its skill; this
specification only fixes where it lives.

### 5.4 Moving parts

`movingParts[name] = { node, kind, axis, pivot?, limits?, rest?, unit?, link?, description? }`: `kind` is `hinge` (turns about `axis` through `pivot`,
radians), `slider` (moves along `axis`, metres) or `rotor` (turns without limits). `limits` is `[min, max]`; `rest` the value in the glTF as modelled.
`link = { to, ratio, offset? }` ties it to another moving part: its value is `ratio` times the other's plus `offset`. Programs set the value by the
part's name (section 7).

**Frame and values.** `axis` and `pivot` are in the drawn frame of the model the part belongs to (the frame of docks and bodies, 5.3), not in its parent's: a
parent turned at rest (a `Base` rotated a quarter turn) does not change them. A hinge or rotor turns its node about `axis` through `pivot`; a slider
moves it along `axis`. The value is the change from `rest` (the pose in the glTF is the value `rest`, default 0): the node is the rest pose moved by that
change, so the part's children, a skinned mesh bound to it and its included instances go with it. A positive angle turns by Babylon's rule in that frame.
`limits` hold the value; a linked part cannot be set, only its master. A moving part of an included instance is `<instance>/<part>`, and the instance's own
`movingParts` act in the instance's frame. Nothing here is read by physics: a moving part moves what is drawn, the bodies and joints are `physics` (5.3).

### 5.5 Scale

Geometry is in the glTF's own units at the drawing scale; `scale.drawn` says how many scene metres one true metre of the object is drawn as (an atom of
10^-10 m drawn 3 m wide has `drawn` = 3e10). Everything in `physics` and `description.json.size` is true SI. A physics capability that works in scene
units multiplies by `scale.drawn`; one with its own units (atomic) reads the true values.

## 6. Docks and includes

### 6.1 Docks

`docks[name] = { node, frame?, description }`. `node` is the node or bone the dock sits on, `frame = { position, rotation }` the place on it (default: the
node's origin). `description` is required: words for an AI and a person: what is docked here, how it is approached and held, what has to be done
first, what must not be docked together, what happens at the limits. There are no dock types, fit tables or refusals in the format: an agent reads the
descriptions of both docks and decides, and asks the engine for the joint (`fmdl.dock`). The descriptions are inherited and overridden like any field.

### 6.2 Includes

`includes[name] = { id, version, at, fuse?, overrides?, optional?, levels? }`:

- `id`, `version`: the included model's package id and a version range (also in `dependencies`);
- `at`: where it is placed: a placement, a list of placements, or `{ "file": "placements/x.json" }` (a JSON list of placements; for many);
  a placement is `{ name?, dock? , to? | node?, position?, rotation?, scale?, overrides? }`; with `dock` (a dock of the including model) the
  included model is put so that its own dock `to` (default: the one named like `dock`) coincides with it (`{ dock: "engine-mount", to: "mount" }`);
  with `node` the placement is a frame (`position`, `rotation`, `scale`) on that node; `name` names the instance, default `<include>#<index>`;
- `fuse`: `"body"` (the default: the included model is a body of its own, joined by the dock) or `"rigid"` (merged into the including body);
- `overrides`: an overlay laid over the included model's resolved model by the merge rules of section 8 (a livery, a material, a hidden part,
  a motion's argument), and respecting its `final`; a placement may carry its own overlay over this one;
- `optional`: the model loads without it when it is missing;
- `levels`: the levels of the whole on which the include is drawn as models of their own (default: all). A coarse level of a whole made of hundreds of
  parts (an atom with 235 nucleons) holds them in its own glTF, merged, and lists only the fine levels here: drawing a coarser level then costs less
  in instances, not only in triangles. The include is still resolved, in the hash, in physics and for addresses; only its drawing on the other levels is left to the level.

The included model's parts, docks, moving parts and motions are addressed as `<instance>/<name>`. It brings its mass and collision into the whole. An include whose
`id` is an abstract model is a **slot**: a child of the including model fills it by overriding `includes.<name>.id` with a concrete descendant
of that abstract model; a concrete model MUST NOT have an abstract include left.

### 6.3 Docks at run time

`ModelDocks` (`@ferret/levels`, `fmdl-docks.ts`) works on the actors of a `ModelStage`. A dock is named `actor#dock` (`o#bond-1`); the dock may be left out when the actor has exactly one free dock.

| What | Command | Form |
|---|---|---|
| the docks of an actor and of the models included in it: description, place and rotation in the world, who holds it | `fmdl.docks {actor}` | |
| dock two docks, the second actor is put so its dock frame meets the first's | `fmdl.dock {a, b, joint?, place?}` | `(dock a b)` |
| take a pair apart, or all an actor or a dock holds | `fmdl.undock {a, b?}` | `(undock a)` |
| the pairs now; save and restore | `fmdl.docked`, `fmdl.docks.save`, `fmdl.docks.restore {fmdlDocks}` | |

The joint is the agent's choice (`joint: {kind, axis?, limits?, breakForce?}`), the model does not name one. `fixed` is the default; `hinge` and `ball` are made by the physics kernel (Havok or Chaos; both bodies must be physics bodies, the second body is moved to the dock and the constraint anchored there; a `breakForce` makes it snap, the pair is then undocked with `reason: "broken"`); between actors that are only drawn a `fixed` dock welds them by parenting, and undocking keeps each where it is. `bond` is made by a capability's backend: for atoms `atomicDocks(cap)` puts the atoms in the molecule's shape (water 104.45 degrees, H2 74 pm, scaled by the drawing scale) and keeps the energy ledger. With no joint given, a pair a backend handles is bonded. A dock holds one other dock; a taken dock, an unknown dock, two docks of one actor, a joint that needs bodies the actors do not have and a `bond` no capability handles are refused with a message that says why. Events: `fmdl:dock {a, b, joint}`, `fmdl:undock {a, b, reason}`. Save is plain JSON `{fmdlDocks: [{a, b, joint}]}`; restore makes it true (pairs not in it are undocked, missing ones docked in place, nothing moves). The `(dock a b)` form is a word of `@ferret/levels` (`installDockForms`), not of the atomic forms; it returns the dock of `b` it used.

## 7. Motions

`motions[name] = { file, description, params?, requires?, duration? }`; `file` is `motions/<name>.fm`, a program of `@ferret/motion` in its text form;
`params` is `{ name: { type: number|boolean|string|vector, default?, unit?, description } }`; `requires.forms` lists the motion forms it uses (added
to the model's `requires`). A scene runs `motion.run { target, motion: "<model id>/<name>", args }`.

A program refers to the model's own names (parts, moving parts, docks, includes, clips, morph states, impostors) by the target it runs on; the forms
that do it (`part-to`, playing a clip, calling `<instance>/<motion>`, `dock`, `undock`, making a model appear, letting includes go) are added to the
language in stages M6 to M8 and are documented in its reference; this specification fixes only where the programs live and how they are named.

**The forms of stage M6** (`@ferret/levels`, `fmdl-motion.ts`; installed by `installModelForms(bridge, stage)`). The actor is `:on name`, else the program's
`target`; the stage's clock is the fixed step's, so a snapshot continues a move.

| Form | What it does |
|---|---|
| `(part-to part value seconds [:curve ease])` | lasts until the part has arrived (by an ease of the language); another move of the part replaces it; the value is held by the limits |
| `(part-set part value)`, `(part-value part)`, `(part-limits part)`, `(parts)` | jump, read, the stops, the names (`<instance>/<part>` for included ones) |
| `(play-clip clip [:loop #t] [:rate r] [:blend s] [:mask (list bone ...)])` | a clip of the model on its own skeleton as a montage; a one-shot lasts until it ends, a loop goes on until `(stop-clip clip)`; a mask moves only those bones and what is below them |
| `(graph-set param value)`, `(graph-trigger name)`, `(clips)` | the animation graph of the actor |
| `(appear model [:name n] [:at (vec x y z)] [:level k] [:scale s] [:on parent])` | a model of the stage appears, named (default `<id>#<n>`); the value is the name |
| `(vanish actor)` | takes it away with everything in it |
| `(let-go [instance])` | the included instances become actors of their own where they are, named `<actor>/<instance>`, no longer moved by the whole; returns the names |

**Running a model's motions** (stage M7, `fmdl-programs.ts`). `ModelPrograms` finds a motion on the *resolved* model of the actor it runs on, so motions are inherited by
name, a child's entry merges over its parent's by the rules of 8.3 (a child that gives a new `file` replaces the program, one that gives a parameter replaces only that
parameter) and the one program of an abstract model runs in every model that extends it, talking about the actor's own parts, clips and atoms through `target`.

- `motion.run { target, motion, args }`: `motion` is `<model>/<name>` (the model is one of the actor's chain: the model itself or a parent) or just `<name>`, or
  `<instance>/<name>` for a motion of an included model, which then runs on that instance (the actor `<actor>/<instance>`). The same as `programs.run(target, ref, args)`.
- The program's parameters are the declared `params` with their defaults, and `target`: the name of the actor. An argument that is not declared, or of the wrong
  type (`number`, `boolean`, `string`, `vector` = three numbers), is refused before anything runs; so is a parameter with no value and no default.
- Running a motion needs the forms in *its* `requires.forms`; a player that lacks one refuses it, naming the forms, before starting. The model's own
  `requires.forms` (the union of its motions') is what `checkModel` tests before the model is placed.
- `(run-motion "name" [:on actor] :param value ...)` from a program runs a motion of the actor, or `"<instance>/<name>"` of an included one, and lasts until it ends.
- The motion files are read once through the model's reader (`preload`, which a game awaits when it places the model; the command and the form need the files read).
- The atom forms of `@ferret/physics-atomic` (`excite`, `fire-photon`, `fire-neutron`, `wait-emission`) are the ones the experiment programs of the abstract `atom` use.

`ModelStage.letGo` keeps each instance's world matrix, so a nucleon let go from a nucleus (M7) leaves where it was. `ModelStage` emits `fmdl:appear`,
`fmdl:vanish` and `fmdl:let-go` when it is given an `emit`. `dock` and `undock` are M8.
Motions are inherited by name; a child's file replaces the parent's of the same name.

## 8. Inheritance and resolution

### 8.1 The chain

A model has at most one parent. The **chain** is the models from the root ancestor to the model. A reader MUST refuse a cycle, a parent that is
not in `dependencies`, a parent version that matches no available package, and a parent of another `fmdl` version it does not read.

### 8.2 Abstract and concrete

An abstract model (`abstract: true`) holds no geometry (`levels` empty or absent, no `nodeEdits`), cannot be placed in a scene, and is a package
like any other: it holds parts by role, motions, docks, moving parts, physics defaults, materials, description. A model that is not abstract is concrete: after resolution it MUST have
at least one level, `physics` with `mass` and collision, `materials` complete (section 5.2), every part with a node that exists in every level, and
every `required` pointer satisfied.

### 8.3 Merge rules

The resolved model is the root's `model.json`, then each descendant's laid over it in chain order, by these rules, applied recursively:

1. **Objects** merge key by key.
2. **Everything else** (numbers, strings, booleans, arrays) in the child replaces the parent's value.
3. **Named collections** (`parts`, `materials`, `movingParts`, `docks`, `includes`, `motions`, `impostors`, `clips`, `physics.collision`,
   `physics.bodies`, `physics.joints`, `physics.modules`) are objects keyed by name and merge by name by rule 1: a new name adds, a known name
   merges with the parent's entry, and `null` removes the name.
4. `null` for any other key removes it from the resolved model.
5. `levels`, `levelEdits` and `nodeEdits` follow sections 4.2 and 4.3, not rules 1 to 4.
6. `final` and `required` lists of descendants are added to the parent's; an entry cannot be removed.
7. `extends`, `abstract`, `id` are the model's own and are not inherited: the resolved `abstract` is the model's, the resolved `id` its own.
8. `physics.computed` is the packer's account of one model and is not inherited: the resolved model has it only when its own model gave it.
9. A model with a parent states its collections' entries **in part**: a dock with a new node and no description, a motion with a new file and no
   description, a collision shape with only a new size, an include with only a new place. What an entry must have (SPEC sections 5 to 7) is checked
   on the resolved model, where the parent's fields have filled in. A model with no parent states every entry whole. In a model with a parent a
   `null` is a removal wherever it stands, and is not checked as a value.

`final`: a descendant MUST NOT change, add or remove any value at or below a `final` pointer; the resolver refuses it and names the pointer. The
pointers are into the resolved model, and a model's own `final` list binds its descendants, not itself.
`required`: after resolution a concrete model MUST hold a value (not `null`, not absent) at every `required` pointer.

### 8.4 Resolving includes

After the chain is merged, each include is resolved recursively as a model of its own (its chain, merge and includes) and attached under
`includes.<name>` of the resolved model as `{ id, version, fuse, optional?, missing?, instances }`. `instances` has one entry for each placement, in the
order of the list (or of the file): `{ name, placement, resolved }`, with `resolved` the resolved model of section 8.7. The instance is named by the
placement's `name`; without one it is `<include>` for a single placement and `<include>.<index>` for a list or a file. Names of instances are
addresses (`<instance>/<part>`), so they are unique across the model.

The include's `overrides` and then the placement's `overrides` are laid over the included model's chain, after its own merge, by the rules of
section 8.3 and its `final` list; the files they name are those of the including package. A model resolved for the same package, version and overlays
is resolved once and shared by every placement (235 nucleons are one resolved nucleon).

Refused: a cycle of includes (the message gives the way: `a > b > a`); a missing package, unless the include is `optional` (then it is
`missing: true` with no instances); a version that does not fit; an overlay that sets `id`, `extends`, `abstract` or `fmdl`; a placement at a dock the
including model has not, or one whose `to` is not a dock of the included model; a placement at a node that is not in the including model's levels;
a file of placements that is missing, is not JSON, or holds a wrong placement; an included model whose own resolution has issues (they are reported
with the way to them: `/resolved/includes/<include>/<instance>/...`); and, for a model that can be placed, an include left abstract. An abstract model
may keep its slots open. A change of an included package reaches every model that includes it at its next resolution, within the version range.

### 8.5 The resolved hash

`resolvedHash` is the sha256 (hex) of the canonical form of the resolved model, a line feed, and the sha256 of every file the geometry comes from,
one per line: the level files in order, then the sources of the node edits, each file once. Canonical form: JSON with object keys sorted, no
whitespace, numbers as JSON writes them. The resolved model in the hash has no `impostors` (they are made from it) and its levels have no `thresholds` and no `load` (the packer measures them: measuring does not make another model), carries the paths qualified
(section 8.7), and is the model alone: the chain's versions, the lineage and the description are not in it, so the same content and geometry
give the same hash whatever packages it comes from. `physics.computed` is not in it either (it follows from what is). The `resolvedHash` of every instance (with its address) and the placements file are part of the hash: a moved electron or a changed proton makes another whole. The impostors' `modelHash` is this
value; the packer writes it into the impostor entries and `check` compares: an impostor inherited from a parent whose geometry the child changed is
stale and is reported.

### 8.6 The lineage

The resolved model carries `lineage`: the ids of the chain from the root (`["aircraft", "biplane", "swordfish"]`). It is written into the description.

### 8.7 The resolved model as a document

`ferret fmdl resolve` and the resolver give one object: `fmdl`, `id`, `abstract`, `lineage`, `chain` (`{ id, version }` of every package the chain was read
from, the root first), `resolvedHash`, `model` (the merged `model.json`, with no `extends` or `levelEdits`, and the `nodeEdits` of the whole chain), and
`description` (the merged `description.json` with `lineage`), and `includes` (section 8.4; absent when the model includes nothing). The files of a chain live in different packages, so the paths inside `model` are
**qualified**: `fmdl://<package id>/<path>`; the path of a material's map that is already a `ferret://` reference stays as it is. The resolved model is
checked as a model of its own: its schema, the references of section 8.2, the node names in every level after the node edits, `required`, the
impostors' hashes, and a summary and a kind for a model that can be placed.

## 9. The description

`description.json` is the source and `description.md` is written from it by the packer, plus a free part that only the author writes (the part of
`description.md` after the marker line `<!-- author -->`; the packer keeps it). Both inherit: a child's `description.json` merges over the parent's by
the rules of section 8.3 (`text` and `summary` replace; `tags` replace), and the markdown shows the lineage's texts from the root down, then the model's own.

`description.json` fields (every one optional except `summary` and `kind` in a concrete model):

| Field | Meaning |
|---|---|
| `summary` | one line |
| `kind`, `category`, `tags` | what it is (person, animal, aircraft, ship, vehicle, machine, building, furniture, prop, plant, particle, atom, molecule ...), free words; the packer writes none of them |
| `purpose` | what it is for, how it is used, by whom; tied to the docks and motions that do it |
| `size` | true size in metres: `height`, `length`, `width`, `span`; `drawScale` (= `scale.drawn`) when not 1; `mass` (kg) |
| `period`, `place` | where and when it applies |
| `parts` | the model's parts and what each one is, by name (written from `parts`; the author adds lines) |
| `includes` | the included models: instance names, ids, what each does |
| `motions` | by name: one line and the parameters (written from `motions`) |
| `docks` | by name: the dock's description (the same text as in `model.json`) |
| `materials` | what it is made of, in words and by part |
| `physics` | in short: mass, whether it floats, how it breaks (written from `physics`) |
| `levels` | by index: triangles, bytes, the device tier |
| `lineage` | the ancestors (written by the resolver) |
| `source` | author, licence, where it came from, as `source` of the library item |
| `text` | free text of the author |

The text fields are for reading: no program is allowed to depend on their wording; the structured fields they restate are in `model.json`.

### 9.1 Written by the packer, read by an agent

`ferret fmdl pack` writes the structured fields of `description.json` from `model.json` (`generateDescription` in `@ferret/assets`): `parts` (the part's own `description` or `role`, else the node), `includes` (id, version, number placed), `motions` (the summary and every parameter as text: what it is, unit, type, default or "required"), `docks` (exactly the text of the dock), `materials`, `physics` (mass, charge, binding energy, how many shapes, bodies, joints, modules), `size.mass` and `size.drawScale`, `levels` (triangles, bytes, tier). The author's words win for `parts`, `includes`, `materials`, `physics` and `size`; `docks` and `motions` always follow the model, because `check` compares them. A file that is already as it should be is not written again. `description.md` is written from the **resolved** model (`renderDescriptionMd`): the title and summary, kind and tags, the lineage, the texts of every ancestor root first and then the model's own, the use, the size, the parts, includes, docks and motions with their parameters, the materials, the physics, the levels, and after the line `<!-- author -->` the author's free part, which the packer keeps. `ferret fmdl describe <model> [--json]` prints the markdown or `describeResolved` (the whole description as data: the inherited motions and docks, the includes counted, the computed mass).

What an agent calls (`ModelCatalogue` and `registerCatalogueCommands` in `@ferret/levels`, `fmdl-catalogue.ts`):

| Command | Gives |
|---|---|
| `fmdl.models {text?, kind?, tag?, abstract?}` | the models whose id, summary, kind, tags and descriptions match the words of a sentence, best first; abstract models only with `abstract: true` |
| `fmdl.describe {model}` or `{actor}` | id, lineage, the description as data, the markdown |
| `fmdl.appear {model, name?, at?}` | puts the model on the stage; the files of its motions are read before the command answers, so a motion can run at once |
| `fmdl.vanish {actor}`, `fmdl.actors` | takes an actor away; the actors with their models and places |

A model that stands for an atom says so in `physics.modules.atom` (`{"nuclide": "H-1"}`, or `{"Z", "A", "electrons"}`): `bindAtomModels` (`@ferret/physics-atomic`) makes the capability's atom when the actor appears, at its place and under its name, and removes it when the actor vanishes. A child replaces the entry (`{"nuclide": "H-2"}`), so an isotope is a child. With the docks of 6.3 and the motions of 7, an agent that has only these commands and the descriptions can build a molecule, excite an atom and split a nucleus.

## 10. What `check` verifies

A package of kind `model` is valid when: the manifest is valid for kind `model` (section 2); `model.json` and `description.json` match their schemas; every file named
exists and every file is hashed; ids and names follow the rules; the node names of parts, moving parts, docks, collision and bodies exist in every level
(for a concrete model, after resolution); the chain, includes and `final`/`required` rules of section 8 hold; materials and physics are complete for a
concrete model; a motion's `requires.forms` are listed in `requires`; every impostor's `modelHash` equals the resolved hash; thresholds and level costs are
present and agree with the files; `description.json` agrees with the structured fields it restates; the signature, when present, holds.

## 11. The example

`examples/seat/` is an abstract seat (parts by role, a `seat` dock described in words, `required` values) and `examples/chair/` a concrete oak chair
that extends it: size, weight, materials (oak frame, leather seat), a `seat` dock placed on the node, a `push-back` motion and two quality levels. The values
are for illustration. The glTF and motion files they name are not in the examples: they show the structure and are what the schemas are tested against.

## 12. The command line

`ferret fmdl` needs no release folder; it works on files.

| Command | What it does |
|---|---|
| `ferret fmdl check <model.fmdl\|dir> [--path <dir>]...` | runs the checks of section 10 (a folder before packing has no hashes; a file also checks the hashes and the signature); a model with a parent is also resolved and the result checked; exit 1 and one line per problem, or `ok` |
| `ferret fmdl info <model.fmdl\|dir>` | the model in a few lines: levels with their costs, parts, docks, includes, motions, materials, mass, dependencies |
| `ferret fmdl resolve <model.fmdl\|dir> [--path <dir>]...` | prints the resolved model of section 8.7; the problems go to the error output and the exit code is 1 |
| `ferret fmdl pack <dir> <model.fmdl> [--key <file>] [--password <pw>]` | writes what the packer measures into `model.json` (`bytes`, `triangles`, `drawCalls`, `bones` of every level, from its glTF), refuses a folder that does not check, then packs, signing with the key and encrypting with the password when given |
| `ferret fmdl describe <model.fmdl\|dir> [--json]` | what an agent reads: the markdown of section 9.1, or the whole description as data |
| `ferret fmdl import <level.glb>... --id <id> --summary <text> --kind <word> --mass <kg> --material <name>=<physical>... --out <dir>` | a glTF as a model folder (section 13) |
| `ferret fmdl unpack <model.fmdl> <dir>` | the files of the package as a folder |

The parents of a model are looked for in every folder given with `--path` and in the folder the model is in: `.fmdl` files and folders with a model
in them, by id; the highest version that fits the range is taken. In a running world a parent is found through the packages that are open
(`PackageSet`) or through the catalogs a package names. An encrypted package is opened with `--password <pw>`. What the packer measures later (thresholds, the load of each level, the computed mass, the
resolved hash) is written by the stages that define it (plan M2, M4, M5).

## 13. Import paths

Every path that makes models in Ferret ends in `modelFilesFromGlb` (`@ferret/assets`, `model-import.ts`): a glTF per quality level plus what the path knows goes in, a model folder comes out (`ferret.json`, `model.json`, `description.json`, `levels/N.glb`, and any files the path adds), ready for `ferret fmdl pack`. The costs of the levels are measured and the description is generated from the measured model (section 9.1). **Nothing is invented**: the mass in kg, the physical material of every glTF material (a table name's numbers, or numbers) and the summary and kind are given by the path, and a call without them throws naming what is missing.

What the importer makes by itself: one part for every node that carries a mesh **in every level** (a node a lower level has merged away is no part; no such node is an error), one material per named glTF material with `gltf` and the physical side, one collision box of the first level's bounds (half sizes and centre) unless the path gives its own shapes, `levels` with `maxTier` where the path gives tiers. Anything else of the model (`physics.modules`, `requires`, docks, motions, `forward`, `scale`) is passed in and merged over it by key. A collision `cylinder` has `size: [radius, half height]`.

| Path | Where | What it gives the importer |
|---|---|---|
| a glTF file | `ferret fmdl import <level.glb>... --id --summary --kind --mass --material <glTF name>=<physical> --out <dir>` (`gltfModelFiles`) | everything is on the command line: the levels are the files given, the best first, one device tier each (desktop, mobile, low) |
| the asset library, so the Unreal export too (`type: model` items) | `libraryModelFiles` (`@ferret/fmdl-import`) | the tiers become the levels, the materials' alpha and sidedness the render side, the item's box or cylinder the collision, its tags and source the description; the mass and the physical materials are the caller's |
| terrain rocks | `rockModelFiles` | the mesh of `makeRock` scaled to the size; the mass is the exact volume of the closed mesh times the density of its material; the collision is the hull |
| terrain plants | `plantModelFiles` | the mesh of a plant shape scaled to the height, vertex colours kept, masked and double sided; a static body, the collision a cylinder of the trunk's radius measured at the foot of the mesh over the whole height; the mass is the caller's |
| humans | `figureModelFiles` | `exportGlb` of the figure at each tier asked for, the body's density (1010 kg/m3) for every material, the spec rides in the package as `spec.json`; the mass is the caller's |
| destruction cars | `carModelFiles` | the glb of a car; `buildCar` makes the parts, links, crush zones, glass panes and wheels from the node names and bounds, and they are kept as data in `physics.modules.destruction` with `requires.capabilities: ["destruction"]`; the mass is in the table for the two library cars, else the caller's |

`glbNodes` (world bounds of every named node, whether it carries a mesh, its material, its triangles), `glbBounds`, `glbOfMeshes` (a glb from raw mesh arrays: positions, normals, vertex colours, uvs, indices; the generators have no file) and `meshVolume` are in the same module.

## 14. Editing

`FmdlSession` (`@ferret/editor`, `fmdl.ts`) is a model folder in memory. Every change is made on a copy and **checked before it is kept**: the folder as `ferret fmdl check` sees it, and, for a model with a parent or includes, the chain and the included models resolved together. A change that makes the model wrong throws `FmdlEditError` naming the issues and the draft stays as it was. Undo and redo keep the files before and after each change. The packer is the command line's: `prepareModelFolder` / `packModelFolder` (`@ferret/assets`, `model-pack.ts`) measure the levels, compute mass and charge, write `description.json` and `description.md`, check, pack; `ferret fmdl pack` and the editor's `pack` are one code path.

| Call | What it does |
|---|---|
| `FmdlSession.open(files, { loader })` | a model folder; the parents and the included models are found through `loader` |
| `makeChild(id, { summary?, kind?, name?, version? })` | a new model that extends this one (`^<version>`): nothing of the parent is copied, a child holds only what it changes; a child of a draft sees the draft's edits |
| `setDescription`, `setName`, `setParent` | the author's description (merged by key, `null` removes), the package name, the parent (its package becomes a dependency) |
| `addInclude`, `setInclude`, `removeInclude` | includes (6.2); in a child an inherited include is removed by `null` (8.3); the dependencies follow |
| `setDock`, `setPart`, `setMaterial`, `setMovingPart`, `setPhysics`, `setMotion`, `remove*` | one entry of the group; physics is merged by key; a motion writes `motions/<name>.fm` and adds its forms to `requires.forms`; in a child `remove*` of an inherited entry writes `null` |
| `patch(ops)` | anything else: JSON-pointer `add`/`replace`/`remove` on `model.json` |
| `check()`, `resolved()`, `snapshot()` | the issues of the draft; the resolved model (what a game places); it with the reader of its files |
| `undo()`, `redo()`, `history()`, `changedFiles()` | the history; the files that differ from what was opened (a new child: all of them) |
| `prepare()`, `pack()` | the folder as the packer writes it; the `.fmdl` bytes |

An agent has the same by commands (`registerFmdlEditCommands`): `fmdl.edit.open | child | sessions | use | close | get | describe | parent | include | dock | part | material | physics | moving | motion | patch | check | resolve | undo | redo | diff | pack | save | run`. `save` and `run` ask the host (`FmdlEditHost.save`, `.run`): the editor has no world of its own. The viewer page `?fmdl[=<models url>]` (`tools/viewer/src/fmdl.ts`) is such a host: models are `<url><id>.fmdl`, `fmdl.edit.show` draws the draft as the game would (stage, docks marked on top), `fmdl.edit.run` runs a motion of the draft on it, `save` hands the `.fmdl` to the browser; it also has `fmdl.models | describe | appear | docks | dock | motion.run` of M9.

The end-to-end case in `packages/editor/test/fmdl.test.ts`: hydrogen is opened, a child `deuterium` is made, a neutron is included at the nucleus, the binding energy and `modules.atom` (`H-2`) are set, the description is given, and the packed `.fmdl` opens, resolves with its parent, computes its mass (proton + neutron + electron less the binding energy's mass defect, charge 0) and is an H-2 atom; hydrogen stays H-1.

## `.fmdl` models in the asset library

A `.fmdl` is a package of kind `model`, and the library lists packages, so it goes in as it is: `node tools/asset-lib/build.mjs --fmdl <folder of .fmdl> --out <dir>` puts each file in the library unchanged (the package's hash is the file's) and writes one item of type `fmdl` for it, with the name from its manifest and the tags and kind from its `description.json`; `publish.mjs --from <dir>` sends the result to the library on the server. The item has no tiers (those belong to type `model`, a plain glTF): a game finds it by rubric and tags in the catalog and opens it with the model tools (`ModelCatalogue`, `ModelStage`); `library.model()` refuses it. Rubric rules for `fmdl` are in `tools/asset-lib/rubrics.mjs` (the lab's models: `education/atoms-and-matter/{atoms,molecules,crystals,samples}`).
