FERRETGame engine over Babylon.js
Ferret

@ferret/levels

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

471 exports · source in packages/levels/src

Classes

AssetLibrary class

class AssetLibrary implements Service
readonly name: "asset-library"
qualityBusy(): booleanfor 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): LibraryEntryAn 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 | undefinedAbsolute 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(): PlacementResolverWhat 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(): voidFree what the library made: materials, textures, characters. Packages stay open (they cost the mount nothing but the index).
dispose(): void

packages/levels/src/library.ts:165

CatalogClient class

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>

packages/levels/src/catalog.ts:46

ClipPlayer class

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[] } = {}): Waitableplay 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): voidone rendered frame
dispose(): void

packages/levels/src/fmdl-motion.ts:223

CodeLoader class

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 | undefinedThe 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 disposes 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(): voidCall the dispose that install returned, newest first (the modules themselves stay: a page cannot unload them).

packages/levels/src/code.ts:70

CollisionChunks class

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

packages/levels/src/collision-chunks.ts:32

DecalBuffer class

class DecalBuffer
readonly target: BABYLON.RenderTargetTexture
constructor(private readonly scene: BABYLON.Scene)
get count(): numberthe decal meshes drawn into the buffer now
dispose(): void

packages/levels/src/decal-buffer.ts:17

DependencyError class

class DependencyError extends Error
constructor(message: string, readonly id: string, readonly range: string, readonly tried: { url: string; error?: string }[])

packages/levels/src/dependencies.ts:36

DependencyResolver class

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.

packages/levels/src/dependencies.ts:43

DistanceFieldTextures class

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

packages/levels/src/distance-field.ts:74

DockHost class

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: Rolesthe roles service; made by the host if the parent has not added one
entered: numberhow many levels were docked and ended, for the tests that count round trips
left: number
constructor(private o: DockHostOptions)
get current(): string | undefinedthe 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.

packages/levels/src/dock.ts:74

FmdlModel class

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(): voidRelease 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): AssemblyPlanthe plan of a level (the device tier applied)
build(level: number, name = `${this.resolved.id}:${level}`): BABYLON.TransformNodeThe 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.

packages/levels/src/fmdl.ts:46

FogVeil class

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: numberextinction 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(): numberthe 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()

packages/levels/src/fog-veil.ts:58

HeightFogMaterials class

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()

packages/levels/src/height-fog-material.ts:102

LevelMaterials class

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): voidadd 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): voida 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

packages/levels/src/level-materials.ts:212

LevelService class

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: TransitionRegistrythe 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): booleanRemove a level from the registry (a catalog that no longer lists it). The level being played is not touched.
replace(def: LevelDef): thisRegister, 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): thisAn 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): thisEntities that go with the player to every level.
async travel(id: string, opts: TravelOptions = {}): Promise<LevelReport>
spawn(id?: string): SpawnPoint | nullThe 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(): numberhow 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 | nullRestore what saveData made; returns the level to travel to (or null).
dispose()

packages/levels/src/levels.ts:114

LightBudget class

class LightBudget
readonly def: LightBudgetDef
onChange?: (entered: number[], left: number[]) => voidcalled after a re-ranking when real lights changed hands: indices that entered and left the pool
onSounds?: (start: number[], stop: number[]) => voidcalled 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(): booleanis 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): numberthe 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()

packages/levels/src/light-budget.ts:192

LookPlugin class

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.

packages/levels/src/material-models.ts:451

ModelCatalogue class

class ModelCatalogue
add(resolved: ResolvedModel, authorText = ''): thisa 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

packages/levels/src/fmdl-catalogue.ts:25

ModelCode class

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): thisMake every function (those loaded later too) a word of the motion runtime: (name instance args...).
link(game: ModelCodeGame): () => voidGive 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 | undefinedthe instance of an actor that has code
step(dt: number): voidthe step hooks of every instance, in the order they appeared (the parent's module first)
dispose(): void

packages/levels/src/fmdl-code.ts:90

ModelDocks class

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[] }): voidMake 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.

packages/levels/src/fmdl-docks.ts:69

ModelPrograms class

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): voidthrows, 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> = {}): Programthe 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 }

packages/levels/src/fmdl-programs.ts:33

ModelStage class

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): () => voidtell 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): Actorput an already built model on the stage under a name (a model the game made itself)
actor(name: string): ActorAn 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 } = {}): Actora model appears: built on level, placed at at, named name (default <id>#<n>)
vanish(name: string): voidtake 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 } = {}): ClipPlayerput 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(): NodeHostthe nodes of the actors as handles of the language (move-along, turn-to)

packages/levels/src/fmdl-motion.ts:332

OcclusionCulling class

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

packages/levels/src/occlusion-culling.ts:21

OceanView class

class OceanView
readonly mesh: BABYLON.Mesh
readonly material: BABYLON.ShaderMaterial
get ready(): booleanhas 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()

packages/levels/src/ocean.ts:209

PackageMount class

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: MountAssetsgive this to the level loader instead of the asset cache (installPackages does)
readonly loader: PackageLoaderOptionsthe 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 | nullThe 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): voidDrop everything cached for a package (its blob URLs): it was replaced by another version.
dispose(): void

packages/levels/src/ferret.ts:36

PartRig class

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): numberthe 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): numberjump to a value, held inside the part's limits; the parts linked to it follow
to(address: string, v: number, seconds: number, curve = 'smooth'): Waitablego 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(): voidbring every move up to the clock (also the instances')
moving(): boolean
detach(instance: string): PartRig | undefineda rig for an instance that is let go: the whole no longer moves it

packages/levels/src/fmdl-motion.ts:71

PlacementSource class

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 | undefinedthe 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

packages/levels/src/placements.ts:286

PrefetchService class

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 } = {}): () => voidDoors and zones: entering zone makes levelId wanted (the player is probably about to go there).
hint(id: string, o: { inSeconds?: number; from?: 'level' | 'game' } = {}): voidid 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[]): voidOnly these are wanted from now on: every other background download stops at its next file.
cancel(id: string): void
get bandwidth(): numberThe 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

packages/levels/src/prefetch.ts:31

ProbeVolume class

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()

packages/levels/src/probe-volume.ts:118

ProgramPlugin class

class ProgramPlugin extends BABYLON.MaterialPluginBase
active: boolean
constructor(material: BABYLON.Material, built: BuiltProgram)
get program(): MaterialProgram
getClassName()Gets the current class name useful for serialization or dynamic coding.
deactivate()
prepareDefinesBeforeAttributes(defines: BABYLON.MaterialDefines)Sets the defines for the next rendering. Called before PrepareDefinesForAttributes is called.
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, _engine: BABYLON.AbstractEngine, subMesh: BABYLON.SubMesh)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.

packages/levels/src/material-program.ts:296

PropellerView class

class PropellerView
disc: BABYLON.TransformNode | nullthe disc, once made (the first frame it is wanted)
hidden: booleanboth blades and disc hidden (a view from the cockpit that does not want them)
constructor(private scene: BABYLON.Scene, readonly props: BABYLON.TransformNode[], o: PropellerViewOptions = {})
setLayerMask(mask: number)the layer mask the disc is drawn on (a cockpit camera's layer; the blades' meshes are the caller's)
update(omega: number | readonly number[], dt: number)call each frame: omega the shaft speed of the engine behind each propeller node (rad/s; one number for all), dt the frame's time
dispose()

packages/levels/src/propeller.ts:27

RuntimeAssets class

class RuntimeAssets implements Service
readonly name: "runtime-assets"
constructor(private readonly o: RuntimeAssetsOptions)
init(world: World): void
async bytes(ref: string, o: Pick<RequireOptions, 'priority' | 'signal' | 'sha256' | 'size' | 'pkg'> = {}): Promise<Uint8Array>The verified bytes of any reference.
async url(ref: string, o: Pick<RequireOptions, 'priority' | 'signal' | 'sha256' | 'size' | 'pkg'> = {}): Promise<string>A URL the engine's loaders (Audio, Texture, video) can read, for any reference.
status(ref: string): string
model(ref: string, o: ModelOptions = {}): ModelHandleAsk for a model. Returns at once with the placeholder in place.
get scene(): BABYLON.Scene
get events()
get models()
forget(h: ModelHandleImpl): void
async modelUrl(ref: string, o: ModelOptions): Promise<string>
dispose(): void

packages/levels/src/runtime.ts:55

ScreenDecals class

class ScreenDecals
readonly colour: BABYLON.RenderTargetTexturethe buffer of colour (rgb premultiplied by the opacity) and opacity
readonly surface: BABYLON.RenderTargetTexturethe buffer of roughness, metallic (premultiplied) and opacity
readonly pass: { value: number; }which of the two passes is being drawn: the decal materials read it each time they are bound
constructor(private readonly scene: BABYLON.Scene)
get count(): numberthe boxes drawn now
add(box: BABYLON.AbstractMesh): voidput a decal's box mesh in: it is taken out of the camera's picture and drawn only into the buffers
dispose(): void

packages/levels/src/screen-decals.ts:43

SequencePlayer class

class SequencePlayer

Plays one sequence on the scene. update(dt) once per frame.

time: number
playing: boolean
finished: numberhow many times it has ended (a looping one counts each wrap)
constructor(readonly def: SequenceDef, private scene: BABYLON.Scene, private find: (name: string) => BABYLON.TransformNode | null, private emit: (name: string, data: unknown) => void = () => undefined)
play(from = 0)
stop()
update(dt: number)
apply()

packages/levels/src/sequence.ts:92

ShipWake class

class ShipWake
readonly mesh: BABYLON.Mesh
constructor(scene: BABYLON.Scene, name: string, private pose: (t: number) => { x: number; z: number; dx: number; dz: number }, o: ShipWakeOptions)
update(t: number)call each frame with the time the ship's pose is read at
dispose()

packages/levels/src/wake.ts:42

SnapshotRendering class

class SnapshotRendering implements Service
readonly name: "snapshot-rendering"
stats: { records: number; invalidations: number; }how many times the draw list changed under a recording, for the debug view and tests
constructor(private o: SnapshotOptions = {})
get supported(): boolean
get active(): booleanis a snapshot recorded or being replayed now
init(world: World): void
enable(): voidstart snapshotting (a no-op on WebGL2)
disable(): void
invalidate(): voidthe draw list changed: draw normally for a few frames, then record again
qualityKnobs(): QualityKnob[]
dispose(): void

packages/levels/src/snapshot-rendering.ts:24

StillCameraFreeze class

class StillCameraFreeze implements Service

The CPU knob of the plan-OFFLOAD G1: while the camera has not moved for stillFrames frames (a dialogue, a cutscene, a menu over the scene) the list of active meshes is frozen (scene.freezeActiveMeshes(): no frustum test of thousands of meshes a frame) and given back the frame the camera moves or the scene's mesh list changes. Meshes that move keep drawing at their new places; what a freeze cannot see is a mesh entering the view while the camera is still, so the knob is the regulator's last resort among the CPU ones (visibility 0.6), and the list is taken anew every refreshFrames frames (a mesh switched on or shown meanwhile appears then). A freeze the scene carries out later (it waits until it is ready) is taken back if it is no longer wanted. Level 0 (the default) is off, level 1 is on.

readonly name: "still-camera-freeze"
stillFrames: number
refreshFrames: numberhow many frames a frozen list lives before it is taken anew
init(world: World): void
attach(scene: BABYLON.Scene): void
qualityKnobs(): QualityKnob[]
dispose(): void

packages/levels/src/still-camera.ts:21

StreamingDebugView class

class StreamingDebugView
constructor(private readonly world: World, private readonly sv: StreamingService, private readonly block: () => { cells: Record<string, { bounds: number[] }> } | null)
get visible(): boolean
show(): void
hide(): void

packages/levels/src/streaming-debug.ts:13

StreamingService class

class StreamingService implements Service
readonly name: "streaming"
tuning: { radiusScale: number; budgetScale: number; memoryScale: number; }Runtime scales on top of the options
init(world: World): void
get active(): boolean
blockDef(): StreamingBlock | nullthe block being streamed (for the debug view and tools)
begin(block: StreamingBlock, source: CellSource, o: StreamingOptions): voidStart streaming a level. The cells within loadRadius of the focus are what ready() waits for.
end(): voidStop streaming and release everything this service added. Called when the level is unloaded.
cellLevel(id: string): number | undefinedthe variant resident (or being made) now, for tools and tests: 0 is the full file; undefined for an unknown cell
memory(): { resident: number; cap: number | null; pinned: number }Bytes the resident cells take against the cap (pinned ones are counted and never evicted).
gate(): string[]The cells that must be in before the level is playable: those within loadRadius of the focus.
ready(): Promise<void>Resolves when every cell of the gate is loaded (or has failed: a missing far cell must not hold the player).
update(_dt = 0): voidCalled once per rendered frame.
async loadBundle(id: string): Promise<void>Load a bundle (the files an interior needs) now; resolves when it is in. Loading it twice is one load.
bundleState(id: string): State | undefined
bundleRoots(id: string): BABYLON.TransformNode[]
hasCell(id: string): boolean
cellRoot(id: string): BABYLON.TransformNode | nullthe root of a resident cell's instance (what an entity that needs the cell looks its node up in), else null
cellState(id: string): State | undefined
snapshot(): { cells: Record<string, State>; bundles: Record<string, State> }
dispose(): void

packages/levels/src/streaming.ts:67

SwarmSim class

class SwarmSim
readonly pos: Float32Arrayx y z of every agent, flat
readonly vel: Float32Array
readonly scale: Float32Array
centre: [number, number, number]
constructor(readonly def: SwarmDef)
step(dt: number, wind?: { intensity: number; direction: [number, number] })

packages/levels/src/swarm.ts:69

TransitionRegistry class

class TransitionRegistry
register(name: string, t: Transition | (() => Transition)): thisRegister a transition by name: one object, or a function that makes a fresh one per travel. Registering default sets what is used when nothing else is chosen.
has(name: string): boolean
names(): string[]
choose(fn: TransitionChooser): this(from, to, plan) => name: decides per travel (a theme in to.tags, a short wait in plan.cached).
pick(from: LevelDef | null, to: LevelDef, plan: LevelPlan, named?: string): stringThe name to use: the one the call named, else the chooser's, else default, else the bar. A name that is not registered falls back to the bar.
create(name: string): Transition

packages/levels/src/transitions.ts:55

TransitionRun class

class TransitionRun

A transition with the guarantees of 5.1 around it: enter has 2 s to be on screen; a throw anywhere is logged and the bar takes over; a broken transition never blocks the travel. After a fallback every further call is a no-op and name reads bar.

name: string
fellBack: string | nullset when the game's transition failed and the engine's bar replaced it
constructor(readonly wanted: string, private readonly t: Transition, private readonly ctx: TransitionContext, private readonly o: RunOptions = {})
async enter(): Promise<void>
update(p: TransitionProgress): void
async ready(): Promise<void>Resolves when the game lets the player in. A cancel does not hold the player in a transition that waits for a button.
async fail(err: StreamError): Promise<boolean>True when the transition showed the failure itself.
dispose(): void

packages/levels/src/transitions.ts:91

TravelAborted class

class TravelAborted extends Error

The player (or the menu) cancelled the travel.

constructor(readonly id: string)

packages/levels/src/levels.ts:66

VisibilityService class

class VisibilityService implements Service

Draws only what the player can see from the grid cell they stand in (VisibilityBlock). A lookup when the cell changes, nothing per frame otherwise. Cells streamed in later are covered too (the nodes are looked for again when a cell arrives). A cell the table does not know shows everything.

readonly name: "visibility"
stats: { changes: number; hiddenGroups: number; hiddenMeshes: number; }counts for tests and the debug view
init(world: World): void
get active(): boolean
current(): string | null
isShown(group: string): boolean
begin(block: VisibilityBlock, root: BABYLON.Node, o: VisibilityOptions = {}): void
end(): void
dispose(): void
keyAt(x: number, z: number): stringThe grid cell of a point.
update(_dt = 0): voidCalled once per rendered frame.

packages/levels/src/visibility.ts:14

Functions

acquireDepthRenderer function

function acquireDepthRenderer(scene: BABYLON.Scene, cam: BABYLON.Nullable<BABYLON.Camera>): BABYLON.DepthRenderer | null

the scene's depth pass, drawn while a material asks for it (the glow's DepthFade reads it)

packages/levels/src/material-models.ts:439

actorMatrix function

function actorMatrix(a: Placement): BABYLON.Matrix

The actor's transform as a matrix (scale, then rotation, then position).

packages/levels/src/placements.ts:147

addScreenDecals function

async function addScreenDecals(scene: BABYLON.Scene, mats: LevelMaterials, specs: readonly ScreenDecalSpec[]): Promise<{ count: number; dispose(): void }>

The decals of a level in the scene: for each spec a box mesh with the decal's material (a master of the level carried whole, made as a projected decal), placed by its matrix. Returns what disposes them. The meshes are made one by one (a clone of one cube shares its geometry): each has its own matrix, which its material reads.

packages/levels/src/screen-decals.ts:119

alphaAt function

function alphaAt(keys: Array<[number, number]>, t: number): number

the alpha at the normalised life t (linear between the keys; clamped at both ends)

packages/levels/src/ambient-particles.ts:59

ambientCapacity function

function ambientCapacity: (d: Pick<AmbientParticlesDef, "rate" | "lifetime">) => number

how many particles are alive at once: rate x the longest life (plus a margin)

packages/levels/src/ambient-particles.ts:56

applyEnvironment function

function applyEnvironment(scene: BABYLON.Scene, def: EnvironmentDef, name = 'env', o: { /** the game's shared clock in seconds (the world's time): waves are drawn from it, so every peer sees the same sea at the same moment */ clock?: () => number; /** a height field of what moves a river (see `WaterResponseMap`) */ waterResponse?: WaterResponseMap; /** parts the game draws itself: left out */ skip?: Array<'sun' | 'ambient' | 'fog' | 'sky' | 'water'>; /** makes an effect of the vfx catalogue for an `effects` entry that names one (`vfx`); without it such an entry is the simple fire */ vfx?: (name: string, at: Vec3, scale: number, params?: Record<string, number>) => EnvironmentVfx } = {}): Environment

Build the environment in a scene. Dispose it when the level unloads.

packages/levels/src/environment.ts:286

applyFoliageWind function

function applyFoliageWind(scene: BABYLON.Scene, def: FoliageWindDef, o: { clock?: () => number; flowMap?: FoliageFlowMap } = {}): FoliageWindHandle

packages/levels/src/foliage-wind.ts:249

applyLandscape function

async function applyLandscape(scene: BABYLON.Scene, def: LandscapeDef, o: ApplyLandscapeOptions): Promise<LandscapeView>

Put a landscape's layer blend on its mesh's material, mark a far plane, and bake the virtual texture and hand it to the props. A problem (a texture that does not load, a mesh that is not there) is a warning in the view, never a thrown error: the level still loads with the baked look.

packages/levels/src/landscape.ts:754

applyMaterialLook function

function applyMaterialLook(material: BABYLON.Material, look: LookDef, o: ApplyLookOptions): () => void

Put the model on a PBR material; returns the function that takes it off again. A material with none of its fields is left as it is.

packages/levels/src/material-models.ts:610

applyMaterialLooks function

function applyMaterialLooks(scene: BABYLON.Scene, initial: MaterialLooks | undefined, o: MaterialLooksOptions = {}): MaterialLooksHandle

packages/levels/src/material-look.ts:200

applyMaterialProgram function

function applyMaterialProgram(material: BABYLON.Material, program: MaterialProgram, o: ApplyProgramOptions): () => void

Put a program on a PBR material; returns the function that takes it off again.

packages/levels/src/material-program.ts:471

applyMaterialScale function

function applyMaterialScale(scene: BABYLON.Scene, defs: MaterialScaleDef[]): { dispose(): void; flush(force?: boolean): void; scaled: number; meshesCleared: number }

packages/levels/src/material-scale.ts:42

applySunShadows function

function applySunShadows(sun: BABYLON.DirectionalLight, def: SunShadowsDef = {}): SunShadows

Shadows from the sun on the meshes handed to add. A mesh of a material with an opacity mask or alpha test casts by its mask.

packages/levels/src/sun-shadows.ts:57

assignShadowRoles function

function assignShadowRoles(generator: Pick<BABYLON.ShadowGenerator, 'addShadowCaster'>, meshes: Iterable<BABYLON.AbstractMesh>, o: ShadowRoleOptions = {}): ShadowRoleResult

One function that chooses the roles of the meshes of a scene for a shadow generator: every mesh whose material is of a type that takes shadows (takesShadows) receives them, and those casts picks (default all of them) cast. Meshes with no vertices or a material of another type (the ground's and the sea's own shaders) are skipped.

packages/levels/src/sun-shadows.ts:116

atmosphereColours function

function atmosphereColours(t: AtmosphereTable, sunScale = 1, sunColor: Vec3 = [1, 1, 1]): { top: Vec3; horizon: Vec3; ground: Vec3 }

colours of the sky that the rest of the environment uses (water, reflection, fog): the zenith, the horizon away from the sun, the ground

packages/levels/src/atmosphere.ts:190

bendOffset function

function bendOffset(p: V3, player: V3, distance: number, strength: number, v: number, radius = 0): V3

MF_Collusion (Unreal cm): grass pushed away from player

packages/levels/src/foliage-wind.ts:93

bindPropulsors function

function bindPropulsors(actor: Actor, o: PropulsorBindOptions): PropulsorSet | undefined

Bind the propulsors of actor. Returns the set (call update() once a step after the actuators) or undefined when the model declares none.

packages/levels/src/fmdl-propulsors.ts:38

blendWeights function

function blendWeights(weights: number[], heights: number[] = [], heightBlend: number[] = []): number[]

Weights of the layers at a point -> the weights the material uses: normalised to sum 1 (no paint at all = the first layer), then height blended.

packages/levels/src/landscape.ts:210

bloomWeight function

function bloomWeight(intensity: number): number

packages/levels/src/environment.ts:147

buildAmbientParticles function

function buildAmbientParticles(scene: BABYLON.Scene, d: AmbientParticlesDef, texture: BABYLON.Texture, name: string): { ps: BABYLON.ParticleSystem; at: BABYLON.Vector3; radius: number }

the Babylon side; texture is any soft sprite

packages/levels/src/ambient-particles.ts:66

buildAtmosphereTable function

function buildAtmosphereTable(def: AtmosphereDef | undefined, sunElevation: number, n = LUT_SIZE): AtmosphereTable

Fill the table for the sun at sunElevation radians above the observer's horizon.

packages/levels/src/atmosphere.ts:118

buildPlacements function

async function buildPlacements(file: PlacementFile, o: PlacementBuildOptions): Promise<PlacementInstance>

Make the instances of a placement list: one clone of each mesh of a model per group, carrying the group's actors as thin instances.

packages/levels/src/placements.ts:187

buildSwarm function

function buildSwarm(scene: BABYLON.Scene, d: SwarmDef, source: BABYLON.Mesh, name: string, wind?: () => { intensity: number; direction: [number, number] }, follow?: BABYLON.TransformNode)

one mesh drawn once per agent (instances), turned along its flight; returns what to update and dispose

packages/levels/src/swarm.ts:114

buildWater function

function buildWater(scene: BABYLON.Scene, def: WaterDef, o: { response?: WaterResponseMap; name: string; skyTop: Vec3; skyHorizon: Vec3; sunDir: Vec3; sunColor: Vec3; /** the game's shared clock in seconds: with it every peer draws the same waves at the same moment (default: this surface's own time since it was built) */ clock?: () => number }): WaterSurfaceView

