FERRETGame engine over Babylon.js
Ferret

@ferret/levels

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

344 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 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:148

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:37

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

packages/levels/src/code.ts:65

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

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. 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:40

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.
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:35

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

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

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 = {})
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
nodeHost(): NodeHostthe nodes of the actors as handles of the language (move-along, turn-to)

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

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)
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
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:173

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 } = {})
async load(url: string): Promise<void>
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:205

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:89

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

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). Level 0 (the default) is off, level 1 is on.

readonly name: "still-camera-freeze"
stillFrames: number
init(world: World): void
attach(scene: BABYLON.Scene): void
qualityKnobs(): QualityKnob[]
dispose(): void

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

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

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:102

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'> } = {}): Environment

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

packages/levels/src/environment.ts:232

applyFoliageWind function

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

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

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:412

applyMaterialLook function

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

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

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

applyMaterialLooks function

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

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

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

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:86

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:37

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:126

bloomWeight function

function bloomWeight(intensity: number): number

packages/levels/src/environment.ts:127

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:138

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

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

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:142

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

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:40

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:136

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:119

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:22

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:30

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:177

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:308

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:33

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:83

groupPlacements function

function groupPlacements(file: PlacementFile): PlacementGroup[]

packages/levels/src/placements.ts:90

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

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:159

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:113

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:167

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:156

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:172

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:440

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:50

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

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:109

isHairFibreMaterial function

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

Is this glTF material a strand material?

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

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:25

layerBlendGlsl function

function layerBlendGlsl(layers: LandscapeLayerDef[], pos: string, tex = 'texture', linear = 'toLinearSpace', up = '1.0'): 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>. Leaves vec3 lsColour (linear) and, with normal maps, vec3 lsNormal (tangent space) 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.

packages/levels/src/landscape.ts:187

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:321

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

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:398

lookDefine function

function lookDefine: (s: LookStructure) => string

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

lookGlsl function

function lookGlsl(s: LookStructure): string

The model as GLSL statements for the fragment shader's "before lights" point: needs surfaceAlbedo, vPositionW, vNormalW, the varying vFerretLkUv (first UV set) and, with a ground blend, vFerretLkH (the object's height, metres). Leaves the colour in surfaceAlbedo.

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

lookMasks function

function lookMasks(s: LookStructure): string[]

the mask pictures of a structure in the order samplers are numbered

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

lookStructure function

function lookStructure(look: { colourLayers?: ColourLayersDef; macro?: MacroVariationDef[]; groundBlend?: GroundBlendDef }): LookStructure

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

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

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:59

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:54

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

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:136

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:48

projectionWeights function

function projectionWeights(n: Vec3, sharpness = MACRO_DEFAULT_SHARPNESS): Vec3

The weights of the three projections (XY, YZ, XZ planes of Unreal) from the world normal given in this world's axes.

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

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:300

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:76

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

scopeKey function

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

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

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:65

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:144

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:147

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:62

spawnFromManifest function

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

packages/levels/src/levels.ts:435

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:226

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:94

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

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:82

validateFoliageWind function

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

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

validateLandscapes function

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

packages/levels/src/landscape.ts:80

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:53

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:165

validateMaterialLooks function

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

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

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:200

validatePlacements function

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

packages/levels/src/placements.ts:55

validateProbes function

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

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

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:331

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

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:153

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:273

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
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:388

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

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

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
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:34

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:88

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

packages/levels/src/library.ts:108

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:12

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:24

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:76

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:70

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
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:48

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

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

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

DockedPair interface

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

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

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

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
ambient?: BABYLON.HemisphericLight
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:129

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

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

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:217

FoliageWindDef interface

interface FoliageWindDef
wind: { intensity: number; direction: [number, number] }Unreal's Wind_intensity and Wind_direction (X, Y)
rules: FoliageWindRule[]

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

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:219

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 } }
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:428

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:105

GroundSource interface

interface GroundSource

The baked ground (colour in rgb, ground height in a) 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

packages/levels/src/landscape.ts:296

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

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

packages/levels/src/landscape.ts:58

LandscapeLayerDef interface

interface LandscapeLayerDef
name: string
albedo: stringcolour image (sRGB); with heightBlend its alpha channel is the layer's height map
normal?: stringoptional tangent-space normal image
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

packages/levels/src/landscape.ts:21

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:45

LandscapeTextures interface

