# Building a scene

# Building a scene

A scene is chosen, placed and told what happens. What it is made of is taken ready; what is new is made as a piece the next scene can take.

## The stages
1. **The scene's plan.** A file of the project that says what the scene is, what it is built from (assets and mechanisms as `id@version`, and the skills used), the stages, and where the work stands.
2. **Find.** Every thing and every mechanism is looked up first: the asset library (`GET api/search?q=<english words>`, mechanisms with `&type=module`), and in a checkout of the engine `docs/mechanics.md`, the index of what the examples already hold.
3. **Make what is missing.** A thing: a model, a material, a sound. A mechanism that neither the engine nor the library has: a module in the game language, with TypeScript externs only for what the language cannot say, with its parameters and its own test (the game language's guide, "A mechanism as a module"). It does not go into the scene's own TypeScript.
4. **The scene as data and programs.** The levels (manifest or the language's forms) say what stands where; the scene's `.fgl` files choose the mechanisms, give them parameters and say what happens on which event. The scene's own part is short.
5. **Change it live.** Looks and places by `edit.*` commands, logic by `edit.game.set`; in a checkout of the engine `ferret dev <example>` keeps the scene open and rebuilds only the example's own code when TypeScript changes. No full build for one edit.
6. **Check each part as it is made.** Every mechanism and every part of the scene has its own short test that runs alone: a headless unit test, or one Ferretic test in the running scene. A change is checked by the test of what it changed. Whole test sets and builds of everything are run only when the person asks.
7. **The final look.** One frame beside the reference (`ferret-frame-check`), or a film for motion.

## Models learn as they are used
A scene often needs a thing to do what its model cannot yet do: an aircraft to take off and land, a ship to set its sails or turn to a course. Before writing it, ask whether it is particular to this game.
- **Not particular:** another scene with the same thing would want it. It goes into the model as a motion (`fmdl.edit.motion`, or a file `motions/<name>.fm` named in `model.json`) with a description, since an agent reads nothing else. What differs from use to use or from model to model is a parameter. What a whole family of models does the same way goes into their abstract parent: its motions run in every model that extends it.
- **Particular:** this game's route, targets, rules and what follows an event. It stays in the scene's own files, which call the model's actions.
- Then the draft is checked, the action gets its own test, the model is packed and sent to the library with its `uid` and a `rubric`. The library issues a new version; a scene that refers to the old `id@version` is not changed.

## Facts in text, looks in pictures
A question of fact is answered by a probe or a test: in view or hidden and by what, how many, on the ground or in the air, errors, a value of the game (`probe.*`, Ferretic's `INVIEW`, `COUNT`, `ONGROUND`, `HEIGHT`, `ERRORS`, `EXPECT`). A picture is taken where looks are the question and for the final comparison.

## Keeping the work light
A long session pays for everything it has seen, again at every step.
- At the end of each stage write into the scene's plan what is done, how it was checked and what comes next, so that a fresh session continues from the file.
- Read long answers a page at a time (`offset`, `count`) and only the part asked about.
- Keep pictures few. A loop with many frames or a film to look through is work whose result is a text answer; where helpers may be started for it, it is theirs, and they answer in text.

## Loading a library item in a game: through the engine, by id@version
A game takes a library item with `AssetLibrary` (`@ferret/levels`): it reads the catalog from the library's URL, fetches only the files of the item, caches them and opens the package itself. **Never download a `.ferret` file into the project and unpack it with a zip of your own** (it copies the package into the game, loses the version and the cache, and skips the signature and size checks).
```ts
import { AssetStore, PersistentCache, detectBackend, RuntimeAssets } from '@ferret/assets';
import { AssetLibrary } from '@ferret/levels';
const store = new AssetStore({ cache: new PersistentCache(await detectBackend()), base: document.baseURI });
const runtime = world.addService(new RuntimeAssets({ store, models: ctx.mount.assets, mount: ctx.mount }));
const lib = world.addService(new AssetLibrary({ store, mount: ctx.mount, assets: runtime, policy: { allowUnsigned: true }, tier: ctx.tier }));
await lib.open('https://builder.ferret3d.com/ferret/library/catalog.json');
const tree = await lib.model('u-f8e64d8c7982@1.0.0', { parent: holder });   // a static model; await tree.model.ready; place many with GPU instancing (placements)
const grass = await lib.texture('<texture id>@1.0.0');                      // { basecolor, normal, orm, ... } as Babylon textures
const hit = await lib.sound(...); const fx = await lib.flipbook('<id>@1.0.0'); const mod = await lib.module('<id>@1.0.0');
```
A level that must hold to the versions lists them in `ferret.json` `dependencies` and `catalogs`; the game then passes them as `pins`. `lib.entry(ref)`, `lib.list({type, tags})` and `lib.find({q})` answer what the catalog holds.

**An item of type `fmdl`** (a rigged or detailed model: street trees, ships, guns; the card says `fmdl`, and `lib.model` refuses it: it is for type `model`) is opened as a model package and put on the stage; the package id is `lib.entry(ref).package`:
```ts
import { modelSourceOf, openCatalogPackage, resolveModel, catalogLoader } from '@ferret/assets';
import { FmdlModel, ModelStage } from '@ferret/levels';
const catalog = await lib.open(url);                                        // the Catalog it returns is what the next calls take
const pkg = lib.entry('u-3571aad3c839@1.1.0').package;
const r = await resolveModel(await modelSourceOf(await openCatalogPackage(store, catalog, pkg)), catalogLoader(store, [catalog]));
if (!r.resolved || !r.read) throw new Error(JSON.stringify(r.issues));
const model = await FmdlModel.load(r.resolved, r.read, scene, { tier: ctx.tier });   // once per item
const stage = world.addService(new ModelStage({ scene })); stage.addModel(model.stageModel());   // once per game
const a = stage.appear(pkgModelId, { name: 'tree-0', at: [x, 0, z] });          // as many copies as needed; a.root is the TransformNode (rotation.y, scaling)
```
`pkgModelId` is the id the stage names the model by (`stage.modelIds()`). If a library model does not load, read the error (`viewer_log`), fix the call; never rebuild the thing by hand from textures or fetch it from the web while the library has it.
