# @ferret/levels: API

Level manifests, the level registry, load, unload and travel, environment and the `.ferret` package format.

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

## Classes

### AssetLibrary

*class* · `packages/levels/src/library.ts:165`

```ts
class AssetLibrary implements Service
```

- `readonly name: "asset-library"`
- `qualityBusy(): boolean` — for the quality regulator (`QualityService` finds it): something of the library is loading
- `constructor(private readonly o: AssetLibraryOptions)`
- `init(world: World): void`
- `async find(q: LibraryFind = {}): Promise<LibraryCard[]>` — Candidates for a request, from the service: a keyword search that returns a generous set (`car` brings `carbon` too), as cards for the one who asks to read and pick from. The library is English only: whoever asks translates the user's words first. The service returns at most 200 candidates, so `offset` pages within them.
- `async open(url?: string): Promise<Catalog>` — Open the catalog (once; again to refresh).
- `list(q: LibraryQuery = {}): LibraryEntry[]` — Items of the catalog, filtered; no package is opened.
- `rubrics(under?: string): RubricNode[]` — The tree of the library with the number of items in each rubric (`under`: only that branch, itself included).
- `has(ref: string): boolean`
- `versionsOf(id: string, e: CatalogAsset = this.cat.assets![id]): string[]` — the versions of an item (the server's numbers, oldest first): those of its package that hold it; a catalog made before versions has 1.0.0 only
- `entry(ref: string): LibraryEntry` — An item by reference (`id` or `id@version`), with the version it resolves to: the reference's own, else the version the package is already open at, else 1.0.0, else (an item added by a later version of its package) the first version that holds it. Never the latest.
- `previewUrl(ref: string): string | undefined` — Absolute URL of an item's preview image (from the catalog, nothing is opened).
- `async pkg(pkgId: string): Promise<FerretPackage>` — The package of the catalog, open in the mount (with its dependencies), at the version this instance selected (default 1.0.0, never the latest).
- `async item<T extends LibraryItem = LibraryItem>(ref: string): Promise<T>` — The item file, read from its package.
- `async impostor(id: string, pose?: string): Promise<{ entry: ImpostorEntry; bytes: Uint8Array } | null>` — The baked impostor of an item and its packed atlas bytes (`@ferret/perspective`'s `unpackAtlas` reads them): the item's own (`impostor`), or for a character the one of a pose (`impostors[pose]`: stand, walk, sit...). Null when the item has none.
- `async vatBake(id: string): Promise<{ entry: VatBakeEntry; bytes: Uint8Array } | null>` — The baked vertex animation of a character (`vat` of its item) and its packed bytes (`@ferret/crowd`'s `unpackVat` reads them), shipped in the figure's package so that any game with the figure gets it for free. Null when the character has none.
- `async url(ref: string): Promise<string>` — A URL the engine's loaders can read for a `ferret://<package>/<path>` reference (a clip set's file, a map).
- `async texture(id: string, o: { scene?: BABYLON.Scene } = {}): Promise<Partial<Record<TextureChannel, BABYLON.Texture>>>` — The maps of a texture item as Babylon textures (colour spaces set: base colour and emissive are sRGB, the others linear).
- `async image(id: string, channel: TextureChannel): Promise<ImageBitmap>` — one map of a texture item as a decoded image (no colour conversion), for code that packs maps itself (the ground's texture arrays of
- `material(id: string, o: MaterialOptions = {}): Promise<BABYLON.PBRMaterial>` — A PBR material from a material item (and a variant of it): the description maps one to one to `PBRMaterial`.
- `async clipsOf(characterId: string, o: { compatible?: boolean } = {}): Promise<ClipRef[]>` — The clip sets a character names (and the clip sets of its skeleton in the catalog), with the reference of each file.
- `async bindClips(c: LibraryCharacter, o: BindOptions = {}): Promise<BoundClips>` — Put the clip sets of a character on its bones (matched by bone name; a clip set is loaded once however many bodies use it). Waits for the model. `groups` are one AnimationGroup per clip name, ready for an `Animator` or `group.start()`.
- `async character(id: string, o: CharacterOptions = {}): Promise<LibraryCharacter>` — A character in the world at once (a placeholder until the model is in).
- `async model(id: string, o: ModelPlacement = {}): Promise<LibraryModel>` — A static model of the library in the world at once (a placeholder of its bounds until the file is in).
- `async modelRef(id: string, tier?: LibraryTier): Promise<string>` — The `ferret://` file of a static model (its tier chosen as `model()` does): what a placement list names by library id.
- `placementResolver(): PlacementResolver` — What placement lists (`*.placements.json`, placements.ts) need to find models and materials of this library by id; give it to the package loader's `placements`.
- `async attach(character: LibraryCharacter, partId: string, o: AttachOptions = {}): Promise<LibraryCharacter | null>` — Hang a part (a weapon, a hat, a rider) on a body that is in, by a socket of the body's item (`sockets`: a bone and an offset) or by a bone and an offset of your own. The part follows the bone through every clip. Resolves with the part (dispose it to take it off), or null when the body or the bone is not found. Offsets are in the glTF's own space: metres of the bone's local frame and a quaternion.
- `async module<T = Record<string, unknown>>(id: string): Promise<T>` — A ready-made package of code (a `module` item): its package is opened through the catalog with its dependencies, its code runs once under the code policy (`code` of the options: the library's own origin, or a signature), checked against the sha256 in its manifest, and its exports come back. The same module asked twice runs once. `const sea = await library.module<typeof import('sea')>('sea-surface'); new sea.SeaView(scene)`.
- `soundFormat(item: SoundItem, o: { format?: 'wav' | 'mp3'; tier?: LibraryTier } = {}): 'wav' | 'mp3'` — Which file of a sound item a device takes.
- `async sound(id: string, o: SoundOptions): Promise<LibrarySound>` — A sound item made playable: its file is read from the package, handed to the audio service and defined there with the item's bus, volume, loop (and loop points) and distance falloff.
- `async flipbook(id: string): Promise<{ item: FlipbookItem; files: Partial<Record<keyof FlipbookItem['files'], Uint8Array>> }>` — A flipbook item and the bytes of its images (the encoded files, by name: color, light, light2, motion, depth). Decoding them into textures is the effects view's work, so this stays free of the drawing code.
- `async volume(id: string): Promise<{ item: VolumeItem; bytes: Uint8Array }>` — A volume item and its voxel bytes (frames x z x y x x, one byte per channel per voxel).
- `async preload(id: string, tier?: LibraryTier): Promise<void>` — Bring an item's files to the device now (a model's file, a texture's maps), so a later call does not wait.
- `release(): void` — Free what the library made: materials, textures, characters. Packages stay open (they cost the mount nothing but the index).
- `dispose(): void`

### CatalogClient

*class* · `packages/levels/src/catalog.ts:46`

```ts
class CatalogClient
```

- `readonly registrations: CatalogRegistration[]` — every catalog registered through this client, in order
- `constructor(private readonly levels: LevelService, private readonly mount: PackageMount, private readonly store: AssetStore, private readonly defaults: CatalogOptions = {})`
- `async register(url: string, o: CatalogOptions = {}): Promise<CatalogRegistration>`

### ClipPlayer

*class* · `packages/levels/src/fmdl-motion.ts:223`

```ts
class ClipPlayer
```

the skeletal clips of a model on its own skeleton: a graph with a state of the first clip, montages over it

- `readonly groups: Record<string, BABYLON.AnimationGroup>`
- `readonly graph: AnimGraph`
- `readonly missing: Record<string, string[]>`
- `constructor(scene: BABYLON.Scene, root: Node, clips: ClipJson[], o: { graph?: GraphDef; rest?: string } = {})`
- `names(): string[]`
- `duration(clip: string): number`
- `play(clip: string, o: { loop?: boolean; rate?: number; blend?: number; mask?: string[] } = {}): Waitable` — play a clip over the graph; a one-shot is done when it ends, a loop when it is stopped
- `stop(clip: string): void`
- `playingNow(): string[]`
- `update(dt: number): void` — one rendered frame
- `dispose(): void`

### CodeLoader

*class* · `packages/levels/src/code.ts:70`

```ts
class CodeLoader
```

- `constructor(readonly world: World, readonly mount: PackageMount, private o: CodeLoaderOptions = {})`
- `list(): LoadedCode[]` — The code loaded so far, in load order.
- `exports(id: string): LibraryModule | null | undefined` — The exports of a loaded package's code, or undefined.
- `require(id: string, range = '*'): Promise<LoadedCode>` — Load the code of a package (and of its dependencies first) and run its `install` once. Resolves at once when it is loaded; concurrent calls share one load. Rejects with the reason when the package may not run code or something is missing.
- `module(id: string, range = '*'): Promise<{ exports: LibraryModule; pkg: FerretPackage; ferret: unknown }>` — The code module of a package of kind `levels` that is docked into a parent game: checked, imported and kept, but `install` is NOT called: the dock calls it at every entry and `dispose`s at every exit. The same checks as `require` (policy, sha256); one import per page, however often the level is entered.
- `async importFile(pkg: FerretPackage, path: string): Promise<unknown>` — Run another module of a loaded level's package (its kernels): the same checks as its entry (the manifest's hash, or the origin's trust), the same shared engine.
- `dispose(): void` — Call the `dispose` that `install` returned, newest first (the modules themselves stay: a page cannot unload them).

### CollisionChunks

*class* · `packages/levels/src/collision-chunks.ts:32`

```ts
class CollisionChunks
```

Keeps the chunks round the player resident. `update` is cheap (a few dozen boxes); fetching and instancing happen in the background.

- `constructor(private def: CollisionChunksDef, private assets: PackageAssets, private at: (file: string) => string, private name: string, private places: () => [number, number, number][], private onError: (message: string) => void = () => {})`
- `async ready(): Promise<void>` — Start the chunks near `places` and wait for them (the level is not playable before the ground round the spawn is solid).
- `update(): void`
- `get loaded(): number`
- `dispose(): void`

### DecalBuffer

*class* · `packages/levels/src/decal-buffer.ts:17`

```ts
class DecalBuffer
```

- `readonly target: BABYLON.RenderTargetTexture`
- `constructor(private readonly scene: BABYLON.Scene)`
- `get count(): number` — the decal meshes drawn into the buffer now
- `dispose(): void`

### DependencyError

*class* · `packages/levels/src/dependencies.ts:36`

```ts
class DependencyError extends Error
```

- `constructor(message: string, readonly id: string, readonly range: string, readonly tried: { url: string; error?: string }[])`

### DependencyResolver

*class* · `packages/levels/src/dependencies.ts:43`

```ts
class DependencyResolver
```

- `readonly opened: OpenedDependency[]` — every dependency opened by this resolver, in the order it was opened
- `constructor(private readonly o: DependencyOptions)`
- `async find(id: string, range = '*', extra: readonly string[] = []): Promise<OpenedDependency | null>` — Find a package by id and range in `extra` (searched first) and then the resolver's own catalogs, and open it. Null when no catalog has it; throws a DependencyError that names every catalog tried and why when one has it but not in range, or none could be read.
- `async openAll(pkg: FerretPackage, into: DependencyTarget, base: string): Promise<OpenedDependency[]>` — Open every dependency of `pkg` (and theirs) that `into` does not hold yet, and add it there. `base` is the URL `pkg` was loaded from: its own relative `catalogs` are read from there. A dependency that is open already must fit its range. A package `pkg` names itself is opened by `pkg`'s range wherever it is first asked for, so that the versions a game pins are the ones it gets. Returns what was opened.
- `hook(extra: readonly string[] = []): (id: string, range: string) => Promise<FerretPackage | null>` — The code loader's `open` hook: a package required later (by id) is searched in the resolver's catalogs.

### DistanceFieldTextures

*class* · `packages/levels/src/distance-field.ts:74`

```ts
class DistanceFieldTextures
```

a distance field on the graphics card: the table of bricks and the atlas as two 3D textures

- `readonly table: BABYLON.BaseTexture`
- `readonly atlas: BABYLON.BaseTexture`
- `constructor(readonly header: DistanceFieldHeader, bytes: Uint8Array, scene: BABYLON.Scene)`
- `dispose(): void`

### DockHost

*class* · `packages/levels/src/dock.ts:74`

```ts
class DockHost implements Service
```

The service of the parent that docks levels. `enter` is what a docked level's `LevelDef.build` calls; the level ends when the engine unloads it (`levels.onUnload`),
whichever way it goes (a door, the menu, `levels.evict`). Events on the world's bus: `dock:enter` { id }, `dock:leave` { id }, `dock:failed` { id, error }.

- `readonly name: "dock"`
- `readonly roles: Roles` — the roles service; made by the host if the parent has not added one
- `entered: number` — how many levels were docked and ended, for the tests that count round trips
- `left: number`
- `constructor(private o: DockHostOptions)`
- `get current(): string | undefined` — the id of the level docked now
- `dispose()`
- `async enter(def: LevelDef, build: LevelContext, packageId: string): Promise<void>` — The build step of a docked level: run its code under the transition.

### FmdlModel

*class* · `packages/levels/src/fmdl.ts:46`

```ts
class FmdlModel
```

A resolved model with its files loaded: every glTF any level of it needs is read once and shared by every placement. Building a level is then synchronous
(a lazy rung of the perspective backend makes its meshes when first shown).

- `static async load(resolved: ResolvedModel, read: FileReader, scene: BABYLON.Scene, o: FmdlLoadOptions = {}): Promise<FmdlModel>` — The plans of the levels this device draws, loaded: read every file of every level, once.
- `dispose(): void` — Release what the model loaded: its glTF containers (meshes, materials, textures, geometry) and the maps it read itself (a library texture given by `texture` stays its giver's). What was built from the model shares these, so this is for when none of it is drawn any more: a model drawn by a level is disposed in the level's `onUnload`.
- `plan(level: number): AssemblyPlan` — the plan of a level (the device tier applied)
- `build(level: number, name = `${this.resolved.id}:${level}`): BABYLON.TransformNode` — The nodes of one level of the model, with every included instance placed on it. The meshes are instances of the loaded glTF's, so a thousand of the same model share their vertex data. The node is not parented: the caller hangs it where it belongs and disposes it.
- `stageModel(): { id: string; resolved: ResolvedModel; read: FileReader; make(level: number, name: string): { root: BABYLON.TransformNode; plan: AssemblyPlan } }` — This model as something a `ModelStage` can place by name (`fmdl-motion.ts`): the nodes of a level and the plan they were made from.
- `ladder(o: { impostor?: string } = {}): ModelRung[]` — The ladder this device draws the model by: its levels, the impostor, the point (`ladderOfModel`); throws, naming them, when thresholds were not measured.
- `async place_entity(entity: Entity, backend: BabylonBackend, o: { impostor?: string; coherence?: { kind?: string; link?: number; gap?: number }; fade?: number; keepFrames?: number; /** the entity does not move once placed: the meshes of a rung keep their world matrices from the moment they are made (the CPU cost of thousands of parts) */ static?: boolean } = {}): Promise<Perspective>` — Give an entity this model, drawn by size on the screen: a lazy rung for each level (made when first shown, dropped when long unused), the impostor rung from the model's baked atlas, the point from the atlas's look. Like models are one coherent group (`coherence.kind` is the model's id, or the one given), so a field of atoms is drawn as one: neighbours never differ by a level. Returns the entity's `Perspective` component.
- `bounds(): { centre: Vec3; radius: number }` — The bounding sphere of the whole in its own frame (its finest level, includes placed), measured once: the lazy rungs have no meshes to measure until shown.

### FogVeil

*class* · `packages/levels/src/fog-veil.ts:58`

```ts
class FogVeil
```

The veil on the scene's PBR materials; `density` follows the height fog at the camera (set by the environment every frame).

- `enabled: boolean`
- `density: number` — extinction per metre now (the height fog's density at the camera times the extinction scale)
- `colour: [number, number, number]` — linear colour (the fog's colour times the albedo)
- `constructor(readonly scene: BABYLON.Scene, readonly def: FogVeilDef)`
- `factor(): number` — the share of a point beyond the veil's depth that the veil covers: what a sky or a far sea mixes toward the colour
- `dispose()`

### HeightFogMaterials

*class* · `packages/levels/src/height-fog-material.ts:102`

```ts
class HeightFogMaterials
```

The height fog integrated along each ray on every PBR and standard material of the scene; `update(h)` every frame with the camera's height.

- `enabled: boolean`
- `values: [number, number, number, number]`
- `get minTransmittance()` — what of the surface always comes through (Unreal's FogMaxOpacity, of an exact fog)
- `constructor(readonly scene: BABYLON.Scene, readonly def: HeightFogDef)`
- `update(h: number)`
- `dispose()`

### LevelMaterials

*class* · `packages/levels/src/level-materials.ts:212`

```ts
class LevelMaterials
```

The materials of one level: definitions by name, textures read once, materials made once.

- `readonly defs: Map<string, MaterialDef>`
- `readonly policy: LevelCodecPolicy`
- `constructor(readonly scene: BABYLON.Scene, private readonly files: LevelFiles, private readonly o: LevelMaterialsOptions = {})`
- `add(materials?: unknown, textures?: unknown): void` — add definitions (a `ferret-materials/1` object) and/or a texture catalogue, already read
- `async load(o: { materials?: string; textures?: string; distanceField?: string }): Promise<void>` — read the files of the level: the catalogue first, then the definitions (either may be inline: `add`)
- `async loadDistanceField(path: string): Promise<void>` — the level's distance field: its header, and the data file the header names beside it
- `setDistanceField(f: DistanceFieldData): void` — a distance field already read; the materials made from now on see it
- `has(name: string): boolean`
- `get names(): string[]`
- `fileOf(stem: string): { file: string; srgb?: boolean }` — the file a texture stem is read from under the policy, and whether it is colour by the catalogue
- `material(name: string): Promise<BABYLON.PBRMaterial>` — The material of a name (made once).
- `screenDecalMaterial(name: string): Promise<BABYLON.PBRMaterial>` — The material of a projected decal (screen-decals.ts): the level material `name` (a master carried whole, `decal: true`) as the shader of the decal's box. It is drawn into the scene's screen decal buffers (made if the scene has none yet), back faces only, no depth, blended with premultiplied alpha; it has no light of its own.
- `async ready(): Promise<void>` — Resolves when every texture asked for so far is loaded and decoded, and every material asked for is made.
- `get materialsMade(): Promise<BABYLON.PBRMaterial[]>` — The made materials, in order of use.
- `dispose(): void`

### LevelService

*class* · `packages/levels/src/levels.ts:114`

```ts
class LevelService implements Service
```

The level registry and travel between levels. `travel(id)` shows the loading screen (events), removes the old level with
everything it made, builds or loads the new one, moves the persistent entities (the player) to the spawn point and announces
the new level. Events: `level:loading` { id, progress }, `level:ready` { id, report }, `level:unloaded` { id }, `level:failed` { id, error }.
`state` is the game's data that survives travel and goes to `Platform.state` with `saveData`.

- `readonly name: "levels"`
- `state: Record<string, unknown>` — persistent state across levels: inventory, flags, health ... plain JSON
- `readonly spawns: Map<string, SpawnPoint>`
- `readonly transitions: TransitionRegistry` — the game's transitions: register them by name and choose which one a travel uses
- `current: LevelDef | null`
- `travelling: boolean`
- `report: LevelReport`
- `animGraphs: Record<string, any>` — the animation graphs of the current level package (its manifest's `animGraphs`), by name
- `movement: Record<string, number>` — the player character values of the current level package (its manifest's `movement`), over the engine's defaults
- `libraries?: (manifest: import('./manifest').LevelManifest, levelId: string) => Promise<void>` — plugged in by `installLevelLibraries` (./libraries): require the libraries a level's manifest needs before the level is built
- `packageLoader?: (ctx: LevelContext, level: LevelDef, report: LevelReport) => Promise<void>`
- `readonly persistent: Set<Entity>` — entities that always travel with the player (the player itself): they are placed at the spawn, never removed
- `constructor(readonly opts: LevelOptions = {})`
- `init(world: World)`
- `register(def: LevelDef): this`
- `unregister(id: string): boolean` — Remove a level from the registry (a catalog that no longer lists it). The level being played is not touched.
- `replace(def: LevelDef): this` — Register, or replace a level of the same id that is not the one being travelled to (a catalog update).
- `catalogs?: { register(url: string, o?: unknown): Promise<unknown> }` — Plugged in by `installCatalogs` (./catalog): the remote levels of a catalog.
- `registerCatalog(url: string, o?: unknown): Promise<unknown>` — Fetch a catalog and register its levels; needs `installCatalogs`.
- `has(id: string): boolean`
- `get(id: string): LevelDef`
- `list(): LevelDef[]`
- `exempt(e: Entity): this` — An entity that is not part of any level though it appears while one loads (another player's avatar): it is not removed with the level.
- `keep(e: Entity): this` — Entities that go with the player to every level.
- `async travel(id: string, opts: TravelOptions = {}): Promise<LevelReport>`
- `spawn(id?: string): SpawnPoint | null` — The spawn point with that id, or the level's default one.
- `place(e: Entity, s: SpawnPoint)` — Put an entity at a spawn point (any entity with a CharacterMovement is teleported properly).
- `hold<T>(work: Promise<T>, label = 'artefact'): Promise<T>` — An artefact the level is not ready without. An entity of the level calls this while the level is built (a behaviour's `onAttach`) with the promise of what it still loads (a character's model, its clips). `level:ready` is announced when the last of them has settled, or after `holdMs`; a rejected one is a warning of the report. Outside a travel the hold is ignored. Returns the promise.
- `get holding(): number` — how many holds of the level being built are not taken up yet or still open
- `unload()`
- `async evict(id: string, to: string, spawn?: string, o: TravelOptions = {}): Promise<boolean>` — End a level at once: the parent has changed or removed the door it was entered by. If the level is the current one the player is taken to `to` (at `spawn`) by an ordinary travel, which unloads it with everything it made; if it is not current, nothing happens. Resolves when the player is out.
- `onUnload(fn: () => void)` — Run `fn` when the current level is removed (release assets, clear a service).
- `saveData(): { level: string | null; state: Record<string, unknown> }` — What to hand to `Platform.saveState`: the game's state and where the player is.
- `loadData(data: { level?: string | null; state?: Record<string, unknown> } | null | undefined): string | null` — Restore what `saveData` made; returns the level to travel to (or null).
- `dispose()`

### LightBudget

*class* · `packages/levels/src/light-budget.ts:192`

```ts
class LightBudget
```

- `readonly def: LightBudgetDef`
- `onChange?: (entered: number[], left: number[]) => void` — called after a re-ranking when real lights changed hands: indices that entered and left the pool
- `onSounds?: (start: number[], stop: number[]) => void` — called when the nearest lamps with a sound change: indices to start and to stop
- `constructor(readonly scene: BABYLON.Scene, def: LightBudgetDef, readonly opts: LightBudgetOptions = {})`
- `get clustered(): boolean` — is every lamp a real light through clustered lighting
- `get name()`
- `get size()`
- `get real(): number[]` — the lights that are real now (fading ones included)
- `get glowMesh()`
- `glowSize(i: number): number` — the size in metres of lamp `i`'s glow dot now (0: hidden, because it is a real light or out of reach)
- `get lights(): (BABYLON.PointLight | BABYLON.SpotLight)[]`
- `stats(): LightBudgetStats`
- `setBudget(n: number)` — change the budget while running (a quality switch): the pool grows or shrinks, and the next re-ranking fills it
- `update(dt: number)` — one step of the budget: `dt` seconds since the last. It runs by itself every frame; tests call it with a clock of their own
- `dispose()`

### LookPlugin

*class* · `packages/levels/src/material-models.ts:451`

```ts
class LookPlugin extends BABYLON.MaterialPluginBase
```

- `readonly structure: LookStructure`
- `readonly define: string`
- `active: boolean`
- `constructor(material: BABYLON.Material, readonly look: LookDef, readonly masks: Record<string, BABYLON.BaseTexture>)`
- `getClassName()` — Gets the current class name useful for serialization or dynamic coding.
- `deactivate()`
- `prepareDefinesBeforeAttributes(defines: BABYLON.MaterialDefines)` — a material with no texture of its own draws without UVs unless asked: the masks are read at the first set
- `prepareDefines(defines: BABYLON.MaterialDefines, _scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh)` — Sets the defines for the next rendering
- `isReadyForSubMesh()` — Specifies that the submesh is ready to be used.
- `getActiveTextures(t: BABYLON.BaseTexture[])` — Returns an array of the actively used textures.
- `hasTexture(t: BABYLON.BaseTexture)` — Checks to see if a texture is used in the material.
- `getAttributes(attributes: string[], _scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh)` — Gets the attributes used by the plugin.
- `getSamplers(samplers: string[])` — Gets the samplers used by the plugin.
- `getUniforms()` — Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos)
- `bindForSubMesh(ubo: BABYLON.UniformBuffer, scene: BABYLON.Scene)` — Binds the material data.
- `dispose(force?: boolean)` — Disposes the resources of the material.
- `getCustomCode(shaderType: string): Record<string, string>` — Returns a list of custom shader code fragments to customize the shader.

### ModelCatalogue

*class* · `packages/levels/src/fmdl-catalogue.ts:25`

```ts
class ModelCatalogue
```

- `add(resolved: ResolvedModel, authorText = ''): this` — a resolved model: the description is made from it (`authorText` is the free part of its `description.md`)
- `has(id: string): boolean`
- `ids(): string[]`
- `list(q: { text?: string; kind?: string; tag?: string; abstract?: boolean } = {}): ModelListing[]` — the models whose words match, best first; the words of a sentence are taken one by one (short and filler words are left out)
- `describe(id: string): ModelDescribed`

### ModelCode

*class* · `packages/levels/src/fmdl-code.ts:90`

```ts
class ModelCode
```

- `constructor(readonly stage: ModelStage, private o: ModelCodeOptions = {})`
- `async load(model: LoadableModel): Promise<this>` — Check and import the code of a model and of the models it includes, once; a model has to be loaded before it is placed.
- `install(rt: MotionRuntime): this` — Make every function (those loaded later too) a word of the motion runtime: `(name instance args...)`.
- `link(game: ModelCodeGame): () => void` — Give every function (those loaded later too) to a game of the game language, before its files are loaded. Returns what takes them back.
- `call(fn: string, instance: unknown, ...args: unknown[]): unknown` — `(fn instance args...)`: the function `fn` of the model of `instance` (the actor's name, or the instance itself)
- `functions(instance?: string): ModelFunctionInfo[]` — the functions of an instance, or every function name the scene knows
- `instance(name: string): ModelInstance | undefined` — the instance of an actor that has code
- `step(dt: number): void` — the `step` hooks of every instance, in the order they appeared (the parent's module first)
- `dispose(): void`

### ModelDocks

*class* · `packages/levels/src/fmdl-docks.ts:69`

```ts
class ModelDocks
```

- `constructor(readonly stage: ModelStage, private o: DocksOptions = {})`
- `dispose(): void`
- `parse(ref: string): { actor: Actor; dock: string }` — `<actor>#<dock>` split into the actor and the dock; the dock may be left out when the actor has just one free dock
- `frame(actor: Actor, dock: string): { matrix: BABYLON.Matrix; local: BABYLON.Matrix }` — the dock's frame in the world: the node it sits on and the frame on it, as the loader places them (6.2)
- `describe(name: string): DockInfo[]` — every dock of an actor, and of the models included in it, with the words that say what goes there
- `docked(): DockedPair[]` — the pairs docked now
- `dock(aRef: string, bRef: string, o: DockOptions = {}): DockedPair`
- `undock(ref: string, other?: string): DockedPair[]` — take a pair apart (`undock('h1', 'o')`), or everything an actor or a dock holds (`undock('h1')`, `undock('o#bond-1')`)
- `save(): { fmdlDocks: DockedPair[] }` — the docked pairs as plain JSON: what a level or a game's saved state holds, and what a replica is sent
- `restore(saved: { fmdlDocks: DockedPair[] }): void` — Make the docked pairs of a save (or of the host's replica) true here: pairs that are not in it are undocked, the ones that are missing are docked. A pair is docked where its actors already are (`place: false`: the save was made with them in place, a replica has their poses from the net), so a restored pair does not move anything; a `bond` is rebuilt by its backend, which puts the atoms in the molecule's shape again.

### ModelPrograms

*class* · `packages/levels/src/fmdl-programs.ts:33`

```ts
class ModelPrograms
```

- `constructor(readonly stage: ModelStage, private host: ProgramHost)`
- `find(target: string, ref: string): { actor: Actor; resolved: ResolvedModel; name: string; motion: ModelMotion }` — the motion a name leads to on an actor (the instance's actor, for `<instance>/<name>`)
- `args(resolved: ResolvedModel, name: string, motion: ModelMotion, given: Record<string, unknown> = {}): Record<string, Value>` — the arguments checked against `params` (types, unknown names) and the defaults filled in
- `missingForms(motion: ModelMotion): string[]` — the forms the motion itself uses (`requires.forms` of the motion) that the language does not have: running it needs only those
- `missingModelForms(resolved: ResolvedModel): string[]` — the forms a whole model needs (its `requires.forms`, which holds those of all its motions) that the language does not have: a player refuses the model before running it
- `checkModel(target: string): void` — throws, naming the forms, when this runtime lacks one the actor's model needs
- `async run(target: string, ref: string, args: Record<string, unknown> = {}): Promise<Program>` — Start a motion on an actor. The file is read first (once), so the program is returned when it has started.
- `runNow(target: string, ref: string, args: Record<string, unknown> = {}): Program` — the same for a caller that cannot wait (a command, a form): the files must have been read by `preload`
- `async preload(target: string): Promise<void>` — read every motion file of an actor's model and of the models included in it
- `resolver()` — the `motionResolver` of the actuators' capability: `motion.run { motion, target, args }`

### ModelStage

*class* · `packages/levels/src/fmdl-motion.ts:332`

```ts
class ModelStage
```

The placed models of a world by name. A `Service` of `@ferret/core`: add it to the world and its clock is the fixed step's; in a test call `step`.

- `readonly name: "fmdl-stage"`
- `readonly actors: Map<string, Actor>`
- `constructor(private o: StageOptions = {})`
- `watch(w: StageWatcher): () => void` — tell `w` of what the stage does; returns what ends it
- `time(): number`
- `fixedUpdate(dt: number): void`
- `update(dt: number): void`
- `step(dt: number): void`
- `addModel(model: StageModel): this`
- `modelIds(): string[]`
- `adopt(name: string, id: string, root: Node, plan: AssemblyPlan, from?: string): Actor` — put an already built model on the stage under a name (a model the game made itself)
- `actor(name: string): Actor` — An actor by name. An included instance is addressed `<actor>/<instance>` (and deeper: `<actor>/<instance>/<instance>`): it is the instance's nodes and parts of the whole it is in, seen as an actor of its own, so a motion of the included model runs on it.
- `appear(id: string, o: { name?: string; at?: Vec3; level?: number; scale?: number; parent?: string } = {}): Actor` — a model appears: built on `level`, placed at `at`, named `name` (default `<id>#<n>`)
- `vanish(name: string): void` — take an actor away, with the actors let go from it staying
- `letGo(name: string, instance?: string): string[]` — Let included instances go: each becomes an actor of its own, `<actor>/<instance>`, where it is (its world matrix kept), no longer a part of the whole's nodes. With no instance named, every one. Returns the new names.
- `attachClips(name: string, clips: ClipJson[], o: { graph?: GraphDef; rest?: string } = {}): ClipPlayer` — put the skeletal clips of an actor on its own skeleton
- `async loadClips(name: string, o: { sets?: string[]; graph?: GraphDef; rest?: string } = {}): Promise<ClipPlayer>` — read the clip sets of the actor's model (all of them, or `sets`) and put them on its skeleton: it begins in `idle`, else in the first clip
- `nodeHost(): NodeHost` — the nodes of the actors as handles of the language (`move-along`, `turn-to`)

### OcclusionCulling

*class* · `packages/levels/src/occlusion-culling.ts:21`

```ts
class OcclusionCulling implements Service
```

- `readonly name: "occlusion-culling"`
- `init(world: World): void`
- `get supported(): boolean`
- `get meshes(): number`
- `apply(o: OcclusionOptions): number` — give queries to the level's big meshes (and to those that load later under the root)
- `unapply(): void`
- `qualityKnobs(): QualityKnob[]`
- `dispose(): void`

### OceanView

*class* · `packages/levels/src/ocean.ts:209`

```ts
class OceanView
```

- `readonly mesh: BABYLON.Mesh`
- `readonly material: BABYLON.ShaderMaterial`
- `get ready(): boolean` — has every depth texture been baked at least once (for loading screens and tests)
- `constructor(private scene: BABYLON.Scene, private o: OceanOptions = {})`
- `setSea(o: { whitecaps: number; streaks: number; wavelength: number; wind: number })` — the state of the sea for its foam and chop: the share of the surface under whitecaps (`seaCondition(...).whitecaps` of
- `setWind(dirDeg: number)`
- `setWaves(list: OceanWave[])`
- `get waves(): readonly OceanWave[]`
- `setLight(o: { toSun: V3; sunColor: V3; light?: number; skyTop?: V3; skyHorizon?: V3; rain?: number })` — the light: the direction TO the sun, its colour, how bright the day is (0..1), the sky colours for a missing cube, the rain 0..1
- `setColors(o: { deep?: V3; shallow?: V3; foam?: number; clarity?: number })` — the colours of the water: deep and shallow (linear 0..1), and how much the crests foam; `clarity`: metres of water the bed shows through (default 4: a murky sea; a clear bay over sand shows its bed through 10 m and more), the shallow colour fades out over 1.5 times that
- `setFog(color: V3 | BABYLON.Color3, density: number)`
- `setHeightFog(values: readonly [number, number, number, number] | null)` — the height fog along each ray instead of the flat `fogDensity` (`env.heightFog.values`, heightFogShaderValues); null: the flat fog
- `setReflection(tex: BABYLON.BaseTexture | null)` — the sky the sea mirrors: a cube texture of the sky and its clouds (`createSkyProbe`); null: the two sky colours
- `setDetail(o: { normal?: BABYLON.BaseTexture; near?: number; far?: number; strength?: number; speed?: number; foam?: BABYLON.BaseTexture; foamScale?: number })` — a tiled normal map for the small waves (read at `near` and `far` metres per tile, `strength` of the normal's slope, drifting with the wind at `speed` m/s) and a tiled foam map (`foamScale` metres per tile; its red channel shapes the foam); both optional. The textures are RGB normals (0..1, flat = 0.5, 0.5, 1) and any foam picture.
- `setVeil(o: { density: number; distance: number; colour: V3 } | null)` — the volumetric fog's veil over the sea (`fogVeilOf(scene)`): extinction per metre, its depth in metres and colour; null: none
- `setTone(o: { exposure: number; contrast: number; aces: boolean | 'unreal' } | null)` — the scene's image processing for the sea (exposure, the ACES curve, contrast, gamma): a shader of its own does not get it; off by default
- `prime(cam: V3)` — bake the depth round a point at once (a loading screen)
- `update(time: number, cam: V3, level = 0)` — each frame: the clock, the water level, the camera (the grid follows it; the depth boxes move when the camera has gone a quarter of their size)
- `dispose()`

### PackageMount

*class* · `packages/levels/src/ferret.ts:36`

```ts
class PackageMount
```

Connects packages to a LevelService. `add(pkg)` registers the package's levels (as `<id>` for the first package, `<pkgid>/<id>`
for the others, or with the `prefix` given); `url(pkg, path)` gives a blob URL for any file of a package, for sounds, textures
and video. Nothing is unpacked: a file is read from the package when a level asks for it, and a model's blob URL goes when the
level that held it is gone.

- `readonly packages: PackageSet`
- `readonly assets: MountAssets` — give this to the level loader instead of the asset cache (`installPackages` does)
- `readonly loader: PackageLoaderOptions` — the options the level loader runs with: hand this to `installEditor` as its `loader` so the editor's draft shows in reloads
- `constructor(readonly levels: LevelService, private inner: MountAssets, readonly opts: MountOptions = {})`
- `add(pkg: FerretPackage, o: { prefix?: string } = {}): LevelDef[]` — Open a package into the mount and register its levels. Returns what was registered.
- `startLevel(pkg: FerretPackage): string | null` — The level a package starts in (`entry.level` of a game, else its first), as registered.
- `async url(pkg: FerretPackage, path: string): Promise<string>` — A blob URL for a file of a package (`path` inside `pkg`, or `ferret://other/path`). Stays valid until `dispose`.
- `async fetch(url: string): Promise<FetchResult>` — The loader's `fetch` for package urls; anything else goes to the real one.
- `forget(pkgId: string): void` — Drop everything cached for a package (its blob URLs): it was replaced by another version.
- `dispose(): void`

### PartRig

*class* · `packages/levels/src/fmdl-motion.ts:71`

```ts
class PartRig
```

- `readonly parts: Map<string, Part>`
- `readonly children: Map<string, PartRig>` — the rigs of the included instances by instance name
- `constructor(readonly root: Node, readonly plan: AssemblyPlan, private clock: () => number = () => 0)`
- `names(): string[]` — every moving part's address, the instances' as `<instance>/<part>`
- `has(address: string): boolean`
- `value(address: string): number` — the value of a part now (radians for a hinge or a rotor, metres for a slider), the moves brought up to the clock
- `limits(address: string): [number, number] | null`
- `kind(address: string): 'hinge' | 'slider' | 'rotor'`
- `set(address: string, v: number): number` — jump to a value, held inside the part's limits; the parts linked to it follow
- `to(address: string, v: number, seconds: number, curve = 'smooth'): Waitable` — go to a value over `seconds` by an ease of the language; the waitable is done when it has arrived or another move of the part took over
- `advance(): void` — bring every move up to the clock (also the instances')
- `moving(): boolean`
- `detach(instance: string): PartRig | undefined` — a rig for an instance that is let go: the whole no longer moves it

### PlacementSource

*class* · `packages/levels/src/placements.ts:286`

```ts
class PlacementSource implements CellSource
```

A `CellSource` that also understands placement lists: a cell whose file is `*.placements.json` is read through `get` (the loader's fetch), its models are loaded through the inner
source, and `instantiate` gives the thin-instance root; any other file goes to the inner source untouched. Streaming, memory budgets and `ready()` need no change.

- `constructor(private readonly inner: CellSource, private readonly scene: BABYLON.Scene, private readonly get: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>, private readonly o: { resolver?: PlacementResolver; warn?: PlacementWarnings; /** the level's materials shared by every list (the manifest's `levelMaterials`) */ levelMaterials?: LevelMaterials; /** how a list's own `levelMaterials` files are read (the package loader's fetch, relative to the list's folder); without it a list can hold its materials inline only */ files?: (listUrl: string) => LevelFiles } = {})`
- `async load(url: string): Promise<void>`
- `levelMaterialsOf(url: string): LevelMaterials | undefined` — the level materials a list draws with: its own when it names some, else the shared ones
- `async read(url: string): Promise<{ file: PlacementFile; urls: Map<string, string> }>` — read and check a list, and load every model it names (once each)
- `async instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }>`
- `release(url: string): void`

### PrefetchService

*class* · `packages/levels/src/prefetch.ts:31`

```ts
class PrefetchService implements Service
```

- `readonly name: "prefetch"`
- `constructor(private readonly levels: LevelService, o: PrefetchOptions = {})`
- `init(world: World): void`
- `near(zone: string, levelId: string, o: { inSeconds?: number } = {}): () => void` — Doors and zones: entering `zone` makes `levelId` wanted (the player is probably about to go there).
- `hint(id: string, o: { inSeconds?: number; from?: 'level' | 'game' } = {}): void` — `id` is wanted. With `inSeconds` (the player will need it in about that long) the start is put off as long as the estimate allows it to still finish in time; without it the download starts at once (when no travel is running).
- `focus(ids: string[]): void` — Only these are wanted from now on: every other background download stops at its next file.
- `cancel(id: string): void`
- `get bandwidth(): number` — The smoothed link speed in bytes per second, 0 when nothing was measured.
- `state(id: string): JobState | 'none'`
- `async idle(id: string): Promise<void>` — Resolves when the level's background download has finished (done, cancelled or failed).
- `status(): { rate: number; jobs: Record<string, { state: JobState; wanted: boolean; bytes: number }> }`
- `dispose(): void`

### ProbeVolume

*class* · `packages/levels/src/probe-volume.ts:118`

```ts
class ProbeVolume
```

The baked grid on the GPU and the plugin on every PBR material of the scene (also those added later).

- `readonly textures: BABYLON.RawTexture3D[]`
- `enabled: boolean`
- `constructor(readonly scene: BABYLON.Scene, readonly def: ProbeVolumeDef, data: ArrayBuffer)`
- `setEnabled(on: boolean)` — Switch the baked light on or off (the materials recompile).
- `dispose()`

