# Levels and packages

# Levels and packages

A level is a folder (or a `.ferret` package) with a glTF scene and a **manifest** that says which nodes are gameplay entities, where the player may start and how the level looks and behaves. Artists move things in Unreal or in the editor; because the manifest refers to nodes **by name**, the wiring survives a re-export.

## The manifest

`manifest.json` (`LevelManifest`) sits next to `scene.glb`:

```json
{
  "version": 1,
  "name": "Yard",
  "scene": "scene.glb",
  "navmesh": "navmesh.bin",
  "defaultSpawn": "gate",
  "spawns": [{ "id": "gate", "position": [0, 0, 8], "yaw": 3.14 }],
  "entities": [
    { "id": "door1", "node": "Door_Main", "behaviour": "Door", "params": { "slide": [0, 2.4, 0] } },
    { "id": "key",   "node": "Key",       "behaviour": "Pickup", "params": { "item": "brass-key" } }
  ],
  "colliders": [{ "node": "Fence_Decor", "collide": false }],
  "environment": { "sun": { "intensity": 3 }, "fog": { "density": 0.01 } },
  "physics": { "capabilities": ["gravity", "friction"], "gravity": { "vector": [0, -9.81, 0] } }
}
```

| Field | Meaning |
|---|---|
| `scene`, `navmesh`, `collision` | file names; a `collision` mesh of simple shapes replaces the visible meshes as solids |
| `collisionChunks` | the solid shapes outside the play area in chunks (`loadRadius`, `unloadRadius`, `chunks`: a file and its bounds each); a chunk is fetched when the player is within `loadRadius` of its bounds and released beyond `unloadRadius`; needs `collision` |
| `navBuild` | how to build the NavMesh when `navmesh.bin` is missing: agent size, climb, slope, cell size; `bounds` (one `{min, max}` box in world metres, or a list: the NavMesh is built inside the union, like several Unreal NavMeshBoundsVolumes); `exclude` (boxes where nothing is walkable, like NavModifierVolumes with the null area; `yaw`, radians about +y, turns a box about its centre) |
| `entities` | `ManifestEntity`: a node to wrap (or a new empty one), a behaviour or several components, params, tags, a transform |
| `spawns`, `defaultSpawn` | where the player may start; the level is entered at `defaultSpawn` when none is named |
| `zones` | named zones for the `ZoneService` |
| `movement` | the player's movement values for this level, over Ferret's defaults |
| `animGraphs` | animation graphs by name |
| `colliders` | per-node overrides: make a node solid or walk-through whatever the export says |
| `materialLooks` | the look of the scene's glTF materials in two scopes: `types` (a model by its uid: all its instances) and `instances` (one object by its uid: wins over the type), each `uid: { <glTF material name>: look }`. A look: `baseColor` (linear), `metallic`, `roughness`, `emissive`, `emissiveStrength`, `normalScale`, `alpha` (`mode`, `cutoff`), `doubleSided`, `maps` (`baseColor`, `normal`, `orm`, `emissive`, `opacity`: a file of the level, a URL or `ferret://`). Uids: glTF node `extras.ferret.uid` (`type`, `instance`, written by the Unreal exporter), else the placement `models` key / library id / glTF mesh name (type) and the entity `id` / placement `actor` / node path (instance); an address two things answer to is ambiguous and the editor refuses to write on it. Put on the scene when the level loads, also on what a streamed cell adds; written by the editor's `edit.material.set`. What is not named stays as the file made it, a level without the block loads as before |
| `levelMaterials` | the level's own materials and KTX2 textures (`materials`, `textures` files, `codec` policy `best` / `light` / `chosen`); see Level materials below |
| `environment` | sun (with `shadows`), ambient light, fog, sky, fixed effects (`EnvironmentDef`) |
| `physics` | realism for this level: materials, pair rules, capabilities and their values (Physics overview (skill `ferret`)) |

`validateManifest` returns a list of problems (path and message); an empty list means the manifest is usable. The same check runs at load time and in the editor.

### Material looks: type and instance

`materialLooks` changes how glTF materials look without touching the file or rebuilding the package. A material is never addressed by its bare name across the scene (the same name stands in many places). The block has two scopes, then the glTF material name **inside that model**:

```json
"materialLooks": {
  "types":     { "/Game/Props/SM_Board": { "MI_Wood": { "roughness": 0.7 } } },
  "instances": { "StaticMeshActor_12":   { "MI_Wood": { "baseColor": [0.4, 0.2, 0.1] } } }
}
```

A **type** look goes to that material of the model in all its instances; an **instance** look goes to one object and wins over the type's, value by value. A mesh with a look gets its own copy of the material, so nothing leaks to other objects that share the file's material. An instance of a shared glTF mesh, or one placed actor of a placement group, that has a look of its own is drawn by a mesh of its own (taken out of the shared draw).