interface LandscapeTextures
weights: BABYLON.BaseTexture[]
albedo: BABYLON.BaseTexture[]
normal: (BABYLON.BaseTexture | undefined)[]

packages/levels/src/landscape.ts:230

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
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:377

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

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
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:82

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

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:67

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:99

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:19

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:57

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:65

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:86

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:33

LibraryQuery interface

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

packages/levels/src/library.ts:56

LibrarySound interface

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

packages/levels/src/library.ts:131

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

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:38

LookDef interface

interface LookDef
colourLayers?: ColourLayersDef
macro?: MacroVariationDef[]
groundBlend?: GroundBlendDef

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

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.

base: 'albedo' | 'colour' | 'none'
layers: { mask: string; channel: MaskChannel }[]
macro: { mask: string }[]
ground: boolean

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

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:151

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:14

ManifestIssue interface

interface ManifestIssue
path: string
message: string

packages/levels/src/manifest.ts:159

ManifestSpawn interface

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

packages/levels/src/manifest.ts:80

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:144

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:29

MaterialLooks interface

interface MaterialLooks
types?: LookTable
instances?: LookTable

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

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:163

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:135

MaterialOptions interface

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

packages/levels/src/library.ts:115

MaterialOverride interface

interface MaterialOverride

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

library: string
variant?: string

packages/levels/src/placements.ts:33

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

ModelDescribed interface

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

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

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

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:83

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:16

OceanWave interface

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

packages/levels/src/ocean.ts:15

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

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:23

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:29

Placement interface

interface Placement
actor: string
model: stringa key of models
position: Vec3
rotation?: Quat
scale?: number | Vec3
materials?: Record<string, MaterialOverride>

packages/levels/src/placements.ts:34

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)
warn?: PlacementWarnings
name?: stringthe root of the new nodes is named so (default placements)

packages/levels/src/placements.ts:123

PlacementFile interface

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

packages/levels/src/placements.ts:43

PlacementGroup interface

interface PlacementGroup
key: string
model: string
materials?: Record<string, MaterialOverride>
actors: Placement[]

packages/levels/src/placements.ts:88

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:114

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:31

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:46

PlacementWarnings interface

interface PlacementWarnings
(message: string): void

packages/levels/src/placements.ts:113

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)

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

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:132

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

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

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:38

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:123

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:118

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:265

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:287

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:32

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:49

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:52

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

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)

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:47

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:146

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

LookScope type

type LookScope = 'type' | 'instance'

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

LookTable type

type LookTable = Record<string, Record<string, MaterialLookDef>>

uid → glTF material name → look

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

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:26

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

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

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

DEFAULT_LIBRARY_URL const

const DEFAULT_LIBRARY_URL: "/lib/ferret-assets/catalog.json"

packages/levels/src/library.ts:32

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:76

LOOK_SCOPES const

const LOOK_SCOPES: readonly LookScope[]

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

LUT_SIZE const

const LUT_SIZE: 24

packages/levels/src/atmosphere.ts:49

MACRO_DEFAULT_SHARPNESS const

const MACRO_DEFAULT_SHARPNESS: 1

Exponent of the world-normal weights that blend the three projections of a macro picture. WorldCoordinate3Way leaves its Blend Exponent inputs unconnected in the exported graphs, so the engine function's own default decides in Unreal: that function is not part of the export. 1 (weight = |n|, normalised) until its text is exported.

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

MANIFEST_VERSION const

const MANIFEST_VERSION: 1

packages/levels/src/manifest.ts:12

MATERIAL_MAP_SLOTS const

const MATERIAL_MAP_SLOTS: readonly MaterialMapSlot[]

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

MAX_LANDSCAPE_LAYERS const

const MAX_LANDSCAPE_LAYERS: 8

packages/levels/src/landscape.ts:72

MAX_LANDSCAPE_SAMPLERS const

const MAX_LANDSCAPE_SAMPLERS: 11

WebGL guarantees 16 texture units; the PBR material uses a few, so layers + normals + weightmaps stay under this

packages/levels/src/landscape.ts:74

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:157

MULTI_SCATTER const

const MULTI_SCATTER: 0.3

packages/levels/src/atmosphere.ts:48

PLACEMENTS_FORMAT const

const PLACEMENTS_FORMAT: "ferret-placements/1"

packages/levels/src/placements.ts:22

UE_UNITS_PER_METRE const

const UE_UNITS_PER_METRE: 100

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