Build one water surface in a scene. sky and sun come from the rest of the environment.

packages/levels/src/water.ts:395

captureRoomReflection function

function captureRoomReflection(scene: BABYLON.Scene, def: RoomReflectionDef, o: { name?: string; fallbackBox?: { center: Vec3; size: Vec3 }; onError?: (m: string) => void } = {}): RoomReflection

Draws the level into a cube map once the scene is ready and installs it as scene.environmentTexture. The probe draws the meshes as they are, with the image processing of the scene's materials (exposure, curve), so the reflected light is divided by the exposure to land at the picture's own brightness. fallbackBox is the probe grid's bounds, used when the definition has no box of its own.

packages/levels/src/room-reflection.ts:56

catalogUrls function

function catalogUrls(list: readonly string[] | undefined, base: string): string[]

The catalog URLs a manifest names, made absolute against the URL the package was loaded from. Bad entries are skipped (validation reports them).

packages/levels/src/dependencies.ts:30

cellDistance function

function cellDistance(b: StreamCellDef['bounds'], x: number, z: number): number

Distance on the ground plane from a point to a cell's box (0 inside it).

packages/levels/src/streaming.ts:62

checkDistanceField function

function checkDistanceField(h: unknown, bytes?: Uint8Array): string | undefined

what is wrong with a distance field, or undefined

packages/levels/src/distance-field.ts:43

compileProgram function

function compileProgram(p: MaterialProgram, o: { srgb?: readonly number[]; unlit?: boolean; arrays?: readonly (readonly number[])[]; screenDecal?: boolean } = {}): CompiledProgram

The GLSL of a program. srgb lists the indices of its textures that are colour and are decoded in the shader; unlit the material has no lighting.

packages/levels/src/material-program.ts:60

createKtx2Array function

function createKtx2Array(scene: BABYLON.Scene, layers: readonly DecodedKtx2[], o: { name?: string; anisotropy?: number } = {}): BABYLON.BaseTexture

One array texture of layers (all with the same layout; layer k = layers[k]). Trilinear, repeat, the given anisotropy. The texture owns its GL object: dispose() frees it.

packages/levels/src/texture-array.ts:38

createSkyProbe function

function createSkyProbe(scene: BABYLON.Scene, meshes: BABYLON.AbstractMesh[], o: { size?: number; every?: number; at?: [number, number, number] } = {}): BABYLON.RenderTargetTexture

A cube map of the sky for water to mirror: renders meshes (the sky dome, cloud layers, anything far away) into a cube from at (default: the camera, so a dome that follows the camera is seen from inside) and refreshes it every every frames (default 30: clouds drift slowly; 0 renders once). Give the result to WaterSurfaceView.setReflection.

packages/levels/src/water.ts:266

curl function

function curl(x: number, y: number, z: number, seed = 0): [number, number, number]

a smooth divergence-free vector field (the curl of a vector potential made of sines), in [-~1.7, ~1.7]; the same point gives the same vector

packages/levels/src/swarm.ts:60

decalBoxMatrix function

function decalBoxMatrix(d: Pick<ScreenDecalSpec, 'position' | 'axes' | 'half'>): BABYLON.Matrix

the world matrix of a unit cube [-1, 1]^3 that is the decal's box (columns: the axes scaled by the half extents, then the position)

packages/levels/src/screen-decals.ts:33

decalBufferOf function

function decalBufferOf(scene: BABYLON.Scene, create = false): DecalBuffer | undefined

The scene's decal buffer; with create, made if there is none (the rendertarget part of Babylon must be loaded), and every material is told to look for it.

packages/levels/src/decal-buffer.ts:62

decodeKtx2 function

async function decodeKtx2(engine: BABYLON.AbstractEngine, bytes: Uint8Array): Promise<DecodedKtx2>

Decode a KTX2 file the way Babylon's own texture loader does (same decoder, same worker pool, the formats this GPU takes).

packages/levels/src/texture-array.ts:14

deepColour function

function deepColour(absorption: Vec3 = [110, 158, 350], scattering: Vec3 = [0.05, 0.05, 0.05]): Vec3

The deep colour of the water from Unreal's absorption distances and scattering (linear RGB).

packages/levels/src/water.ts:141

defaultLibraryUrl function

function defaultLibraryUrl(): string

packages/levels/src/library.ts:159

distanceFieldSizes function

function distanceFieldSizes(h: DistanceFieldHeader): { table: number; atlas: number; texels: [number, number, number] }

the bytes the data of a header holds: the table, then the atlas

packages/levels/src/distance-field.ts:37

distanceFieldUniforms function

function distanceFieldUniforms(h: DistanceFieldHeader): [string, number, number, number, number][]

the uniforms of the lookup, in this order (material-program.ts declares and fills them)

packages/levels/src/distance-field.ts:93

distanceToBounds function

function distanceToBounds(b: CollisionChunkDef['bounds'], x: number, y: number, z: number): number

Distance from a point to a box (0 inside).

packages/levels/src/collision-chunks.ts:14

ditherValue function

function ditherValue(x: number, y: number, noise: number, threshold = PIXEL_DEPTH_THRESHOLD): number

DitherTemporalAA's value for a pixel (Unreal's graph with no temporal sample; noise is the noise texture's red channel, 0..1): threshold + (mod(x + 2y, 5) + noise) * 0.16665.

packages/levels/src/material-models.ts:90

dockPhysicsOf function

function dockPhysicsOf(host: { bodies: Iterable<{ node: Node; body: unknown }>; kernel: { addConstraint(d: any): any; removeConstraint(c: any): void; setPosition(b: any, p: Vec3): void; onConstraintBreak(cb: (c: any) => void): () => void } }): DockPhysics

the kernel of a physics host as the docks' physics

packages/levels/src/fmdl-docks.ts:250

effectiveFogDensity function

function effectiveFogDensity(f: HeightFogDef, h: number): number

the flat density Babylon's exponential fog takes for a view at height h: the density of the air there (a ray along the ground is what a walker sees most)

packages/levels/src/height-fog.ts:44

engineImports function

function engineImports(text: string): string[]

The package names the code of a module imports from the shared engine (@ferret/<name>), in order of appearance.

packages/levels/src/dock-engine.ts:17

ensureLocalBounds function

function ensureLocalBounds(mesh: BABYLON.AbstractMesh): boolean

The bounds of a mesh's own vertices (Unreal's ObjectLocalBounds), as two constant vertex attributes of the source mesh so every instance reads them.

packages/levels/src/material-program.ts:253

ensureObjectHeight function

function ensureObjectHeight(mesh: BABYLON.AbstractMesh): boolean

The height of a mesh's own local bounds along y, metres: Unreal's ObjectBounds (its z). Written once as a constant vertex attribute of the source mesh so the shader can read it per object, thin instances included.

packages/levels/src/material-models.ts:412

environmentBabylonParts function

function environmentBabylonParts(env?: EnvironmentDef): string[]

The Babylon parts a level's environment needs beyond the core: the post-processing pipeline for bloom, particles for fire.

packages/levels/src/environment.ts:138

flickerFactor function

function flickerFactor(l: Pick<BudgetLight, 'flicker'>, phase: number, t: number): number

the multiplier of a light's intensity at time t seconds

packages/levels/src/light-budget.ts:142

flickerValue function

function flickerValue(phase: number, t: number): number

a smooth repeatable noise in 0..1: two sines of unrelated rate, per light phase (no random state, so tests and replays agree)

packages/levels/src/light-budget.ts:137

fogDensityAt function

function fogDensityAt(f: HeightFogDef, h: number): number

extinction per metre at height h

packages/levels/src/height-fog.ts:26

fogOpticalDepth function

function fogOpticalDepth(f: HeightFogDef, h0: number, dirY: number, dist: number): number

Optical depth of a straight ray from a point at height h0 going dist metres along a direction with vertical component dirY (-1..1): the integral of the density, exact for each layer. The transmittance is exp(-depth).

packages/levels/src/height-fog.ts:34

fogVeilOf function

function fogVeilOf(scene: BABYLON.Scene): FogVeil | undefined

the veil of the scene's environment, if its fog has one (for shaders of their own: the sky, the sea)

packages/levels/src/fog-veil.ts:86

freezeStatic function

function freezeStatic(world: World, scene: BABYLON.Scene, o: FreezeOptions): number

freeze every static mesh of the level; returns how many were frozen

packages/levels/src/static-freeze.ts:35

gammaOfLinear function

function gammaOfLinear: (k: number) => number

the albedo colour is a gamma colour for the shader: a linear multiplier k is k^(1/2.2) of it

packages/levels/src/material-scale.ts:38

gradientFaces function

function gradientFaces(top: Vec3, horizon: Vec3, ground: Vec3, n = 8): Uint8Array[]

A cube map of the sky's gradient (ground below the horizon, top above): every face a few texels, smooth at every mip level, so any roughness reads it.

packages/levels/src/environment.ts:203

graphGlsl function

function graphGlsl(e: GraphExpr, smp: (name: string, uv: string) => string, depthCm = 'ferretLkDepthCm'): Typed

one node as a GLSL expression, float (t 1) or vec3 (t 3); smp reads a named picture at a uv; depthCm is the pixel's distance along the view axis in centimetres

packages/levels/src/material-models.ts:224

graphMeanColour function

function graphMeanColour(n: any): [number, number, number] | undefined

The colour a master's colour graph gives where its pictures read a middle value (0.5): constants, lerp, power, add, mul. Undefined for anything else.

packages/levels/src/level-materials.ts:190

groundBlendAttributes function

function groundBlendAttributes(w: number, own: { metallic: number; roughness: number; occlusion: number }, ground: { roughness: number }): { metallic: number; roughness: number; occlusion: number }

What BlendMaterialAttributes leaves of an object's own attributes where the ground weighs w: the ground's roughness, the metallic of a MakeMaterialAttributes default (0), occlusion 1.

packages/levels/src/material-models.ts:57

groundSourceOf function

function groundSourceOf(scene: BABYLON.Scene, name?: string): GroundSource | undefined

The ground of the landscape called name, or of the first landscape that has one; undefined while none is baked (a material then draws without the blend).

packages/levels/src/landscape.ts:599

groundWeight function

function groundWeight(h: number, objectHeight: number, up: number, g: GroundBlendDef): number

The share of the ground colour at a pixel h metres over the ground, on an object objectHeight metres high, whose vertex normal points up by up (-1..1).

packages/levels/src/material-models.ts:50

groupByLayout function

function groupByLayout(files: readonly DecodedKtx2[]): number[][]

Indices of files grouped by layout, in the order the layouts first occur.

packages/levels/src/texture-array.ts:29

groupKey function

function groupKey(a: Placement): string

The group an actor draws in: its model and its material overrides, so actors of one group are one thin-instance draw.

packages/levels/src/placements.ts:119

groupPlacements function

function groupPlacements(file: PlacementFile): PlacementGroup[]

packages/levels/src/placements.ts:135

hairFibreMaterial function

function hairFibreMaterial(scene: BABYLON.Scene, o: HairFibreOptions = {}): BABYLON.ShaderMaterial

The fibre material for a scene (one per scene and option set).

packages/levels/src/hair-fibre.ts:67

hasLook function

function hasLook(look: LookDef): boolean

Does a definition carry anything of this model?

packages/levels/src/material-models.ts:212

hasPackedNormals function

function hasPackedNormals: (layers: LandscapeLayerDef[]) => boolean

does a packed landscape carry normals or occlusion

packages/levels/src/landscape.ts:431

heightFogOf function

function heightFogOf(scene: BABYLON.Scene): HeightFogMaterials | undefined

the scene's height fog along the rays, if its environment asks for one (fog.alongRay): shaders of their own (the sea) take its values

packages/levels/src/height-fog-material.ts:99

heightFogShaderValues function

function heightFogShaderValues(f: HeightFogDef, h: number): [number, number, number, number]

Per-layer numbers of the shader at the camera's height h: [density of the first layer at the eye (per metre), its falloff k (per metre, natural log), the same for the second layer (0, 0 without one)]. The density along a ray is d0 x exp(-k x (y - h)).

packages/levels/src/height-fog-material.ts:87

heightRaster function

function heightRaster(positions: ArrayLike<number>, rect: [number, number, number, number], w: number, h: number): Float32Array