Where a uid comes from (the first the scene has wins, the rest are fallbacks, so a level exported before uids existed still works):

| | from the export | fallbacks, in order |
|---|---|---|
| type | glTF node `extras.ferret.uid.type` (the Unreal asset path) | the `models` key of a placement list, its library id, the glTF mesh name |
| instance | glTF node `extras.ferret.uid.instance` (the actor name) | the manifest entity `id`, the placement `actor`, the node path (names from the scene root, joined with `/`) |

The exporter (`tools/ue-export`) writes them: `ue/gltf.py` records every static mesh component in `uids.json`, `postprocess.mjs --uids uids.json` writes the node extras. Existing exports are not changed by this. The steps that join or instance nodes (`--merge-static`, `--instance-min`) leave those objects without a node of their own, so they lose their per-node uid.

An address that more than one thing answers to (two glTF meshes of one name, two nodes of one path) is **ambiguous**: `edit.material.list` shows it with the reason, the loader applies the look to every match and warns, and `edit.material.set` refuses to write on it. The type list shows a model by its best uid; its other names work as addresses too. Values: `baseColor` (linear 0..1, an optional alpha), `metallic`, `roughness`, `emissive`, `emissiveStrength`, `normalScale`, `alpha` (`mode`, `cutoff`), `doubleSided`, `maps` (`baseColor`, `normal`, `orm`, `emissive`, `opacity`: a file of the level, a URL or `ferret://`). With an `orm` map, `metallic` and `roughness` multiply that map's channels, as in glTF.

### Level materials: the level's own materials and textures

A level may carry its own materials, made from Unreal's graphs, without the asset library. Manifest (or a placement list, same block):

```json
"levelMaterials": { "materials": "materials.json", "textures": "textures.json", "codec": "best" }
```