Spread vertices (x, y, z; z is the plane's second axis) over a w x h raster of the rectangle: the height of the nearest vertex per texel, holes filled.

packages/levels/src/landscape.ts:243

importFromBytes function

async function importFromBytes(bytes: Uint8Array): Promise<LibraryModule>

The default import: the checked bytes as a module behind a blob URL (so what runs is exactly what was checked).

packages/levels/src/code.ts:223

indexGlb function

function indexGlb(bytes: ArrayBuffer | Uint8Array): GlbIndex

read the JSON chunk of a .glb (or the bytes of a .gltf)

packages/levels/src/material-look.ts:114

installCatalogCommands function

function installCatalogCommands(world: import('@ferret/core').World, levels: LevelService, client: CatalogClient): void

The catalog commands: the viewer and an agent open a catalog, list its levels with their state on the device, refresh it and travel into a level. catalog.levels {check: true} opens each level's package (a few ranged reads) to say whether its core set is cached or missing and how many bytes a visit would download; without check the state is unknown.

packages/levels/src/catalog.ts:176

installCatalogs function

function installCatalogs(levels: LevelService, mount: PackageMount, store: AssetStore, defaults: CatalogOptions = {}): CatalogClient

Plug catalog support into a LevelService: afterwards levels.registerCatalog(url) works.

packages/levels/src/catalog.ts:165

installCode function

function installCode(world: World, mount: PackageMount, o: CodeLoaderOptions = {}): CodeLoader

Let a mount run the code of its packages.

packages/levels/src/code.ts:230

installCodeCommands function

function installCodeCommands(world: World, code: CodeLoader): void

pkg.require and pkg.loaded: run the code of an open package (and of its dependencies) through a CodeLoader, and list what runs.

packages/levels/src/commands.ts:121

installDockForms function

function installDockForms(bridge: DockBridgeLike, docks: ModelDocks): void

(dock a b [:joint fixed|hinge|ball|bond] [:axis (vec x y z)] [:limits (list lo hi)] [:break N] [:place #f]) and (undock a [b]). a and b are refs (actor#dock, or an actor alone when it has one free dock). The value of dock is the second ref.

packages/levels/src/fmdl-docks.ts:283

installLevelLibraries function

function installLevelLibraries(levels: LevelService, code: CodeLoader): void

Make travel require the libraries of every package level before it is built. The ones the manifest names are found through the loader's open hook (the catalog) when they are not open yet; the ones only the open libraries' provides imply are already open. Emits level:libraries { level, libraries } with what was required.

packages/levels/src/libraries.ts:63

installModelForms function

function installModelForms(bridge: FormBridgeLike, stage: ModelStage): void

packages/levels/src/fmdl-motion.ts:492

installPackageCommands function

function installPackageCommands(world: World, mount: PackageMount, hooks: PackageCommandHooks = {}): void

The pkg.* commands (PLAN.md 4.9), by hand and through MCP alike, over a PackageMount: pkg.open, pkg.unlock, pkg.level, pkg.list, pkg.info, pkg.validate, pkg.deps, pkg.verify, pkg.code, pkg.pack, pkg.save, pkg.keys, pkg.catalog and pkg.publish. installCodeCommands adds pkg.require and pkg.loaded (running a package's code).

packages/levels/src/commands.ts:33

installPackageLoader function

function installPackageLoader(levels: LevelService, o: PackageLoaderOptions): void

Teach a LevelService to load level packages: a folder with manifest.json, scene.glb and optionally navmesh.bin. Problems with the wiring (a node the manifest names is missing, a behaviour is not registered) do not stop the level: they are collected in the report so the game still runs and the artist sees what to fix.

packages/levels/src/package.ts:54

installPackages function

function installPackages(levels: LevelService, assets: MountAssets, o: MountOptions = {}): PackageMount

Set a LevelService up to play packages.

packages/levels/src/ferret.ts:169

installProgramForms function

function installProgramForms(bridge: ProgramBridgeLike, programs: ModelPrograms): void

(run-motion "name" [:on actor] :param value ...): lasts until the motion's program has ended

packages/levels/src/fmdl-programs.ts:140

installSequences function

function installSequences(world: { events: { on(n: string, f: (e: any) => void): () => void; emit(n: string, d?: unknown): void } }, scene: BABYLON.Scene, defs: SequenceDef[], find: (name: string) => BABYLON.TransformNode | null)

Plays a level's sequences: begin ones at once, trigger ones when the trigger volume with that id is entered (the world's trigger:enter), manual ones when the game calls play(name). Returns the players by name; dispose() removes the listeners.

packages/levels/src/sequence.ts:144

installStreamCommands function

function installStreamCommands(world: World, store: AssetStore): void

stream.status and stream.cache: what the store is doing and what it holds on the device.

packages/levels/src/runtime.ts:205

installStreamingDebug function

function installStreamingDebug(world: World, sv: StreamingService): StreamingDebugView

stream.debug {on?}: show or hide the cell boxes of the streamed level; returns whether they are shown.

packages/levels/src/streaming-debug.ts:57

installTravelCommands function

function installTravelCommands(world: World, registry: TransitionRegistry): void

The travel.* commands: travel.preview {name, seconds?, bytes?, fail?, cached?} and travel.transitions.

packages/levels/src/transitions.ts:196

installUnrealFilm function

function installUnrealFilm(): void

Make Babylon's PBR and standard materials able to tone map with Unreal's film curve (toneMappingType = UNREAL_FILM_TONEMAPPING). Safe to call again.

packages/levels/src/unreal-film.ts:85

instanceMatrix function

function instanceMatrix(w: BABYLON.Matrix, t: BABYLON.Matrix): BABYLON.Matrix

The instance matrix for a mesh whose world matrix inside the model is w and an actor transform t: w * t * w^-1.

packages/levels/src/placements.ts:154

isHairFibreMaterial function

function isHairFibreMaterial(m: BABYLON.Material | null | undefined): boolean

Is this glTF material a strand material?

packages/levels/src/hair-fibre.ts:51

isMirrored function

function isMirrored(a: Placement): boolean

an actor whose scale turns space over (an odd number of negative axes): its faces wind the other way, so it is drawn by a mesh of its own with the culling turned round

packages/levels/src/placements.ts:124

isPlacementsFile function

function isPlacementsFile: (name: string) => boolean

a file name that holds a placement list (a streaming cell's file ending so is placed, not loaded as a glb)

packages/levels/src/placements.ts:29

isReliefDecal function

function isReliefDecal: (m: AbstractMesh) => boolean

packages/levels/src/decal-buffer.ts:15

ktx2Layout function

function ktx2Layout: (d: DecodedKtx2) => string

The key two decoded files must share to be layers of one array: size, GL format, number of levels.

packages/levels/src/texture-array.ts:26

layerBlendGlsl function

function layerBlendGlsl(layers: LandscapeLayerDef[], pos: string, tex = 'texture', linear = 'toLinearSpace', up = '1.0', o: BlendGlslOptions = {}): string

The layer blend as GLSL statements. Needs in scope: vec2 <pos> (metres in the landscape's coordinates), uniform vec4 ferretLsRect (minX, minZ, 1/sizeX, 1/sizeZ), samplers ferretLsW<i>, ferretLsA<k>, ferretLsN<k>, ferretLsR<k>, ferretLsX<k>. Leaves vec3 lsColour (linear), with normal maps vec3 lsNormal (tangent space) and, when a layer says anything of its roughness (image, scale or alpha), float lsRoughness set. tex is the sampling function (texture in GLSL ES 3, texture2D in the procedural texture's shader), linear converts sRGB to linear. up is a GLSL float expression: the up component of the ground normal, for the layers with a slope or a world.

packages/levels/src/landscape.ts:312

levelCost function

function levelCost(model: FmdlModel, level: number): { files: number; instances: number }

How much a level of a placed model costs, from its plan: the files, and the instances drawn (a whole with its includes).

packages/levels/src/fmdl.ts:384

levelFilesFromFetch function

function levelFilesFromFetch(get: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any>; arrayBuffer?(): Promise<ArrayBuffer> }>, at: (path: string) => string): LevelFiles & { revoke(): void }

LevelFiles over a fetch like the package loader's: at turns a level-relative path into the URL the fetch takes.

packages/levels/src/level-materials.ts:153

levelLibraries function

function levelLibraries(manifest: LevelManifest, providers: Iterable<Provider>): Record<string, string>

Which libraries a level needs: those its manifest names, and every one of providers whose provides the level uses (a level key with content, a capability it switches on, an actuator or rotor kind, a flow source). Id -> version range, sorted by id.

packages/levels/src/libraries.ts:42

levelMaterialRefs function

function levelMaterialRefs(def: MaterialDef): { ref: string; slot: string; colour: boolean }[]

every texture reference of a definition: the maps and the pictures (masks), with the slot they are read for

packages/levels/src/level-materials.ts:88

levelTextureStem function

function levelTextureStem(ref: string): string | undefined

tex/<stem> (or tex/<stem>.ktx2, or the library form ferret://tex-<stem>/<stem>.ktx2) -> the stem; undefined for anything else

packages/levels/src/level-materials.ts:80

loadLandscapeTexture function

function loadLandscapeTexture(url: string, scene: BABYLON.Scene, o: { srgb: boolean; repeat: boolean }): Promise<BABYLON.BaseTexture>

the default landscape texture: a Babylon Texture from a URL the browser can load (http, blob, data), resolved once loaded

packages/levels/src/landscape.ts:703

loadLandscapeTextureArray function

async function loadLandscapeTextureArray(urls: string[], scene: BABYLON.Scene, read?: (url: string) => Promise<Blob>): Promise<BABYLON.BaseTexture>

The default texture array: the images drawn straight into the layers of one WebGL2 array texture (raw RGBA, no colour conversion, no premultiplication, rows as stored: v = 0 is the image's top row, as in Unreal), then the mip chain and repeat wrapping with anisotropic filtering. The images are decoded by the browser one at a time, so no more than one stands in memory beside the texture.

packages/levels/src/landscape.ts:717

lookCompositionGlsl function

function lookCompositionGlsl(s: LookStructure): string

Before the final composition: the graph's emissive; the direct diffuse light gets back what Babylon's PBR took from it with the occlusion (Unreal's occlusion dims indirect light only).

packages/levels/src/material-models.ts:366

lookDefine function

function lookDefine: (s: LookStructure) => string

packages/levels/src/material-models.ts:209

lookDepthGlsl function

function lookDepthGlsl(s: LookStructure): string

Before the colour is written: the pixel's depth is pushed away from the camera by Ditcher_Effect centimetres times DitherTemporalAA.

packages/levels/src/material-models.ts:393

lookFadeGlsl function

function lookFadeGlsl(s: LookStructure): string

After the albedo block: the opacity fades along u or v, by a constant and by the depth of the scene behind the surface (Unreal's DepthFade: saturate((scene depth - pixel depth) / distance)).

packages/levels/src/material-models.ts:374

lookGlsl function

function lookGlsl(s: LookStructure): string

The model as GLSL statements for the fragment shader's "before lights" point: needs surfaceAlbedo, normalW, vPositionW, vNormalW, the varying vFerretLkUv (first UV set) and, with a ground blend, vFerretLkH (the object's height, metres). Leaves the colour in surfaceAlbedo, with a ground blend also the blended normal in normalW and the weight in the global ferretLkW (the metallic, roughness and occlusion blends read it later, see lookReflectivityGlsl and lookReflectionGlsl).

packages/levels/src/material-models.ts:274

lookMasks function

function lookMasks(s: LookStructure): string[]

the pictures of a structure in the order samplers are numbered

packages/levels/src/material-models.ts:193

lookPictures function

function lookPictures(look: LookDef): string[]

every picture a definition reads, by the name it is looked up under (a name of masks or a texture reference itself)

packages/levels/src/material-models.ts:202

lookReflectionGlsl function

function lookReflectionGlsl(s: LookStructure): string

After the geometry's occlusion terms: the graph's, a pattern's over it by its mask, the ground takes it to 1 by its weight, the vertex colour's red channel multiplies it.

packages/levels/src/material-models.ts:352

lookReflectivityGlsl function

function lookReflectivityGlsl(s: LookStructure): string

In the metallic / roughness step (a hook inside the reflectivity block): the graph's own, then the ground blend takes the metallic to 0 and the roughness to the ground's by its weight.

packages/levels/src/material-models.ts:343

lookStructure function

function lookStructure(look: LookDef): LookStructure

packages/levels/src/material-models.ts:167

lutElevation function

function lutElevation(i: number, n = LUT_SIZE): number

the view elevation (radians above the horizon) of table entry i: dense near the horizon, where the sky changes fastest

packages/levels/src/atmosphere.ts:80

macroBlendAlphas function

function macroBlendAlphas(n: Vec3, b: MacroBlend = macroBlendOf({})): { yz: number; xy: number }

WorldCoordinate3Way's two blend factors from the world normal given in this world's axes: yz is the share of the YZ projection over the XZ one (Unreal's |nx|, our |x|), xy the share of the XY projection (the top one) over that mix (Unreal's |nz|, our |y|).

packages/levels/src/material-models.ts:73

macroBlendOf function

function macroBlendOf(m: Pick<MacroVariationDef, 'blend'>): MacroBlend

The blend inputs of a macro variation with the function's defaults filled in.

packages/levels/src/material-models.ts:64

macroMix function

function macroMix(xy: Vec3, yz: Vec3, xz: Vec3, n: Vec3, b?: MacroBlend): Vec3

The three projected samples blended as WorldCoordinate3Way does: lerp(lerp(xz, yz, a.yz), xy, a.xy), per channel.

packages/levels/src/material-models.ts:78

maskSample function

function maskSample(texel: [number, number, number, number], channel: MaskChannel = 'rgb'): Vec3

The mask sample of a channel choice: one channel repeated, or the three colour channels.

packages/levels/src/material-models.ts:105

miePhase function

function miePhase(c: number, g: number): number

packages/levels/src/atmosphere.ts:83

mixLayer function

function mixLayer(colour: Vec3, color: Vec3, mask: Vec3, power = 1): Vec3

mix(colour, layer.color, pow(mask, power)) per colour channel (mask is the picture's sample: one value repeated, or its three channels for rgb).

packages/levels/src/material-models.ts:100

modelClips function

async function modelClips(resolved: ResolvedModel, read: (qualified: string) => Promise<Uint8Array>, sets?: string[]): Promise<ClipJson[]>

The skeletal clips the files of a model hold (clips: { set: path }, SPEC 3), set by set in the order of the model. A set file is one ClipJson or a list of them; a clip's name is its own in the whole model. sets limits the reading to some sets.

packages/levels/src/fmdl-motion.ts:266

movingNodes function

function movingNodes(world: World, scene: BABYLON.Scene, o: FreezeOptions): Set<BABYLON.Node>

the nodes that move: entity nodes, sequence targets, the listed ones

packages/levels/src/static-freeze.ts:26

parseLevelTextures function

function parseLevelTextures(json: unknown): LevelTextureCatalogue

Read a texture catalogue: { textures: { stem: entry } }, { textures: [entry, ...] } or a bare list/object of entries; an entry's files is an object by codec or a list of file names.

packages/levels/src/level-materials.ts:48

patchImageProcessing function

function patchImageProcessing(code: string): string

code is Babylon's imageProcessingFunctions chunk; the same text with Unreal's film curve in the place of the PBR Neutral one (unchanged when already done or the chunk differs)

packages/levels/src/unreal-film.ts:78

pickCodecFile function

function pickCodecFile(item: Pick<TextureItem, 'codec' | 'codecs'>, policy: TextureCodecPolicy = 'chosen', path = ''): string

The file of a texture item under a codec policy; path (the file maps names) when the item has one codec or none.

packages/levels/src/library.ts:37

pickLevelTextureFile function

function pickLevelTextureFile(e: Pick<LevelTextureEntry, 'codec' | 'files'>, policy: LevelCodecPolicy = 'best'): string | undefined

The file of a texture under the policy: the policy's codec where it exists, else the other (a texture made in one codec only is that one), else the chosen codec's, else any.

packages/levels/src/level-materials.ts:72

pickTier function

function pickTier<T>(have: Partial<Record<LibraryTier, T>>, want: LibraryTier = 'desktop'): { tier: LibraryTier; value: T } | null

The first tier at or below want that the item has (a low-end device asks for low and gets low, never desktop).

packages/levels/src/library.ts:153

pixelDepthPush function

function pixelDepthPush(d: PixelDepthDef, x: number, y: number, noise: number): number

the push of a pixel away from the camera, metres: Ditcher_Effect (cm) times the dither

packages/levels/src/material-models.ts:95

planCollisionChunks function

function planCollisionChunks(def: CollisionChunksDef, at: [number, number, number][], resident: ReadonlySet<number>): { load: number[]; drop: number[] }

Which chunks to load and which to drop for the places in at (metres), given the ones resident. A chunk stays while it is within unloadRadius of any place; it comes when within loadRadius.

packages/levels/src/collision-chunks.ts:20

previewTransition function

async function previewTransition(world: World, registry: TransitionRegistry, name: string, o: PreviewOptions = {}): Promise<{ name: string; fellBack: string | null; updates: number; ended: 'ready' | 'failed' }>

Run a registered transition against a fake travel, without travelling: the author sees it in the viewer and tests it in Playwright. Returns what the transition was told.

packages/levels/src/transitions.ts:163

projectionUvs function

function projectionUvs(p: Vec3, scale: number): [[number, number], [number, number], [number, number]]

Where a macro picture is read for a world position (metres): the UVs of the XY, YZ and XZ projections of Unreal, scale in Unreal units.

packages/levels/src/material-models.ts:84

propellerBlur function

function propellerBlur(omega: number, dt: number, blades = 3, from = 0.25, to = 0.7): number

how much of the propeller is blur: 0 blades only, 1 the disc only; omega rad/s, dt the frame's time, s

packages/levels/src/propeller.ts:22

propulsorsOf function

function propulsorsOf: (a: Actor) => [string, ModelPropulsor][]

the declared propulsors of an actor's model (empty for a model that declares none)

packages/levels/src/fmdl-propulsors.ts:21

rankNearest function

function rankNearest(items: readonly { position: Vec3; priority?: number; range?: number }[], at: Vec3, n: number, opts: { held?: ReadonlySet<number>; hysteresis?: number; maxDistance?: number; filter?: (i: number) => boolean; byView?: (position: Vec3, radius: number) => boolean } = {}): number[]

The indices of the n lights that matter most to a viewer at at: the smallest distance / priority, within maxDistance. Lights in held (the ones that are real now) count as nearer by hysteresis, so a newcomer has to be clearly nearer to take over.

packages/levels/src/light-budget.ts:116

rayleighPhase function

function rayleighPhase(c: number): number

packages/levels/src/atmosphere.ts:82

refKind function

function refKind(ref: string): RefKind

Which scheme a reference uses.

packages/levels/src/runtime.ts:17

registerCatalogueCommands function

function registerCatalogueCommands(register: RegisterFn, catalogue: ModelCatalogue, stage: ModelStage, o: { ready?: (actor: string) => Promise<void> | void } = {}): void

ready is awaited when a model has appeared (the programs read the model's motion files then, so a motion can run at once)

packages/levels/src/fmdl-catalogue.ts:70

registerDockCommands function

function registerDockCommands(register: RegisterFn, docks: ModelDocks): void

fmdl.docks, fmdl.dock, fmdl.undock, fmdl.docked, fmdl.docks.restore: what an agent calls

packages/levels/src/fmdl-docks.ts:265

registerGroundSource function

function registerGroundSource(scene: BABYLON.Scene, name: string, src: GroundSource): () => void

Make a landscape's baked ground findable by materials of the scene; returns the function that takes it away again.

packages/levels/src/landscape.ts:591

relativeTo function

function relativeTo(list: string, ref: string): string

a model ref without a scheme is a file of the list's own package, relative to the list (../meshes/a.glb); a package url is joined and normalised by the loader

packages/levels/src/placements.ts:70

releaseDepthRenderer function

function releaseDepthRenderer(scene: BABYLON.Scene, _dr: BABYLON.DepthRenderer)

packages/levels/src/material-models.ts:445

resolveAtmosphere function

function resolveAtmosphere(a: AtmosphereDef = {}): ResolvedAtmosphere

packages/levels/src/atmosphere.ts:60

riverRibbon function

function riverRibbon(points: Vec3[], widths: number[])

The ribbon of a river: two vertices per point, at half the width to either side of the centre line (sideways = the horizontal tangent turned a quarter). uv = (metres along the river, metres across from the centre); side is -1 / +1 (the bank), tangent the horizontal direction downstream (x, z).

packages/levels/src/water.ts:95

rotateAboutAxis function

function rotateAboutAxis(axis: V3, turns: number, pivot: V3, pos: V3): V3

Unreal's RotateAboutAxis: the offset (new minus old position) of pos turned by turns about the axis through pivot

packages/levels/src/foliage-wind.ts:83

sampleDistanceField function

function sampleDistanceField(f: DistanceFieldData, p: readonly [number, number, number] | number[]): number

the distance at a world point (metres), filtered as the shader filters it

packages/levels/src/distance-field.ts:56

sampleKeys function

function sampleKeys(keys: Key<number | number[]>[], t: number, quat = false): number | number[]

the value of a key track at time t: held before the first and after the last key

packages/levels/src/sequence.ts:68

samplerPlan function

function samplerPlan(layers: LandscapeLayerDef[], packed = false): SamplerPlan

packages/levels/src/landscape.ts:270

scopeKey function

function scopeKey: (s: LookScope) => "types" | "instances"

packages/levels/src/material-look.ts:46

screenDecalsOf function

function screenDecalsOf(scene: BABYLON.Scene, create = false): ScreenDecals | undefined

The scene's screen decals; with create, made if there is none, and every material is told to look for it.

packages/levels/src/screen-decals.ts:105

settleDrawing function

async function settleDrawing(scene: BABYLON.Scene, o: SettleOptions): Promise<SettleReport>

packages/levels/src/level-ready.ts:36

shareEngine function

function shareEngine(packages: Record<string, object>, target: object = globalThis): void

Publish the packages a parent holds (`{ core: <namespace of

packages/levels/src/dock-engine.ts:11

shoreDistance function

function shoreDistance(outline: [number, number][], x: number, z: number): number

signed distance from (x, z) to the outline's edge, metres: positive inside, negative outside (even-odd rule, nearest edge)

packages/levels/src/water.ts:67

simpleGrassWind function

function simpleGrassWind(p: V3, time: number, intensity: number, weight: number, speed: number, additional: V3 = [0, 0, 0]): V3

SimpleGrassWind (Unreal cm, seconds): the offset of a vertex at p (the world position, cm)

packages/levels/src/foliage-wind.ts:72

skyRadiance function

function skyRadiance(t: AtmosphereTable, elevation: number, cosSun: number, sunScale = 1, sunColor: Vec3 = [1, 1, 1]): Vec3

Radiance of the sky in a direction, in the picture's units for a sun of unit colour and strength: elevation of the view above the horizon, cosSun the cosine of the angle between the view and the sun. The dome's shader does the same on the GPU.

packages/levels/src/atmosphere.ts:175

slopeAlpha function

function slopeAlpha(up: number, r: SlopeRamp): number

Unreal's WorldAlignedBlend ("w/Vertex Normals") over the ground normal's up component (1 = flat, 0 = vertical): the dot with the world up is remapped to 0..1, times Blend Sharpness, plus Blend Bias minus half the sharpness, saturated = saturate(0.5 sharpness up + bias). (The reference the GLSL of layerBlendGlsl repeats.)

packages/levels/src/landscape.ts:228

slopeShares function

function slopeShares(up: number, s: LandscapeSlope): [number, number, number]

Weights of the three pictures of a slope layer (steep[0], steep[1], own) at a ground whose normal has up component up; they sum to 1.

packages/levels/src/landscape.ts:231

smoothTri function

function smoothTri: (x: number) => number

Unreal's three-component (3 - 2a) a^2 of a = |frac(x + 0.5) * 2 - 1|

packages/levels/src/foliage-wind.ts:69

spawnFromManifest function

function spawnFromManifest(s: ManifestSpawn): { id: string; position: [number, number, number]; yaw?: number }

packages/levels/src/levels.ts:449

sunLightColour function

function sunLightColour(color: Vec3, transmittance: Vec3, amount: number): Vec3

The sun light's colour after the atmosphere: the transmittance along the sun ray (scaled to a strongest channel of 1) mixed in by amount.

packages/levels/src/environment.ts:277

takesShadows function

function takesShadows(m: BABYLON.AbstractMesh): boolean

The materials that take a shadow map: the engine's PBR and standard materials (and a multi-material of them). A terrain's, a sea's or a sky's own shader does not.

packages/levels/src/sun-shadows.ts:97

tierPath function

function tierPath(pkg: { has(path: string): boolean }, tiers: Partial<Record<string, string>> | undefined, tier: string, path: string): string

The path of a file as the parent's quality tier sees it: the tier's folder (docking.tiers) holds a file of the same path, or the root does.

packages/levels/src/dock.ts:211

treeSway function

function treeSway(p: V3, pivot: V3, time: number, intensity: number, windIntensity: number, dir: [number, number], heightInBox: number): V3

MF_TreesWind's "wind offset" (Unreal cm): the tree turns about its pivot

packages/levels/src/foliage-wind.ts:101

unfreezeStatic function

function unfreezeStatic(scene: BABYLON.Scene, root?: string): number

give the frozen meshes back (all of the scene's, or those under root)

packages/levels/src/static-freeze.ts:48

unrealFalloff function

function unrealFalloff(d: number, range: number): number

Unreal's legacy point light: (1 - (d/R)^2)^8, no 1/d^2 (its default falloff exponent)

packages/levels/src/light-budget.ts:169

useHairFibre function

function useHairFibre(root: BABYLON.Node, o: HairFibreOptions = {}): number

Swap every strand material under root for the fibre material. Returns how many meshes were changed.

packages/levels/src/hair-fibre.ts:99

useSharedEngine function

function useSharedEngine(text: string, held?: Iterable<string>): string

Rewrite the @ferret/* imports of a module's text to read the shared engine: import { a, b as c } from "@ferret/core" becomes const { a, b: c } = globalThis.__ferretEngine["core"]. Throws for what it cannot read from the shared engine: a package the parent does not hold (held), a re-export of one.

packages/levels/src/dock-engine.ts:33

useUnrealFalloff function

function useUnrealFalloff(): boolean

Babylon's standard (linear) light falloff becomes Unreal's legacy curve in the PBR shader (GLSL and WGSL), for every material compiled after this call. Done once per page, before the pool's lights are made, so no material was compiled with the old one.

packages/levels/src/light-budget.ts:176

validateAmbientParticles function

function validateAmbientParticles(v: unknown, at = 'motes'): ManifestIssue[]

packages/levels/src/ambient-particles.ts:32

validateAtmosphere function

function validateAtmosphere(a: unknown, at = 'environment.skyAtmosphere'): { path: string; message: string }[]

packages/levels/src/atmosphere.ts:64

validateEnvironment function

function validateEnvironment(e: unknown, at = 'environment'): ManifestIssue[]

packages/levels/src/environment.ts:97

validateFogVeil function

function validateFogVeil(x: unknown, at = 'environment.fog.volumetric'): { path: string; message: string }[]

packages/levels/src/fog-veil.ts:15

validateFoliageWind function

function validateFoliageWind(v: unknown, at = 'foliageWind'): ManifestIssue[]

packages/levels/src/foliage-wind.ts:39

validateLandscapes function

function validateLandscapes(l: unknown, at: string): { path: string; message: string }[]

packages/levels/src/landscape.ts:146

validateLevelMaterials function

function validateLevelMaterials(x: unknown, at = 'materials', cat?: LevelTextureCatalogue): ManifestIssue[]

packages/levels/src/level-materials.ts:119

validateLightBudget function

function validateLightBudget(d: unknown, at = 'environment.lights'): ManifestIssue[]

packages/levels/src/light-budget.ts:82

validateLookDef function

function validateLookDef(d: unknown, p: string, bad: (path: string, message: string) => void): void

the problems of one look (d is the object at path p)

packages/levels/src/material-look.ts:54

validateManifest function

function validateManifest(m: unknown): ManifestIssue[]

Check a manifest against the schema. Returns the problems; an empty list means the manifest is usable.

packages/levels/src/manifest.ts:169

validateMaterialLooks function

function validateMaterialLooks(v: unknown, at = 'materialLooks'): ManifestIssue[]

packages/levels/src/material-look.ts:79

validateMaterialScale function

function validateMaterialScale(v: unknown, at = 'materialScale'): ManifestIssue[]

packages/levels/src/material-scale.ts:20

validatePackage function

async function validatePackage(pkg: FerretPackage, o: ValidateOptions = {}): Promise<PackageIssue[]>

pkg.validate: the package's own checks (manifest, files, sha256, no code in kinds without code) and then every level: its manifest against the schema, and that the scene, collision mesh and navmesh it names exist — in the package or, through ferret://, in a declared dependency.

packages/levels/src/ferret.ts:202

validatePlacements function

function validatePlacements(x: unknown, at = 'placements'): ManifestIssue[]

packages/levels/src/placements.ts:77

validateProbes function

function validateProbes(p: unknown, at = 'environment.probes'): { path: string; message: string }[]

packages/levels/src/probe-volume.ts:30

validateRelevance function

function validateRelevance(r: unknown): ManifestIssue[]

the relevance block: numbers that are positive and finite, modes keyed by name

packages/levels/src/manifest.ts:347

validateRoomReflection function

function validateRoomReflection(r: unknown, at = 'environment.roomReflection'): ManifestIssue[]

packages/levels/src/room-reflection.ts:28

validateSequences function

function validateSequences(v: unknown, at = 'sequences'): ManifestIssue[]

packages/levels/src/sequence.ts:39

validateSunShadows function

function validateSunShadows(x: unknown, at = 'environment.sun.shadows'): ManifestIssue[]

packages/levels/src/sun-shadows.ts:33

validateSwarm function

function validateSwarm(v: unknown, at = 'swarms'): ManifestIssue[]

packages/levels/src/swarm.ts:38

validateVisibility function

function validateVisibility(v: any): ManifestIssue[]

packages/levels/src/visibility.ts:117

validateWater function

function validateWater(w: unknown, at: string): { path: string; message: string }[]

packages/levels/src/water.ts:113

virtualTextureShare function

function virtualTextureShare(above: number, blendHeight: number, strength = 1): number

The colour a prop takes at height above metres over the ground: the share of the ground colour (virtual texture) it keeps.

packages/levels/src/landscape.ts:237

wakeFade function

function wakeFade(age: number): { core: number; arm: number }

how much of its first strength a row of the track keeps age seconds after the ship passed: the foam core slowly, the wave arms several times faster (they disperse)

packages/levels/src/wake.ts:30

wakeProfile function

function wakeProfile(o: ShipWakeOptions): WakeRow[]

the shape of the track: pure, for the picture and for tests

packages/levels/src/wake.ts:33

waveHeight function

function waveHeight(waves: WaterWave[], x: number, z: number, t: number): number

Height of the waves at (x, z) and time t: the sum of Gerstner waves' vertical part, metres above the level.

packages/levels/src/water.ts:148

Interfaces

Actor interface

interface Actor
name: string
id: stringthe id of the model, or of the included model an instance was let go from
root: Node
rig: PartRig
clips?: ClipPlayer
from?: stringthe actor this one was let go from
resolved?: ResolvedModelthe model it is of (its resolved form, its reader)
read?: (qualified: string) => Promise<Uint8Array>

packages/levels/src/fmdl-motion.ts:297

AmbientParticlesDef interface

interface AmbientParticlesDef

Motes in a box of air (dust in a sunbeam, pollen, falling leaves): a particle emitter that spawns at random places of a box, lives a few seconds, drifts with a small random velocity and fades in and out. Unreal's Cascade dust (P_Ambient_Dust: ParticleModuleLocation box, Lifetime uniform, Velocity uniform, Size, ColorOverLife with an alpha curve, spawn rate) maps one to one; the numbers come from the particle asset (see vschool_ferret tools/ambient-particles.mjs). Lengths are metres. It runs only while the camera is within radius (default 40 m) of the box centre, as the fires do.

name?: string
position: [number, number, number]the centre of the box
size: [number, number, number]the box's full size
rate: numberparticles per second
lifetime: [number, number]seconds, [min, max]
sprite: [number, number]the sprite's size in metres, [min, max]
color: [number, number, number]linear colour 0..1
alpha?: Array<[number, number]>alpha over the normalised life: [[t, alpha], ...] with t rising from 0 to 1
velocity?: { min: [number, number, number]; max: [number, number, number] }m/s: each axis is drawn between the two
radius?: numbermetres: the emitter runs only within this distance of the camera (default 40)

packages/levels/src/ambient-particles.ts:10

ApplyLandscapeOptions interface

interface ApplyLandscapeOptions
at: (file: string) => stringturn a file name of the def into a URL
texture?: (url: string, scene: BABYLON.Scene, o: { srgb: boolean; repeat: boolean }) => BABYLON.BaseTexture | Promise<BABYLON.BaseTexture>create a texture from a URL (default: a Babylon Texture, resolved once loaded); tests pass their own
textureArray?: (urls: string[], scene: BABYLON.Scene) => BABYLON.BaseTexture | Promise<BABYLON.BaseTexture>create one texture array from image URLs (layer i = url i; images of one size); default: loadLandscapeTextureArray. Used by a packed landscape
scope?: BABYLON.AbstractMesh[]the name pattern of the meshes of the virtual texture's props is searched among these (default: all meshes of the scene)

packages/levels/src/landscape.ts:691

ApplyLookOptions interface

interface ApplyLookOptions
masks: Record<string, BABYLON.BaseTexture>the picture of each name of the material's masks, loaded as data (not sRGB), repeating
srgb?: readonly string[]the names of the pictures that are colour (sRGB) and must be decoded in the shader; default none: the pictures are data (a colour picture whose GPU format decodes itself is not listed either)

packages/levels/src/material-models.ts:602

ApplyProgramOptions interface

interface ApplyProgramOptions
textures: BABYLON.BaseTexture[]the pictures of the program's textures, by index
srgb?: readonly number[]indices of the pictures that are colour (sRGB) and must be decoded in the shader
arrays?: readonly { texture: BABYLON.BaseTexture; members: readonly number[] }[]Pictures read from texture arrays (a fragment shader has 16 texture units, a master may read more): texture is the array, members[k] the program's picture that is layer k (texture-array.ts). The entry of textures at a member's index is not read (give the array itself); the others are bound as before.
cutoff?: numberthe alpha test's clip value for opacityMask (Unreal's OpacityMaskClipValue; default 0.3333)
writeDecal?: booleana relief decal: the material writes its normal and opacity into the decal buffer instead of a colour (decal-buffer.ts)
receiveDecals?: booleandoes the surface take the decals lying on it (default true; a decal or a translucent material does not)
screenDecal?: { pass: { value: number } }a projected decal (screen-decals.ts): the material draws its colour, roughness and metallic into the screen decal buffers; pass says which one is being drawn
distanceField?: DistanceFieldTexturesthe level's distance field, for the programs that read it (near)

packages/levels/src/material-program.ts:272

AssetLibraryOptions interface

interface AssetLibraryOptions
store: AssetStore
mount: PackageMount
assets?: RuntimeAssetsneeded for characters
tier?: LibraryTierthe package tier to open (default desktop); a tier a package does not have falls back to its plain file
pins?: Record<string, string>the versions of packages the game holds to, by package id (the exact dependencies of its package): what a reference without a version means for them
texCodec?: TextureCodecPolicywhich codec of a KTX2 map kept in both (TextureItem.codecs): chosen (the one the encoder's check chose, default), best (UASTC when there is one: the parity tier), light (ETC1S when there is one)
policy?: CatalogPolicythe catalog policy (trusted keys, allowUnsigned)
session?: () => string | null | undefinedthe SW session of the person, for the calls that change the library (library.add, library.accept, library.reject, library.incoming); default: the world's account service
onModelReady?: (root: BABYLON.TransformNode, id: string) => voidcalled with the root of every static model of the library when its file is in (its yaw set): a game's hook for what it does to each model, such as the culling of parts too small to see (PartCuller.add)
code?: { origin?: boolean | ((pkg: FerretPackage) => boolean); trusted?: () => Iterable<string> | undefined; engine?: Record<string, unknown>; loader?: CodeLoader; importModule?: CodeLoaderOptions['importModule'] }How the code of module items may run (module(id)). origin: the library is the game's own, so its code is the game's (default: the catalog is on the page's own origin); otherwise a package must carry a valid signature, from trusted keys when given. engine: the engine's API the code reads its @ferret/* imports from (default globalThis.Ferret, the shared engine of lib/ferret/ferret.js); a game that bundles the engine passes the packages the modules need ({ ...terrain, ...waves }), and they are set as globalThis.Ferret when the page has none. loader: a code loader of the game's own.

packages/levels/src/library.ts:44

AtmosphereDef interface

interface AtmosphereDef

Unreal's SkyAtmosphere component. Every field is optional and defaults to the component's own default. Lengths km, coefficients per km.

groundRadius?: numberplanet radius, km (6360)
atmosphereHeight?: numberthickness of the air, km (60)
rayleighScattering?: Vec3Rayleigh scattering per km (0.005802, 0.013558, 0.0331)
rayleighScaleHeight?: numberRayleigh scale height, km (8)
mieScattering?: Vec3Mie scattering per km (0.003996 each)
mieAbsorption?: Vec3Mie absorption per km (0.00444 each)
mieScaleHeight?: numberMie scale height, km (1.2)
mieAnisotropy?: numberMie anisotropy g, -1..1 (0.8)
absorption?: Vec3ozone absorption per km at the middle of its layer (0.00065, 0.001881, 0.000085)
groundAlbedo?: Vec3colour of the ground the air sits on (0.402 each)
multiScatteringFactor?: numberhow much of the single scattering comes back as multiple scattering (1)
skyLuminanceFactor?: Vec3colour factor on the sky's luminance (1 each)
observerAltitude?: numberhow far the observer is above the ground, km (0)

packages/levels/src/atmosphere.ts:18

AtmosphereTable interface

interface AtmosphereTable
n: number
rayleigh: Vec3[]Rayleigh in-scatter per view elevation, phase left out, per channel, in units of the sun's irradiance
mie: Vec3[]the same for Mie
sunTransmittance: Vec3share of the sun's light that reaches the observer: the sun disc's and the lit ground's colour (zero with the sun under the horizon)
ground: Vec3colour of the ground below the horizon, in the same units (albedo x sun and sky light)
g: number
skyLuminanceFactor: Vec3
multiScatter: number
sunElevation: number

packages/levels/src/atmosphere.ts:88

AttachOptions interface

interface AttachOptions
socket?: stringa socket of the body's item (grip_r, axe_r...)
bone?: stringa bone by name, with position and rotation of your own (they win over the socket's)
position?: [number, number, number]
rotation?: [number, number, number, number]
compatibleClips?: booleanalso bind the clip sets of other skeletons that fit the part by bone names, and the other sets of its own skeleton (as for CharacterOptions): a rider's riding clips

packages/levels/src/library.ts:102

BindOptions interface

interface BindOptions
map?: Record<string, string>graph clip name -> clip name in the clip sets (default: every clip under its own name)
oneShot?: string[]graph clip names that do not loop
positionBones?: string[]the only bones whose translations the clips set, each scaled by the body's rest offset over the clip skeleton's (retargetGroup's positionBones): a body of its own proportions on the clips' skeleton keeps its bone lengths (['pelvis']: the hips move as the clip moves them, at this body's height). Default: every bone's translation is taken

packages/levels/src/library.ts:122

BlendGlslOptions interface

interface BlendGlslOptions
depth?: stringGLSL float: the pixel's camera depth in metres, for the near/far blends (default 0: the near pictures)
pos3?: stringGLSL vec3: the position in the landscape's own coordinates (x, height, z), for the world aligned layers (default: height 0)
normal?: stringGLSL vec3: the ground normal in the same axes, for the projections of the world aligned layers (default: up)
packed?: booleanthe landscape keeps its pictures in texture arrays (LandscapeDef.packed): normals and occlusion come from them

packages/levels/src/landscape.ts:294

BudgetLight interface

interface BudgetLight

A level with hundreds of lamps, candles, torches and fires (Unreal draws them all as movable lights) cannot give each a real light: every real light is paid for in every pixel of every lit surface. The light budget keeps a small pool of real lights and moves it to the lights nearest the camera, from time to time; every other lamp is a glowing dot (an emissive instance of one shared mesh: one draw call for all). The pool never changes size while it runs, so no shader is rebuilt when a light changes hands. A light that changes hands fades out and in instead of popping. This is a performance limit, not a design: Unreal lights all of them.

id?: stringa name for events and tests (the source actor's)
group?: stringa group of lamps of one kind ('torch', 'candle'), for statistics and the sound budget
position: Vec3the level's metres
color: Vec3linear colour 0..1
intensity: numberBabylon intensity at 1 m (already converted from the source engine's units, see tools/ue-export/lights.mjs)
range: numberthe metres where the light reaches zero (the source engine's attenuation radius)
kind?: 'point' | 'spot'
direction?: Vec3a spot's axis (the way the light travels) and full cone angle in radians
angle?: number
innerAngle?: numbera spot's full bright core in radians (Unreal's 2 x inner cone angle): the light fades from it to angle as Unreal's cone does (glTF falloff only); default 0
flicker?: { min: number; max: number; rate?: number }a flame's flicker: the intensity moves between min and max times its value, rate times a second
priority?: numbernearer than a light of priority 1 by this factor when ranking (a chandelier over a candle); default 1
size?: numberthe size of the glow dot in metres (default from the range)
sound?: stringa looping sound this lamp makes (a torch's crackle); it is budgeted by sounds, the caller plays it

packages/levels/src/light-budget.ts:13

CatalogOptions interface

interface CatalogOptions extends CatalogPolicy
tier?: stringdevice tier: packages with a tiers[tier] file use it
prefix?: stringput in front of every level id of this catalog (two catalogs may share ids)
decorate?: (def: LevelDef, entry: CatalogLevel) => LevelDef | voidWhat the game adds to a level the catalog lists: its build step, its default spawn, its own name. Called with the def the catalog made (prepare, plan and fetch are set) and the catalog's entry; the returned def (or the same one changed in place) is registered. Runs again for every level when a refresh brings a new version.

packages/levels/src/catalog.ts:21

CatalogRegistration interface

interface CatalogRegistration
readonly url: string
readonly catalog: Catalog
readonly stale: booleanthe catalog came from the copy kept by an earlier session (no network)
readonly unsigned: booleandevelopment only: the catalog was not signed
readonly levels: string[]ids registered in the LevelService
refresh(): Promise<{ changed: boolean; stale: boolean }>Ask the server again. changed when a new version replaced the registered levels; a failure leaves everything as it was.

packages/levels/src/catalog.ts:33

CellSource interface

interface CellSource

What the service needs from the asset layer (an AssetCache fits): fetch and parse a file, then instantiate it.

load(url: string): Promise<void>
instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }>
release(url: string): void

packages/levels/src/streaming.ts:19

CharacterOptions interface

interface CharacterOptions extends Omit<ModelOptions, 'pkg'>
compatibleClips?: booleanalso bind the clip sets of other skeletons that list this body's skeleton as compatible, and the other sets of its own skeleton (as <set id>/<clip>)
tier?: LibraryTier
yaw?: number

packages/levels/src/library.ts:90

ClipRef interface

interface ClipRef

A clip set a character can use: where its file is, and the clips in it. Bind them with bindClips of @ferret/animation.

id: string
ref: string
skeleton: string
clips: ClipsItem['clips']
prefix?: stringset for a clip set that only fits by bone names (compatible): its clips are bound as <prefix><clip>, so they never replace the body's own

packages/levels/src/library.ts:84

CodeLoaderOptions interface

interface CodeLoaderOptions
origin?: (pkg: FerretPackage) => booleandoes this package come from where the game does (shipped with it, its own site)? Then its code is the game's (CodePolicy.origin)
trusted?: () => Iterable<string> | undefinedkey ids whose signatures are trusted; without them any valid signature is enough
ferret?: unknownthe engine's API handed to the code (default globalThis.Ferret, the shared engine)
esm?: booleanthe engine is ES modules: the code imports @ferret/* itself, so no engine API object is needed and ctx.ferret may be undefined
extendContext?: (ctx: LibraryContext, pkg: FerretPackage) => voidadd to the context handed to a package's install (the player adds game, levels, root, args, tier)
open?: (id: string, range: string) => Promise<FerretPackage | null>a package that is not open yet (a dependency, a require by id): open it, e.g. through the catalog; null when there is none
sharedEngine?: () => Iterable<string>the parent ships its engine inside its own bundle (shareEngine, ./dock-engine): a docked level's @ferret/* imports are rewritten to read it; the function names the packages it holds
onLoaded?: (id: string, exports: LibraryModule | null) => voida library package's code was loaded (its install ran): a parent that ships its engine in its bundle publishes an engine package it loaded from its library (engine-<name>) here
importModule?: (bytes: Uint8Array, path: string, pkg: FerretPackage) => Promise<LibraryModule>import the module from its checked bytes (default: a blob URL and import(); tests use a data URL)

packages/levels/src/code.ts:49

CollisionChunkDef interface

interface CollisionChunkDef
file: string
bounds: [number, number, number, number, number, number]

packages/levels/src/collision-chunks.ts:10

CollisionChunksDef interface

interface CollisionChunksDef
loadRadius: number
unloadRadius: number
chunks: CollisionChunkDef[]

packages/levels/src/collision-chunks.ts:11

CompiledProgram interface

interface CompiledProgram
types: ProgramType[]the components of every node
uses: ProgramUses
code: stringthe statements before the normal, the normal's, and the rest, for the fragment shader's "before lights" point
define: stringnames the structure: equal for two programs that differ only in parameter values and texture files

packages/levels/src/material-program.ts:20

DecodedKtx2 interface

interface DecodedKtx2

One KTX2 file, transcoded for this GPU: the levels from the largest down, in the GL format format (a compressed one, or RGBA8 / R8 / RG8).

width: number
height: number
format: number
levels: { width: number; height: number; data: Uint8Array }[]

packages/levels/src/texture-array.ts:9

DependencyOptions interface

interface DependencyOptions
store: AssetStorethe store the catalogs and packages are fetched through (give it a PersistentCache to keep them across sessions)
catalogs?: string[]catalogs searched first, in order, as absolute URLs (the page's own, from <ferret-player catalogs>)
tier?: stringthe device tier: a catalog package with a file for this tier uses it
policy?: (catalogUrl: string) => CatalogPolicyhow a catalog is checked (signature, trusted keys), by its URL; default: signed by any valid key

packages/levels/src/dependencies.ts:12

DependencyTarget interface

interface DependencyTarget

Something that can hold open packages: a PackageMount (add registers its levels too) or a plain PackageSet.

get(id: string): FerretPackage | undefined
add(pkg: FerretPackage): unknown

packages/levels/src/dependencies.ts:27

DistanceBlend interface

interface DistanceBlend

Unreal's Distance_Blend in metres: alpha = saturate((camera depth + offset) / range); 0 = the near picture, 1 = the far picture

offset: number
range: number

packages/levels/src/landscape.ts:67

DistanceFieldData interface

interface DistanceFieldData
header: DistanceFieldHeader
bytes: Uint8Array

packages/levels/src/distance-field.ts:32

DistanceFieldHeader interface

interface DistanceFieldHeader
format: 'ferret-distance-field/1'
voxel: numberthe spacing of the samples, metres
range: numberthe distance a byte reaches, metres, either way
brick: numbercells along a side of a brick
origin: [number, number, number]the world place of sample 0 of brick (0, 0, 0), metres
grid: [number, number, number]bricks of the table along x, y, z
atlas: [number, number, number]bricks of the atlas along x, y, z
gradientScale: number
data: stringthe data file, beside this one

packages/levels/src/distance-field.ts:13

DockBackend interface

interface DockBackend

a join the geometry of which belongs to a capability (atoms): it places what it joins

handles(a: string, b: string): boolean
dock(a: string, b: string): { placed: Record<string, Vec3>; info?: Record<string, unknown> }
undock(a: string, b: string): void

packages/levels/src/fmdl-docks.ts:42

DockBridgeLike interface

interface DockBridgeLike
define(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => unknown): unknown

packages/levels/src/fmdl-docks.ts:274

DockContext interface

interface DockContext

What a docked level's install is given: the game's context as an example's code knows it (game, levels, root, args, tier) with the views of a dock.

game: DockParent['game']the parent's game seen through the scope: its world, scene and input record what the code adds
world: World
levels: LevelService
root: HTMLElementthe level's own element in the parent's UI (its docking.ui fragment is inserted here); removed with the level
args: URLSearchParams
tier: DockParent['tier']
restart(): voidstart the level over: the same level is entered again under a travel (a standalone game reloads its page)
mount: PackageMount
url(path: string): Promise<string>a blob URL for a file of the level's package
scope: Scopethe level's scope: everything registered through it, and through game and world, is taken back at the end
parent: DockParentthe parent as it is, outside the scope (for a completion layer that must reach it)
roles: Roles
level: LevelDef
pkg: { id: string; version: string; manifest: FerretPackage['manifest'] }
docking: DockingBlock
build: LevelContextthe level's build context: addSpawn is the way to declare where the player stands
ferret: unknownthe engine's API as the code loader holds it (undefined for code that imports @ferret/* itself)

packages/levels/src/dock.ts:28

DockedLevel interface

interface DockedLevel

What a docked level's install may return: the end of the level, and ready when the level goes on loading after install (the travel waits for it, with the world running).

dispose?(): void | Promise<void>
ready?: Promise<unknown>

packages/levels/src/dock.ts:57

DockedPair interface

interface DockedPair
a: string
b: string
joint: DockJoint
info?: Record<string, unknown>

packages/levels/src/fmdl-docks.ts:58

DockHostOptions interface

interface DockHostOptions
loader: CodeLoader
mount: PackageMount
parent: DockParent
levels: LevelService
onEnter?(ctx: DockContext): void | (() => void)called with the context just before install and after the roles are docked (the parent parks its hero, hides its own HUD ...); returns what it does at the end

packages/levels/src/dock.ts:59

DockInfo interface

interface DockInfo
ref: string
actor: string
dock: string
description: string
position: Vec3world position and rotation of the dock's frame
rotation: Quat
heldBy: string | nullthe ref of the dock holding this one, or null when it is free

packages/levels/src/fmdl-docks.ts:48

DockJoint interface

interface DockJoint
kind: 'fixed' | 'hinge' | 'ball' | 'bond'
axis?: Vec3
limits?: [number, number]
breakForce?: number

packages/levels/src/fmdl-docks.ts:27

DockOptions interface

interface DockOptions
joint?: DockJoint
place?: boolean

packages/levels/src/fmdl-docks.ts:28

DockParent interface

interface DockParent

Docked travel: a level of kind levels with a docking block and code, entered from a parent game. The parent's door starts an ordinary travel; the level's build step (DockHost.enter) runs the code's install(DockContext) under the transition, and the engine's unload of the level ends it: dispose, then the scope (everything the code registered is taken back), the level's UI, the roles. The same engine runs both: the code is handed scoped views of the parent's game (scopedGame), so what it adds is recorded and what the parent holds (the input, the player's character) answers for the roles the level does not bring itself.

game: { world: World; scene: BABYLON.Scene; input?: any; display?: { trackCamera?(cam: BABYLON.Camera): void } }the parent's game: { world, scene, input, display, ... }
root: HTMLElementthe element the parent's UI lives in; a level's own UI fragment goes in a child of it
args: URLSearchParams
tier: 'desktop' | 'mobile' | 'low'
engineModule?(name: string): string | undefineda URL of an engine package a worker of a level may import (@ferret/<name>); a parent that ships its engine inside its bundle has none, and a worker then must carry what it uses
camera?(): BABYLON.Camera | undefinedthe parent's own view, made current again when a level goes; without it the camera that was current when the level came, if it still exists

packages/levels/src/dock.ts:14

DockPhysics interface

interface DockPhysics

what the kernel of a physics host gives: bodies of nodes and constraints (dockPhysicsOf(host))

bodyOf(node: Node): unknown | undefined
addConstraint(def: { type: 'fixed' | 'hinge' | 'ball'; a: any; b: any; anchor?: Vec3; axis?: Vec3; limits?: [number, number]; maxForce?: number; userData?: unknown }): { broken: boolean; userData?: unknown }
removeConstraint(c: any): void
moveBody(body: any, position: Vec3, orientation: Quat): voidput a body where its node was placed (the docked actor was moved to the dock)
onBreak(cb: (c: any) => void): () => voidcalled when a constraint breaks; returns the unsubscribe

packages/levels/src/fmdl-docks.ts:31

DocksOptions interface

interface DocksOptions
physics?: DockPhysics
backends?: DockBackend[]
emit?: (name: string, payload: unknown) => void

packages/levels/src/fmdl-docks.ts:61

Environment interface

interface Environment
post?: BABYLON.DefaultRenderingPipeline
sun?: BABYLON.DirectionalLight
shadows?: SunShadowsthe sun's shadows, when the definition asks for them: add(meshes) lets meshes cast and receive
ambient?: BABYLON.HemisphericLight
veil?: FogVeilthe volumetric fog's veil (fog.volumetric); shaders of their own read fogVeilOf(scene)
heightFog?: HeightFogMaterialsthe height fog integrated along each ray (fog.alongRay); values are the shader's numbers at the camera (heightFogShaderValues)
sky?: BABYLON.Mesh
particles: BABYLON.ParticleSystem[]
water: WaterSurfaceView[]
lights?: LightBudget
warnings: string[]effects that could not be made (an unknown kind)
dispose(): void

packages/levels/src/environment.ts:149

EnvironmentDef interface

interface EnvironmentDef

The look of a level beyond its meshes: sun, ambient light, fog, sky and fixed effects. It is the manifest's environment; tools/ue-export writes it from an Unreal level (sun, sky light, height fog, particle emitters). Every part is optional.

sun?: { direction: Vec3; color?: Vec3; intensity?: number; /** 0..1: how much of the atmosphere's reddening of the sun ray (its transmittance at the sun's elevation, scaled so the strongest channel stays 1) tints the light on the ground, as Unreal's atmosphere sun light does; needs `skyAtmosphere`; default 0 */ atmosphereTint?: number; /** cascaded shadow maps of the sun (see sun-shadows.ts); the level loader lets the placed groups and the scene's meshes cast and receive them */ shadows?: SunShadowsDef }the directional light; direction is where the light travels. intensity is in the source engine's units (Unreal lux-like): 4 is about 1 here
ambient?: { color?: Vec3; intensity?: number; direction?: Vec3; ground?: Vec3 }ambient light from the sky: a hemispheric light, a bit darker below. direction is the way its bright side faces (default up: floors are lit most); ground is the colour of the dark side (default color x 0.45). An interior lit from its ceiling faces it down: [0, -1, 0].
fog?: { density?: number; color?: Vec3; heightFalloff?: number; height?: number; maxOpacity?: number; start?: number; cutoff?: number; second?: { density: number; heightFalloff: number; heightOffset?: number }; /** with `heightFalloff`: integrate the fog along each ray from the eye, as Unreal does (height-fog-material.ts), instead of the camera's density for every distance; far peaks keep their shade */ alongRay?: boolean; /** with `alongRay`: Unreal's factor exactly: the transmittance is 2^-(the integral of the density), not e^-, and never below 1 - `maxOpacity` */ unreal?: boolean; /** Unreal's volumetric fog: a veil of the height fog's density times `extinctionScale` over the first `distance` metres (see fog-veil.ts) */ volumetric?: FogVeilDef }exponential fog; density in the source engine's units (per metre, about 10 times smaller here). With heightFalloff it is Unreal's ExponentialHeightFog: the density halves every 1 / (falloff x 0.1) metres above height (the fog actor's height, metres) and grows below it; the view's density follows the camera's height every frame. second is the component's second fog layer. Not done: maxOpacity, start and cutoff (Babylon's exponential fog has no such terms; they are carried in the manifest for a tool that wants them).
skyAtmosphere?: AtmosphereDefUnreal's SkyAtmosphere: the sky dome is the scattering of the sun's light in the planet's air (see atmosphere.ts) instead of the colour gradient. {} is the component's defaults. The sun gives the direction and colour; top / horizon / ground of sky still override the colours the water, the reflection and the fog take from it. The level's BP_Sky_Sphere actor adds nothing: the engine's sky sphere only recolours itself when a level asks it to, and the dome replaces it (postprocess drops the actor).
sky?: { top?: Vec3; horizon?: Vec3; ground?: Vec3 }the sky dome: a gradient from horizon to top with the sun's glow; colours default from the fog colour
reflection?: { intensity?: number; top?: Vec3; horizon?: Vec3; ground?: Vec3; sky?: boolean; size?: number }what metal and gloss reflect: a small cube map filled with a gradient (top / horizon / ground of its own, else the sky's), as the scene's environment texture. Without it a metal surface has nothing to reflect and draws near black (an interior has no sky for it). intensity scales both the reflection and the light the map adds to every surface (default 1; interiors want 0.3-0.6). With sky the map is the sky dome itself, drawn once into a cube of size pixels (default 128) when the dome's shader is ready: the gloss of wet ground and the metal of a hall reflect the clouds, the horizon's glow and the sun as the sky shows them. It only reflects: the light surfaces take from the sky stays the ambient's.
post?: { bloom?: number; threshold?: number }post-processing of the picture: bloom is the source engine's bloom intensity (Unreal's post process volume: 0.675 default, a glowing interior 3-4); bright parts (lamps, windows) glow around. A tier for weak GPUs leaves it out. threshold is the brightness that starts to glow (default 0.95).
probes?: ProbeVolumeDefbaked global illumination (tools/ue-export/bake-gi): when present it lights every surface instead of the flat ambient light
roomReflection?: RoomReflectionDefan interior's reflections: the room drawn once into a cube map after loading (see room-reflection.ts); glass, glaze, metal and polished floors reflect it
effects?: { name?: string; kind?: 'fire'; template?: string; position: Vec3; scale?: number; /** an effect of the vfx catalogue (`fire.torch`, `fire.candle`, `fire.hearth` ...): drawn by the world's vfx service when it has one (else the simple fire); still near the camera only */ vfx?: string; params?: Record<string, number> }[]fixed effects placed in the level
motes?: AmbientParticlesDef[]motes in boxes of air (dust, pollen), see ambient-particles.ts
effectsRadius?: numbermetres: when set, a fire burns only while the camera is within this distance of it (hundreds of torches and candles cost nothing far away); it goes out beyond 1.25 x
water?: WaterDef | WaterDef[]open water: an ocean or a lake (see water.ts); swimming in it is the physics medium of the same surface
landscapes?: LandscapeDef[]layered landscapes (near ground, far backdrop) and the virtual texture blend of the props on them (see landscape.ts); the package loader applies them
materialScale?: MaterialScaleDef[]albedo repairs of baked materials that came out too dark (see material-scale.ts)
foliageWind?: FoliageWindDefwind in the foliage, bending grass, swaying trees and cloth, as Unreal's materials do it (see foliage-wind.ts)
lights?: LightBudgetDefhundreds of lamps and flames under a budget: the nearest few are real lights, the rest glow (see light-budget.ts)

packages/levels/src/environment.ts:24

EnvironmentVfx interface

interface EnvironmentVfx

An effect of the vfx catalogue placed by the environment: it is made out (no particles) and started and stopped as the camera comes near and goes.

start(): void
stop(): void
dispose(): void

packages/levels/src/environment.ts:283

FmdlLoadOptions interface

interface FmdlLoadOptions
tier?: ModelTierthe device tier: which levels are loaded (default desktop)
texture?: (ref: string, srgb: boolean) => Promise<BABYLON.Texture>a texture of the library by its ferret:// reference (default: the file of the dependency package, read through the resolved model's reader; a model's own maps are read from its packages)
variant?: stringthe name of a variant of the materials (render.variants.<name>), a livery or a wear state

packages/levels/src/fmdl.ts:20

Focus interface

interface Focus

A place the player (or a camera) is, with the way it faces: cells ahead are fetched first.

position: BABYLON.Vector3
forward?: BABYLON.Vector3

packages/levels/src/streaming.ts:26

FogVeilDef interface

interface FogVeilDef
extinctionScale: numberUnreal's VolumetricFogExtinctionScale: the veil's density is the height fog's density at the camera times this
distance: numberUnreal's VolumetricFogDistance, metres: the veil's depth
albedo?: [number, number, number]Unreal's VolumetricFogAlbedo (linear, 0..1): the veil's colour is the fog's colour times this (default white)

packages/levels/src/fog-veil.ts:6

FoliageFlowMap interface

interface FoliageFlowMap

a local flow map the foliage reads on top of the wind (FlowMap of

readonly size: number
readonly cell: number
readonly originX: number
readonly originZ: number
readonly data: Float32Array
readonly active: boolean
readonly version: number
readonly lowHeight?: number
readonly highHeight?: number

packages/levels/src/foliage-wind.ts:235

FoliageWindDef interface

interface FoliageWindDef
wind: { intensity: number; direction: [number, number] }Unreal's Wind_intensity and Wind_direction (X, Y)
rules: FoliageWindRule[]
fromMaterials?: booleanthe library materials that carry a grassWind (their master's SimpleGrassWind inputs) flutter by it, with no rule of their own to write; rules may then be empty

packages/levels/src/foliage-wind.ts:31

FoliageWindHandle interface

interface FoliageWindHandle
readonly materials: numberhow many materials took a rule
bendAt(p: { x: number; y: number; z: number } | null, radius?: number): voidthe player's position in the engine's metres (grass bends away from it); null: nobody
setWind(w: { intensity?: number; direction?: [number, number] }): voidchange the wind at run time
readonly current: { intensity: number; direction: [number, number] }the wind now (the same object every call: do not keep it across a change)
dispose(): void

packages/levels/src/foliage-wind.ts:237

FoliageWindRule interface

interface FoliageWindRule

Wind in the foliage, as Unreal's materials do it: the vertex shader moves the vertices (world position offset). Four programs, each a material of Unreal's own set-up (their graphs are written out in plans/port-forest.md), selected by the flags of a rule: - flutter: the engine's SimpleGrassWind function: a vertex swings about a point 10 cm below it, its angle two travelling triangle waves of the world position and time,

   scaled by a weight (a constant, or 1 - v of the first UV set) and by the vertex colour's red channel when the mesh has one (the painted mask: tips move, roots stay);
   a steady push along the wind direction is added (`directional`);

- bend: MF_Collusion (grass bends away from the player): offset = (1 - clamp(distance to the player / distance)) (1 - v)^2 horizontal direction away * strength; - sway: MF_TreesWind's whole-tree rotation about the object's pivot, about the horizontal axis perpendicular to the wind, by an angle of

   ((sin(0.25 (pivotY + t)) + intensity) / 8) * windIntensity / 60 turns, weighted by the height of the vertex in the mesh's bounding box (0 at the foot, 1 at the top);

- swing: the clothesline (M_ClothesLine): a hanging cloth swings about the object's local X axis through the pivot and droops by sin(pi u) * droop (u: the vertex's place

   along the bounding box's X), the swing angle a sine of time shifted by the pivot, the vertex colour's alpha and u, plus a SimpleGrassWind flutter weighted by the alpha.

The wind itself is two numbers of the level (intensity, direction: Unreal's Wind_intensity and Wind_direction of the MPC_Wind_And_COLOR_Parameter collection, the direction in Unreal's X, Y). All lengths here are Unreal's centimetres and turns, the shader converts the engine's metres (x, y, z) to Unreal's (-x, z, y) * 100 and back. The player's position (for bend) is given at run time with bendAt.

match: stringa regular expression over the glTF material name
flutter?: { influence: number; speed?: number; weight?: number; weightFromUV?: boolean; directional?: number; useVertexColor?: boolean; alphaWeight?: { multiplier: number; offset: number }; /** the influence is not scaled by the level's wind and the added offset is `push` centimetres on all three axes: a leaf master's own SimpleGrassWind (see `GrassWindDef` of @ferret/assets) */ absolute?: boolean; push?: number; /** the whole flutter is scaled by one channel (0 r .. 3 a) of a picture the material carries (`levelMaterial.grassWindWeight`), read at the vertex's first texture coordinates */ weightMap?: { channel: number } }
bend?: { distance: number; strength: number }
sway?: { intensity: number }
swing?: { droop: number; speed: number; vertexColorDistortion: number; uvTimeDistortion: number; angleAlongWind: number; againstWind: number; windMultiplier: number; flutterWeight: number; flutterSpeed: number }

packages/levels/src/foliage-wind.ts:19

FormBridgeLike interface

interface FormBridgeLike
define(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => unknown): unknown
lasting(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => { done(): boolean; result?: unknown }): unknown

packages/levels/src/fmdl-motion.ts:480

FreezeOptions interface

interface FreezeOptions
root: stringthe level root's name: only meshes named <root>/... are frozen
sequences?: { tracks?: { target?: unknown }[] }[]sequences of the level (their string track targets are moving)
find?: (name: string) => BABYLON.Node | nullfinds a scene node by a track target / name (the game's own lookup; default: by exact name or /name suffix)
moving?: Iterable<BABYLON.Node>more nodes that move
keepLive?: (mesh: BABYLON.AbstractMesh) => booleanmeshes under the root that a name test keeps live (a game's own rule)

packages/levels/src/static-freeze.ts:10

GlbIndex interface

interface GlbIndex

what the scene glb says about its names: which glTF mesh each node name draws, and how many meshes carry a name

nodeMesh: Map<string, string | null>node name → glTF mesh name (null: nodes of that name draw meshes of different names)
meshCount: Map<string, number>glTF mesh name → how many glTF meshes carry it

packages/levels/src/material-look.ts:106

GroundSource interface

interface GroundSource

The baked ground (colour in rgb, ground height in a; and surface: normal and roughness) of a landscape with a virtual texture, over its rectangle, as materials that blend with the ground read it.

texture: BABYLON.BaseTexture
rect: [number, number, number, number]
toLandscape: () => BABYLON.Matrix
surface?: BABYLON.BaseTexturethe second baked picture: the ground normal's x and z in the landscape's frame (its y is rebuilt: sqrt(1 - x^2 - z^2)) in r and g, the ground roughness in b; absent when the ground has none

packages/levels/src/landscape.ts:581

HairFibreOptions interface

interface HairFibreOptions
exposure?: numberOverall brightness before the tone curve (default 0.6).
lights?: { dir: [number, number, number]; color: [number, number, number] }[]Lights as directions towards the light and colours (intensity folded in). Default: the scene's directional lights (up to three), else a studio key, rim and fill.
ambient?: [number, number, number]Ambient colour (default from the scene's hemispheric lights, else 1).

packages/levels/src/hair-fibre.ts:57

HeightFogDef interface

interface HeightFogDef
density: number
heightFalloff: number
height: numberheight of the fog actor, metres
second?: HeightFogLayer
exact?: booleanthe rays take Unreal's factor exactly (height-fog-material.ts): 2^-integral
maxOpacity?: numberwith exact: the most the fog may cover, 0..1 (default 1)

packages/levels/src/height-fog.ts:10

HeightFogLayer interface

interface HeightFogLayer
density: number
heightFalloff: number
heightOffset?: number

packages/levels/src/height-fog.ts:8

Key interface

interface Key<V>
t: number
v: V
interp?: Interp

packages/levels/src/sequence.ts:16

LandscapeDef interface

interface LandscapeDef
name: string
mesh?: stringregex source for the landscape's mesh names (default ^<name>$)
rect: [number, number, number, number][minX, minZ, maxX, maxZ], metres, in the mesh's own coordinates; the weightmaps and the virtual texture cover it
layers: LandscapeLayerDef[]
weights: string[]weightmap images over rect: file i holds the weights of layers 4i..4i+3 in R, G, B, A
far?: booleanthe far backdrop: no collision, never picked, always drawn; layers and weights are optional for it
virtualTexture?: VirtualTextureDef
packed?: booleanKeep every picture of the landscape in two texture arrays (colour with roughness in alpha; normal with occlusion in alpha) instead of one sampler each: a material then needs the weightmaps, two array samplers and the macro picture, however many layers, far pictures and world aligned pictures there are. Pictures of one array share a size.

packages/levels/src/landscape.ts:119

LandscapeFar interface

interface LandscapeFar
tile: number
albedo?: string
nao?: string

packages/levels/src/landscape.ts:65

LandscapeLayerDef interface

interface LandscapeLayerDef
name: string
albedo: stringcolour image (sRGB); with heightBlend its alpha channel is the layer's height map. '' for a layer that has only a colour
colour?: Vec3a constant colour (linear) instead of a picture: Unreal's far plane master blends vector parameters, not pictures
normal?: stringoptional tangent-space normal image
nao?: stringa packed image of the near picture's normal map (rgb, as stored) and ambient occlusion (alpha), read at the layer's tiling; needs LandscapeDef.packed
flatten?: numberUnreal's FlattenNormal on the layer's normal: the normal moves toward (0, 0, 1) by this fraction (negative: the relief is exaggerated); the layer function's Normal_Intensity
roughness?: stringoptional roughness image (data, its red channel), read at the layer's tiling: Unreal's layer function multiplies it by roughnessScale
roughnessScale?: numberthe layer's roughness multiplier (the function's scalar parameter); with no roughness image the layer's roughness is this number (default 1 when either is given)
tile: numbermetres of one repeat of the layer's textures (Unreal: 100 / the material's UV scale)
tint?: Vec3multiplies the albedo (linear)
heightBlend?: number0 = plain weight blend; above 0 = Unreal's height blend, the layer's height (albedo alpha) times this decides who wins where weights overlap
slope?: LandscapeSlopeUnreal's slope-driven automatic layer (WorldAlignedBlend on the ground normal): see LandscapeSlope
far?: LandscapeFarthe picture for far distances: another tile size (and image); tile 0 is the one texel at uv 0 (a layer whose far scale is 0). Mixed with the near picture by blend
blend?: DistanceBlendthe camera-depth mix of the near and the far picture (Unreal's Distance_Blend); without it the near picture is always used
roughnessAlpha?: booleanthe albedo image's alpha channel is the layer's roughness (data), packed so that the layer needs no sampler of its own for it
saturation?: numberUnreal's Desaturation node: the colour moves toward its luminance by this fraction (negative: more saturated)
power?: numberUnreal's Power node on the colour (the picture's colour, linear)
hue?: numberUnreal's HueShift function: the colour plus the colour turned about the grey axis by this many revolutions (0 turns nothing, so the colour comes out doubled, as the graph's Add does)
world?: LandscapeWorldAligneda world aligned layer: its own picture is the one on steep faces, projected along the axes; see LandscapeWorldAligned

packages/levels/src/landscape.ts:25

LandscapePicture interface

interface LandscapePicture

one picture of a world aligned layer

albedo: stringcolour image, or the same file as another layer's albedo (it then shares that layer's sampler)
tile: number
far?: LandscapeFar
blend?: DistanceBlend
roughnessAlpha?: boolean
roughnessScale?: number
saturation?: number
power?: number
hue?: number
nao?: string
flatten?: number

packages/levels/src/landscape.ts:70

LandscapeSlope interface

interface LandscapeSlope

The layer shows its own picture where the ground is flat and the pictures of two other layers (indices into layers, whatever their paint weights say) where it is steep: colour = mix(mix(steep[0], steep[1], mix), own, flat), each ramp over the up component of the ground normal. Unreal: the M_Landcape 'auto' layer blends rock and gravel by one WorldAlignedBlend and that with the grass by another.

steep: [number, number]
flat: SlopeRamp
mix: SlopeRamp

packages/levels/src/landscape.ts:106

LandscapeTextures interface

interface LandscapeTextures
arrays?: { albedo: BABYLON.BaseTexture; nao?: BABYLON.BaseTexture }
weights: BABYLON.BaseTexture[]
albedo: (BABYLON.BaseTexture | undefined)[]
normal: (BABYLON.BaseTexture | undefined)[]
roughness?: (BABYLON.BaseTexture | undefined)[]
extra?: BABYLON.BaseTexture[]

packages/levels/src/landscape.ts:464

LandscapeView interface

interface LandscapeView
def: LandscapeDef
meshes: BABYLON.AbstractMesh[]
virtualTexture?: BABYLON.BaseTexturethe baked virtual texture (colour in rgb, ground height in a), when the landscape has one
virtualSurface?: BABYLON.BaseTextureits second picture: the ground normal (x, z in the landscape's frame) and the roughness (see GroundSource.surface)
requiredMaxZ?: numbercamera depth (maxZ) a far landscape needs to be seen whole: the rectangle's diagonal plus the camera's height over it, rounded up
warnings: string[]
dispose(): void

packages/levels/src/landscape.ts:678

LandscapeWorldAligned interface

interface LandscapeWorldAligned

Unreal's MF_Rock_Cliff: three world aligned pictures stacked by the slope of the ground. The layer's own picture is on steep faces; flat takes over where the up component of the ground normal rises over flatRamp ([from, to]: 0 below from, 1 above to), top (grass) over topRamp. macro multiplies the colour by powers of a large scale variation picture (Unreal's Micro_Variation inputs): the colour times prod(pow(texture(uv / tiles[k]).rgb, powers[k])); the picture is data, not colour.

flat: LandscapePicture
flatRamp: [number, number]
top?: LandscapePicture
topRamp?: [number, number]
macro?: { albedo: string; tiles: [number, number, number]; powers: [number, number, number] }

packages/levels/src/landscape.ts:90

LevelContext interface

interface LevelContext

What a level's builder gets. Everything it makes (nodes, lights, materials, entities) is removed again when the level goes.

world: World
scene: BABYLON.Scene
level: LevelDef
addSpawn(s: { id: string; position: BABYLON.Vector3 | [number, number, number]; yaw?: number; human?: string }): voiddeclare where the player may start
progress(p: number): voidreport progress 0..1 to the loading screen

packages/levels/src/levels.ts:11

LevelDef interface

interface LevelDef

One entry of the level registry (the equivalent of a row of UE's DT_LevelInfo).

id: string
name?: string
url?: stringa level package folder: scene.glb, manifest.json, navmesh.bin (see ./package)
build?(ctx: LevelContext): void | Promise<void>or code that builds the level: procedural levels, greyboxes, tests
spawn?: stringthe spawn used when the level is entered without naming one (default: the first declared)
data?: Record<string, unknown>anything the game wants to keep with the level: music, weather, display name
tags?: string[]free tags (a theme, a chapter): handed to the game's choices, never read by the engine
environment?: { skip?: EnvironmentPart[] }parts of the level's environment the game draws itself (its own sky, its own water): the loader leaves them out; the rest is as the manifest says
prepare?(progress: (p: number) => void, signal?: AbortSignal): Promise<void>Get what the level needs ready before the old level is touched (a remote level opens its package here). If it throws the travel fails and the player stays in the current level. progress takes 0..1 of this step.
plan?(): Promise<LevelPlan>What fetching the level will download, known after prepare: bytes and files not held yet, and whether everything is already on the device.
fetch?(ctx: { signal: AbortSignal; progress(loaded: number, total: number, files: number): void; /** files read at once (default: the level's own choice; a background prefetch asks for 1) */ concurrency?: number }): Promise<void>Step 4 of a travel: bring the core set of the level to the device. progress takes bytes. A failure or a cancel leaves the old level in place.

packages/levels/src/levels.ts:22

LevelFiles interface

interface LevelFiles

What the level materials read the package through (the package loader's own fetch, never the library).

json(path: string): Promise<any>
blobUrl(path: string): Promise<string>a URL the engine can load the file from (a blob URL of the fetched bytes)

packages/levels/src/level-materials.ts:146

LevelManifest interface

interface LevelManifest
version: number
name?: string
scene?: stringfile names inside the package folder (defaults: scene.glb, navmesh.bin)
navmesh?: string
navBuild?: { agentRadius?: number; agentHeight?: number; maxClimb?: number; maxSlope?: number; cellSize?: number; bounds?: NavBoxDef | NavBoxDef[]; exclude?: (NavBoxDef & { yaw?: number })[] }how to build the NavMesh from the level's solid meshes: used when navmesh.bin is missing (or being rebuilt by the editor)
collision?: stringa mesh of simple collision shapes (invisible, solid). When present, the visible meshes of the scene do not collide
collisionChunks?: CollisionChunksDefthe solid shapes outside the play area, cut into chunks that are fetched as the player nears them (see CollisionChunksDef); written by tools/ue-export/collision.mjs. Needs collision
movement?: Partial<Record<(typeof MOVEMENT_KEYS)[number], number>>the values of the level's player character (metres, seconds; see CharacterParams in
animGraphs?: Record<string, unknown>animation graphs by name (see GraphDef in
entities?: ManifestEntity[]
spawns?: ManifestSpawn[]
zones?: unknown[]
physics?: Record<string, unknown>realistic physics for this level (see PhysicsConfig in
vfx?: { defs?: unknown[]; place?: unknown[] }effects of the level (see VfxBlock in
libraries?: Record<string, string>the library packages the level needs, id -> version range: written by the editor from what the open libraries provide; travel requires them before the level is built
colliders?: { node: string; collide: boolean }[]collision overrides by glTF node name: make a node (and its meshes) solid or walk-through whatever the export says
defaultSpawn?: stringthe spawn used when the level is entered without naming one
environment?: EnvironmentDefsun, ambient light, fog, sky and fixed effects (see EnvironmentDef)
materialLooks?: MaterialLooksthe look of the scene's glTF materials, by TYPE (a model: its uid, all instances) and by INSTANCE (one object: its uid, over the type's look), then by the glTF material name inside the model (see material-look.ts): colour, metallic, roughness, emissive, normal scale, alpha mode, maps; set live by the editor (edit.material.set)
tags?: string[]free tags and data for the game (a theme, a chapter, a mood): handed to the game's choices (LevelDef.tags / data), never read by the engine
data?: Record<string, unknown>
placements?: string[]placement lists (*.placements.json, see placements.ts) loaded with the core: library models placed with GPU instancing, material overrides per actor
levelMaterials?: LevelMaterialsRefthe level's own materials (level-materials.ts): materials a file of definitions (ferret-materials/1) or them inline, textures the catalogue of the level's KTX2 files (a file or inline), codec the one policy that picks UASTC or ETC1S (best, light, chosen; default best). A mesh slot of a placed model takes the material of its name; no library is asked
streaming?: StreamingBlockstreaming inside the level: scene is then the core (what is visible and solid at the spawn) and the rest arrives by cell
visibility?: VisibilityBlockprecomputed visibility for a level of rooms: what is not in sight from the player's grid cell is not drawn (see VisibilityBlock)
snapshot?: booleanthe level keeps its draw list while it runs (its moving things only move): on a WebGPU engine its frame is recorded once and replayed
occlusion?: boolean | { minRadius?: number; minIndices?: number; algorithm?: 'conservative' | 'accurate' }occlusion queries on the level's big meshes; sizes in metres and indices
relevance?: RelevanceBlockthe level's own values for the relevance service: per camera mode the largest turn rate omega (rad/s) and the horizon (s), and the tuning; they win over what the engine reads from the camera

packages/levels/src/manifest.ts:84

LevelMaterialOverride interface

interface LevelMaterialOverride

A material of the level (level-materials.ts) standing in for a material of the model, by the name it has in the level's definitions.

material: string

packages/levels/src/placements.ts:39

LevelMaterialsFile interface

interface LevelMaterialsFile
format: typeof LEVEL_MATERIALS_FORMAT
materials: Record<string, MaterialDef>

packages/levels/src/level-materials.ts:42

LevelMaterialsOptions interface

interface LevelMaterialsOptions
policy?: LevelCodecPolicythe file policy of two-codec textures (default best)
warn?: (message: string) => void
makeTexture?: (path: string, o: { srgb: boolean; scene: BABYLON.Scene }) => BABYLON.BaseTexture | Promise<BABYLON.BaseTexture>make a texture from a file of the level (default: a Babylon texture from the blob URL, resolved when loaded; tests pass their own)
anisotropy?: numberthe anisotropy of the textures (default 8, Unreal's default texture filter)
programTextureBudget?: numberHow many pictures a program (a master carried whole) may read one by one (default 8: a fragment shader has 16 texture units and Babylon's own lighting, shadows, reflection and the level's decal buffer and distance field take some). A program with more has its pictures put into texture arrays by size and format (texture-array.ts): one unit per array. Not used with makeTexture (a test's own pictures are not KTX2 files).
readyTimeoutMs?: numberthe longest ready() waits for the transcoding of textures already read (default 20000 ms; a texture still not decoded is a warning)
video?: (mediaTexture: string, scene: BABYLON.Scene) => BABYLON.BaseTexture | undefined | Promise<BABYLON.BaseTexture | undefined>the picture of a video material (an unlit master whose colour is a media texture): the level's assembly hands the video source; none given, the surface stays its base colour

packages/levels/src/level-materials.ts:169

LevelMaterialsRef interface

interface LevelMaterialsRef

Where the level's own materials come from: file names (read through the loader) or definitions inline, the texture catalogue likewise, and the codec policy (default best).

materials?: string | Record<string, MaterialDef>
textures?: string | Record<string, unknown> | unknown[]
codec?: LevelCodecPolicy
distanceField?: stringthe header of the level's distance field (distance-field.ts), for the materials that read it
screenDecals?: stringthe file of the level's projected decals (screen-decals.ts): { decals: ScreenDecalSpec[] }, each naming one of the level's materials

packages/levels/src/placements.ts:41

LevelOptions interface

interface LevelOptions

Minimum time the loading screen stays up, so it does not flash (ms; 0 in tests).

minLoadingMs?: number
slowMs?: numberno new bytes for this long while the target downloads: travel:slow {slow: true} (default 5000)
holdMs?: numberthe longest the level waits, after it is built, for what its entities asked to be waited for (hold) before it is announced ready anyway (default 20000; what was missing goes to the report's warnings)
keepOldUntilReady?: booleantrue on devices with room: a failed travel rebuilds the old level and returns the player to the spot; false (console): to the hub
transitionEnterMs?: numberhow long a transition has to get on screen before the engine's bar replaces it (default 2000)

packages/levels/src/levels.ts:86

LevelPlan interface

interface LevelPlan
bytes: number
files: number
cached: boolean

packages/levels/src/levels.ts:51

LevelReport interface

interface LevelReport
warnings: string[]things the manifest asked for that the level could not provide: missing nodes, unknown behaviours ...

packages/levels/src/levels.ts:80

LevelTextureCatalogue interface

interface LevelTextureCatalogue
textures: Map<string, LevelTextureEntry>

packages/levels/src/level-materials.ts:40

LevelTextureEntry interface

interface LevelTextureEntry
stem: string
srgb?: boolean
codec?: LevelCodec
files: Partial<Record<LevelCodec, string>>

packages/levels/src/level-materials.ts:39

LibraryCard interface

interface LibraryCard

a candidate as the AI that asks reads it

id: string
uid?: string
type: string
name: string
tags: string[]
rubric?: string
description?: string
preview?: string
size?: number
versions?: string[]

packages/levels/src/library.ts:81

LibraryCharacter interface

interface LibraryCharacter
readonly id: string
readonly item: CharacterItem
readonly model: ModelHandle
readonly clips: ClipRef[]the clip sets of the character, resolved from the catalog
dispose(): void

packages/levels/src/library.ts:113

LibraryContext interface

interface LibraryContext

What install gets.

world: World
ferret: anythe engine's API (every package's exports in one namespace)
pkg: { id: string; version: string; manifest: FerretPackage['manifest'] }this package
mount: PackageMount
url(path: string): Promise<string>a blob URL for a file of this package, or ferret://dep/path of a declared dependency
require(id: string): unknownthe exports of a declared dependency's code (already loaded before this one)

packages/levels/src/code.ts:20

LibraryEntry interface

interface LibraryEntry extends CatalogAsset
id: string
version?: stringthe library version this entry was resolved to (the reference's, or 1.0.0); set by entry(), absent from list()
versions?: string[]every version of the asset (the server's numbers, oldest first); set by list()

packages/levels/src/library.ts:71

LibraryFind interface

interface LibraryFind

a request to the library service: keywords (English), narrowed by exact type, rubric (and everything beneath it) and tags

q?: string
type?: string
rubric?: string
tags?: string[]
limit?: number
offset?: number

packages/levels/src/library.ts:79

LibraryModel interface

interface LibraryModel

A static library model on its way (a tree, a rock): model is the handle, item its file (bounds, collision).

readonly id: string
readonly item: ModelItem
readonly model: ModelHandle
dispose(): void

packages/levels/src/library.ts:100

LibraryModule interface

interface LibraryModule

What a package's code module exports. install may return { dispose } or a promise of it.

install?(ctx: LibraryContext): unknown
[name: string]: unknown

packages/levels/src/code.ts:34

LibraryQuery interface

interface LibraryQuery
type?: LibraryItem['type']
tags?: string[]
text?: string
rubric?: string

packages/levels/src/library.ts:70

LibrarySound interface

interface LibrarySound
readonly id: string
readonly name: string
readonly item: SoundItem
readonly format: 'wav' | 'mp3'

packages/levels/src/library.ts:148

LightBudgetDef interface

interface LightBudgetDef
budget: numberhow many real lights at most. A quality tier sets it in its own manifest (a weak GPU 2-3, a strong one 8-12)
items: BudgetLight[]
perMesh?: numberhow many real lights one material draws (the cost per pixel), default the budget, at most MAX_MATERIAL_LIGHTS - 2. Each mesh takes the pool's lights that reach it first (see sortMeshLights), so a pool larger than this costs no more per pixel: a big pool with a small perMesh lights a hall of hundreds of lamps where each surface sees its own nearest few
interval?: numberseconds between two re-rankings (default 0.25)
fade?: numberseconds a light takes to fade out of / into a real light (default 0.35)
hysteresis?: numbera new light must be nearer than the one it replaces by this share to take its place (default 0.15): no flapping between two equal lamps
maxDistance?: numberlights farther from the camera than this are nothing at all (default 200 m)
rank?: 'distance' | 'view'how the real lights are chosen. 'distance' (default): the nearest to the camera. 'view': the ones whose reach (sphere of range) is in the camera's view, largest on screen first (range / distance): a lamp behind the camera that lights nothing in view gives way to the lamps that light what the player sees (Castle: the lamps at a door 20 m ahead lost to the candles over the player's head)
falloff?: 'gltf' | 'linear' | 'unreal'how a light fades with distance. 'gltf' (default): 1/d^2 cut off at range (physical, Unreal's inverse-squared lights). 'linear': 1 - d/range, the intensity is the value at the source (Babylon's standard falloff): Unreal's legacy lights fade as (1 - (d/R)^2)^8 and stay near their source, which a line through the same half-value point follows closely (tools/ue-export/lights.mjs falloff), but its edge is a visible ring on a near wall. 'unreal': Unreal's own curve (1 - (d/range)^2)^8 with range the attenuation radius, soft to zero at its edge. It replaces Babylon's standard falloff in the PBR shader for the whole page (see useUnrealFalloff; nothing else in Ferret uses the standard falloff)
excludeMeshes?: stringa regular expression on mesh names: the pool's real lights do not light these meshes (a surface that already carries its lamps' light baked in, see tools/ue-export/bake-direct.mjs: the real light would count twice, and the baked one shows at any distance)
glow?: { enabled?: boolean; /** colour multiplier (above 1 feeds bloom), default 2 */ boost?: number; /** metres, default from each light's range */ size?: number }the dot for lamps that are not real lights
clustered?: booleanevery lamp is a real light, drawn through Babylon's clustered lighting (ClusteredLightContainer: lights are binned into screen tiles and depth slices, a material reads only its tile's lights) instead of a pool of the nearest few: no 8-light limit per material, no ranking, no glow dots, no per-mesh sorting. budget is ignored (every item is a light). Needs WebGL2 / WebGPU and spot or point lights; where the engine cannot (BABYLON.ClusteredLightContainer missing or unsupported) the pool works as before. excludeMeshes does not apply to clustered lights
sounds?: { budget: number; maxDistance?: number }the nearest lamps that have a sound: events tell which to start and stop

packages/levels/src/light-budget.ts:42

LightBudgetOptions interface

interface LightBudgetOptions
name?: string
viewer?: () => Vec3 | undefinedwhere the viewer is, in the level's metres; default the active camera
materials?: booleanraise the materials' light limit to fit the pool plus the sun and ambient lights (default true)

packages/levels/src/light-budget.ts:157

LightBudgetStats interface

interface LightBudgetStats
items: number
budget: number
real: number
glowing: number
reranks: number
soundsOn: number

packages/levels/src/light-budget.ts:155

LoadableModel interface

interface LoadableModel

what load takes: a resolved model with the reader of its chain's files (FmdlModel.stageModel(), a ResolveResult)

resolved?: ResolvedModel
read?: (qualified: string) => Promise<Uint8Array>

packages/levels/src/fmdl-code.ts:66

LoadedCode interface

interface LoadedCode
id: string
version: string
exports: LibraryModule | nullthe module's exports; null for a package without code (only its dependencies were loaded)
commands: string[]commands and behaviours that appeared while install ran
behaviours: string[]

packages/levels/src/code.ts:39

LookDef interface

interface LookDef
colourLayers?: ColourLayersDef
macro?: MacroVariationDef[]
groundBlend?: GroundBlendDef
vertexMasks?: VertexMasksDef
aoOnIndirect?: boolean
pixelDepth?: PixelDepthDef
detailNormal?: DetailNormalDef
patternLayer?: PatternLayerDef
flatten?: numberUnreal's FlattenNormal of the material's own normal map: n' = normalize(vec3(n.xy * s, 1 - (1 - n.z) * s)); a level material's normalScale (not 1)
opacityGradient?: OpacityGradientDef
depthFade?: DepthFadeDef
opacity?: number
graph?: GraphDef
srgb?: readonly string[]names of the pictures of masks that are sRGB colour

packages/levels/src/material-models.ts:145

LookStructure interface

interface LookStructure

What the shader is built from: part of the define's name, so two materials of one structure share a program and two of different structure never do. Fields that are off are absent.

base: 'albedo' | 'colour' | 'graph' | 'none'
layers: { mask: string; channel: MaskChannel; uv?: true; invert?: true }[]uv: its mask is read at a scale of its own; invert: the colour is painted where the mask is 0
macro: { mask: string }[]
ground: boolean
vc?: { ao: boolean; opacity: boolean }vertex colours read as masks: the red channel as occlusion, the alpha as a factor of the opacity mask
depth?: truepixel depth offset
flat?: truethe material's own normal is flattened exactly as Unreal's FlattenNormal (the tilt and the z term scaled)
detail?: { map: string }the detail normal's picture
pattern?: { mask: string; channel: MaskChannel; normal?: string; occlusion?: string; occlusionChannel: 'r' | 'g' | 'b' | 'a' }a pattern's normal and occlusion over the material's own by a mask
fade?: { gradient?: { axis: 'u' | 'v'; invert: boolean }; opacity?: true; depth?: true }the opacity: a gradient along u or v, a constant, the depth behind the surface
gview?: truethe graph reads the pixel's depth: the view matrix is bound
graph?: GraphDefthe master as an expression tree (which outputs it sets is read off the tree)
srgb?: string[]names of the pictures that are colour (sRGB), decoded in the shader
aoIndirect?: truethe material's occlusion dims indirect light only

packages/levels/src/material-models.ts:117

LookTarget interface

interface LookTarget

an address the scene answers to

scope: LookScope
uid: string
via: string[]where the uid comes from: extras, model, library, mesh (type); extras, entity, actor, path (instance)
meshes: numbermeshes (placed actors count once each) it covers
materials: string[]the glTF material names found on them
ambiguous?: stringwhy a write on it is refused (absent: it is one thing)

packages/levels/src/material-look.ts:152

MacroBlend interface

interface MacroBlend
exponentX: number
multX: number
exponentYZ: number
multYZ: number

packages/levels/src/material-models.ts:61

ManifestEntity interface

interface ManifestEntity
id: string
behaviour?: stringa behaviour or component registered in the world (world.components)
components?: { name: string; params?: Record<string, unknown> }[]several components, each with its own parameters, when one behaviour is not enough
node?: stringthe name of a glTF node to wrap; without it a new empty node is made
transform?: { position?: [number, number, number]; rotation?: [number, number, number]; scale?: [number, number, number] }local transform applied to the node (or the new node)
params?: Record<string, unknown>
tags?: string[]
needs?: stringthe id of a streaming bundle this entity depends on: it is created once the bundle is in, and a placeholder stands at its position until then. It may also be the id of a streaming cell: the entity wraps a node of that cell, is made whenever the cell is resident and destroyed when the cell is released (no placeholder)

packages/levels/src/manifest.ts:16

ManifestIssue interface

interface ManifestIssue
path: string
message: string

packages/levels/src/manifest.ts:163

ManifestSpawn interface

interface ManifestSpawn
id: string
position: [number, number, number]
yaw?: number
human?: string

packages/levels/src/manifest.ts:82

MaterialInfo interface

interface MaterialInfo
name: string
meshes: number
look: boolean
baseColor: [number, number, number, number]
metallic: number | null
roughness: number | null
emissive: [number, number, number]
emissiveStrength: number
normalScale: number | null
alphaMode: 'opaque' | 'mask' | 'blend'
doubleSided: boolean
maps: Partial<Record<MaterialMapSlot, boolean>>

packages/levels/src/material-look.ts:145

MaterialLookDef interface

interface MaterialLookDef
baseColor?: [number, number, number] | [number, number, number, number]
metallic?: number
roughness?: number
emissive?: [number, number, number]
emissiveStrength?: number
normalScale?: number
alpha?: { mode: 'opaque' | 'mask' | 'blend'; cutoff?: number }
doubleSided?: boolean
maps?: Partial<Record<MaterialMapSlot, string>>

packages/levels/src/material-look.ts:30

MaterialLooks interface

interface MaterialLooks
types?: LookTable
instances?: LookTable

packages/levels/src/material-look.ts:43

MaterialLooksHandle interface

interface MaterialLooksHandle
update(looks: MaterialLooks | undefined): voidreplace the looks: only what changed is touched
targets(scope: LookScope, o?: { filter?: string; limit?: number; aliases?: boolean }): Promise<{ entries: LookTarget[]; total: number; truncated: boolean }>the scene's addresses of a scope (regex filter on the uid; the most used first, limit of them). A model is listed by its best uid; aliases lists its other names (placement key, library id, glTF mesh name) too: they all work as addresses
resolve(scope: LookScope, uid: string): Promise<LookTarget | null>one address, or null when nothing of the scene answers to it
read(scope: LookScope, uid: string, material: string): MaterialInfo | nullthe values of that material on the first mesh the address covers, now (what the screen shows)
ready(): Promise<void>resolves when the names the looks need are read and the scene is in step with them
dispose(): voidtakes every look off and stops watching

packages/levels/src/material-look.ts:164

MaterialLooksOptions interface

interface MaterialLooksOptions
textureUrl?: (ref: string) => Promise<string> | stringthe URL a map reference is read from (a file of the level's folder, a URL, a ferret:// file); default: absolute URLs as they are
warn?: (message: string) => voida problem to report (a map that could not be read, an ambiguous address)
glbIndex?: () => Promise<GlbIndex | null>the names of the scene glb (for the type fallback by glTF mesh name); read only when a look or a listing needs it

packages/levels/src/material-look.ts:136

MaterialOptions interface

interface MaterialOptions
variant?: string
name?: string
scene?: BABYLON.Scene

packages/levels/src/library.ts:132

MaterialOverride interface

interface MaterialOverride

A library material standing in for a material of the model.

library: string
variant?: string

packages/levels/src/placements.ts:37

MaterialScaleDef interface

interface MaterialScaleDef

Repair of baked materials that came out wrong from the Unreal export. match is a regular expression over the glTF material name; then - flat: [r, g, b] (0..255, sRGB) replaces the albedo picture by one colour (the picture's average over its painted texels, kept in the build config).

   The exporter bakes some materials over the lightmap UVs, so the picture is an atlas of islands on a black background while the mesh reads it through
   its first UV set: part of the surface lands on black. The surface turns matte (the bake's metal/roughness picture is the same wrong atlas); the normal map stays;

- flatLinear: [r, g, b] (0..1, LINEAR, as a material parameter of the original gives it) does the same with the colour as the shader takes it: flat divides

   its sRGB numbers by 255 and hands them to the shader as they are, so it draws lighter than the picture it was read from (kept as it is for the levels built on it);

- albedo is a LINEAR multiplier of the albedo (the light the surface returns): 2 makes it twice as bright; - noVertexColors: true stops the meshes of the material from tinting it with their vertex colours. Unreal's painted vertex colours are masks the

   material blends with (moss, dirt), already baked into the picture, but glTF viewers multiply the albedo by them: violet and cyan blotches on the walls.
   (An InstancedMesh draws with its source mesh's flag, so the source is the one switched.)

It covers the materials that exist now and every one a streamed cell adds later (they are handled once their picture or mesh is set, at most 300 frames later).

match: string
flat?: [number, number, number]
flatLinear?: [number, number, number]
albedo?: number
noVertexColors?: boolean

packages/levels/src/material-scale.ts:18

ModelCodeGame interface

interface ModelCodeGame

the part of the game language's binding the code gives its functions to (installGame)

provide(functions: Record<string, (...args: any[]) => unknown>, declarations?: Array<{ name: string; kind: ModelFunctionKind; args?: ModelValueType[] | null; returns?: ModelValueType | null }>): () => void

packages/levels/src/fmdl-code.ts:68

ModelCodeOptions interface

interface ModelCodeOptions
world?: Worldthe world: its physics host runs the step hooks, and it gets the commands model.functions and model.call
origin?: (pkg: string, manifest: PackageManifest) => booleandoes this package come from where the game does (shipped with it, its own site)? Then its code is the game's
trusted?: () => Iterable<string> | undefinedkey ids whose signatures are trusted; without them any valid signature is enough
sharedEngine?: () => Iterable<string>the parent ships its engine inside its bundle (shareEngine): the names of the packages it holds
importModule?: (bytes: Uint8Array, path: string) => Promise<ModuleExports>import a module from its checked bytes (default: a blob URL and import())

packages/levels/src/fmdl-code.ts:53

ModelDescribed interface

interface ModelDescribed
id: string
abstract: boolean
lineage: string[]
description: ModelDescription
markdown: string

packages/levels/src/fmdl-catalogue.ts:21

ModelFunctionInfo interface

interface ModelFunctionInfo
name: string
kind: ModelFunctionKind
params: NonNullable<ModelFunction['params']>
returns?: ModelValueType
description: string
model: string

packages/levels/src/fmdl-code.ts:71

ModelHandle interface

interface ModelHandle

A model on its way. node is the placeholder until the model is in, then the model's root.

readonly ref: string
readonly state: ModelState
readonly node: BABYLON.TransformNode | null
readonly ready: Promise<{ root: BABYLON.TransformNode; dispose(): void } | null>resolves with the instance, or null when it failed or was disposed (the reason is in error and the asset:failed event)
readonly error?: StreamError
dispose(): void

packages/levels/src/runtime.ts:37

ModelInstance interface

interface ModelInstance

What a function and a hook of a model's code get first: the instance it works on.

readonly name: stringthe name of the actor on the stage
readonly model: stringthe id of its model, and of the chain it comes from (the root ancestor first)
readonly lineage: string[]
readonly data: ModelJsonthe merged model.json: the model's own data is in its physics and in its x- fields
readonly actor: Actor
readonly root: Actor['root']
readonly rig: PartRig
readonly stage: ModelStage
readonly world: World | undefined
readonly time: numberthe stage's time, seconds of fixed steps
readonly state: Record<string, any>what this instance keeps between calls and steps
call(fn: string, ...args: unknown[]): unknowna function of this instance
other(name: string): ModelInstance | undefinedanother instance that has code
read(path: string): Promise<Uint8Array>a file of the model by the path data names it with

packages/levels/src/fmdl-code.ts:27

ModelListing interface

interface ModelListing
id: string
summary?: string
kind?: string
category?: string
tags: string[]
abstract: boolean
extends?: string
score: number

packages/levels/src/fmdl-catalogue.ts:20

ModelOptions interface

interface ModelOptions extends Pick<RequireOptions, 'priority' | 'signal' | 'sha256' | 'size' | 'pkg'>
placeholder?: PlaceholderSpecshown at once, replaced by the model (default: a small box); 'none' shows nothing until the model is in
parent?: BABYLON.TransformNodethe node the model hangs from (an entity's node): the placeholder and then the model are its children
position?: [number, number, number]
name?: string

packages/levels/src/runtime.ts:25

ModelPlacement interface

interface ModelPlacement extends Omit<ModelOptions, 'pkg'>
tier?: LibraryTier
yaw?: number

packages/levels/src/library.ts:97

MountAssets interface

interface MountAssets extends PackageAssets

What the mount needs from the asset cache (an AssetCache fits).

load(url: string, ext?: string): Promise<void>

packages/levels/src/ferret.ts:14

MountOptions interface

interface MountOptions
packages?: PackageSetthe packages that are open together (default: a new set); ferret://<id>/<path> is looked up in it
loader?: Partial<PackageLoaderOptions>passed on to the level loader (collisions, an editor's draft manifests ...)
fetch?: (url: string) => Promise<FetchResult>replace fetch for urls that are not in a package

packages/levels/src/ferret.ts:21

OcclusionOptions interface

interface OcclusionOptions

Occlusion queries for the big meshes of an interior: the GPU says which large meshes are hidden behind others (a castle's walls hide most of the level), and the CPU stops recording their draws. Babylon runs the queries on WebGL2 (mesh.occlusionType); a query's answer is a frame late, so only meshes that are large and heavy enough to be worth a query get one (minRadius metres of bounding sphere, minIndices indices), and the type is optimistic: a mesh with no answer yet is drawn. Meshes under root only; unapply gives them back. Where the engine has no occlusion queries nothing happens.

root: stringthe level root's name: only meshes named <root>/... get queries
minRadius?: numberbounding sphere radius a mesh needs, metres (default 3)
minIndices?: numberindices a mesh needs (default 3000)
algorithm?: 'conservative' | 'accurate''conservative' (default: a query is skipped for a frame after it was seen) or 'accurate' (a query every frame)

packages/levels/src/occlusion-culling.ts:10

OceanOptions interface

interface OceanOptions
name?: string
radius?: numberhow far the grid reaches, metres (default 150 km: the horizon from 6 km up is 280 km away, but the haze has the rest)
rings?: number
sectors?: number
depthAt?: (x: number, z: number) => numbermetres of water under (x, z), negative on land; omitted: deep everywhere
far?: numberthe three depth boxes round the camera: edge length in metres (default 400 km, 48 km and 8 km) and texels (default 256); the far one tells the land from the sea to the horizon, so the sea is never drawn under distant land (where the depth buffer could not keep them apart)
coarse?: number
fine?: number
texels?: number
rowsPerFrame?: numberrows of a depth texture baked per frame once it has to move (default 24)
fog?: 'exp' | 'exp2'the fog: 'exp' (density per metre) or 'exp2'

packages/levels/src/ocean.ts:17

OceanWave interface

interface OceanWave
wavelength: number
amplitude: number
steepness?: number
direction?: number

packages/levels/src/ocean.ts:16

OpenedDependency interface

interface OpenedDependency

A dependency that was opened: which catalog it came from and the URL of the file that was read.

id: string
version: string
range: string
catalog: string
url: string
pkg: FerretPackage
libraryVersion?: string

packages/levels/src/dependencies.ts:24

PackageAssets interface

interface PackageAssets

What the loader needs from @ferret/assets (an AssetCache fits).

load(url: string): Promise<void>
instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }>
release(url: string): void

packages/levels/src/package.ts:27

PackageCommandHooks interface

interface PackageCommandHooks
resolve?: (url: string) => PackageInput | Promise<PackageInput>turn a url or name into something FerretPackage.open reads (default: the url itself)
opened?: (pkg: FerretPackage, url: string) => voidtold when a package was opened from url (so a host can write changes back to where it came from)
write?: (pkg: FerretPackage, name: string, bytes: Uint8Array) => Promise<void>write a built .ferret (a file next to the source, a download); without it pkg.pack only reports what it built
publish?: (files: Record<string, Uint8Array>) => Promise<void>put the files of pkg.publish where the server serves them: { path: bytes }, paths relative to the site root (a folder to upload, a CDN)
persist?: (pkg: FerretPackage) => Promise<{ files?: number; bytes?: number; appended?: number; dead?: number; compacted?: boolean } | void>keep an edited package: a folder package writes its changed files, a zip is packed again. Called by \pkg.save\
compact?: (pkg: FerretPackage) => Promise<{ before: number; after: number }>write a project (.fprj) again without the bytes its saves left behind (compactZip): where it came from, or a download. Called by pkg.compact
behaviours?: () => Iterable<string>behaviours the game registers itself (for \pkg.validate\)
trusted?: () => Iterable<string> | undefinedkey ids the reader trusts (for \pkg.verify\ and the code check)

packages/levels/src/commands.ts:8

PackageLoaderOptions interface

interface PackageLoaderOptions
assets: PackageAssets
fetch?: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any>; arrayBuffer(): Promise<ArrayBuffer> }>replace fetch (tests, a Platform file API)
collisions?: booleanmake the level's meshes collide (default true)
manifest?: (def: LevelDef) => LevelManifest | undefineda manifest to use instead of the one in the package: the editor's draft (return undefined to load the file)
streamingRadiusScale?: numberscale the streaming radii of every streamed level (a tier may ask for less)
forceNavBuild?: (def: LevelDef) => booleanbuild the NavMesh from navBuild even if navmesh.bin exists (the editor, after a rebuild)
placements?: PlacementResolverfinds library models and materials by id for placement lists (*.placements.json; an AssetLibrary gives it: placementResolver()); lists that name only ferret:// files need none

packages/levels/src/package.ts:33

Placement interface

interface Placement
actor: string
model: stringa key of models
position: Vec3
rotation?: Quat
scale?: number | Vec3
materials?: Record<string, MaterialOverride | LevelMaterialOverride>
node?: stringDraw this actor on its own, not as a thin instance: a node of this name (Actor>Component: a node Actor with a child Component, as an entity's node names it) that a behaviour can move (a door that swings). Actor holds the actor's position and rotation, Component is the part that is turned (identity), and the model's meshes hang under it with the actor's scale; the cell that holds the list is the needs of the entity. Without a > the single node holds position and rotation.

packages/levels/src/placements.ts:46

PlacementBuildOptions interface

interface PlacementBuildOptions
scene: BABYLON.Scene
instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }>make an instance of a loaded model file (an asset cache's instantiate)
urls: Map<string, string>the file reference of each model name of the placement list (resolved before; see PlacementSource.load)
resolver?: PlacementResolver
materials?: Map<string, Promise<BABYLON.Material>>library materials already made, by id#variant (shared by the cells of one level: a material is made once, the library owns it)
levelMaterials?: LevelMaterialsthe level's own materials: a mesh slot named like one of them takes it, and { material } overrides pick one by name
warn?: PlacementWarnings
name?: stringthe root of the new nodes is named so (default placements)

packages/levels/src/placements.ts:170

PlacementFile interface

interface PlacementFile
format: typeof PLACEMENTS_FORMAT
models: Record<string, PlacementModel>
actors: Placement[]
levelMaterials?: LevelMaterialsRef

packages/levels/src/placements.ts:59

PlacementGroup interface

interface PlacementGroup
key: string
model: string
mirrored?: boolean
materials?: Record<string, MaterialOverride | LevelMaterialOverride>
actors: Placement[]
node?: string

packages/levels/src/placements.ts:133

PlacementInstance interface

interface PlacementInstance
root: BABYLON.TransformNode
groups: { key: string; model: string; meshes: BABYLON.Mesh[]; actors: string[] }[]one entry per drawn group: the meshes that carry its thin instances and the actors in their order
count: numberinstances drawn
dispose(): void

packages/levels/src/placements.ts:161

PlacementModel interface

interface PlacementModel

A model by library item id, or by a file reference of a package.

library?: string
ref?: string
tier?: LibraryTier

packages/levels/src/placements.ts:35

PlacementResolver interface

interface PlacementResolver

What the placement needs to find models and materials of the library by id (an AssetLibrary gives it: placementResolver()).

modelRef(m: PlacementModel): Promise<string> | stringthe ferret:// file of a library model (its tier chosen)
material(o: MaterialOverride): Promise<BABYLON.Material>a library material to put on the model's meshes

packages/levels/src/placements.ts:62

PlacementWarnings interface

interface PlacementWarnings
(message: string): void

packages/levels/src/placements.ts:160

PrefetchOptions interface

interface PrefetchOptions
settleMs?: numberwait this long after a level is ready before the first background download (the level's own first seconds come first)
margin?: numbersafety factor on the estimate: start early enough to finish in eta * margin (default 1.5)
assumedRate?: numberassumed link speed in bytes/s until something has been measured (default: unknown, so hints start at once)
now?: () => number
setTimer?: (fn: () => void, ms: number) => unknown
clearTimer?: (t: unknown) => void

packages/levels/src/prefetch.ts:16

PreviewOptions interface

interface PreviewOptions
seconds?: numberhow long the fake download lasts
bytes?: number
files?: number
fail?: booleanend with a failure instead of readiness (to see the game's failure screen)
cached?: booleancached: plan says the wait is short
signal?: AbortSignal

packages/levels/src/transitions.ts:147

ProbeVolumeDef interface

interface ProbeVolumeDef

Baked global illumination: a regular grid of L1 spherical harmonics (the radiance arriving at each point, RGB), written by tools/ue-export/bake-gi. The shader of every PBR material looks up the grid trilinearly at the surface and adds the diffuse light the lamps, the sky and the bounces give there. It replaces the flat hemispheric ambient light (which the loader turns off when a volume exists).

file: stringthe baked grid, relative to the package: probes.bin
origin: [number, number, number]the position of the first probe, metres
spacing: numbermetres between probes
dims: [number, number, number]probes along x, y, z
gain?: numberscale of the baked light (default 1)
fill?: numberhow much of the level's flat ambient light stays on beside the baked light, 0..1 (default 0: none). A hemispheric fill that brightens ceilings and darkens floors where the bake's bounce light is short
down?: numberthe share of the baked light that faces turned down (ceilings) get, 0..1 (default 1: all of it)
specular?: numberthe baked light mirrored by every surface, 0 and more (default 0: none; 1: as much as arrives). What Unreal's SkyLight and reflection captures give: the radiance the grid holds toward the reflection (the sky outdoors, the dim room indoors), blurred with the roughness, times the surface's F0 and the split sum's environment BRDF (Karis' fit), dimmed by the ambient occlusion as Unreal's specular occlusion does. Wet planks and stone seen at a low angle lose their saturation to it.

packages/levels/src/probe-volume.ts:7

ProgramBridgeLike interface

interface ProgramBridgeLike
lasting(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => { done(): boolean; result?: unknown }): unknown

packages/levels/src/fmdl-programs.ts:134

ProgramHost interface

interface ProgramHost
run(program: string, o: { target?: string; params: Record<string, Value> }): Programstart a program text with its parameters on a target (the runtime's: the actuators' cap.run)
knows(name: string): booleanis name a word of the language

packages/levels/src/fmdl-programs.ts:24

ProgramUses interface

interface ProgramUses

What the shader of a program reads from the surface and the scene.

uv0: boolean
uv1: boolean
uv2: boolean
vertexColor: boolean
matrix: boolean
local: boolean
bounds: boolean
near: boolean
time: boolean
view: boolean
depth: boolean
screen: boolean
tangent: boolean

packages/levels/src/material-program.ts:16

PropellerViewOptions interface

interface PropellerViewOptions

The picture of a spinning propeller. The shaft speed comes from the flight model (Aeroplane.propOmega, rad/s): a real propeller turns at 1000..1500 rpm, 3 or 4 blades pass a point 60..100 times a second, and the screen shows 60 frames: a blade seen at its true angle strobes, and looks slow or runs backwards. So the blades are drawn at their true angle only while a blade moves a small part of the blade spacing in a frame (taxiing, starting); as the speed rises they fade into the disc the eye sees at speed (a faint disc, darker where the blades sweep, the tips a ring), which fades in. propellerBlur is that blend, pure, for the picture and for tests.

Nodes: the propeller's node (Prop, or Prop_L and Prop_R) has its pivot on the shaft, which is its local X axis.

blades?: numberblades on the propeller (default 3)
radius?: numberthe disc's radius, m (default: read off the blades' bounds, else 1.6)
blurFrom?: numberthe blur starts when a blade moves this share of the blade spacing in one frame (default 0.25) ...
blurTo?: number... and is complete at this share (default 0.7)

packages/levels/src/propeller.ts:10

PropulsorBindOptions interface

interface PropulsorBindOptions
field: FlowField
actuator?: (name: string) => { force: V3; on: boolean } | undefinedthe state of a named actuator: its force (N) and whether it is running; undefined when the physics does not run
surface?: SurfaceQuery
scale?: numberthe multiplier of every jet (the game's override)
onGroundEffect?: (actor: string, id: string, extra: V3, at: V3) => void

packages/levels/src/fmdl-propulsors.ts:10

RelevanceBlock interface

interface RelevanceBlock
modes?: Record<string, { omega?: number; horizon?: number; floorOmega?: number }>
hold?: numberseconds a thing stays in a finer class before it may go to a coarser one
gonePx?: numberbelow this many pixels a thing is not drawn at all

packages/levels/src/manifest.ts:136

RiverDef interface

interface RiverDef
points: Vec3[]the centre line, close points [x, y, z] in metres (y is the surface there); the spline is sampled by the exporter, a metre or so apart
widths: number[]the width at each point, metres
flow: numbermetres per second the surface moves downstream (the first point to the last)

packages/levels/src/water.ts:80

RoomReflection interface

interface RoomReflection
readonly cube?: BABYLON.RenderTargetTexture
readonly drawn: Promise<void>settles when the room has been drawn into the cube (or the capture failed or was disposed): a game keeps its loading screen up until then, the first draw compiles shaders
refresh(): voiddraw the room again (after a change of light or furniture)
dispose(): void

packages/levels/src/room-reflection.ts:42

RoomReflectionDef interface

interface RoomReflectionDef

What the glossy and the clear surfaces of an interior reflect: the room itself. The level is drawn once into a cube map from a point of the room (the lit walls, the windows, the furniture, with the baked light on them) after it has loaded, and that cube becomes the scene's environment texture. Without it an interior has no sky to reflect, and dark ceramic, glass, metal and polished floors draw as dull flat colour.

With a box the lookup is box-projected: a reflection ray is cut against the room's walls instead of read at infinity, so a floor shows the window where the window is. One capture serves the whole room; a mirror or a very large room wants more than one point (not done).

position?: Vec3where the cube is drawn from, metres (the package's frame). Default: the box's centre at 1.4 m above its floor.
box?: { center: Vec3; size: Vec3 }the room: the box the reflection rays are cut against. Default: the baked probe grid's bounds.
resolution?: numberside of a cube face in pixels (default 256: 6 x 256 x 256 half floats, about 3 MB with its mip levels)
intensity?: numberscale of the reflected light (default 1: the picture's own exposure is taken out, see capture)

packages/levels/src/room-reflection.ts:15

RunOptions interface

interface RunOptions
enterTimeoutMs?: number
log?: (event: string, detail: Record<string, unknown>) => void

packages/levels/src/transitions.ts:85

RuntimeAssetsOptions interface

interface RuntimeAssetsOptions
store: AssetStore
models: MountAssetsloads and instantiates glTF (an AssetCache, or mount.assets when packages are in use)
mount?: PackageMountneeded for ferret:// references

packages/levels/src/runtime.ts:47

SamplerPlan interface

interface SamplerPlan

The samplers beyond the layers' own albedo images: far images, the pictures of world aligned layers, the macro variation picture (a file a layer already has as its albedo shares that layer's sampler). packed: the pictures are layers of two texture arrays instead (albedoArray, naoArray: their files in order); a sampler is then "#<index>" (colour) or "@<index>" (normal and occlusion), and only the macro picture is a sampler.

extras: { file: string; srgb: boolean }[]
sampler(file: string): string
albedoArray: string[]
naoArray: string[]
nao(file: string): string

packages/levels/src/landscape.ts:269

ScreenDecalSpec interface

interface ScreenDecalSpec

One decal of a level, in the engine's frame (metres): the box's centre, its three unit axes (x is the projection's), and half extents along them.

material: stringthe level material (a master carried whole, decal: true) the box projects
position: [number, number, number]
axes: [[number, number, number], [number, number, number], [number, number, number]]the decal's local x (the projection axis), y and z in the engine's frame
half: [number, number, number]half extents along the axes, m
sortOrder?: number

packages/levels/src/screen-decals.ts:21

SequenceDef interface

interface SequenceDef
name: string
length: number
loop?: boolean
play?: 'begin' | 'trigger' | 'manual'
trigger?: string
rate?: number
tracks: SequenceTrack[]
events?: Array<{ t: number; name: string }>

packages/levels/src/sequence.ts:28

SequenceTrack interface

interface SequenceTrack
target: string | { camera: true }
position?: Key<[number, number, number]>[]
positionAxes?: [boolean, boolean, boolean]which of x, y, z the position keys animate (default all); the others keep the node's own value (Unreal: a transform track with only some channels keyed)
scaleAxes?: [boolean, boolean, boolean]the same for scale
rotation?: Key<[number, number, number, number]>[]
scale?: Key<[number, number, number]>[]
fov?: Key<number>[]

packages/levels/src/sequence.ts:17

SettleOptions interface

interface SettleOptions
meshes: BABYLON.AbstractMesh[]the meshes the level draws (the thin-instance groups of the placements and the level's own)
materials?: LevelMaterials[]the level's materials: their textures are awaited
shadows?: BABYLON.ShadowGenerator[]shadow generators whose depth programs are compiled too
warn?: (message: string) => void
timeoutMs?: numberthe longest the final readiness check polls (default 15000 ms)
parallel?: numberhow many programs compile at once (default 12: the driver compiles them in parallel, and a job mostly waits)

packages/levels/src/level-ready.ts:11

SettleReport interface

interface SettleReport
meshes: number
programs: number
notReady: string[]
ms: number

packages/levels/src/level-ready.ts:25

ShadowRoleOptions interface

interface ShadowRoleOptions
casts?: (m: BABYLON.AbstractMesh) => booleanwhich of the meshes that take shadows also cast them; default: all of them. A game names its casters by what they are (a node's name, a parent, a material's name)
includeDescendants?: booleancasters keep their children out of the shadow generator's includeDescendants (default false: the mesh alone, as the group's other meshes are visited too)

packages/levels/src/sun-shadows.ts:103

ShadowRoleResult interface

interface ShadowRoleResult
casters: number
receivers: number
skipped: number

packages/levels/src/sun-shadows.ts:110

ShipWakeOptions interface

interface ShipWakeOptions

The long wake of a ship on the sea, drawn. A ship's turbulent track runs for kilometres behind a destroyer and hundreds of metres behind a submarine and is seen from any height. It is laid along the path the ship took (each row is where the ship was some seconds ago, so it bends in a turn): a narrow white core that spreads and thins, and the two faint arms of the Kelvin wedge (half angle 19.5 degrees: 0.354 m sideways for every metre astern). Wake of

length: numberhow far astern the track runs, m (a destroyer: 2500; a submarine: 450)
beam: numberthe hull's beam, m
speed: numberthe ship's speed, m/s: the time a row of the track is behind the ship is its distance over this
sternBack?: numberwhere the track starts behind the ship's reference point (its stern), m
rows?: numberrows along the track (default 72)
height?: numberthe height over the water, m (default 1.8: above the waves of a fresh sea)

packages/levels/src/wake.ts:8

ShoreDef interface

interface ShoreDef
outline: [number, number][]
width?: numbermetres of foam inside the edge (default 1.5)

packages/levels/src/water.ts:60

SlopeRamp interface

interface SlopeRamp

Unreal's WorldAlignedBlend parameters (Blend Sharpness, Blend Bias), as the material instance has them: slopeAlpha(up, ramp).

sharpness: number
bias: number

packages/levels/src/landscape.ts:99

SnapshotOptions interface

interface SnapshotOptions

Snapshot rendering of a level that does not change its draw list. On a WebGPU engine Babylon can record the commands of a frame once (render bundles) and replay them: the CPU stops recording thousands of draws. A replay keeps the draw list of the frame it recorded, so the service watches what changes it: meshes, materials, lights and particle systems added or removed, the number of active meshes, the visibility service's cell, a level loading or unloading, and anything the game reports with invalidate() (a node enabled or hidden, a material swapped). When the list changes, the snapshot is switched off, the frame is drawn as usual for settleFrames frames, and a new snapshot is recorded. Nodes that only MOVE (doors, gates, characters, the camera) need nothing: in standard mode uniforms and world matrices are still updated every frame and only the recorded draws are replayed.

fast mode skips the scene's own work while replaying (no uniform updates: only for a scene that does not move at all, a still frame); standard is the default. The mode, and so the whole service, does nothing on the WebGL2 engine. The regulator's knob levels.snapshot (CPU): level 0 is off, 1 is on (the cheaper step).

settleFrames?: numberframes drawn normally after a change before a new snapshot is recorded (default 20)
mode?: 'standard' | 'fast''standard' (default) or 'fast'
auto?: booleanwhen false (default) the service is idle until enable(): a level that declares itself static turns it on

packages/levels/src/snapshot-rendering.ts:15

SoundOptions interface

interface SoundOptions
audio: SoundSink
name?: stringthe name to play it by (default the item id)
format?: 'wav' | 'mp3'the file to use; default by tier: the MP3 (smaller) on mobile and low, the WAV on desktop, whichever there is when only one is
tier?: LibraryTier

packages/levels/src/library.ts:140

SoundSink interface

interface SoundSink

What AssetLibrary.sound needs of the audio service (AudioService of @ferret/media is one): take the bytes of a file and define a sound over them.

addFile(key: string, data: Uint8Array): unknown
define(name: string, def: Record<string, unknown>): unknown
has(name: string): boolean

packages/levels/src/library.ts:135

SpawnPoint interface

interface SpawnPoint
id: string
position: BABYLON.Vector3
yaw: number
human?: string

packages/levels/src/levels.ts:8

StageModel interface

interface StageModel

what the stage can place by id: the loader's FmdlModel is one (stage.addModel), a test gives its own

id: string
resolved?: ResolvedModelthe resolved model and a reader of its files by qualified path: what its motions are found and read from (ModelPrograms)
read?: (qualified: string) => Promise<Uint8Array>
make(level: number, name: string): { root: Node; plan: AssemblyPlan }the nodes of a level, not parented, and the plan they were made from

packages/levels/src/fmdl-motion.ts:289

StageOptions interface

interface StageOptions
scene?: BABYLON.Scene
emit?: (name: string, payload: unknown) => voidthe events of the world (world.events.emit); none in a plain test

packages/levels/src/fmdl-motion.ts:311

StageWatcher interface

interface StageWatcher

Who is told of the models of a stage (the code of models).

appearing?(model: StageModel): voida model is about to appear: throwing refuses it, and nothing is built
appeared?(actor: Actor): voidan actor has appeared, placed; throwing takes it away again
vanishing?(name: string): voidan actor is about to go (its nodes are still there)
step?(dt: number): voida fixed step of the stage

packages/levels/src/fmdl-motion.ts:318

StreamCellDef interface

interface StreamCellDef

One grid cell of a streamed level: visual content only; collision is whole-level and resident. bounds = [minX, minY, minZ, maxX, maxY, maxZ].

bounds: [number, number, number, number, number, number]
file: string
size?: number
priority?: number
pinned?: booleanalways resident (the play area round the spawn): fetched first, part of the ready gate, never released and never evicted for memory
layer?: stringa key of layers: the cell uses that layer's radii instead of the block's (foliage is wanted closer than houses)
memory?: numberbytes the cell takes once resident (geometry plus decoded textures); counted against memoryBudget. Default: size
lod?: stringa low-poly stand-in shown while the cell is farther than loadRadius but within lodRadius (a few percent of the cell's triangles, no textures worth the name)
details?: StreamDetailDef[]Lighter variants of the same cell (fewer triangles, smaller textures), nearest first: the cell is made of its file within fullRadius of the player and of the first variant whose radius reaches it farther out (the last one up to loadRadius). A variant has the cell's mesh names for what it keeps but may leave small things out, so an entity that needs the cell exists only while the full file is the resident one.

packages/levels/src/manifest.ts:34

StreamDetailDef interface

interface StreamDetailDef

One lighter variant of a streamed cell (StreamCellDef.details): radius is the distance from the player up to which it is wanted (increasing along the list, at most loadRadius); size / memory are what it takes once resident.

file: string
radius: number
size?: number
memory?: number

packages/levels/src/manifest.ts:51

StreamingBlock interface

interface StreamingBlock

The streaming block. A level without it loads whole, as before.

cell: numberthe grid size in metres the cells were cut with (informational for tools)
cells: Record<string, StreamCellDef>
loadRadius: numbermetres from the player: cells inside are loaded (and are part of the ready gate at the spawn)
unloadRadius: numbercells farther than this are released; must be at least loadRadius
bundles?: Record<string, { files: string[]; trigger?: string }>groups of files loaded together when a zone is entered (or on demand)
lodRadius?: numbermetres from the player within which a cell's lod stand-in is shown; at least loadRadius (default: unloadRadius)
fullRadius?: numbermetres from the player within which a cell is made of its full file; farther (up to loadRadius) it is made of its details variants. Default: loadRadius (the variants are not used). A change of variant has detailHysteresis metres of margin (default 8), so a player standing on a border does not make a cell swap back and forth.
detailHysteresis?: number
readyRadius?: numbermetres from the player within which the cells are what ready() waits for (the start screen); the rest of loadRadius streams in behind the player, nearest first, under the memory budget. Default: loadRadius.
layers?: Record<string, { loadRadius?: number; unloadRadius?: number; lodRadius?: number; fullRadius?: number }>radii per kind of cell, over the block's: a cell names its layer in layer. unloadRadius must not be below loadRadius (that gap is the hysteresis)
memoryBudget?: numberbytes of cells that may be resident at once (this tier's cap: every tier package has its own block). Pinned cells are counted but never evicted; a nearer cell takes the place of farther ones, and when it still does not fit it waits (event stream:budget)
maxPerFrame?: numberpacing over the service's defaults (2 cells and 4 ms per update, 3 fetches at once); the host's options win
budgetMs?: number
concurrency?: number
texturesProgressive?: booleanreserved: low mips first, upgrade later; nothing acts on it yet

packages/levels/src/manifest.ts:54

StreamingOptions interface

interface StreamingOptions
at(file: string): stringwhere the level's files are (cell and bundle file names are relative to it)
focus?: () => Focus[]the places that matter, asked every update; when it gives none (or is left out): the persistent entities of the level service, else the active camera
radiusScale?: numberscale both radii (a tier may ask for less)
memoryBudget?: numberbytes of resident cells, over the block's memoryBudget (a tier or a device may ask for less)
maxPerFrame?: numbermost cells instantiated in one update
budgetMs?: numbermilliseconds of instantiation work per update; at least one cell is always added when something waits, so streaming cannot starve
concurrency?: numbermost cells fetched at once
now?: () => number

packages/levels/src/streaming.ts:28

SunShadows interface

interface SunShadows
readonly generator: BABYLON.CascadedShadowGenerator
add(meshes: Iterable<BABYLON.AbstractMesh>): voidlet these meshes (and their thin instances) cast and receive the sun's shadows
dispose(): void

packages/levels/src/sun-shadows.ts:49

SunShadowsDef interface

interface SunShadowsDef
cascades?: numbernumber of cascades, 2 to 4 (default 4)
distance?: numberhow far from the camera the sun's shadows are drawn, metres (default 200)
mapSize?: numberside of each cascade's depth map, texels (default 2048)
bias?: numberdepth bias of the map (default 0.0005)
normalBias?: numberbias along the normal, metres (default 0.05)
blend?: numberthe share of a cascade over which it blends into the next (default 0.1)
lambda?: number0 = evenly spaced cascades, 1 = logarithmic: near cascades finer (default 0.95)
filter?: 'pcf' | 'hard'the edge: pcf (soft, the default) or hard

packages/levels/src/sun-shadows.ts:14

SwarmDef interface

interface SwarmDef

A swarm of small flyers (butterflies, a moth round a lamp, fireflies): each agent is pushed by the forces Unreal's Niagara "hanging particulates" stack uses, summed and integrated with drag and a speed limit: a curl-noise field (a swirling, divergence-free drift), a vortex round a vertical axis through the centre, an attraction to the centre, the wind, and an optional repulsion near the centre (a moth bumping off the lamp). Plain numbers, deterministic from the seed; metres, seconds. The Babylon part (buildSwarm) draws every agent as an instance of one mesh, turned along its flight.

name?: string
position: [number, number, number]centre of the swarm
count: number
radius: numberthe agents start inside a sphere of this radius about position + offset
offset?: [number, number, number]
scale?: [number, number]uniform scale range of the mesh
drag?: number1/s
speedLimit?: numberm/s
curl?: Array<{ strength: number; frequency: number }>curl noise layers: strength is m/s^2, frequency 1/m
vortex?: { amount: number; radius: number; pull?: number }
attraction?: { radius: number; strength: number; exponent?: number }pulls towards the centre inside radius with a strength falling off as (1 - d/radius)^exponent
repulsion?: { radius: number; strength: number; exponent?: number }pushes away from the centre inside radius (negative attraction), kill m: an agent closer is put back at the edge
windAir?: numberm/s^2 added along x/z of the level's wind, times this (default 0)
seed?: number
distance?: numberthe swarm runs only while the camera is within this many metres (default 40)

packages/levels/src/swarm.ts:10

Transition interface

interface Transition
enter(ctx: TransitionContext): Promise<void> | voidThe travel starts. Show something at once. Resolve when it is on screen (after 2 s the engine's bar takes over).
update(p: TransitionProgress): voidThe target's progress, many times a second.
ready(ctx: TransitionContext): Promise<void> | voidThe target is ready. Resolve when the game wants to leave: a door has opened, a button was pressed, a timer ran out.
fail(ctx: TransitionContext, err: StreamError): boolean | void | Promise<boolean | void>The target failed or the player cancelled. Return true when the transition shows the failure itself (Retry / Back); otherwise the engine's screen is shown.
dispose(): void

packages/levels/src/transitions.ts:37

TransitionContext interface

interface TransitionContext
from: LevelDef | null
to: LevelDef
plan: LevelPlanwhat the travel will download; cached means a short wait is expected
world: World
events: EventBus
ui?: UIServicethe services a game's splash usually wants, when the game has them
audio?: unknown
input?: unknown
xr?: { active: boolean; state: string }the VR session service when the game has one: a transition may show its interlude world in the headset; xr.active says whether a session runs
persistent: Set<Entity>the player and what travels with them
host?: SceneHostthe scene host (5.3): make a second world for an interlude with host.create, show it with host.show. The engine shows the level's world again when the player is let in. Present when the game added a SceneHost.
signal: AbortSignalthe player cancelled

packages/levels/src/transitions.ts:16

TransitionProgress interface

interface TransitionProgress

What a transition is told, many times a second, while the target downloads. Numbers are honest bytes of what the target needs.

loaded: number
total: number
files: number
rate: number
eta: number
phase: string

packages/levels/src/transitions.ts:14

TravelOptions interface

interface TravelOptions
spawn?: string
keep?: Entity[]keep these entities: they move to the new level's spawn instead of being removed (the player)
keepOld?: booleanKeep the old level's way back: if the new one fails after the old was released, build the old one again and put the player where they were (default: LevelOptions.keepOldUntilReady, else the hub).
signal?: AbortSignalCancel from a menu: before the old level is released the player simply stays; later they are put back.
transition?: stringThe game's transition for this travel, by the name it registered (else its chooser, else default, else the engine's bar).

packages/levels/src/levels.ts:68

ValidateOptions interface

interface ValidateOptions
packages?: PackageSetthe other open packages, for ferret:// references and dependencies
behaviours?: Iterable<string>behaviours the game registers itself (besides those packages provide); when given, an unknown behaviour is an issue
checksums?: booleancheck the sha256 of every file (default true)
engine?: EngineVersions | falsethe engine that is running; default this build's (FERRET_VERSION, BABYLON_VERSION); false skips the check of the manifest's engine
tierView?: booleanset when pkg is already one tier's view of a game (its own call for each tier)
fetched?: booleana build: a dependency that is not open need not be, when the package names catalogs (the player fetches it from there and checks it before the start)

packages/levels/src/ferret.ts:182

VirtualTextureDef interface

interface VirtualTextureDef
resolution?: numbertexels along the longer side of the rectangle (default 2048)
blendHeight?: numbermetres above the ground over which a prop's albedo fades from the ground colour to its own (default 1.5)
strength?: number0..1, how much of the ground colour a prop takes at its foot (default 1)
meshes: stringregex source: the meshes (by name, anywhere in the level) whose materials sample the virtual texture

packages/levels/src/landscape.ts:108

VisibilityBlock interface

interface VisibilityBlock

The visibility block: a level of many rooms (a castle) draws only what can be seen from where the player stands. The level's nodes are split into named groups (a room, a corridor); the floor plan is cut by a grid of cell metres in x and z (origin 0, key "ix_iz" with ix = floor(x / cell)); see[key] lists the groups that can be seen from anywhere in that grid cell. A tool computes the lists (rays against the level's collision, tools/visibility.mjs). The player in a cell that has no entry sees everything: a gap in the table is never a hole.

cell: number
groups: Record<string, { nodes: string[] }>group id -> the glTF node names that make it up (each node with all it carries)
always?: string[]groups that are always drawn (a landmark seen from everywhere)
see: Record<string, string[]>
mode?: 'visible' | 'enable''visible' (default): meshes of an unseen group are not drawn but keep their collision; 'enable': the nodes are disabled (cheapest; collision goes too)

packages/levels/src/manifest.ts:150

VisibilityOptions interface

interface VisibilityOptions
focus?: () => { x: number; z: number } | nullwhere the viewer stands; default the camera

packages/levels/src/visibility.ts:5

Waitable interface

interface Waitable
done(): boolean
result?: unknown

packages/levels/src/fmdl-motion.ts:36

WakeRow interface

interface WakeRow
dist: number
tau: number
coreHalf: number
coreAlpha: number
armOffset: number
armHalf: number
armAlpha: number

packages/levels/src/wake.ts:22

WaterDef interface

interface WaterDef
level: numbery of the surface at rest
centre?: [number, number]centre (x, z) and size (x, z) of the surface, metres
size?: [number, number]
absorption?: Vec3the colour of the water seen from above when deep: Unreal's single-layer water Absorption is the distance per colour channel (cm) light goes before it is gone, Scattering how much the water sends back; the colour is the scattering tinted by those distances
scattering?: Vec3
deepBrightness?: numbera factor on that deep colour (default 1): a scattering of 1 asks for the full colour, which the original shows dimmed by the light that reaches the water in the shade of its banks
sky?: { top?: Vec3; horizon?: Vec3 }the colour of the sky it reflects (default the sky's horizon / top)
roughness?: number0..1 (default 0.02)
specular?: number0..1, the part of the sky a calm surface reflects head-on (default 0.02, about water's Fresnel at normal incidence)
waves?: WaterWave[]
opacity?: number0..1, how opaque the surface draws (default 0.92)
foam?: number0..1, how strongly breaking crests turn to white water (default 0.8; a gentle sea has none whatever this is)
meso?: number0..1: patches, wind streaks and whitecaps that show from high above, where real waves are smaller than a pixel (default 0: off)
river?: RiverDefa river instead of a rectangle (Unreal's WaterBodyRiver: a spline with a width): the surface is a ribbon along the centre line, its ripples run downstream at flow, the banks get a rim of foam. With a river level is the height of the first point, centre, size and waves are not used.
shore?: ShoreDefa lake with a shore (Unreal's WaterBodyLake: a closed spline): the surface is cut to this outline ([x, z] points in metres, 3..64, either winding) and a band of width metres inside the edge turns to foam (a lapping shore). The surface's extent is the outline's bounding box; centre and size are not used.

packages/levels/src/water.ts:21

WaterResponseMap interface

interface WaterResponseMap

a height field of what moves the surface (a jet's dent, rings, a wash) laid over a river: size x size cells of 4 floats (surface height above rest m, slope x, slope z, foam 0..1); @ferret/physics-response fills it from a WaterSurface. Without one a river is drawn as before.

readonly size: number
readonly cell: number
readonly originX: number
readonly originZ: number
readonly data: Float32Array
readonly active: boolean
readonly version: number
readonly rings?: { readonly packed: Float32Array; readonly max: number }the ring sources (RingField of

packages/levels/src/water.ts:279

WaterSurfaceView interface

interface WaterSurfaceView
mesh: BABYLON.Mesh
material: BABYLON.ShaderMaterial
setWaves(waves: WaterWave[]): void
setReflection(tex: BABYLON.BaseTexture | null): void
dispose(): void

packages/levels/src/water.ts:283

WaterWave interface

interface WaterWave
wavelength: numbermetres crest to crest
amplitude: numbermetres, crest above the rest level
steepness?: number0..1: how sharp the crests are (Gerstner Q)
direction?: numberdegrees about the vertical, the way the wave travels (0 = +x)

packages/levels/src/water.ts:10

Types

EnvironmentPart type

type EnvironmentPart = 'sun' | 'ambient' | 'fog' | 'sky' | 'water'

a part of a level's environment a game may leave out (LevelDef.environment.skip)

packages/levels/src/levels.ts:49

FileReader type

type FileReader = (qualified: string) => Promise<Uint8Array>

packages/levels/src/fmdl.ts:16

Interp type

type Interp = 'linear' | 'cubic' | 'step'

A level sequence (Unreal's LevelSequence): tracks that move nodes and the camera over time, played once or looped, on level begin or on a trigger. The JSON is what the exporter (vschool_ferret export/ue/probe_sequences.py, tools/sequences.mjs) writes for each sequence; lengths are metres, angles are quaternions in the engine's frame (the exporter converts from Unreal's cm / Z-up), time is seconds.

  { name, length, loop?, play: 'begin' | 'trigger' | 'manual', trigger?: string (a trigger volume's id), rate?: 1,
    tracks: [ { target: string | { camera: true }, position?: Key3[], rotation?: Key4[], scale?: Key3[], fov?: Key1[] } ],
    events?: [ { t, name } ] }
  Key = { t, v, interp?: 'linear' | 'cubic' | 'step' }        (v: number | [x,y,z] | [x,y,z,w])

target is a scene node ("Actor>Component" or a name); { camera: true } drives the active camera. Events are emitted on the world bus as sequence:event.

packages/levels/src/sequence.ts:15

LevelCodec type

type LevelCodec = 'etc1s' | 'uastc'

packages/levels/src/level-materials.ts:33

LevelCodecPolicy type

type LevelCodecPolicy = 'best' | 'light' | 'chosen'

which file of a texture that exists in both codecs is read: best UASTC, light ETC1S, chosen the one the encoder's check chose

packages/levels/src/level-materials.ts:36

LookScope type

type LookScope = 'type' | 'instance'

packages/levels/src/material-look.ts:44

LookTable type

type LookTable = Record<string, Record<string, MaterialLookDef>>

uid → glTF material name → look

packages/levels/src/material-look.ts:42

MaterialMapSlot type

type MaterialMapSlot = 'baseColor' | 'normal' | 'orm' | 'emissive' | 'opacity'

The look of the glTF materials of a level, set in the manifest (materialLooks) and changed live by the editor (edit.material.*).

A material is never addressed by its name across the whole scene (the same name stands in twenty places). Two scopes: - types[typeUid][materialName]: the TYPE, the model as an asset: the look goes to the named material of that model in ALL its instances ("all boards"); - instances[instanceUid][materialName]: ONE concrete object (a node and what hangs on it, an entity, one placed actor): it goes over the type's look ("this board"). Inside a model the material is named by its glTF material name.

Where a uid comes from (the first that the scene offers wins, the others are fallbacks, so an old level without any extras still works): - type: glTF node extras.ferret.uid.type (the exporter writes the Unreal asset path) | the key of a placement list's models | the library id of that model | the glTF MESH name; - instance: glTF node extras.ferret.uid.instance (the exporter writes the actor name) | the manifest entity id | the placement actor | the node path (names from the scene root, joined with "/"). An address that more than one thing answers to (two glTF meshes of one name, two nodes of one path) is AMBIGUOUS: it still applies on load to everything it matches, edit.material.list shows it, and the editor refuses to write on it (give the object a uid in the export instead).

The values are the ones of a library material (MaterialDef of

packages/levels/src/material-look.ts:27

ModelState type

type ModelState = 'loading' | 'ready' | 'failed'

packages/levels/src/runtime.ts:34

PlaceholderSpec type

type PlaceholderSpec = 'box' | 'none' | { size?: number | [number, number, number]; color?: [number, number, number] } | ((scene: BABYLON.Scene) => BABYLON.TransformNode)

packages/levels/src/runtime.ts:23

ProgramType type

type ProgramType = 1 | 2 | 3 | 4

packages/levels/src/material-program.ts:13

RefKind type

type RefKind = 'package' | 'remote' | 'relative'

packages/levels/src/runtime.ts:14

RegisterFn type

type RegisterFn = (name: string, description: string, fn: (args: any) => unknown) => void

packages/levels/src/fmdl-docks.ts:262

ResolvedAtmosphere type

type ResolvedAtmosphere = Required<AtmosphereDef>

packages/levels/src/atmosphere.ts:59

TextureCodecPolicy type

type TextureCodecPolicy = 'chosen' | 'best' | 'light'

packages/levels/src/library.ts:34

TransitionChooser type

type TransitionChooser = (from: LevelDef | null, to: LevelDef, plan: LevelPlan) => string | undefined | null

packages/levels/src/transitions.ts:53

Constants

ARM_REACH const

const ARM_REACH: 200

packages/levels/src/wake.ts:28

ARM_STRENGTH const

const ARM_STRENGTH: 0.14

The arms of the Kelvin wedge are a train of waves, not foam: faint next to the hull (a fifth of the core's strength at the stern) and spread over a widening band, they are damped and lose their crests within a few hundred metres, while the turbulent core goes on for kilometres. ARM_REACH is the distance over which an arm falls to 1/e.

packages/levels/src/wake.ts:28

ATMOSPHERE_EXPOSURE const

const ATMOSPHERE_EXPOSURE: 30

packages/levels/src/atmosphere.ts:47

ATMOSPHERE_FRAGMENT const

const ATMOSPHERE_FRAGMENT: "precision highp float;\nvarying vec3 vDir;\n#define N 24\nuniform vec3 rayleigh[N]; uniform vec3 mie[N];\nuniform vec3 sunDir; uniform vec3 sunColor; uniform vec3 sunDisc; uniform vec3 lum; uniform vec3 ground; uniform vec3 horizonFill;\nuniform float g; uniform float ms; uniform float exposure;\nvoid main() {\n  vec3 d = normalize(vDir);\n  float h = d.y;\n  vec3 toSun = -sunDir;\n  float c = do …

the sky dome's fragment shader body for the table (arrays of LUT_SIZE entries); uniforms: rayleigh[], mie[], sunDir, sunColor (already x strength), g, ms, lum, ground, exposure

packages/levels/src/atmosphere.ts:198

BAR const

const BAR: "bar"

The engine's own transition: it draws nothing itself, the loading screen of

packages/levels/src/transitions.ts:50

barTransition const

const barTransition: Transition

packages/levels/src/transitions.ts:51

COLOUR_ATTRIBUTE const

const COLOUR_ATTRIBUTE: "#if !defined(VERTEXCOLOR) && !defined(FERRET_COLOR_ATTR)\n#define FERRET_COLOR_ATTR\nattribute vec4 color;\n#endif"

the color attribute, declared once however many plugins (this and the foliage wind) read it; a mesh that uses vertex colours has it declared by Babylon already

packages/levels/src/material-models.ts:409

DEFAULT_LIBRARY_URL const

const DEFAULT_LIBRARY_URL: "/lib/ferret-assets/catalog.json"

packages/levels/src/library.ts:32

DISTANCE_FIELD_GLSL const

const DISTANCE_FIELD_GLSL: "uniform highp sampler3D ferretMpDfTable;\nuniform highp sampler3D ferretMpDfValues;\nfloat ferretMpDfByte(vec3 w) {\n  vec3 v = (w - ferretMpDfOrigin.xyz) / ferretMpDfOrigin.w, b = floor(v / ferretMpDfAtlas.w);\n  if (any(lessThan(b, vec3(0.0))) || any(greaterThanEqual(b, ferretMpDfGrid.xyz))) return 1.0;\n  vec4 e = texelFetch(ferretMpDfTable, ivec3(b), 0);\n  if (e.a < 0.5) return 1.0;\n  vec3  …

the lookup: ferretMpDfByte(world metres) is the stored value 0..1 (1: far), ferretMpDfMetres the distance

packages/levels/src/distance-field.ts:104

ENGINE_GLOBAL const

const ENGINE_GLOBAL: "__ferretEngine"

The engine a docked level's code shares with its parent. A level's code is built like a game's: an ES module that imports @ferret/*. A parent whose engine is ES modules with an import map needs nothing more. A parent that ships its engine inside its own bundle (Ilion) publishes the packages it holds in globalThis.__ferretEngine (shareEngine) and the code loader rewrites the imports of the module's text to read from there (useSharedEngine), so the level and the parent are one engine: one World, one set of registries, one scheduler. A package the parent does not hold is an error that names it; a level that needs one carries it inside its own code (the converter and the scene builder inline it).

packages/levels/src/dock-engine.ts:8

HEIGHT_TRANSITION const

const HEIGHT_TRANSITION: 0.2

how much height a height-blended layer needs to beat the others (score units), as a transition width

packages/levels/src/landscape.ts:142

LEVEL_CODEC_POLICIES const

const LEVEL_CODEC_POLICIES: readonly LevelCodecPolicy[]

packages/levels/src/level-materials.ts:37

LEVEL_CODECS const

const LEVEL_CODECS: readonly LevelCodec[]

packages/levels/src/level-materials.ts:34

LEVEL_MATERIALS_FORMAT const

const LEVEL_MATERIALS_FORMAT: "ferret-materials/1"

packages/levels/src/level-materials.ts:30

LEVEL_TEXTURES_FORMAT const

const LEVEL_TEXTURES_FORMAT: "ferret-textures/1"

packages/levels/src/level-materials.ts:31

LOOK_SCOPES const

const LOOK_SCOPES: readonly LookScope[]

packages/levels/src/material-look.ts:45

LUT_SIZE const

const LUT_SIZE: 24

packages/levels/src/atmosphere.ts:49

MACRO_BLEND_DEFAULT const

const MACRO_BLEND_DEFAULT: 1.5

WorldCoordinate3Way's own default of its four blend inputs (Blend Exponent X / Y Z, Blend Mult X / Y Z): all 1.5 in the exported function

packages/levels/src/material-models.ts:40

MANIFEST_VERSION const

const MANIFEST_VERSION: 1

packages/levels/src/manifest.ts:14

MATERIAL_MAP_SLOTS const

const MATERIAL_MAP_SLOTS: readonly MaterialMapSlot[]

packages/levels/src/material-look.ts:28

MAX_LANDSCAPE_LAYERS const

const MAX_LANDSCAPE_LAYERS: 8

packages/levels/src/landscape.ts:138

MAX_LANDSCAPE_SAMPLERS const

const MAX_LANDSCAPE_SAMPLERS: 13

WebGL guarantees 16 texture units; the PBR material uses a few, so layers + normals + weightmaps stay under this

packages/levels/src/landscape.ts:140

MAX_MATERIAL_LIGHTS const

const MAX_MATERIAL_LIGHTS: 8

most lights one material may light with (uniform-block limit of D3D11 through ANGLE, 12 vertex blocks, 4 taken by scene/material/mesh/bones)

packages/levels/src/light-budget.ts:166

MOVEMENT_KEYS const

const MOVEMENT_KEYS: readonly ["radius", "height", "crouchHeight", "eyeHeight", "walkSpeed", "runSpeed", "crouchSpeed", "jumpVelocity", "gravity", "maxStepHeight", "walkableAngle", "acceleration", "braking", "airControl", "swimSpeed", "buoyancy", "swimAcceleration", "outOfWaterZ", "jumpOutOfWaterPitch", "maxOutOfWaterStepHeight"]

packages/levels/src/manifest.ts:161

MULTI_SCATTER const

const MULTI_SCATTER: 0.3

packages/levels/src/atmosphere.ts:48

PIXEL_DEPTH_THRESHOLD const

const PIXEL_DEPTH_THRESHOLD: 0.5

DitherTemporalAA's Alpha Threshold input default

packages/levels/src/material-models.ts:42

PLACEMENTS_FORMAT const

const PLACEMENTS_FORMAT: "ferret-placements/1"

packages/levels/src/placements.ts:26

programTime const

const programTime: { now: () => number; }

seconds since the module was loaded: the Time of every program (one clock, so equal materials blink together as in the original)

packages/levels/src/material-program.ts:270

RELIEF_DECAL_LAYER const

const RELIEF_DECAL_LAYER: 268435456

the layer of the relief decals: outside a camera's default mask (0x0FFFFFFF)

packages/levels/src/decal-buffer.ts:13

SCREEN_DECAL_LAYER const

const SCREEN_DECAL_LAYER: 536870912

the layer of the decal boxes: outside a camera's default mask (0x0FFFFFFF) and the relief decals' (0x10000000)

packages/levels/src/screen-decals.ts:15

SCREEN_DECAL_PASS const

const SCREEN_DECAL_PASS: { readonly colour: 0; readonly surface: 1; }

the two passes a decal's shader draws: its colour and opacity, then its roughness and metallic

packages/levels/src/screen-decals.ts:18

UE_UNITS_PER_METRE const

const UE_UNITS_PER_METRE: 100

packages/levels/src/material-models.ts:38

UNREAL_FILM_GLSL const

const UNREAL_FILM_GLSL: string

GLSL: vec3 ferretUnrealFilm(vec3 linearSRGB) -> linear sRGB in 0..1 (the caller encodes the gamma)

packages/levels/src/unreal-film.ts:20

UNREAL_FILM_TONEMAPPING const

const UNREAL_FILM_TONEMAPPING: 2

the Babylon tone mapping type that draws Unreal's film curve once installUnrealFilm() has run (it takes the place of the unused glTF PBR Neutral type)

packages/levels/src/unreal-film.ts:71