- `materials.json`: `{ "<material name>": MaterialDef }` (or `{ "format": "ferret-materials/1", "materials": {...} }`). A mesh slot whose glTF material name is a key takes that material by itself; a placement can name one: `materials: { "<slot>": { "material": "<key>" } }`. A name that does not exist warns once and the model keeps its own material. Meshes with a level material ignore their vertex colours as albedo (`vertexMasks` says what they mean).
- `textures.json`: `{ "<stem>": { "srgb": true, "codecs": ["etc1s", "uastc"], "chosen": "etc1s" } }`. A reference in a material is `tex/<stem>`; its file is `tex/<stem>.<codec>.ktx2` (an entry may also list `files` by codec). `srgb` of the entry decides colour or data, whatever the slot.
- `codec` is one policy: `best` (default: UASTC where both exist, else the one that was made), `light` (ETC1S first), `chosen` (the encoder's check).
- What a material may say beyond the glTF fields (`MaterialDef` of `@ferret/assets`): `colourLayers` (`uvScale`, `invert`), `macro`, `groundBlend`, `detailNormal { map, scale, intensity }`, `patternLayer { mask, channel, uvScale, normal, normalScale, occlusion, occlusionChannel }`, `normalScale` (Unreal's FlattenNormal: `normalize(vec3(n.xy * s, 1 - (1 - n.z) * s))`, any `s` from 0 up; Babylon's own scale of x and y is not used), `vertexMasks { opacity, ao }`, `twoSidedFoliage`, `grassWind`, `pixelDepth`, `alpha { mode, cutoff, source }`, `opacityGradient { axis, invert, coordinate }`, `depthFade { opacity, distance }`, `opacity`, `specular`, `video { mediaTexture }` (the picture comes from `LevelMaterialsOptions.video`), and `graph`, the master as an expression tree (`c`, `tex`, `mul`, `add`, `subtract`, `divide`, `lerp`, `oneMinus`, `clamp`, `power`, `cameraDepthFade`, `mask:r|g|b|a`) for baseColor, roughness, metallic, normal, occlusion and emissive. Pictures a field names by `tex/<stem>` itself (a detail map, a pattern's maps, a graph's pictures) need no entry in `masks`.
- The ground the object stands in (`groundBlend`) also takes the landscape's normal and roughness: a landscape's baked ground has a second texture with them (`LandscapeView.virtualSurface`), and a landscape layer may carry a `roughness` picture and `roughnessScale`.
- Foliage: `grassWind` is read by `applyFoliageWind` (`fromMaterials`; its `weightMap { map, channel }` scales the whole flutter by a channel of a picture read in the vertex shader at the first texture coordinates, a master's `lerp(0, SimpleGrassWind, map.g)`); the level emits `level:foliage-wind` with the handle, and `driveFoliageWind` of `@ferret/weather` ties it to the weather's wind.

### Sun shadows and readiness

`environment.sun.shadows` (`{ cascades, distance, mapSize, bias, normalBias, blend, lambda, filter }`) makes the sun cast cascaded shadows; the scene's meshes and the placed groups (thin instances included) cast and receive them. Shadows need no light baked in the files.

`level:ready` waits for the level to be drawable (`settleDrawing`): the level's textures are decoded, every material's program is compiled for the meshes that use it, the shadow generator is compiled, and the instanced groups are ready with their instances. Nothing is drawn in during the first frames.

## The level service

`LevelService` is the level registry and travel. A game registers `LevelDef`s, each with a builder that gets a `LevelContext`. `travel(id)` shows the loading screen, removes the old level, builds the new one, places the player at a spawn and hides the loading screen again; it reports with events (`level:loading`, `level:loaded`, ...). **Everything a builder creates** (nodes, lights, materials, entities) is removed again when the level goes, so levels do not leak into each other.

A `LevelDoor` in the level is the usual way into another one: using it calls `travel`.

### Shadow roles by material type

`assignShadowRoles``(generator, meshes, { casts })` of `@ferret/levels` chooses the roles for a sun shadow generator by what the material is: every mesh whose material is one the shadow map can be read by (PBR, standard, or a multi-material of them: `takesShadows`) receives, and `casts` (default all of them) cast. A terrain's, sea's or sky's own shader is skipped, so a game does not name its meshes one by one.

## Packages

`installPackages` teaches a `LevelService` to play packages: a folder with a manifest, or a single `.ferret` file. `PackageMount` registers the package's levels (the first package's levels as `<id>`, later ones as `<pkgid>/<id>`). Packages are loaded from a URL, from a `File`, or from bytes; the `pkg.*` commands add and remove them at run time (Commands (skill `ferret`)).

A package can be **signed** and its files **encrypted**; the loader checks signatures, hashes and paths before anything is used, and a package that carries code runs under a `CodePolicy`. `validatePackage` runs the package's own checks. See `@ferret/assets` for the format and its security checks.

### Code in a package

A package of kind `library` (or a `game`) may carry code: **one bundled ES module** under `code/`, named in `ferret.json` as `"code": { "entry": "code/index.js" }` (a game may name it as `entry.code`), that exports `install(ctx)`. `installCode` gives a mount a `CodeLoader`; `require(id)` (or the command `pkg.require { id }`) runs a package's code:

1. the code of its dependencies first (each must be open, or opened through the loader's `open` hook, e.g. from the catalog, and fit its version range);
2. the package must pass its `CodePolicy`: it comes from where the game does (`origin`), or it carries a valid signature (from a trusted key when the game keeps a list);
3. the module is read once and checked against its sha256 in the manifest, and **those bytes** are imported (a blob URL), so what runs is what was checked;
4. `install(ctx)` is called once. `ctx` has the `world`, the engine's API as `ctx.ferret`, the package (`ctx.pkg`), `ctx.url(path)` for its files and `ctx.require(dep)` for a dependency's exports. It may return `{ dispose }`.

The module does not import the engine: it is built with `@ferret/*` and Babylon as externals and reaches them through `ctx.ferret` and the global `BABYLON`, so it runs against the **shared engine** (`lib/ferret/ferret.js`, `globalThis.Ferret`). A game that bundles its own copy of the engine passes its API as the loader's `ferret`, or library code is refused with that reason. A page runs one version of a package's code: a module cannot be unloaded, so another version needs a reload. `pkg.loaded` lists what runs; `code:loaded` and `code:failed` are the events. `provides` names what a library's code registers (`capabilities`, `kinds`, `flowSources`, `forms`, `commands`, `levelKeys`), so a level can be resolved to the packages it needs without running them.

## Docked levels

A level of package kind `levels` may carry code and a `docking` block (a `.level`): a mechanic of its own, docked into a parent game that has the player, the camera, the input and the menu. The parent adds a `DockHost` (the engine, a `CodeLoader`, the package mount, the parent's `{ game, root, args, tier }`) and the door's travel builds the level with `dock.enter(def, ctx, packageId)`. `enter` runs the code's `install(ctx)` under the transition; `ctx` is the parent's game seen through a `Scope`, so everything the code adds (commands, services, components, events, observers, input layers) is recorded and taken back when the engine unloads the level, however the player leaves (a door, the menu, `evict`). `install` may return `{ dispose }` for what it made by itself.

`install` may also return `ready`, a promise, when the level goes on loading after `install` (workers, models, the ground round the start, the warm-up of materials). The travel waits for it, with the world running (the parent's pause is lifted for that time and put back), so the transition stays over the picture until the level is whole and nobody can leave a level half made.

Besides what the scope records, `enter` notes the parent's picture before the level's code runs and gives it back when the level goes: the cameras the level made are disposed, `scene.activeCameras` is as it was, render loops the level started on the engine are stopped (a level that runs on its own page with `engine.runRenderLoop` should instead do its per-frame work on `scene.onBeforeRenderObservable` when docked, and leave `world.advance` and `scene.render` to the parent). The camera made current is `DockParent.camera()` when the parent gives one (the parent's own view, whatever was current when the level came), else the camera that was current then, if it still exists.

A service of the parent may offer a view for the code of a docked level: `scopedView(keep)` returns an object that behaves as the service and hands `keep` an undo for everything the level adds through it. `ctx.world.service(name)`, `ctx.world.addService` of a name the parent already holds and `ctx.game.quality` give that view. The audio service forgets the sounds and files the level defines and stops the loops it started; the quality service takes off the knobs the level registers. A service the level itself adds goes with the level, and the quality knobs it offered with `qualityKnobs()` go with it.

The `docking` block says what the level is:

| Field | Meaning |
|---|---|
| `entry` | the level and spawn the parent's door leads to |
| `needs`, `has` | the roles taken from the parent and the roles brought (`player`, `camera`, `input`, `net`, `presence`, `voice`, `account`, `currency`, `hud`, `menu`, `entry`, `exit`, `transition`, `save`); code that makes "its" character or camera gets the parent's through `Roles.takeOver` unless the role is in `has` |
| `namespace` | the prefix of what the level registers (default: the package id) |
| `input` | the level's actions and keys, a layer over the parent's (`InputService.pushLayer`): the later layer wins per action and device kind |
| `ui`, `view` | the level's HUD fragment; the clear colour and other view settings of the game it came from |
| `tiers` | the folders of the quality tiers (as `game.tiers`): a level catalog shows the package through the parent's tier, so a file of `<folder>/<path>` takes the name `<path>` (the docked level itself may lie in `desktop/levels/<id>/`), the root's file is read otherwise; `ctx.url(path)` follows the same rule |
| `packages` | engine packages the parent does not hold and loads from its library on demand (below) |
| `workers`, `kernels` | the level's Web Worker scripts (started with `gameWorker(name)`) and engine kernel modules; they are there while the level is current, and the kernels run in the game's thread when the page starts no kernel workers |

A parent whose engine is inside its own bundle (not an import map) publishes the packages it holds with `shareEngine`; the code loader then rewrites the level's `@ferret/*` imports to read them, so the level and the parent are one engine (one world, one scheduler). A package the parent does not hold is an error that names it, unless the level lists it in `docking.packages`: such a package is a **library package** `engine-<name>` (kind `library`, `code.entry` `code/index.js`, an `install()` that returns nothing), and the level's manifest depends on it (`dependencies: { "engine-terrain": "*" }`). The code loader opens the dependencies of a level before its code (one copy for every level, in the parent's package mount, never inside the parent's bundle and never inlined in the level), the parent's `onLoaded(id, exports)` option of the `CodeLoader` is told when an `engine-<name>` has run, and shares it with `shareEngine({ [name]: exports })`; a library package may itself depend on other `engine-*` packages. `convertGameToLevel` takes the list as its `lazy` option: the imports named there (and not held) become `docking.packages` and the dependencies; any other import the parent does not hold is still refused.

A level's Web Worker (`docking.workers`) is its own thread with no import map and cannot read the parent's bundled engine: a parent that bundles its engine gives `DockParent.engineModule(name)` (a URL of an ES module of the package) or, as Ilion's scene builder does, has the worker's `@ferret/*` imports bundled into the worker file when the level is made.

The engine's own kernel workers are files of the page: a parent that bundles its engine builds `ferret-worker.js` and `ferret-worker-babylon.js` beside its page, and, for the kernels a docked level brings (`docking.kernels`), the kernel modules `kernels/plain.js` and `kernels/babylon.js` into its library folder, which it names as `globalThis.FERRET_LIB` (with `globalThis.FERRET_BABYLON_DIR` for Babylon). `tools/kernels.mjs` builds both (`buildKernelWorkers`, `buildKernelModules`). Without them every kernel runs in the game's thread.

The context of a docked level has `restart()`: it travels to the level again (a page's context reloads the page). A game never reloads the page itself.

`convertGameToLevel` makes a `.level` from a finished game's files (a `.fex`): the code, UI, assets, workers and kernels stay, the signature, `engine`, field of view and touch controls go, and the report lists what was dropped, the roles, the engine packages used and those the parent does not hold. A game whose code reads `location` is refused: a level takes its arguments from `ctx.args`.

## Environment

`applyEnvironment` builds a level's look in the scene (sun, ambient light, fog, sky, effects) and returns an `Environment` to dispose when the level goes. Quality tiers decide which effects are on.
