@ferret/levels
Level manifests, the level registry, load, unload and travel, environment and the .ferret package format.
Classes
AssetLibrary class
class AssetLibrary implements Servicereadonly name: "asset-library" | |
qualityBusy(): boolean | for the quality regulator (QualityService finds it): something of the library is loading |
constructor(private readonly o: AssetLibraryOptions) | |
init(world: World): void | |
async find(q: LibraryFind = {}): Promise<LibraryCard[]> | Candidates for a request, from the service: a keyword search that returns a generous set (car brings carbon too), as cards for the one who asks to read and pick from.
The library is English only: whoever asks translates the user's words first. The service returns at most 200 candidates, so offset pages within them. |
async open(url?: string): Promise<Catalog> | Open the catalog (once; again to refresh). |
list(q: LibraryQuery = {}): LibraryEntry[] | Items of the catalog, filtered; no package is opened. |
rubrics(under?: string): RubricNode[] | The tree of the library with the number of items in each rubric (under: only that branch, itself included). |
has(ref: string): boolean | |
versionsOf(id: string, e: CatalogAsset = this.cat.assets![id]): string[] | the versions of an item (the server's numbers, oldest first): those of its package that hold it; a catalog made before versions has 1.0.0 only |
entry(ref: string): LibraryEntry | An item by reference (id or id@version), with the version it resolves to: the reference's own, else the version the package is already open at,
else 1.0.0, else (an item added by a later version of its package) the first version that holds it. Never the latest. |
previewUrl(ref: string): string | undefined | Absolute URL of an item's preview image (from the catalog, nothing is opened). |
async pkg(pkgId: string): Promise<FerretPackage> | The package of the catalog, open in the mount (with its dependencies), at the version this instance selected (default 1.0.0, never the latest). |
async item<T extends LibraryItem = LibraryItem>(ref: string): Promise<T> | The item file, read from its package. |
async impostor(id: string, pose?: string): Promise<{ entry: ImpostorEntry; bytes: Uint8Array } | null> | The baked impostor of an item and its packed atlas bytes (@ferret/perspective's unpackAtlas reads them): the item's own (impostor), or for a character the one
of a pose (impostors[pose]: stand, walk, sit...). Null when the item has none. |
async vatBake(id: string): Promise<{ entry: VatBakeEntry; bytes: Uint8Array } | null> | The baked vertex animation of a character (vat of its item) and its packed bytes (@ferret/crowd's unpackVat reads them), shipped in the figure's package so
that any game with the figure gets it for free. Null when the character has none. |
async url(ref: string): Promise<string> | A URL the engine's loaders can read for a ferret://<package>/<path> reference (a clip set's file, a map). |
async texture(id: string, o: { scene?: BABYLON.Scene } = {}): Promise<Partial<Record<TextureChannel, BABYLON.Texture>>> | The maps of a texture item as Babylon textures (colour spaces set: base colour and emissive are sRGB, the others linear). |
async image(id: string, channel: TextureChannel): Promise<ImageBitmap> | one map of a texture item as a decoded image (no colour conversion), for code that packs maps itself (the ground's texture arrays of |
material(id: string, o: MaterialOptions = {}): Promise<BABYLON.PBRMaterial> | A PBR material from a material item (and a variant of it): the description maps one to one to PBRMaterial. |
async clipsOf(characterId: string, o: { compatible?: boolean } = {}): Promise<ClipRef[]> | The clip sets a character names (and the clip sets of its skeleton in the catalog), with the reference of each file. |
async bindClips(c: LibraryCharacter, o: BindOptions = {}): Promise<BoundClips> | Put the clip sets of a character on its bones (matched by bone name; a clip set is loaded once however many bodies use it). Waits for the
model. groups are one AnimationGroup per clip name, ready for an Animator or group.start(). |
async character(id: string, o: CharacterOptions = {}): Promise<LibraryCharacter> | A character in the world at once (a placeholder until the model is in). |
async model(id: string, o: ModelPlacement = {}): Promise<LibraryModel> | A static model of the library in the world at once (a placeholder of its bounds until the file is in). |
async modelRef(id: string, tier?: LibraryTier): Promise<string> | The ferret:// file of a static model (its tier chosen as model() does): what a placement list names by library id. |
placementResolver(): PlacementResolver | What placement lists (*.placements.json, placements.ts) need to find models and materials of this library by id; give it to the package loader's placements. |
async attach(character: LibraryCharacter, partId: string, o: AttachOptions = {}): Promise<LibraryCharacter | null> | Hang a part (a weapon, a hat, a rider) on a body that is in, by a socket of the body's item (sockets: a bone and an offset) or by a bone and an
offset of your own. The part follows the bone through every clip. Resolves with the part (dispose it to take it off), or null when the body or
the bone is not found. Offsets are in the glTF's own space: metres of the bone's local frame and a quaternion. |
async module<T = Record<string, unknown>>(id: string): Promise<T> | A ready-made package of code (a module item): its package is opened through the catalog with its dependencies, its code runs once under the code
policy (code of the options: the library's own origin, or a signature), checked against the sha256 in its manifest, and its exports come back.
The same module asked twice runs once. const sea = await library.module<typeof import('sea')>('sea-surface'); new sea.SeaView(scene). |
soundFormat(item: SoundItem, o: { format?: 'wav' | 'mp3'; tier?: LibraryTier } = {}): 'wav' | 'mp3' | Which file of a sound item a device takes. |
async sound(id: string, o: SoundOptions): Promise<LibrarySound> | A sound item made playable: its file is read from the package, handed to the audio service and defined there with the item's bus, volume, loop (and loop points) and distance falloff. |
async flipbook(id: string): Promise<{ item: FlipbookItem; files: Partial<Record<keyof FlipbookItem['files'], Uint8Array>> }> | A flipbook item and the bytes of its images (the encoded files, by name: color, light, light2, motion, depth). Decoding them into textures is the effects view's work, so this stays free of the drawing code. |
async volume(id: string): Promise<{ item: VolumeItem; bytes: Uint8Array }> | A volume item and its voxel bytes (frames x z x y x x, one byte per channel per voxel). |
async preload(id: string, tier?: LibraryTier): Promise<void> | Bring an item's files to the device now (a model's file, a texture's maps), so a later call does not wait. |
release(): void | Free what the library made: materials, textures, characters. Packages stay open (they cost the mount nothing but the index). |
dispose(): void |
packages/levels/src/library.ts:165
CatalogClient class
class CatalogClientreadonly registrations: CatalogRegistration[] | every catalog registered through this client, in order |
constructor(private readonly levels: LevelService, private readonly mount: PackageMount, private readonly store: AssetStore, private readonly defaults: CatalogOptions = {}) | |
async register(url: string, o: CatalogOptions = {}): Promise<CatalogRegistration> |
packages/levels/src/catalog.ts:46
ClipPlayer class
class ClipPlayerthe skeletal clips of a model on its own skeleton: a graph with a state of the first clip, montages over it
readonly groups: Record<string, BABYLON.AnimationGroup> | |
readonly graph: AnimGraph | |
readonly missing: Record<string, string[]> | |
constructor(scene: BABYLON.Scene, root: Node, clips: ClipJson[], o: { graph?: GraphDef; rest?: string } = {}) | |
names(): string[] | |
duration(clip: string): number | |
play(clip: string, o: { loop?: boolean; rate?: number; blend?: number; mask?: string[] } = {}): Waitable | play a clip over the graph; a one-shot is done when it ends, a loop when it is stopped |
stop(clip: string): void | |
playingNow(): string[] | |
update(dt: number): void | one rendered frame |
dispose(): void |
packages/levels/src/fmdl-motion.ts:223
CodeLoader class
class CodeLoaderconstructor(readonly world: World, readonly mount: PackageMount, private o: CodeLoaderOptions = {}) | |
list(): LoadedCode[] | The code loaded so far, in load order. |
exports(id: string): LibraryModule | null | undefined | The exports of a loaded package's code, or undefined. |
require(id: string, range = '*'): Promise<LoadedCode> | Load the code of a package (and of its dependencies first) and run its install once. Resolves at once when it is loaded;
concurrent calls share one load. Rejects with the reason when the package may not run code or something is missing. |
module(id: string, range = '*'): Promise<{ exports: LibraryModule; pkg: FerretPackage; ferret: unknown }> | The code module of a package of kind levels that is docked into a parent game: checked, imported and kept, but install is NOT called:
the dock calls it at every entry and disposes at every exit. The same checks as require (policy, sha256); one import per page, however often the level is entered. |
async importFile(pkg: FerretPackage, path: string): Promise<unknown> | Run another module of a loaded level's package (its kernels): the same checks as its entry (the manifest's hash, or the origin's trust), the same shared engine. |
dispose(): void | Call the dispose that install returned, newest first (the modules themselves stay: a page cannot unload them). |
packages/levels/src/code.ts:70
CollisionChunks class
class CollisionChunksKeeps the chunks round the player resident. update is cheap (a few dozen boxes); fetching and instancing happen in the background.
constructor(private def: CollisionChunksDef, private assets: PackageAssets, private at: (file: string) => string, private name: string, private places: () => [number, number, number][], private onError: (message: string) => void = () => {}) | |
async ready(): Promise<void> | Start the chunks near places and wait for them (the level is not playable before the ground round the spawn is solid). |
update(): void | |
get loaded(): number | |
dispose(): void |
packages/levels/src/collision-chunks.ts:32
DecalBuffer class
class DecalBufferreadonly target: BABYLON.RenderTargetTexture | |
constructor(private readonly scene: BABYLON.Scene) | |
get count(): number | the decal meshes drawn into the buffer now |
dispose(): void |
packages/levels/src/decal-buffer.ts:17
DependencyError class
class DependencyError extends Errorconstructor(message: string, readonly id: string, readonly range: string, readonly tried: { url: string; error?: string }[]) |
packages/levels/src/dependencies.ts:36
DependencyResolver class
class DependencyResolverreadonly opened: OpenedDependency[] | every dependency opened by this resolver, in the order it was opened |
constructor(private readonly o: DependencyOptions) | |
async find(id: string, range = '*', extra: readonly string[] = []): Promise<OpenedDependency | null> | Find a package by id and range in extra (searched first) and then the resolver's own catalogs, and open it. Null when no catalog has
it; throws a DependencyError that names every catalog tried and why when one has it but not in range, or none could be read. |
async openAll(pkg: FerretPackage, into: DependencyTarget, base: string): Promise<OpenedDependency[]> | Open every dependency of pkg (and theirs) that into does not hold yet, and add it there. base is the URL pkg was loaded from: its
own relative catalogs are read from there. A dependency that is open already must fit its range. A package pkg names itself is opened by
pkg's range wherever it is first asked for, so that the versions a game pins are the ones it gets. Returns what was opened. |
hook(extra: readonly string[] = []): (id: string, range: string) => Promise<FerretPackage | null> | The code loader's open hook: a package required later (by id) is searched in the resolver's catalogs. |
packages/levels/src/dependencies.ts:43
DistanceFieldTextures class
class DistanceFieldTexturesa distance field on the graphics card: the table of bricks and the atlas as two 3D textures
readonly table: BABYLON.BaseTexture | |
readonly atlas: BABYLON.BaseTexture | |
constructor(readonly header: DistanceFieldHeader, bytes: Uint8Array, scene: BABYLON.Scene) | |
dispose(): void |
packages/levels/src/distance-field.ts:74
DockHost class
class DockHost implements ServiceThe service of the parent that docks levels. enter is what a docked level's LevelDef.build calls; the level ends when the engine unloads it (levels.onUnload),
whichever way it goes (a door, the menu, levels.evict). Events on the world's bus: dock:enter { id }, dock:leave { id }, dock:failed { id, error }.
readonly name: "dock" | |
readonly roles: Roles | the roles service; made by the host if the parent has not added one |
entered: number | how many levels were docked and ended, for the tests that count round trips |
left: number | |
constructor(private o: DockHostOptions) | |
get current(): string | undefined | the id of the level docked now |
dispose() | |
async enter(def: LevelDef, build: LevelContext, packageId: string): Promise<void> | The build step of a docked level: run its code under the transition. |
packages/levels/src/dock.ts:74
FmdlModel class
class FmdlModelA resolved model with its files loaded: every glTF any level of it needs is read once and shared by every placement. Building a level is then synchronous (a lazy rung of the perspective backend makes its meshes when first shown).
static async load(resolved: ResolvedModel, read: FileReader, scene: BABYLON.Scene, o: FmdlLoadOptions = {}): Promise<FmdlModel> | The plans of the levels this device draws, loaded: read every file of every level, once. |
dispose(): void | Release what the model loaded: its glTF containers (meshes, materials, textures, geometry) and the maps it read itself (a library texture given by texture stays its giver's).
What was built from the model shares these, so this is for when none of it is drawn any more: a model drawn by a level is disposed in the level's onUnload. |
plan(level: number): AssemblyPlan | the plan of a level (the device tier applied) |
build(level: number, name = `${this.resolved.id}:${level}`): BABYLON.TransformNode | The nodes of one level of the model, with every included instance placed on it. The meshes are instances of the loaded glTF's, so a thousand of the same model share their vertex data. The node is not parented: the caller hangs it where it belongs and disposes it. |
stageModel(): { id: string; resolved: ResolvedModel; read: FileReader; make(level: number, name: string): { root: BABYLON.TransformNode; plan: AssemblyPlan } } | This model as something a ModelStage can place by name (fmdl-motion.ts): the nodes of a level and the plan they were made from. |
ladder(o: { impostor?: string } = {}): ModelRung[] | The ladder this device draws the model by: its levels, the impostor, the point (ladderOfModel); throws, naming them, when thresholds were not measured. |
async place_entity(entity: Entity, backend: BabylonBackend, o: { impostor?: string; coherence?: { kind?: string; link?: number; gap?: number }; fade?: number; keepFrames?: number; /** the entity does not move once placed: the meshes of a rung keep their world matrices from the moment they are made (the CPU cost of thousands of parts) */ static?: boolean } = {}): Promise<Perspective> | Give an entity this model, drawn by size on the screen: a lazy rung for each level (made when first shown, dropped when long unused), the impostor
rung from the model's baked atlas, the point from the atlas's look. Like models are one coherent group (coherence.kind is the model's id, or
the one given), so a field of atoms is drawn as one: neighbours never differ by a level. Returns the entity's Perspective component. |
bounds(): { centre: Vec3; radius: number } | The bounding sphere of the whole in its own frame (its finest level, includes placed), measured once: the lazy rungs have no meshes to measure until shown. |
packages/levels/src/fmdl.ts:46
FogVeil class
class FogVeilThe veil on the scene's PBR materials; density follows the height fog at the camera (set by the environment every frame).
enabled: boolean | |
density: number | extinction per metre now (the height fog's density at the camera times the extinction scale) |
colour: [number, number, number] | linear colour (the fog's colour times the albedo) |
constructor(readonly scene: BABYLON.Scene, readonly def: FogVeilDef) | |
factor(): number | the share of a point beyond the veil's depth that the veil covers: what a sky or a far sea mixes toward the colour |
dispose() |
packages/levels/src/fog-veil.ts:58
HeightFogMaterials class
class HeightFogMaterialsThe height fog integrated along each ray on every PBR and standard material of the scene; update(h) every frame with the camera's height.
enabled: boolean | |
values: [number, number, number, number] | |
get minTransmittance() | what of the surface always comes through (Unreal's FogMaxOpacity, of an exact fog) |
constructor(readonly scene: BABYLON.Scene, readonly def: HeightFogDef) | |
update(h: number) | |
dispose() |
packages/levels/src/height-fog-material.ts:102
LevelMaterials class
class LevelMaterialsThe materials of one level: definitions by name, textures read once, materials made once.
readonly defs: Map<string, MaterialDef> | |
readonly policy: LevelCodecPolicy | |
constructor(readonly scene: BABYLON.Scene, private readonly files: LevelFiles, private readonly o: LevelMaterialsOptions = {}) | |
add(materials?: unknown, textures?: unknown): void | add definitions (a ferret-materials/1 object) and/or a texture catalogue, already read |
async load(o: { materials?: string; textures?: string; distanceField?: string }): Promise<void> | read the files of the level: the catalogue first, then the definitions (either may be inline: add) |
async loadDistanceField(path: string): Promise<void> | the level's distance field: its header, and the data file the header names beside it |
setDistanceField(f: DistanceFieldData): void | a distance field already read; the materials made from now on see it |
has(name: string): boolean | |
get names(): string[] | |
fileOf(stem: string): { file: string; srgb?: boolean } | the file a texture stem is read from under the policy, and whether it is colour by the catalogue |
material(name: string): Promise<BABYLON.PBRMaterial> | The material of a name (made once). |
screenDecalMaterial(name: string): Promise<BABYLON.PBRMaterial> | The material of a projected decal (screen-decals.ts): the level material name (a master carried whole, decal: true) as the shader of the decal's box. It is drawn into the
scene's screen decal buffers (made if the scene has none yet), back faces only, no depth, blended with premultiplied alpha; it has no light of its own. |
async ready(): Promise<void> | Resolves when every texture asked for so far is loaded and decoded, and every material asked for is made. |
get materialsMade(): Promise<BABYLON.PBRMaterial[]> | The made materials, in order of use. |
dispose(): void |
packages/levels/src/level-materials.ts:212
LevelService class
class LevelService implements ServiceThe level registry and travel between levels. travel(id) shows the loading screen (events), removes the old level with
everything it made, builds or loads the new one, moves the persistent entities (the player) to the spawn point and announces
the new level. Events: level:loading { id, progress }, level:ready { id, report }, level:unloaded { id }, level:failed { id, error }.
state is the game's data that survives travel and goes to Platform.state with saveData.
readonly name: "levels" | |
state: Record<string, unknown> | persistent state across levels: inventory, flags, health ... plain JSON |
readonly spawns: Map<string, SpawnPoint> | |
readonly transitions: TransitionRegistry | the game's transitions: register them by name and choose which one a travel uses |
current: LevelDef | null | |
travelling: boolean | |
report: LevelReport | |
animGraphs: Record<string, any> | the animation graphs of the current level package (its manifest's animGraphs), by name |
movement: Record<string, number> | the player character values of the current level package (its manifest's movement), over the engine's defaults |
libraries?: (manifest: import('./manifest').LevelManifest, levelId: string) => Promise<void> | plugged in by installLevelLibraries (./libraries): require the libraries a level's manifest needs before the level is built |
packageLoader?: (ctx: LevelContext, level: LevelDef, report: LevelReport) => Promise<void> | |
readonly persistent: Set<Entity> | entities that always travel with the player (the player itself): they are placed at the spawn, never removed |
constructor(readonly opts: LevelOptions = {}) | |
init(world: World) | |
register(def: LevelDef): this | |
unregister(id: string): boolean | Remove a level from the registry (a catalog that no longer lists it). The level being played is not touched. |
replace(def: LevelDef): this | Register, or replace a level of the same id that is not the one being travelled to (a catalog update). |
catalogs?: { register(url: string, o?: unknown): Promise<unknown> } | Plugged in by installCatalogs (./catalog): the remote levels of a catalog. |
registerCatalog(url: string, o?: unknown): Promise<unknown> | Fetch a catalog and register its levels; needs installCatalogs. |
has(id: string): boolean | |
get(id: string): LevelDef | |
list(): LevelDef[] | |
exempt(e: Entity): this | An entity that is not part of any level though it appears while one loads (another player's avatar): it is not removed with the level. |
keep(e: Entity): this | Entities that go with the player to every level. |
async travel(id: string, opts: TravelOptions = {}): Promise<LevelReport> | |
spawn(id?: string): SpawnPoint | null | The spawn point with that id, or the level's default one. |
place(e: Entity, s: SpawnPoint) | Put an entity at a spawn point (any entity with a CharacterMovement is teleported properly). |
hold<T>(work: Promise<T>, label = 'artefact'): Promise<T> | An artefact the level is not ready without. An entity of the level calls this while the level is built (a behaviour's onAttach) with the promise of what it still
loads (a character's model, its clips). level:ready is announced when the last of them has settled, or after holdMs; a rejected one is a warning of the report.
Outside a travel the hold is ignored. Returns the promise. |
get holding(): number | how many holds of the level being built are not taken up yet or still open |
unload() | |
async evict(id: string, to: string, spawn?: string, o: TravelOptions = {}): Promise<boolean> | End a level at once: the parent has changed or removed the door it was entered by. If the level is the current one the player is taken to to
(at spawn) by an ordinary travel, which unloads it with everything it made; if it is not current, nothing happens. Resolves when the player is out. |
onUnload(fn: () => void) | Run fn when the current level is removed (release assets, clear a service). |
saveData(): { level: string | null; state: Record<string, unknown> } | What to hand to Platform.saveState: the game's state and where the player is. |
loadData(data: { level?: string | null; state?: Record<string, unknown> } | null | undefined): string | null | Restore what saveData made; returns the level to travel to (or null). |
dispose() |
packages/levels/src/levels.ts:114
LightBudget class
class LightBudgetreadonly def: LightBudgetDef | |
onChange?: (entered: number[], left: number[]) => void | called after a re-ranking when real lights changed hands: indices that entered and left the pool |
onSounds?: (start: number[], stop: number[]) => void | called when the nearest lamps with a sound change: indices to start and to stop |
constructor(readonly scene: BABYLON.Scene, def: LightBudgetDef, readonly opts: LightBudgetOptions = {}) | |
get clustered(): boolean | is every lamp a real light through clustered lighting |
get name() | |
get size() | |
get real(): number[] | the lights that are real now (fading ones included) |
get glowMesh() | |
glowSize(i: number): number | the size in metres of lamp i's glow dot now (0: hidden, because it is a real light or out of reach) |
get lights(): (BABYLON.PointLight | BABYLON.SpotLight)[] | |
stats(): LightBudgetStats | |
setBudget(n: number) | change the budget while running (a quality switch): the pool grows or shrinks, and the next re-ranking fills it |
update(dt: number) | one step of the budget: dt seconds since the last. It runs by itself every frame; tests call it with a clock of their own |
dispose() |
packages/levels/src/light-budget.ts:192
LookPlugin class
class LookPlugin extends BABYLON.MaterialPluginBasereadonly structure: LookStructure | |
readonly define: string | |
active: boolean | |
constructor(material: BABYLON.Material, readonly look: LookDef, readonly masks: Record<string, BABYLON.BaseTexture>) | |
getClassName() | Gets the current class name useful for serialization or dynamic coding. |
deactivate() | |
prepareDefinesBeforeAttributes(defines: BABYLON.MaterialDefines) | a material with no texture of its own draws without UVs unless asked: the masks are read at the first set |
prepareDefines(defines: BABYLON.MaterialDefines, _scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh) | Sets the defines for the next rendering |
isReadyForSubMesh() | Specifies that the submesh is ready to be used. |
getActiveTextures(t: BABYLON.BaseTexture[]) | Returns an array of the actively used textures. |
hasTexture(t: BABYLON.BaseTexture) | Checks to see if a texture is used in the material. |
getAttributes(attributes: string[], _scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh) | Gets the attributes used by the plugin. |
getSamplers(samplers: string[]) | Gets the samplers used by the plugin. |
getUniforms() | Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos) |
bindForSubMesh(ubo: BABYLON.UniformBuffer, scene: BABYLON.Scene) | Binds the material data. |
dispose(force?: boolean) | Disposes the resources of the material. |
getCustomCode(shaderType: string): Record<string, string> | Returns a list of custom shader code fragments to customize the shader. |
packages/levels/src/material-models.ts:451
ModelCatalogue class
class ModelCatalogueadd(resolved: ResolvedModel, authorText = ''): this | a resolved model: the description is made from it (authorText is the free part of its description.md) |
has(id: string): boolean | |
ids(): string[] | |
list(q: { text?: string; kind?: string; tag?: string; abstract?: boolean } = {}): ModelListing[] | the models whose words match, best first; the words of a sentence are taken one by one (short and filler words are left out) |
describe(id: string): ModelDescribed |
packages/levels/src/fmdl-catalogue.ts:25
ModelCode class
class ModelCodeconstructor(readonly stage: ModelStage, private o: ModelCodeOptions = {}) | |
async load(model: LoadableModel): Promise<this> | Check and import the code of a model and of the models it includes, once; a model has to be loaded before it is placed. |
install(rt: MotionRuntime): this | Make every function (those loaded later too) a word of the motion runtime: (name instance args...). |
link(game: ModelCodeGame): () => void | Give every function (those loaded later too) to a game of the game language, before its files are loaded. Returns what takes them back. |
call(fn: string, instance: unknown, ...args: unknown[]): unknown | (fn instance args...): the function fn of the model of instance (the actor's name, or the instance itself) |
functions(instance?: string): ModelFunctionInfo[] | the functions of an instance, or every function name the scene knows |
instance(name: string): ModelInstance | undefined | the instance of an actor that has code |
step(dt: number): void | the step hooks of every instance, in the order they appeared (the parent's module first) |
dispose(): void |
packages/levels/src/fmdl-code.ts:90
ModelDocks class
class ModelDocksconstructor(readonly stage: ModelStage, private o: DocksOptions = {}) | |
dispose(): void | |
parse(ref: string): { actor: Actor; dock: string } | <actor>#<dock> split into the actor and the dock; the dock may be left out when the actor has just one free dock |
frame(actor: Actor, dock: string): { matrix: BABYLON.Matrix; local: BABYLON.Matrix } | the dock's frame in the world: the node it sits on and the frame on it, as the loader places them (6.2) |
describe(name: string): DockInfo[] | every dock of an actor, and of the models included in it, with the words that say what goes there |
docked(): DockedPair[] | the pairs docked now |
dock(aRef: string, bRef: string, o: DockOptions = {}): DockedPair | |
undock(ref: string, other?: string): DockedPair[] | take a pair apart (undock('h1', 'o')), or everything an actor or a dock holds (undock('h1'), undock('o#bond-1')) |
save(): { fmdlDocks: DockedPair[] } | the docked pairs as plain JSON: what a level or a game's saved state holds, and what a replica is sent |
restore(saved: { fmdlDocks: DockedPair[] }): void | Make the docked pairs of a save (or of the host's replica) true here: pairs that are not in it are undocked, the ones that are missing are docked. A pair
is docked where its actors already are (place: false: the save was made with them in place, a replica has their poses from the net), so a restored
pair does not move anything; a bond is rebuilt by its backend, which puts the atoms in the molecule's shape again. |
packages/levels/src/fmdl-docks.ts:69
ModelPrograms class
class ModelProgramsconstructor(readonly stage: ModelStage, private host: ProgramHost) | |
find(target: string, ref: string): { actor: Actor; resolved: ResolvedModel; name: string; motion: ModelMotion } | the motion a name leads to on an actor (the instance's actor, for <instance>/<name>) |
args(resolved: ResolvedModel, name: string, motion: ModelMotion, given: Record<string, unknown> = {}): Record<string, Value> | the arguments checked against params (types, unknown names) and the defaults filled in |
missingForms(motion: ModelMotion): string[] | the forms the motion itself uses (requires.forms of the motion) that the language does not have: running it needs only those |
missingModelForms(resolved: ResolvedModel): string[] | the forms a whole model needs (its requires.forms, which holds those of all its motions) that the language does not have: a player refuses the model before running it |
checkModel(target: string): void | throws, naming the forms, when this runtime lacks one the actor's model needs |
async run(target: string, ref: string, args: Record<string, unknown> = {}): Promise<Program> | Start a motion on an actor. The file is read first (once), so the program is returned when it has started. |
runNow(target: string, ref: string, args: Record<string, unknown> = {}): Program | the same for a caller that cannot wait (a command, a form): the files must have been read by preload |
async preload(target: string): Promise<void> | read every motion file of an actor's model and of the models included in it |
resolver() | the motionResolver of the actuators' capability: motion.run { motion, target, args } |
packages/levels/src/fmdl-programs.ts:33
ModelStage class
class ModelStageThe placed models of a world by name. A Service of @ferret/core: add it to the world and its clock is the fixed step's; in a test call step.
readonly name: "fmdl-stage" | |
readonly actors: Map<string, Actor> | |
constructor(private o: StageOptions = {}) | |
watch(w: StageWatcher): () => void | tell w of what the stage does; returns what ends it |
time(): number | |
fixedUpdate(dt: number): void | |
update(dt: number): void | |
step(dt: number): void | |
addModel(model: StageModel): this | |
modelIds(): string[] | |
adopt(name: string, id: string, root: Node, plan: AssemblyPlan, from?: string): Actor | put an already built model on the stage under a name (a model the game made itself) |
actor(name: string): Actor | An actor by name. An included instance is addressed <actor>/<instance> (and deeper: <actor>/<instance>/<instance>): it is the instance's nodes and parts
of the whole it is in, seen as an actor of its own, so a motion of the included model runs on it. |
appear(id: string, o: { name?: string; at?: Vec3; level?: number; scale?: number; parent?: string } = {}): Actor | a model appears: built on level, placed at at, named name (default <id>#<n>) |
vanish(name: string): void | take an actor away, with the actors let go from it staying |
letGo(name: string, instance?: string): string[] | Let included instances go: each becomes an actor of its own, <actor>/<instance>, where it is (its world matrix kept), no longer a part of the whole's nodes.
With no instance named, every one. Returns the new names. |
attachClips(name: string, clips: ClipJson[], o: { graph?: GraphDef; rest?: string } = {}): ClipPlayer | put the skeletal clips of an actor on its own skeleton |
async loadClips(name: string, o: { sets?: string[]; graph?: GraphDef; rest?: string } = {}): Promise<ClipPlayer> | read the clip sets of the actor's model (all of them, or sets) and put them on its skeleton: it begins in idle, else in the first clip |
nodeHost(): NodeHost | the nodes of the actors as handles of the language (move-along, turn-to) |
packages/levels/src/fmdl-motion.ts:332
OcclusionCulling class
class OcclusionCulling implements Servicereadonly name: "occlusion-culling" | |
init(world: World): void | |
get supported(): boolean | |
get meshes(): number | |
apply(o: OcclusionOptions): number | give queries to the level's big meshes (and to those that load later under the root) |
unapply(): void | |
qualityKnobs(): QualityKnob[] | |
dispose(): void |
packages/levels/src/occlusion-culling.ts:21
OceanView class
class OceanViewreadonly mesh: BABYLON.Mesh | |
readonly material: BABYLON.ShaderMaterial | |
get ready(): boolean | has every depth texture been baked at least once (for loading screens and tests) |
constructor(private scene: BABYLON.Scene, private o: OceanOptions = {}) | |
setSea(o: { whitecaps: number; streaks: number; wavelength: number; wind: number }) | the state of the sea for its foam and chop: the share of the surface under whitecaps (seaCondition(...).whitecaps of |
setWind(dirDeg: number) | |
setWaves(list: OceanWave[]) | |
get waves(): readonly OceanWave[] | |
setLight(o: { toSun: V3; sunColor: V3; light?: number; skyTop?: V3; skyHorizon?: V3; rain?: number }) | the light: the direction TO the sun, its colour, how bright the day is (0..1), the sky colours for a missing cube, the rain 0..1 |
setColors(o: { deep?: V3; shallow?: V3; foam?: number; clarity?: number }) | the colours of the water: deep and shallow (linear 0..1), and how much the crests foam; clarity: metres of water the bed shows through (default 4: a murky sea;
a clear bay over sand shows its bed through 10 m and more), the shallow colour fades out over 1.5 times that |
setFog(color: V3 | BABYLON.Color3, density: number) | |
setHeightFog(values: readonly [number, number, number, number] | null) | the height fog along each ray instead of the flat fogDensity (env.heightFog.values, heightFogShaderValues); null: the flat fog |
setReflection(tex: BABYLON.BaseTexture | null) | the sky the sea mirrors: a cube texture of the sky and its clouds (createSkyProbe); null: the two sky colours |
setDetail(o: { normal?: BABYLON.BaseTexture; near?: number; far?: number; strength?: number; speed?: number; foam?: BABYLON.BaseTexture; foamScale?: number }) | a tiled normal map for the small waves (read at near and far metres per tile, strength of the normal's slope, drifting with the wind at speed m/s) and a tiled foam map (foamScale metres
per tile; its red channel shapes the foam); both optional. The textures are RGB normals (0..1, flat = 0.5, 0.5, 1) and any foam picture. |
setVeil(o: { density: number; distance: number; colour: V3 } | null) | the volumetric fog's veil over the sea (fogVeilOf(scene)): extinction per metre, its depth in metres and colour; null: none |
setTone(o: { exposure: number; contrast: number; aces: boolean | 'unreal' } | null) | the scene's image processing for the sea (exposure, the ACES curve, contrast, gamma): a shader of its own does not get it; off by default |
prime(cam: V3) | bake the depth round a point at once (a loading screen) |
update(time: number, cam: V3, level = 0) | each frame: the clock, the water level, the camera (the grid follows it; the depth boxes move when the camera has gone a quarter of their size) |
dispose() |
packages/levels/src/ocean.ts:209
PackageMount class
class PackageMountConnects packages to a LevelService. add(pkg) registers the package's levels (as <id> for the first package, <pkgid>/<id>
for the others, or with the prefix given); url(pkg, path) gives a blob URL for any file of a package, for sounds, textures
and video. Nothing is unpacked: a file is read from the package when a level asks for it, and a model's blob URL goes when the
level that held it is gone.
readonly packages: PackageSet | |
readonly assets: MountAssets | give this to the level loader instead of the asset cache (installPackages does) |
readonly loader: PackageLoaderOptions | the options the level loader runs with: hand this to installEditor as its loader so the editor's draft shows in reloads |
constructor(readonly levels: LevelService, private inner: MountAssets, readonly opts: MountOptions = {}) | |
add(pkg: FerretPackage, o: { prefix?: string } = {}): LevelDef[] | Open a package into the mount and register its levels. Returns what was registered. |
startLevel(pkg: FerretPackage): string | null | The level a package starts in (entry.level of a game, else its first), as registered. |
async url(pkg: FerretPackage, path: string): Promise<string> | A blob URL for a file of a package (path inside pkg, or ferret://other/path). Stays valid until dispose. |
async fetch(url: string): Promise<FetchResult> | The loader's fetch for package urls; anything else goes to the real one. |
forget(pkgId: string): void | Drop everything cached for a package (its blob URLs): it was replaced by another version. |
dispose(): void |
packages/levels/src/ferret.ts:36
PartRig class
class PartRigreadonly parts: Map<string, Part> | |
readonly children: Map<string, PartRig> | the rigs of the included instances by instance name |
constructor(readonly root: Node, readonly plan: AssemblyPlan, private clock: () => number = () => 0) | |
names(): string[] | every moving part's address, the instances' as <instance>/<part> |
has(address: string): boolean | |
value(address: string): number | the value of a part now (radians for a hinge or a rotor, metres for a slider), the moves brought up to the clock |
limits(address: string): [number, number] | null | |
kind(address: string): 'hinge' | 'slider' | 'rotor' | |
set(address: string, v: number): number | jump to a value, held inside the part's limits; the parts linked to it follow |
to(address: string, v: number, seconds: number, curve = 'smooth'): Waitable | go to a value over seconds by an ease of the language; the waitable is done when it has arrived or another move of the part took over |
advance(): void | bring every move up to the clock (also the instances') |
moving(): boolean | |
detach(instance: string): PartRig | undefined | a rig for an instance that is let go: the whole no longer moves it |
packages/levels/src/fmdl-motion.ts:71
PlacementSource class
class PlacementSource implements CellSourceA CellSource that also understands placement lists: a cell whose file is *.placements.json is read through get (the loader's fetch), its models are loaded through the inner
source, and instantiate gives the thin-instance root; any other file goes to the inner source untouched. Streaming, memory budgets and ready() need no change.
constructor(private readonly inner: CellSource, private readonly scene: BABYLON.Scene, private readonly get: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>, private readonly o: { resolver?: PlacementResolver; warn?: PlacementWarnings; /** the level's materials shared by every list (the manifest's `levelMaterials`) */ levelMaterials?: LevelMaterials; /** how a list's own `levelMaterials` files are read (the package loader's fetch, relative to the list's folder); without it a list can hold its materials inline only */ files?: (listUrl: string) => LevelFiles } = {}) | |
async load(url: string): Promise<void> | |
levelMaterialsOf(url: string): LevelMaterials | undefined | the level materials a list draws with: its own when it names some, else the shared ones |
async read(url: string): Promise<{ file: PlacementFile; urls: Map<string, string> }> | read and check a list, and load every model it names (once each) |
async instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }> | |
release(url: string): void |
packages/levels/src/placements.ts:286
PrefetchService class
class PrefetchService implements Servicereadonly name: "prefetch" | |
constructor(private readonly levels: LevelService, o: PrefetchOptions = {}) | |
init(world: World): void | |
near(zone: string, levelId: string, o: { inSeconds?: number } = {}): () => void | Doors and zones: entering zone makes levelId wanted (the player is probably about to go there). |
hint(id: string, o: { inSeconds?: number; from?: 'level' | 'game' } = {}): void | id is wanted. With inSeconds (the player will need it in about that long) the start is put off as long as the estimate allows
it to still finish in time; without it the download starts at once (when no travel is running). |
focus(ids: string[]): void | Only these are wanted from now on: every other background download stops at its next file. |
cancel(id: string): void | |
get bandwidth(): number | The smoothed link speed in bytes per second, 0 when nothing was measured. |
state(id: string): JobState | 'none' | |
async idle(id: string): Promise<void> | Resolves when the level's background download has finished (done, cancelled or failed). |
status(): { rate: number; jobs: Record<string, { state: JobState; wanted: boolean; bytes: number }> } | |
dispose(): void |
packages/levels/src/prefetch.ts:31
ProbeVolume class
class ProbeVolumeThe baked grid on the GPU and the plugin on every PBR material of the scene (also those added later).
readonly textures: BABYLON.RawTexture3D[] | |
enabled: boolean | |
constructor(readonly scene: BABYLON.Scene, readonly def: ProbeVolumeDef, data: ArrayBuffer) | |
setEnabled(on: boolean) | Switch the baked light on or off (the materials recompile). |
dispose() |
packages/levels/src/probe-volume.ts:118
ProgramPlugin class
class ProgramPlugin extends BABYLON.MaterialPluginBaseactive: boolean | |
constructor(material: BABYLON.Material, built: BuiltProgram) | |
get program(): MaterialProgram | |
getClassName() | Gets the current class name useful for serialization or dynamic coding. |
deactivate() | |
prepareDefinesBeforeAttributes(defines: BABYLON.MaterialDefines) | Sets the defines for the next rendering. Called before PrepareDefinesForAttributes is called. |
prepareDefines(defines: BABYLON.MaterialDefines, scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh) | Sets the defines for the next rendering |
isReadyForSubMesh() | Specifies that the submesh is ready to be used. |
getActiveTextures(t: BABYLON.BaseTexture[]) | Returns an array of the actively used textures. |
hasTexture(t: BABYLON.BaseTexture) | Checks to see if a texture is used in the material. |
getAttributes(attributes: string[], _scene: BABYLON.Scene, mesh: BABYLON.AbstractMesh) | Gets the attributes used by the plugin. |
getSamplers(samplers: string[]) | Gets the samplers used by the plugin. |
getUniforms() | Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos) |
bindForSubMesh(ubo: BABYLON.UniformBuffer, scene: BABYLON.Scene, _engine: BABYLON.AbstractEngine, subMesh: BABYLON.SubMesh) | Binds the material data. |
dispose(force?: boolean) | Disposes the resources of the material. |
getCustomCode(shaderType: string): Record<string, string> | Returns a list of custom shader code fragments to customize the shader. |
packages/levels/src/material-program.ts:296
PropellerView class
class PropellerViewdisc: BABYLON.TransformNode | null | the disc, once made (the first frame it is wanted) |
hidden: boolean | both 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 Servicereadonly 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 = {}): ModelHandle | Ask for a model. Returns at once with the placeholder in place. |
get scene(): BABYLON.Scene | |
get events() | |
get models() | |
forget(h: ModelHandleImpl): void | |
async modelUrl(ref: string, o: ModelOptions): Promise<string> | |
dispose(): void |
packages/levels/src/runtime.ts:55
ScreenDecals class
class ScreenDecalsreadonly colour: BABYLON.RenderTargetTexture | the buffer of colour (rgb premultiplied by the opacity) and opacity |
readonly surface: BABYLON.RenderTargetTexture | the buffer of roughness, metallic (premultiplied) and opacity |
readonly pass: { value: number; } | which of the two passes is being drawn: the decal materials read it each time they are bound |
constructor(private readonly scene: BABYLON.Scene) | |
get count(): number | the boxes drawn now |
add(box: BABYLON.AbstractMesh): void | put a decal's box mesh in: it is taken out of the camera's picture and drawn only into the buffers |
dispose(): void |
packages/levels/src/screen-decals.ts:43
SequencePlayer class
class SequencePlayerPlays one sequence on the scene. update(dt) once per frame.
time: number | |
playing: boolean | |
finished: number | how 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 ShipWakereadonly 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 Servicereadonly 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(): boolean | is a snapshot recorded or being replayed now |
init(world: World): void | |
enable(): void | start snapshotting (a no-op on WebGL2) |
disable(): void | |
invalidate(): void | the 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 ServiceThe CPU knob of the plan-OFFLOAD G1: while the camera has not moved for stillFrames frames (a dialogue, a cutscene, a menu over the scene) the list of
active meshes is frozen (scene.freezeActiveMeshes(): no frustum test of thousands of meshes a frame) and given back the frame the camera moves or the
scene's mesh list changes. Meshes that move keep drawing at their new places; what a freeze cannot see is a mesh entering the view while the camera is
still, so the knob is the regulator's last resort among the CPU ones (visibility 0.6), and the list is taken anew every refreshFrames frames (a mesh
switched on or shown meanwhile appears then). A freeze the scene carries out later (it waits until it is ready) is taken back if it is no longer wanted.
Level 0 (the default) is off, level 1 is on.
readonly name: "still-camera-freeze" | |
stillFrames: number | |
refreshFrames: number | how many frames a frozen list lives before it is taken anew |
init(world: World): void | |
attach(scene: BABYLON.Scene): void | |
qualityKnobs(): QualityKnob[] | |
dispose(): void |
packages/levels/src/still-camera.ts:21
StreamingDebugView class
class StreamingDebugViewconstructor(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 Servicereadonly 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 | null | the block being streamed (for the debug view and tools) |
begin(block: StreamingBlock, source: CellSource, o: StreamingOptions): void | Start streaming a level. The cells within loadRadius of the focus are what ready() waits for. |
end(): void | Stop streaming and release everything this service added. Called when the level is unloaded. |
cellLevel(id: string): number | undefined | the 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): void | Called 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 | null | the 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 SwarmSimreadonly pos: Float32Array | x 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 TransitionRegistryregister(name: string, t: Transition | (() => Transition)): this | Register 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): string | The 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 TransitionRunA 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 | null | set 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 ErrorThe player (or the menu) cancelled the travel.
constructor(readonly id: string) |
packages/levels/src/levels.ts:66
VisibilityService class
class VisibilityService implements ServiceDraws 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): string | The grid cell of a point. |
update(_dt = 0): void | Called once per rendered frame. |
packages/levels/src/visibility.ts:14
Functions
acquireDepthRenderer function
function acquireDepthRenderer(scene: BABYLON.Scene, cam: BABYLON.Nullable<BABYLON.Camera>): BABYLON.DepthRenderer | nullthe scene's depth pass, drawn while a material asks for it (the glow's DepthFade reads it)
packages/levels/src/material-models.ts:439
actorMatrix function
function actorMatrix(a: Placement): BABYLON.MatrixThe actor's transform as a matrix (scale, then rotation, then position).
packages/levels/src/placements.ts:147
addScreenDecals function
async function addScreenDecals(scene: BABYLON.Scene, mats: LevelMaterials, specs: readonly ScreenDecalSpec[]): Promise<{ count: number; dispose(): void }>The decals of a level in the scene: for each spec a box mesh with the decal's material (a master of the level carried whole, made as a projected decal), placed by its matrix. Returns what disposes them. The meshes are made one by one (a clone of one cube shares its geometry): each has its own matrix, which its material reads.
packages/levels/src/screen-decals.ts:119
alphaAt function
function alphaAt(keys: Array<[number, number]>, t: number): numberthe 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">) => numberhow many particles are alive at once: rate x the longest life (plus a margin)
packages/levels/src/ambient-particles.ts:56
applyEnvironment function
function applyEnvironment(scene: BABYLON.Scene, def: EnvironmentDef, name = 'env', o: { /** the game's shared clock in seconds (the world's time): waves are drawn from it, so every peer sees the same sea at the same moment */ clock?: () => number; /** a height field of what moves a river (see `WaterResponseMap`) */ waterResponse?: WaterResponseMap; /** parts the game draws itself: left out */ skip?: Array<'sun' | 'ambient' | 'fog' | 'sky' | 'water'>; /** makes an effect of the vfx catalogue for an `effects` entry that names one (`vfx`); without it such an entry is the simple fire */ vfx?: (name: string, at: Vec3, scale: number, params?: Record<string, number>) => EnvironmentVfx } = {}): EnvironmentBuild the environment in a scene. Dispose it when the level unloads.
packages/levels/src/environment.ts:286
applyFoliageWind function
function applyFoliageWind(scene: BABYLON.Scene, def: FoliageWindDef, o: { clock?: () => number; flowMap?: FoliageFlowMap } = {}): FoliageWindHandlepackages/levels/src/foliage-wind.ts:249
applyLandscape function
async function applyLandscape(scene: BABYLON.Scene, def: LandscapeDef, o: ApplyLandscapeOptions): Promise<LandscapeView>Put a landscape's layer blend on its mesh's material, mark a far plane, and bake the virtual texture and hand it to the props. A problem (a texture that does not load, a mesh that is not there) is a warning in the view, never a thrown error: the level still loads with the baked look.
packages/levels/src/landscape.ts:754
applyMaterialLook function
function applyMaterialLook(material: BABYLON.Material, look: LookDef, o: ApplyLookOptions): () => voidPut the model on a PBR material; returns the function that takes it off again. A material with none of its fields is left as it is.
packages/levels/src/material-models.ts:610
applyMaterialLooks function
function applyMaterialLooks(scene: BABYLON.Scene, initial: MaterialLooks | undefined, o: MaterialLooksOptions = {}): MaterialLooksHandlepackages/levels/src/material-look.ts:200
applyMaterialProgram function
function applyMaterialProgram(material: BABYLON.Material, program: MaterialProgram, o: ApplyProgramOptions): () => voidPut a program on a PBR material; returns the function that takes it off again.
packages/levels/src/material-program.ts:471
applyMaterialScale function
function applyMaterialScale(scene: BABYLON.Scene, defs: MaterialScaleDef[]): { dispose(): void; flush(force?: boolean): void; scaled: number; meshesCleared: number }packages/levels/src/material-scale.ts:42
applySunShadows function
function applySunShadows(sun: BABYLON.DirectionalLight, def: SunShadowsDef = {}): SunShadowsShadows from the sun on the meshes handed to add. A mesh of a material with an opacity mask or alpha test casts by its mask.
packages/levels/src/sun-shadows.ts:57
assignShadowRoles function
function assignShadowRoles(generator: Pick<BABYLON.ShadowGenerator, 'addShadowCaster'>, meshes: Iterable<BABYLON.AbstractMesh>, o: ShadowRoleOptions = {}): ShadowRoleResultOne function that chooses the roles of the meshes of a scene for a shadow generator: every mesh whose material is of a type that takes shadows (takesShadows) receives
them, and those casts picks (default all of them) cast. Meshes with no vertices or a material of another type (the ground's and the sea's own shaders) are skipped.
packages/levels/src/sun-shadows.ts:116
atmosphereColours function
function atmosphereColours(t: AtmosphereTable, sunScale = 1, sunColor: Vec3 = [1, 1, 1]): { top: Vec3; horizon: Vec3; ground: Vec3 }colours of the sky that the rest of the environment uses (water, reflection, fog): the zenith, the horizon away from the sun, the ground
packages/levels/src/atmosphere.ts:190
bendOffset function
function bendOffset(p: V3, player: V3, distance: number, strength: number, v: number, radius = 0): V3MF_Collusion (Unreal cm): grass pushed away from player
packages/levels/src/foliage-wind.ts:93
bindPropulsors function
function bindPropulsors(actor: Actor, o: PropulsorBindOptions): PropulsorSet | undefinedBind the propulsors of actor. Returns the set (call update() once a step after the actuators) or undefined when the model declares none.
packages/levels/src/fmdl-propulsors.ts:38
blendWeights function
function blendWeights(weights: number[], heights: number[] = [], heightBlend: number[] = []): number[]Weights of the layers at a point -> the weights the material uses: normalised to sum 1 (no paint at all = the first layer), then height blended.
packages/levels/src/landscape.ts:210
bloomWeight function
function bloomWeight(intensity: number): numberpackages/levels/src/environment.ts:147
buildAmbientParticles function
function buildAmbientParticles(scene: BABYLON.Scene, d: AmbientParticlesDef, texture: BABYLON.Texture, name: string): { ps: BABYLON.ParticleSystem; at: BABYLON.Vector3; radius: number }the Babylon side; texture is any soft sprite
packages/levels/src/ambient-particles.ts:66
buildAtmosphereTable function
function buildAtmosphereTable(def: AtmosphereDef | undefined, sunElevation: number, n = LUT_SIZE): AtmosphereTableFill the table for the sun at sunElevation radians above the observer's horizon.
packages/levels/src/atmosphere.ts:118
buildPlacements function
async function buildPlacements(file: PlacementFile, o: PlacementBuildOptions): Promise<PlacementInstance>Make the instances of a placement list: one clone of each mesh of a model per group, carrying the group's actors as thin instances.
packages/levels/src/placements.ts:187
buildSwarm function
function buildSwarm(scene: BABYLON.Scene, d: SwarmDef, source: BABYLON.Mesh, name: string, wind?: () => { intensity: number; direction: [number, number] }, follow?: BABYLON.TransformNode)one mesh drawn once per agent (instances), turned along its flight; returns what to update and dispose
packages/levels/src/swarm.ts:114
buildWater function
function buildWater(scene: BABYLON.Scene, def: WaterDef, o: { response?: WaterResponseMap; name: string; skyTop: Vec3; skyHorizon: Vec3; sunDir: Vec3; sunColor: Vec3; /** the game's shared clock in seconds: with it every peer draws the same waves at the same moment (default: this surface's own time since it was built) */ clock?: () => number }): WaterSurfaceViewBuild 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 } = {}): RoomReflectionDraws 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): numberDistance on the ground plane from a point to a cell's box (0 inside it).
packages/levels/src/streaming.ts:62
checkDistanceField function
function checkDistanceField(h: unknown, bytes?: Uint8Array): string | undefinedwhat is wrong with a distance field, or undefined
packages/levels/src/distance-field.ts:43
compileProgram function
function compileProgram(p: MaterialProgram, o: { srgb?: readonly number[]; unlit?: boolean; arrays?: readonly (readonly number[])[]; screenDecal?: boolean } = {}): CompiledProgramThe GLSL of a program. srgb lists the indices of its textures that are colour and are decoded in the shader; unlit the material has no lighting.
packages/levels/src/material-program.ts:60
createKtx2Array function
function createKtx2Array(scene: BABYLON.Scene, layers: readonly DecodedKtx2[], o: { name?: string; anisotropy?: number } = {}): BABYLON.BaseTextureOne array texture of layers (all with the same layout; layer k = layers[k]). Trilinear, repeat, the given anisotropy. The texture owns its GL object: dispose() frees it.
packages/levels/src/texture-array.ts:38
createSkyProbe function
function createSkyProbe(scene: BABYLON.Scene, meshes: BABYLON.AbstractMesh[], o: { size?: number; every?: number; at?: [number, number, number] } = {}): BABYLON.RenderTargetTextureA cube map of the sky for water to mirror: renders meshes (the sky dome, cloud layers, anything far away) into a cube from at (default: the camera, so a dome that follows the camera is seen from inside) and refreshes it every every frames (default 30: clouds drift slowly; 0 renders once). Give the result to WaterSurfaceView.setReflection.
packages/levels/src/water.ts:266
curl function
function curl(x: number, y: number, z: number, seed = 0): [number, number, number]a smooth divergence-free vector field (the curl of a vector potential made of sines), in [-~1.7, ~1.7]; the same point gives the same vector
packages/levels/src/swarm.ts:60
decalBoxMatrix function
function decalBoxMatrix(d: Pick<ScreenDecalSpec, 'position' | 'axes' | 'half'>): BABYLON.Matrixthe world matrix of a unit cube [-1, 1]^3 that is the decal's box (columns: the axes scaled by the half extents, then the position)
packages/levels/src/screen-decals.ts:33
decalBufferOf function
function decalBufferOf(scene: BABYLON.Scene, create = false): DecalBuffer | undefinedThe scene's decal buffer; with create, made if there is none (the rendertarget part of Babylon must be loaded), and every material is told to look for it.
packages/levels/src/decal-buffer.ts:62
decodeKtx2 function
async function decodeKtx2(engine: BABYLON.AbstractEngine, bytes: Uint8Array): Promise<DecodedKtx2>Decode a KTX2 file the way Babylon's own texture loader does (same decoder, same worker pool, the formats this GPU takes).
packages/levels/src/texture-array.ts:14
deepColour function
function deepColour(absorption: Vec3 = [110, 158, 350], scattering: Vec3 = [0.05, 0.05, 0.05]): Vec3The deep colour of the water from Unreal's absorption distances and scattering (linear RGB).
packages/levels/src/water.ts:141
defaultLibraryUrl function
function defaultLibraryUrl(): stringpackages/levels/src/library.ts:159
distanceFieldSizes function
function distanceFieldSizes(h: DistanceFieldHeader): { table: number; atlas: number; texels: [number, number, number] }the bytes the data of a header holds: the table, then the atlas
packages/levels/src/distance-field.ts:37
distanceFieldUniforms function
function distanceFieldUniforms(h: DistanceFieldHeader): [string, number, number, number, number][]the uniforms of the lookup, in this order (material-program.ts declares and fills them)
packages/levels/src/distance-field.ts:93
distanceToBounds function
function distanceToBounds(b: CollisionChunkDef['bounds'], x: number, y: number, z: number): numberDistance from a point to a box (0 inside).
packages/levels/src/collision-chunks.ts:14
ditherValue function
function ditherValue(x: number, y: number, noise: number, threshold = PIXEL_DEPTH_THRESHOLD): numberDitherTemporalAA's value for a pixel (Unreal's graph with no temporal sample; noise is the noise texture's red channel, 0..1): threshold + (mod(x + 2y, 5) + noise) * 0.16665.
packages/levels/src/material-models.ts:90
dockPhysicsOf function
function dockPhysicsOf(host: { bodies: Iterable<{ node: Node; body: unknown }>; kernel: { addConstraint(d: any): any; removeConstraint(c: any): void; setPosition(b: any, p: Vec3): void; onConstraintBreak(cb: (c: any) => void): () => void } }): DockPhysicsthe kernel of a physics host as the docks' physics
packages/levels/src/fmdl-docks.ts:250
effectiveFogDensity function
function effectiveFogDensity(f: HeightFogDef, h: number): numberthe flat density Babylon's exponential fog takes for a view at height h: the density of the air there (a ray along the ground is what a walker sees most)
packages/levels/src/height-fog.ts:44
engineImports function
function engineImports(text: string): string[]The package names the code of a module imports from the shared engine (@ferret/<name>), in order of appearance.
packages/levels/src/dock-engine.ts:17
ensureLocalBounds function
function ensureLocalBounds(mesh: BABYLON.AbstractMesh): booleanThe bounds of a mesh's own vertices (Unreal's ObjectLocalBounds), as two constant vertex attributes of the source mesh so every instance reads them.
packages/levels/src/material-program.ts:253
ensureObjectHeight function
function ensureObjectHeight(mesh: BABYLON.AbstractMesh): booleanThe height of a mesh's own local bounds along y, metres: Unreal's ObjectBounds (its z). Written once as a constant vertex attribute of the source mesh so the shader can read it per object, thin instances included.
packages/levels/src/material-models.ts:412
environmentBabylonParts function
function environmentBabylonParts(env?: EnvironmentDef): string[]The Babylon parts a level's environment needs beyond the core: the post-processing pipeline for bloom, particles for fire.
packages/levels/src/environment.ts:138
flickerFactor function
function flickerFactor(l: Pick<BudgetLight, 'flicker'>, phase: number, t: number): numberthe 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): numbera 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): numberextinction per metre at height h
packages/levels/src/height-fog.ts:26
fogOpticalDepth function
function fogOpticalDepth(f: HeightFogDef, h0: number, dirY: number, dist: number): numberOptical depth of a straight ray from a point at height h0 going dist metres along a direction with vertical component dirY (-1..1):
the integral of the density, exact for each layer. The transmittance is exp(-depth).
packages/levels/src/height-fog.ts:34
fogVeilOf function
function fogVeilOf(scene: BABYLON.Scene): FogVeil | undefinedthe veil of the scene's environment, if its fog has one (for shaders of their own: the sky, the sea)
packages/levels/src/fog-veil.ts:86
freezeStatic function
function freezeStatic(world: World, scene: BABYLON.Scene, o: FreezeOptions): numberfreeze every static mesh of the level; returns how many were frozen
packages/levels/src/static-freeze.ts:35
gammaOfLinear function
function gammaOfLinear: (k: number) => numberthe albedo colour is a gamma colour for the shader: a linear multiplier k is k^(1/2.2) of it
packages/levels/src/material-scale.ts:38
gradientFaces function
function gradientFaces(top: Vec3, horizon: Vec3, ground: Vec3, n = 8): Uint8Array[]A cube map of the sky's gradient (ground below the horizon, top above): every face a few texels, smooth at every mip level, so any roughness reads it.
packages/levels/src/environment.ts:203
graphGlsl function
function graphGlsl(e: GraphExpr, smp: (name: string, uv: string) => string, depthCm = 'ferretLkDepthCm'): Typedone node as a GLSL expression, float (t 1) or vec3 (t 3); smp reads a named picture at a uv; depthCm is the pixel's distance along the view axis in centimetres
packages/levels/src/material-models.ts:224
graphMeanColour function
function graphMeanColour(n: any): [number, number, number] | undefinedThe colour a master's colour graph gives where its pictures read a middle value (0.5): constants, lerp, power, add, mul. Undefined for anything else.
packages/levels/src/level-materials.ts:190
groundBlendAttributes function
function groundBlendAttributes(w: number, own: { metallic: number; roughness: number; occlusion: number }, ground: { roughness: number }): { metallic: number; roughness: number; occlusion: number }What BlendMaterialAttributes leaves of an object's own attributes where the ground weighs w: the ground's roughness, the metallic of a MakeMaterialAttributes default (0), occlusion 1.
packages/levels/src/material-models.ts:57
groundSourceOf function
function groundSourceOf(scene: BABYLON.Scene, name?: string): GroundSource | undefinedThe ground of the landscape called name, or of the first landscape that has one; undefined while none is baked (a material then draws without the blend).
packages/levels/src/landscape.ts:599
groundWeight function
function groundWeight(h: number, objectHeight: number, up: number, g: GroundBlendDef): numberThe share of the ground colour at a pixel h metres over the ground, on an object objectHeight metres high, whose vertex normal points up by up (-1..1).
packages/levels/src/material-models.ts:50
groupByLayout function
function groupByLayout(files: readonly DecodedKtx2[]): number[][]Indices of files grouped by layout, in the order the layouts first occur.
packages/levels/src/texture-array.ts:29
groupKey function
function groupKey(a: Placement): stringThe group an actor draws in: its model and its material overrides, so actors of one group are one thin-instance draw.
packages/levels/src/placements.ts:119
groupPlacements function
function groupPlacements(file: PlacementFile): PlacementGroup[]packages/levels/src/placements.ts:135
hairFibreMaterial function
function hairFibreMaterial(scene: BABYLON.Scene, o: HairFibreOptions = {}): BABYLON.ShaderMaterialThe fibre material for a scene (one per scene and option set).
packages/levels/src/hair-fibre.ts:67
hasLook function
function hasLook(look: LookDef): booleanDoes a definition carry anything of this model?
packages/levels/src/material-models.ts:212
hasPackedNormals function
function hasPackedNormals: (layers: LandscapeLayerDef[]) => booleandoes a packed landscape carry normals or occlusion
packages/levels/src/landscape.ts:431
heightFogOf function
function heightFogOf(scene: BABYLON.Scene): HeightFogMaterials | undefinedthe scene's height fog along the rays, if its environment asks for one (fog.alongRay): shaders of their own (the sea) take its values
packages/levels/src/height-fog-material.ts:99
heightFogShaderValues function
function heightFogShaderValues(f: HeightFogDef, h: number): [number, number, number, number]Per-layer numbers of the shader at the camera's height h: [density of the first layer at the eye (per metre), its falloff k (per metre, natural log),
the same for the second layer (0, 0 without one)]. The density along a ray is d0 x exp(-k x (y - h)).
packages/levels/src/height-fog-material.ts:87
heightRaster function
function heightRaster(positions: ArrayLike<number>, rect: [number, number, number, number], w: number, h: number): Float32ArraySpread vertices (x, y, z; z is the plane's second axis) over a w x h raster of the rectangle: the height of the nearest vertex per texel, holes filled.
packages/levels/src/landscape.ts:243
importFromBytes function
async function importFromBytes(bytes: Uint8Array): Promise<LibraryModule>The default import: the checked bytes as a module behind a blob URL (so what runs is exactly what was checked).
packages/levels/src/code.ts:223
indexGlb function
function indexGlb(bytes: ArrayBuffer | Uint8Array): GlbIndexread the JSON chunk of a .glb (or the bytes of a .gltf)
packages/levels/src/material-look.ts:114
installCatalogCommands function
function installCatalogCommands(world: import('@ferret/core').World, levels: LevelService, client: CatalogClient): voidThe catalog commands: the viewer and an agent open a catalog, list its levels with their state on the device,
refresh it and travel into a level. catalog.levels {check: true} opens each level's package (a few ranged reads) to say whether
its core set is cached or missing and how many bytes a visit would download; without check the state is unknown.
packages/levels/src/catalog.ts:176
installCatalogs function
function installCatalogs(levels: LevelService, mount: PackageMount, store: AssetStore, defaults: CatalogOptions = {}): CatalogClientPlug catalog support into a LevelService: afterwards levels.registerCatalog(url) works.
packages/levels/src/catalog.ts:165
installCode function
function installCode(world: World, mount: PackageMount, o: CodeLoaderOptions = {}): CodeLoaderLet a mount run the code of its packages.
packages/levels/src/code.ts:230
installCodeCommands function
function installCodeCommands(world: World, code: CodeLoader): voidpkg.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): voidMake 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): voidpackages/levels/src/fmdl-motion.ts:492
installPackageCommands function
function installPackageCommands(world: World, mount: PackageMount, hooks: PackageCommandHooks = {}): voidThe 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): voidTeach a LevelService to load level packages: a folder with manifest.json, scene.glb and optionally navmesh.bin.
Problems with the wiring (a node the manifest names is missing, a behaviour is not registered) do not stop the level:
they are collected in the report so the game still runs and the artist sees what to fix.
packages/levels/src/package.ts:54
installPackages function
function installPackages(levels: LevelService, assets: MountAssets, o: MountOptions = {}): PackageMountSet 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): voidstream.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): StreamingDebugViewstream.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): voidThe travel.* commands: travel.preview {name, seconds?, bytes?, fail?, cached?} and travel.transitions.
packages/levels/src/transitions.ts:196
installUnrealFilm function
function installUnrealFilm(): voidMake Babylon's PBR and standard materials able to tone map with Unreal's film curve (toneMappingType = UNREAL_FILM_TONEMAPPING). Safe to call again.
packages/levels/src/unreal-film.ts:85
instanceMatrix function
function instanceMatrix(w: BABYLON.Matrix, t: BABYLON.Matrix): BABYLON.MatrixThe instance matrix for a mesh whose world matrix inside the model is w and an actor transform t: w * t * w^-1.
packages/levels/src/placements.ts:154
isHairFibreMaterial function
function isHairFibreMaterial(m: BABYLON.Material | null | undefined): booleanIs this glTF material a strand material?
packages/levels/src/hair-fibre.ts:51
isMirrored function
function isMirrored(a: Placement): booleanan actor whose scale turns space over (an odd number of negative axes): its faces wind the other way, so it is drawn by a mesh of its own with the culling turned round
packages/levels/src/placements.ts:124
isPlacementsFile function
function isPlacementsFile: (name: string) => booleana file name that holds a placement list (a streaming cell's file ending so is placed, not loaded as a glb)
packages/levels/src/placements.ts:29
isReliefDecal function
function isReliefDecal: (m: AbstractMesh) => booleanpackages/levels/src/decal-buffer.ts:15
ktx2Layout function
function ktx2Layout: (d: DecodedKtx2) => stringThe key two decoded files must share to be layers of one array: size, GL format, number of levels.
packages/levels/src/texture-array.ts:26
layerBlendGlsl function
function layerBlendGlsl(layers: LandscapeLayerDef[], pos: string, tex = 'texture', linear = 'toLinearSpace', up = '1.0', o: BlendGlslOptions = {}): stringThe layer blend as GLSL statements. Needs in scope: vec2 <pos> (metres in the landscape's coordinates), uniform vec4 ferretLsRect (minX, minZ, 1/sizeX, 1/sizeZ),
samplers ferretLsW<i>, ferretLsA<k>, ferretLsN<k>, ferretLsR<k>, ferretLsX<k>. Leaves vec3 lsColour (linear), with normal maps vec3 lsNormal (tangent space) and, when a layer says anything of its
roughness (image, scale or alpha), float lsRoughness set.
tex is the sampling function (texture in GLSL ES 3, texture2D in the procedural texture's shader), linear converts sRGB to linear.
up is a GLSL float expression: the up component of the ground normal, for the layers with a slope or a world.
packages/levels/src/landscape.ts:312
levelCost function
function levelCost(model: FmdlModel, level: number): { files: number; instances: number }How much a level of a placed model costs, from its plan: the files, and the instances drawn (a whole with its includes).
packages/levels/src/fmdl.ts:384
levelFilesFromFetch function
function levelFilesFromFetch(get: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any>; arrayBuffer?(): Promise<ArrayBuffer> }>, at: (path: string) => string): LevelFiles & { revoke(): void }LevelFiles over a fetch like the package loader's: at turns a level-relative path into the URL the fetch takes.
packages/levels/src/level-materials.ts:153
levelLibraries function
function levelLibraries(manifest: LevelManifest, providers: Iterable<Provider>): Record<string, string>Which libraries a level needs: those its manifest names, and every one of providers whose provides the level uses (a level key
with content, a capability it switches on, an actuator or rotor kind, a flow source). Id -> version range, sorted by id.
packages/levels/src/libraries.ts:42
levelMaterialRefs function
function levelMaterialRefs(def: MaterialDef): { ref: string; slot: string; colour: boolean }[]every texture reference of a definition: the maps and the pictures (masks), with the slot they are read for
packages/levels/src/level-materials.ts:88
levelTextureStem function
function levelTextureStem(ref: string): string | undefinedtex/<stem> (or tex/<stem>.ktx2, or the library form ferret://tex-<stem>/<stem>.ktx2) -> the stem; undefined for anything else
packages/levels/src/level-materials.ts:80
loadLandscapeTexture function
function loadLandscapeTexture(url: string, scene: BABYLON.Scene, o: { srgb: boolean; repeat: boolean }): Promise<BABYLON.BaseTexture>the default landscape texture: a Babylon Texture from a URL the browser can load (http, blob, data), resolved once loaded
packages/levels/src/landscape.ts:703
loadLandscapeTextureArray function
async function loadLandscapeTextureArray(urls: string[], scene: BABYLON.Scene, read?: (url: string) => Promise<Blob>): Promise<BABYLON.BaseTexture>The default texture array: the images drawn straight into the layers of one WebGL2 array texture (raw RGBA, no colour conversion, no premultiplication, rows as stored: v = 0 is the image's top row, as in Unreal), then the mip chain and repeat wrapping with anisotropic filtering. The images are decoded by the browser one at a time, so no more than one stands in memory beside the texture.
packages/levels/src/landscape.ts:717
lookCompositionGlsl function
function lookCompositionGlsl(s: LookStructure): stringBefore the final composition: the graph's emissive; the direct diffuse light gets back what Babylon's PBR took from it with the occlusion (Unreal's occlusion dims indirect light only).
packages/levels/src/material-models.ts:366
lookDefine function
function lookDefine: (s: LookStructure) => stringpackages/levels/src/material-models.ts:209
lookDepthGlsl function
function lookDepthGlsl(s: LookStructure): stringBefore the colour is written: the pixel's depth is pushed away from the camera by Ditcher_Effect centimetres times DitherTemporalAA.
packages/levels/src/material-models.ts:393
lookFadeGlsl function
function lookFadeGlsl(s: LookStructure): stringAfter the albedo block: the opacity fades along u or v, by a constant and by the depth of the scene behind the surface (Unreal's DepthFade: saturate((scene depth - pixel depth) / distance)).
packages/levels/src/material-models.ts:374
lookGlsl function
function lookGlsl(s: LookStructure): stringThe model as GLSL statements for the fragment shader's "before lights" point: needs surfaceAlbedo, normalW, vPositionW, vNormalW, the varying vFerretLkUv (first UV set)
and, with a ground blend, vFerretLkH (the object's height, metres). Leaves the colour in surfaceAlbedo, with a ground blend also the blended normal in normalW and
the weight in the global ferretLkW (the metallic, roughness and occlusion blends read it later, see lookReflectivityGlsl and lookReflectionGlsl).
packages/levels/src/material-models.ts:274
lookMasks function
function lookMasks(s: LookStructure): string[]the pictures of a structure in the order samplers are numbered
packages/levels/src/material-models.ts:193
lookPictures function
function lookPictures(look: LookDef): string[]every picture a definition reads, by the name it is looked up under (a name of masks or a texture reference itself)
packages/levels/src/material-models.ts:202
lookReflectionGlsl function
function lookReflectionGlsl(s: LookStructure): stringAfter the geometry's occlusion terms: the graph's, a pattern's over it by its mask, the ground takes it to 1 by its weight, the vertex colour's red channel multiplies it.
packages/levels/src/material-models.ts:352
lookReflectivityGlsl function
function lookReflectivityGlsl(s: LookStructure): stringIn the metallic / roughness step (a hook inside the reflectivity block): the graph's own, then the ground blend takes the metallic to 0 and the roughness to the ground's by its weight.
packages/levels/src/material-models.ts:343
lookStructure function
function lookStructure(look: LookDef): LookStructurepackages/levels/src/material-models.ts:167
lutElevation function
function lutElevation(i: number, n = LUT_SIZE): numberthe view elevation (radians above the horizon) of table entry i: dense near the horizon, where the sky changes fastest
packages/levels/src/atmosphere.ts:80
macroBlendAlphas function
function macroBlendAlphas(n: Vec3, b: MacroBlend = macroBlendOf({})): { yz: number; xy: number }WorldCoordinate3Way's two blend factors from the world normal given in this world's axes: yz is the share of the YZ projection over the XZ one
(Unreal's |nx|, our |x|), xy the share of the XY projection (the top one) over that mix (Unreal's |nz|, our |y|).
packages/levels/src/material-models.ts:73
macroBlendOf function
function macroBlendOf(m: Pick<MacroVariationDef, 'blend'>): MacroBlendThe blend inputs of a macro variation with the function's defaults filled in.
packages/levels/src/material-models.ts:64
macroMix function
function macroMix(xy: Vec3, yz: Vec3, xz: Vec3, n: Vec3, b?: MacroBlend): Vec3The three projected samples blended as WorldCoordinate3Way does: lerp(lerp(xz, yz, a.yz), xy, a.xy), per channel.
packages/levels/src/material-models.ts:78
maskSample function
function maskSample(texel: [number, number, number, number], channel: MaskChannel = 'rgb'): Vec3The mask sample of a channel choice: one channel repeated, or the three colour channels.
packages/levels/src/material-models.ts:105
miePhase function
function miePhase(c: number, g: number): numberpackages/levels/src/atmosphere.ts:83
mixLayer function
function mixLayer(colour: Vec3, color: Vec3, mask: Vec3, power = 1): Vec3mix(colour, layer.color, pow(mask, power)) per colour channel (mask is the picture's sample: one value repeated, or its three channels for rgb).
packages/levels/src/material-models.ts:100
modelClips function
async function modelClips(resolved: ResolvedModel, read: (qualified: string) => Promise<Uint8Array>, sets?: string[]): Promise<ClipJson[]>The skeletal clips the files of a model hold (clips: { set: path }, SPEC 3), set by set in the order of the model. A set file is one ClipJson or a list of
them; a clip's name is its own in the whole model. sets limits the reading to some sets.
packages/levels/src/fmdl-motion.ts:266
movingNodes function
function movingNodes(world: World, scene: BABYLON.Scene, o: FreezeOptions): Set<BABYLON.Node>the nodes that move: entity nodes, sequence targets, the listed ones
packages/levels/src/static-freeze.ts:26
parseLevelTextures function
function parseLevelTextures(json: unknown): LevelTextureCatalogueRead a texture catalogue: { textures: { stem: entry } }, { textures: [entry, ...] } or a bare list/object of entries; an entry's files is an object by codec or a list of file names.
packages/levels/src/level-materials.ts:48
patchImageProcessing function
function patchImageProcessing(code: string): stringcode is Babylon's imageProcessingFunctions chunk; the same text with Unreal's film curve in the place of the PBR Neutral one (unchanged when already done or the chunk differs)
packages/levels/src/unreal-film.ts:78
pickCodecFile function
function pickCodecFile(item: Pick<TextureItem, 'codec' | 'codecs'>, policy: TextureCodecPolicy = 'chosen', path = ''): stringThe file of a texture item under a codec policy; path (the file maps names) when the item has one codec or none.
packages/levels/src/library.ts:37
pickLevelTextureFile function
function pickLevelTextureFile(e: Pick<LevelTextureEntry, 'codec' | 'files'>, policy: LevelCodecPolicy = 'best'): string | undefinedThe file of a texture under the policy: the policy's codec where it exists, else the other (a texture made in one codec only is that one), else the chosen codec's, else any.
packages/levels/src/level-materials.ts:72
pickTier function
function pickTier<T>(have: Partial<Record<LibraryTier, T>>, want: LibraryTier = 'desktop'): { tier: LibraryTier; value: T } | nullThe first tier at or below want that the item has (a low-end device asks for low and gets low, never desktop).
packages/levels/src/library.ts:153
pixelDepthPush function
function pixelDepthPush(d: PixelDepthDef, x: number, y: number, noise: number): numberthe push of a pixel away from the camera, metres: Ditcher_Effect (cm) times the dither
packages/levels/src/material-models.ts:95
planCollisionChunks function
function planCollisionChunks(def: CollisionChunksDef, at: [number, number, number][], resident: ReadonlySet<number>): { load: number[]; drop: number[] }Which chunks to load and which to drop for the places in at (metres), given the ones resident. A chunk stays while it is within unloadRadius of any place; it comes when within loadRadius.
packages/levels/src/collision-chunks.ts:20
previewTransition function
async function previewTransition(world: World, registry: TransitionRegistry, name: string, o: PreviewOptions = {}): Promise<{ name: string; fellBack: string | null; updates: number; ended: 'ready' | 'failed' }>Run a registered transition against a fake travel, without travelling: the author sees it in the viewer and tests it in Playwright. Returns what the transition was told.
packages/levels/src/transitions.ts:163
projectionUvs function
function projectionUvs(p: Vec3, scale: number): [[number, number], [number, number], [number, number]]Where a macro picture is read for a world position (metres): the UVs of the XY, YZ and XZ projections of Unreal, scale in Unreal units.
packages/levels/src/material-models.ts:84
propellerBlur function
function propellerBlur(omega: number, dt: number, blades = 3, from = 0.25, to = 0.7): numberhow 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): numberpackages/levels/src/atmosphere.ts:82
refKind function
function refKind(ref: string): RefKindWhich 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 } = {}): voidready 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): voidfmdl.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): () => voidMake a landscape's baked ground findable by materials of the scene; returns the function that takes it away again.
packages/levels/src/landscape.ts:591
relativeTo function
function relativeTo(list: string, ref: string): stringa model ref without a scheme is a file of the list's own package, relative to the list (../meshes/a.glb); a package url is joined and normalised by the loader
packages/levels/src/placements.ts:70
releaseDepthRenderer function
function releaseDepthRenderer(scene: BABYLON.Scene, _dr: BABYLON.DepthRenderer)packages/levels/src/material-models.ts:445
resolveAtmosphere function
function resolveAtmosphere(a: AtmosphereDef = {}): ResolvedAtmospherepackages/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): V3Unreal's RotateAboutAxis: the offset (new minus old position) of pos turned by turns about the axis through pivot
packages/levels/src/foliage-wind.ts:83
sampleDistanceField function
function sampleDistanceField(f: DistanceFieldData, p: readonly [number, number, number] | number[]): numberthe distance at a world point (metres), filtered as the shader filters it
packages/levels/src/distance-field.ts:56
sampleKeys function
function sampleKeys(keys: Key<number | number[]>[], t: number, quat = false): number | number[]the value of a key track at time t: held before the first and after the last key
packages/levels/src/sequence.ts:68
samplerPlan function
function samplerPlan(layers: LandscapeLayerDef[], packed = false): SamplerPlanpackages/levels/src/landscape.ts:270
scopeKey function
function scopeKey: (s: LookScope) => "types" | "instances"packages/levels/src/material-look.ts:46
screenDecalsOf function
function screenDecalsOf(scene: BABYLON.Scene, create = false): ScreenDecals | undefinedThe scene's screen decals; with create, made if there is none, and every material is told to look for it.
packages/levels/src/screen-decals.ts:105
settleDrawing function
async function settleDrawing(scene: BABYLON.Scene, o: SettleOptions): Promise<SettleReport>packages/levels/src/level-ready.ts:36
shoreDistance function
function shoreDistance(outline: [number, number][], x: number, z: number): numbersigned 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]): V3SimpleGrassWind (Unreal cm, seconds): the offset of a vertex at p (the world position, cm)
packages/levels/src/foliage-wind.ts:72
skyRadiance function
function skyRadiance(t: AtmosphereTable, elevation: number, cosSun: number, sunScale = 1, sunColor: Vec3 = [1, 1, 1]): Vec3Radiance 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): numberUnreal's WorldAlignedBlend ("w/Vertex Normals") over the ground normal's up component (1 = flat, 0 = vertical): the dot with the world up is remapped to
0..1, times Blend Sharpness, plus Blend Bias minus half the sharpness, saturated = saturate(0.5 sharpness up + bias).
(The reference the GLSL of layerBlendGlsl repeats.)
packages/levels/src/landscape.ts:228
smoothTri function
function smoothTri: (x: number) => numberUnreal's three-component (3 - 2a) a^2 of a = |frac(x + 0.5) * 2 - 1|
packages/levels/src/foliage-wind.ts:69
spawnFromManifest function
function spawnFromManifest(s: ManifestSpawn): { id: string; position: [number, number, number]; yaw?: number }packages/levels/src/levels.ts:449
sunLightColour function
function sunLightColour(color: Vec3, transmittance: Vec3, amount: number): Vec3The sun light's colour after the atmosphere: the transmittance along the sun ray (scaled to a strongest channel of 1) mixed in by amount.
packages/levels/src/environment.ts:277
takesShadows function
function takesShadows(m: BABYLON.AbstractMesh): booleanThe materials that take a shadow map: the engine's PBR and standard materials (and a multi-material of them). A terrain's, a sea's or a sky's own shader does not.
packages/levels/src/sun-shadows.ts:97
tierPath function
function tierPath(pkg: { has(path: string): boolean }, tiers: Partial<Record<string, string>> | undefined, tier: string, path: string): stringThe path of a file as the parent's quality tier sees it: the tier's folder (docking.tiers) holds a file of the same path, or the root does.
packages/levels/src/dock.ts:211
treeSway function
function treeSway(p: V3, pivot: V3, time: number, intensity: number, windIntensity: number, dir: [number, number], heightInBox: number): V3MF_TreesWind's "wind offset" (Unreal cm): the tree turns about its pivot
packages/levels/src/foliage-wind.ts:101
unfreezeStatic function
function unfreezeStatic(scene: BABYLON.Scene, root?: string): numbergive 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): numberUnreal'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 = {}): numberSwap 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(): booleanBabylon's standard (linear) light falloff becomes Unreal's legacy curve in the PBR shader (GLSL and WGSL), for every material compiled after this call. Done once per page, before the pool's lights are made, so no material was compiled with the old one.
packages/levels/src/light-budget.ts:176
validateAmbientParticles function
function validateAmbientParticles(v: unknown, at = 'motes'): ManifestIssue[]packages/levels/src/ambient-particles.ts:32
validateAtmosphere function
function validateAtmosphere(a: unknown, at = 'environment.skyAtmosphere'): { path: string; message: string }[]packages/levels/src/atmosphere.ts:64
validateEnvironment function
function validateEnvironment(e: unknown, at = 'environment'): ManifestIssue[]packages/levels/src/environment.ts:97
validateFogVeil function
function validateFogVeil(x: unknown, at = 'environment.fog.volumetric'): { path: string; message: string }[]packages/levels/src/fog-veil.ts:15
validateFoliageWind function
function validateFoliageWind(v: unknown, at = 'foliageWind'): ManifestIssue[]packages/levels/src/foliage-wind.ts:39
validateLandscapes function
function validateLandscapes(l: unknown, at: string): { path: string; message: string }[]packages/levels/src/landscape.ts:146
validateLevelMaterials function
function validateLevelMaterials(x: unknown, at = 'materials', cat?: LevelTextureCatalogue): ManifestIssue[]packages/levels/src/level-materials.ts:119
validateLightBudget function
function validateLightBudget(d: unknown, at = 'environment.lights'): ManifestIssue[]packages/levels/src/light-budget.ts:82
validateLookDef function
function validateLookDef(d: unknown, p: string, bad: (path: string, message: string) => void): voidthe problems of one look (d is the object at path p)
packages/levels/src/material-look.ts:54
validateManifest function
function validateManifest(m: unknown): ManifestIssue[]Check a manifest against the schema. Returns the problems; an empty list means the manifest is usable.
packages/levels/src/manifest.ts:169
validateMaterialLooks function
function validateMaterialLooks(v: unknown, at = 'materialLooks'): ManifestIssue[]packages/levels/src/material-look.ts:79
validateMaterialScale function
function validateMaterialScale(v: unknown, at = 'materialScale'): ManifestIssue[]packages/levels/src/material-scale.ts:20
validatePackage function
async function validatePackage(pkg: FerretPackage, o: ValidateOptions = {}): Promise<PackageIssue[]>pkg.validate: the package's own checks (manifest, files, sha256, no code in kinds without code) and then every level: its
manifest against the schema, and that the scene, collision mesh and navmesh it names exist — in the package or, through
ferret://, in a declared dependency.
packages/levels/src/ferret.ts:202
validatePlacements function
function validatePlacements(x: unknown, at = 'placements'): ManifestIssue[]packages/levels/src/placements.ts:77
validateProbes function
function validateProbes(p: unknown, at = 'environment.probes'): { path: string; message: string }[]packages/levels/src/probe-volume.ts:30
validateRelevance function
function validateRelevance(r: unknown): ManifestIssue[]the relevance block: numbers that are positive and finite, modes keyed by name
packages/levels/src/manifest.ts:347
validateRoomReflection function
function validateRoomReflection(r: unknown, at = 'environment.roomReflection'): ManifestIssue[]packages/levels/src/room-reflection.ts:28
validateSequences function
function validateSequences(v: unknown, at = 'sequences'): ManifestIssue[]packages/levels/src/sequence.ts:39
validateSunShadows function
function validateSunShadows(x: unknown, at = 'environment.sun.shadows'): ManifestIssue[]packages/levels/src/sun-shadows.ts:33
validateSwarm function
function validateSwarm(v: unknown, at = 'swarms'): ManifestIssue[]packages/levels/src/swarm.ts:38
validateVisibility function
function validateVisibility(v: any): ManifestIssue[]packages/levels/src/visibility.ts:117
validateWater function
function validateWater(w: unknown, at: string): { path: string; message: string }[]packages/levels/src/water.ts:113
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): numberHeight 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 Actorname: string | |
id: string | the id of the model, or of the included model an instance was let go from |
root: Node | |
rig: PartRig | |
clips?: ClipPlayer | |
from?: string | the actor this one was let go from |
resolved?: ResolvedModel | the model it is of (its resolved form, its reader) |
read?: (qualified: string) => Promise<Uint8Array> |
packages/levels/src/fmdl-motion.ts:297
AmbientParticlesDef interface
interface AmbientParticlesDefMotes 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: number | particles 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?: number | metres: the emitter runs only within this distance of the camera (default 40) |
packages/levels/src/ambient-particles.ts:10
ApplyLandscapeOptions interface
interface ApplyLandscapeOptionsat: (file: string) => string | turn a file name of the def into a URL |
texture?: (url: string, scene: BABYLON.Scene, o: { srgb: boolean; repeat: boolean }) => BABYLON.BaseTexture | Promise<BABYLON.BaseTexture> | create a texture from a URL (default: a Babylon Texture, resolved once loaded); tests pass their own |
textureArray?: (urls: string[], scene: BABYLON.Scene) => BABYLON.BaseTexture | Promise<BABYLON.BaseTexture> | create one texture array from image URLs (layer i = url i; images of one size); default: loadLandscapeTextureArray. Used by a packed landscape |
scope?: BABYLON.AbstractMesh[] | the name pattern of the meshes of the virtual texture's props is searched among these (default: all meshes of the scene) |
packages/levels/src/landscape.ts:691
ApplyLookOptions interface
interface ApplyLookOptionsmasks: Record<string, BABYLON.BaseTexture> | the picture of each name of the material's masks, loaded as data (not sRGB), repeating |
srgb?: readonly string[] | the names of the pictures that are colour (sRGB) and must be decoded in the shader; default none: the pictures are data (a colour picture whose GPU format decodes itself is not listed either) |
packages/levels/src/material-models.ts:602
ApplyProgramOptions interface
interface ApplyProgramOptionstextures: BABYLON.BaseTexture[] | the pictures of the program's textures, by index |
srgb?: readonly number[] | indices of the pictures that are colour (sRGB) and must be decoded in the shader |
arrays?: readonly { texture: BABYLON.BaseTexture; members: readonly number[] }[] | Pictures read from texture arrays (a fragment shader has 16 texture units, a master may read more): texture is the array, members[k] the program's picture that is layer k
(texture-array.ts). The entry of textures at a member's index is not read (give the array itself); the others are bound as before. |
cutoff?: number | the alpha test's clip value for opacityMask (Unreal's OpacityMaskClipValue; default 0.3333) |
writeDecal?: boolean | a relief decal: the material writes its normal and opacity into the decal buffer instead of a colour (decal-buffer.ts) |
receiveDecals?: boolean | does the surface take the decals lying on it (default true; a decal or a translucent material does not) |
screenDecal?: { pass: { value: number } } | a projected decal (screen-decals.ts): the material draws its colour, roughness and metallic into the screen decal buffers; pass says which one is being drawn |
distanceField?: DistanceFieldTextures | the level's distance field, for the programs that read it (near) |
packages/levels/src/material-program.ts:272
AssetLibraryOptions interface
interface AssetLibraryOptionsstore: AssetStore | |
mount: PackageMount | |
assets?: RuntimeAssets | needed for characters |
tier?: LibraryTier | the package tier to open (default desktop); a tier a package does not have falls back to its plain file |
pins?: Record<string, string> | the versions of packages the game holds to, by package id (the exact dependencies of its package): what a reference without a version means for them |
texCodec?: TextureCodecPolicy | which codec of a KTX2 map kept in both (TextureItem.codecs): chosen (the one the encoder's check chose, default), best (UASTC when there is one: the parity tier), light (ETC1S when there is one) |
policy?: CatalogPolicy | the catalog policy (trusted keys, allowUnsigned) |
session?: () => string | null | undefined | the 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) => void | called with the root of every static model of the library when its file is in (its yaw set): a game's hook for what it does to each model, such as the culling of parts too small to see (PartCuller.add) |
code?: { origin?: boolean | ((pkg: FerretPackage) => boolean); trusted?: () => Iterable<string> | undefined; engine?: Record<string, unknown>; loader?: CodeLoader; importModule?: CodeLoaderOptions['importModule'] } | How the code of module items may run (module(id)). origin: the library is the game's own, so its code is the game's (default: the catalog is on the
page's own origin); otherwise a package must carry a valid signature, from trusted keys when given. engine: the engine's API the code reads its
@ferret/* imports from (default globalThis.Ferret, the shared engine of lib/ferret/ferret.js); a game that bundles the engine passes the packages
the modules need ({ ...terrain, ...waves }), and they are set as globalThis.Ferret when the page has none. loader: a code loader of the game's own. |
packages/levels/src/library.ts:44
AtmosphereDef interface
interface AtmosphereDefUnreal's SkyAtmosphere component. Every field is optional and defaults to the component's own default. Lengths km, coefficients per km.
groundRadius?: number | planet radius, km (6360) |
atmosphereHeight?: number | thickness of the air, km (60) |
rayleighScattering?: Vec3 | Rayleigh scattering per km (0.005802, 0.013558, 0.0331) |
rayleighScaleHeight?: number | Rayleigh scale height, km (8) |
mieScattering?: Vec3 | Mie scattering per km (0.003996 each) |
mieAbsorption?: Vec3 | Mie absorption per km (0.00444 each) |
mieScaleHeight?: number | Mie scale height, km (1.2) |
mieAnisotropy?: number | Mie anisotropy g, -1..1 (0.8) |
absorption?: Vec3 | ozone absorption per km at the middle of its layer (0.00065, 0.001881, 0.000085) |
groundAlbedo?: Vec3 | colour of the ground the air sits on (0.402 each) |
multiScatteringFactor?: number | how much of the single scattering comes back as multiple scattering (1) |
skyLuminanceFactor?: Vec3 | colour factor on the sky's luminance (1 each) |
observerAltitude?: number | how far the observer is above the ground, km (0) |
packages/levels/src/atmosphere.ts:18
AtmosphereTable interface
interface AtmosphereTablen: 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: Vec3 | share 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: Vec3 | colour 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 AttachOptionssocket?: string | a socket of the body's item (grip_r, axe_r...) |
bone?: string | a 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?: boolean | also bind the clip sets of other skeletons that fit the part by bone names, and the other sets of its own skeleton (as for CharacterOptions): a rider's riding clips |
packages/levels/src/library.ts:102
BindOptions interface
interface BindOptionsmap?: Record<string, string> | graph clip name -> clip name in the clip sets (default: every clip under its own name) |
oneShot?: string[] | graph clip names that do not loop |
positionBones?: string[] | the only bones whose translations the clips set, each scaled by the body's rest offset over the clip skeleton's (retargetGroup's positionBones): a body of its own
proportions on the clips' skeleton keeps its bone lengths (['pelvis']: the hips move as the clip moves them, at this body's height). Default: every bone's translation is taken |
packages/levels/src/library.ts:122
BlendGlslOptions interface
interface BlendGlslOptionsdepth?: string | GLSL float: the pixel's camera depth in metres, for the near/far blends (default 0: the near pictures) |
pos3?: string | GLSL vec3: the position in the landscape's own coordinates (x, height, z), for the world aligned layers (default: height 0) |
normal?: string | GLSL vec3: the ground normal in the same axes, for the projections of the world aligned layers (default: up) |
packed?: boolean | the landscape keeps its pictures in texture arrays (LandscapeDef.packed): normals and occlusion come from them |
packages/levels/src/landscape.ts:294
BudgetLight interface
interface BudgetLightA 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?: string | a name for events and tests (the source actor's) |
group?: string | a group of lamps of one kind ('torch', 'candle'), for statistics and the sound budget |
position: Vec3 | the level's metres |
color: Vec3 | linear colour 0..1 |
intensity: number | Babylon intensity at 1 m (already converted from the source engine's units, see tools/ue-export/lights.mjs) |
range: number | the metres where the light reaches zero (the source engine's attenuation radius) |
kind?: 'point' | 'spot' | |
direction?: Vec3 | a spot's axis (the way the light travels) and full cone angle in radians |
angle?: number | |
innerAngle?: number | a 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?: number | nearer than a light of priority 1 by this factor when ranking (a chandelier over a candle); default 1 |
size?: number | the size of the glow dot in metres (default from the range) |
sound?: string | a 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 CatalogPolicytier?: string | device tier: packages with a tiers[tier] file use it |
prefix?: string | put in front of every level id of this catalog (two catalogs may share ids) |
decorate?: (def: LevelDef, entry: CatalogLevel) => LevelDef | void | What the game adds to a level the catalog lists: its build step, its default spawn, its own name. Called with the def the catalog made (prepare, plan and fetch
are set) and the catalog's entry; the returned def (or the same one changed in place) is registered. Runs again for every level when a refresh brings a new version. |
packages/levels/src/catalog.ts:21
CatalogRegistration interface
interface CatalogRegistrationreadonly url: string | |
readonly catalog: Catalog | |
readonly stale: boolean | the catalog came from the copy kept by an earlier session (no network) |
readonly unsigned: boolean | development only: the catalog was not signed |
readonly levels: string[] | ids registered in the LevelService |
refresh(): Promise<{ changed: boolean; stale: boolean }> | Ask the server again. changed when a new version replaced the registered levels; a failure leaves everything as it was. |
packages/levels/src/catalog.ts:33
CellSource interface
interface CellSourceWhat 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?: boolean | also bind the clip sets of other skeletons that list this body's skeleton as compatible, and the other sets of its own skeleton (as <set id>/<clip>) |
tier?: LibraryTier | |
yaw?: number |
packages/levels/src/library.ts:90
ClipRef interface
interface ClipRefA 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?: string | set for a clip set that only fits by bone names (compatible): its clips are bound as <prefix><clip>, so they never replace the body's own |
packages/levels/src/library.ts:84
CodeLoaderOptions interface
interface CodeLoaderOptionsorigin?: (pkg: FerretPackage) => boolean | does 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> | undefined | key ids whose signatures are trusted; without them any valid signature is enough |
ferret?: unknown | the engine's API handed to the code (default globalThis.Ferret, the shared engine) |
esm?: boolean | the 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) => void | add to the context handed to a package's install (the player adds game, levels, root, args, tier) |
open?: (id: string, range: string) => Promise<FerretPackage | null> | a package that is not open yet (a dependency, a require by id): open it, e.g. through the catalog; null when there is none |
sharedEngine?: () => Iterable<string> | the parent ships its engine inside its own bundle (shareEngine, ./dock-engine): a docked level's @ferret/* imports are rewritten to read it; the function names the packages it holds |
onLoaded?: (id: string, exports: LibraryModule | null) => void | a library package's code was loaded (its install ran): a parent that ships its engine in its bundle publishes an engine package it loaded from its library (engine-<name>) here |
importModule?: (bytes: Uint8Array, path: string, pkg: FerretPackage) => Promise<LibraryModule> | import the module from its checked bytes (default: a blob URL and import(); tests use a data URL) |
packages/levels/src/code.ts:49
CollisionChunkDef interface
interface CollisionChunkDeffile: string | |
bounds: [number, number, number, number, number, number] |
packages/levels/src/collision-chunks.ts:10
CollisionChunksDef interface
interface CollisionChunksDefloadRadius: number | |
unloadRadius: number | |
chunks: CollisionChunkDef[] |
packages/levels/src/collision-chunks.ts:11
CompiledProgram interface
interface CompiledProgramtypes: ProgramType[] | the components of every node |
uses: ProgramUses | |
code: string | the statements before the normal, the normal's, and the rest, for the fragment shader's "before lights" point |
define: string | names the structure: equal for two programs that differ only in parameter values and texture files |
packages/levels/src/material-program.ts:20
DecodedKtx2 interface
interface DecodedKtx2One KTX2 file, transcoded for this GPU: the levels from the largest down, in the GL format format (a compressed one, or RGBA8 / R8 / RG8).
width: number | |
height: number | |
format: number | |
levels: { width: number; height: number; data: Uint8Array }[] |
packages/levels/src/texture-array.ts:9
DependencyOptions interface
interface DependencyOptionsstore: AssetStore | the 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?: string | the device tier: a catalog package with a file for this tier uses it |
policy?: (catalogUrl: string) => CatalogPolicy | how 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 DependencyTargetSomething that can hold open packages: a PackageMount (add registers its levels too) or a plain PackageSet.
get(id: string): FerretPackage | undefined | |
add(pkg: FerretPackage): unknown |
packages/levels/src/dependencies.ts:27
DistanceBlend interface
interface DistanceBlendUnreal's Distance_Blend in metres: alpha = saturate((camera depth + offset) / range); 0 = the near picture, 1 = the far picture
offset: number | |
range: number |
packages/levels/src/landscape.ts:67
DistanceFieldData interface
interface DistanceFieldDataheader: DistanceFieldHeader | |
bytes: Uint8Array |
packages/levels/src/distance-field.ts:32
DistanceFieldHeader interface
interface DistanceFieldHeaderformat: 'ferret-distance-field/1' | |
voxel: number | the spacing of the samples, metres |
range: number | the distance a byte reaches, metres, either way |
brick: number | cells along a side of a brick |
origin: [number, number, number] | the world place of sample 0 of brick (0, 0, 0), metres |
grid: [number, number, number] | bricks of the table along x, y, z |
atlas: [number, number, number] | bricks of the atlas along x, y, z |
gradientScale: number | |
data: string | the data file, beside this one |
packages/levels/src/distance-field.ts:13
DockBackend interface
interface DockBackenda 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 DockBridgeLikedefine(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => unknown): unknown |
packages/levels/src/fmdl-docks.ts:274
DockContext interface
interface DockContextWhat a docked level's install is given: the game's context as an example's code knows it (game, levels, root, args, tier) with the views of a dock.
game: DockParent['game'] | the parent's game seen through the scope: its world, scene and input record what the code adds |
world: World | |
levels: LevelService | |
root: HTMLElement | the level's own element in the parent's UI (its docking.ui fragment is inserted here); removed with the level |
args: URLSearchParams | |
tier: DockParent['tier'] | |
restart(): void | start the level over: the same level is entered again under a travel (a standalone game reloads its page) |
mount: PackageMount | |
url(path: string): Promise<string> | a blob URL for a file of the level's package |
scope: Scope | the level's scope: everything registered through it, and through game and world, is taken back at the end |
parent: DockParent | the parent as it is, outside the scope (for a completion layer that must reach it) |
roles: Roles | |
level: LevelDef | |
pkg: { id: string; version: string; manifest: FerretPackage['manifest'] } | |
docking: DockingBlock | |
build: LevelContext | the level's build context: addSpawn is the way to declare where the player stands |
ferret: unknown | the engine's API as the code loader holds it (undefined for code that imports @ferret/* itself) |
packages/levels/src/dock.ts:28
DockedLevel interface
interface DockedLevelWhat a docked level's install may return: the end of the level, and ready when the level goes on loading after install (the travel waits for it, with the world running).
dispose?(): void | Promise<void> | |
ready?: Promise<unknown> |
packages/levels/src/dock.ts:57
DockedPair interface
interface DockedPaira: string | |
b: string | |
joint: DockJoint | |
info?: Record<string, unknown> |
packages/levels/src/fmdl-docks.ts:58
DockHostOptions interface
interface DockHostOptionsloader: CodeLoader | |
mount: PackageMount | |
parent: DockParent | |
levels: LevelService | |
onEnter?(ctx: DockContext): void | (() => void) | called with the context just before install and after the roles are docked (the parent parks its hero, hides its own HUD ...); returns what it does at the end |
packages/levels/src/dock.ts:59
DockInfo interface
interface DockInforef: string | |
actor: string | |
dock: string | |
description: string | |
position: Vec3 | world position and rotation of the dock's frame |
rotation: Quat | |
heldBy: string | null | the ref of the dock holding this one, or null when it is free |
packages/levels/src/fmdl-docks.ts:48
DockJoint interface
interface DockJointkind: 'fixed' | 'hinge' | 'ball' | 'bond' | |
axis?: Vec3 | |
limits?: [number, number] | |
breakForce?: number |
packages/levels/src/fmdl-docks.ts:27
DockOptions interface
interface DockOptionsjoint?: DockJoint | |
place?: boolean |
packages/levels/src/fmdl-docks.ts:28
DockParent interface
interface DockParentDocked travel: a level of kind levels with a docking block and code, entered from a parent game. The parent's door starts an ordinary travel; the
level's build step (DockHost.enter) runs the code's install(DockContext) under the transition, and the engine's unload of the level ends it: dispose, then the scope
(everything the code registered is taken back), the level's UI, the roles. The same engine runs both: the code is handed scoped views of the parent's game (scopedGame), so
what it adds is recorded and what the parent holds (the input, the player's character) answers for the roles the level does not bring itself.
game: { world: World; scene: BABYLON.Scene; input?: any; display?: { trackCamera?(cam: BABYLON.Camera): void } } | the parent's game: { world, scene, input, display, ... } |
root: HTMLElement | the element the parent's UI lives in; a level's own UI fragment goes in a child of it |
args: URLSearchParams | |
tier: 'desktop' | 'mobile' | 'low' | |
engineModule?(name: string): string | undefined | a URL of an engine package a worker of a level may import (@ferret/<name>); a parent that ships its engine inside its bundle has none, and a worker then must carry what it uses |
camera?(): BABYLON.Camera | undefined | the parent's own view, made current again when a level goes; without it the camera that was current when the level came, if it still exists |
packages/levels/src/dock.ts:14
DockPhysics interface
interface DockPhysicswhat 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): void | put a body where its node was placed (the docked actor was moved to the dock) |
onBreak(cb: (c: any) => void): () => void | called when a constraint breaks; returns the unsubscribe |
packages/levels/src/fmdl-docks.ts:31
DocksOptions interface
interface DocksOptionsphysics?: DockPhysics | |
backends?: DockBackend[] | |
emit?: (name: string, payload: unknown) => void |
packages/levels/src/fmdl-docks.ts:61
Environment interface
interface Environmentpost?: BABYLON.DefaultRenderingPipeline | |
sun?: BABYLON.DirectionalLight | |
shadows?: SunShadows | the sun's shadows, when the definition asks for them: add(meshes) lets meshes cast and receive |
ambient?: BABYLON.HemisphericLight | |
veil?: FogVeil | the volumetric fog's veil (fog.volumetric); shaders of their own read fogVeilOf(scene) |
heightFog?: HeightFogMaterials | the height fog integrated along each ray (fog.alongRay); values are the shader's numbers at the camera (heightFogShaderValues) |
sky?: BABYLON.Mesh | |
particles: BABYLON.ParticleSystem[] | |
water: WaterSurfaceView[] | |
lights?: LightBudget | |
warnings: string[] | effects that could not be made (an unknown kind) |
dispose(): void |
packages/levels/src/environment.ts:149
EnvironmentDef interface
interface EnvironmentDefThe look of a level beyond its meshes: sun, ambient light, fog, sky and fixed effects. It is the manifest's environment;
tools/ue-export writes it from an Unreal level (sun, sky light, height fog, particle emitters). Every part is optional.
sun?: { direction: Vec3; color?: Vec3; intensity?: number; /** 0..1: how much of the atmosphere's reddening of the sun ray (its transmittance at the sun's elevation, scaled so the strongest channel stays 1) tints the light on the ground, as Unreal's atmosphere sun light does; needs `skyAtmosphere`; default 0 */ atmosphereTint?: number; /** cascaded shadow maps of the sun (see sun-shadows.ts); the level loader lets the placed groups and the scene's meshes cast and receive them */ shadows?: SunShadowsDef } | the directional light; direction is where the light travels. intensity is in the source engine's units (Unreal lux-like): 4 is about 1 here |
ambient?: { color?: Vec3; intensity?: number; direction?: Vec3; ground?: Vec3 } | ambient light from the sky: a hemispheric light, a bit darker below. direction is the way its bright side faces (default up: floors are lit most);
ground is the colour of the dark side (default color x 0.45). An interior lit from its ceiling faces it down: [0, -1, 0]. |
fog?: { density?: number; color?: Vec3; heightFalloff?: number; height?: number; maxOpacity?: number; start?: number; cutoff?: number; second?: { density: number; heightFalloff: number; heightOffset?: number }; /** with `heightFalloff`: integrate the fog along each ray from the eye, as Unreal does (height-fog-material.ts), instead of the camera's density for every distance; far peaks keep their shade */ alongRay?: boolean; /** with `alongRay`: Unreal's factor exactly: the transmittance is 2^-(the integral of the density), not e^-, and never below 1 - `maxOpacity` */ unreal?: boolean; /** Unreal's volumetric fog: a veil of the height fog's density times `extinctionScale` over the first `distance` metres (see fog-veil.ts) */ volumetric?: FogVeilDef } | exponential fog; density in the source engine's units (per metre, about 10 times smaller here). With heightFalloff it is Unreal's
ExponentialHeightFog: the density halves every 1 / (falloff x 0.1) metres above height (the fog actor's height, metres) and grows below it; the
view's density follows the camera's height every frame. second is the component's second fog layer. Not done: maxOpacity, start and cutoff
(Babylon's exponential fog has no such terms; they are carried in the manifest for a tool that wants them). |
skyAtmosphere?: AtmosphereDef | Unreal's SkyAtmosphere: the sky dome is the scattering of the sun's light in the planet's air (see atmosphere.ts) instead of the colour gradient.
{} is the component's defaults. The sun gives the direction and colour; top / horizon / ground of sky still override the colours the water,
the reflection and the fog take from it. The level's BP_Sky_Sphere actor adds nothing: the engine's sky sphere only recolours itself when a level
asks it to, and the dome replaces it (postprocess drops the actor). |
sky?: { top?: Vec3; horizon?: Vec3; ground?: Vec3 } | the sky dome: a gradient from horizon to top with the sun's glow; colours default from the fog colour |
reflection?: { intensity?: number; top?: Vec3; horizon?: Vec3; ground?: Vec3; sky?: boolean; size?: number } | what metal and gloss reflect: a small cube map filled with a gradient (top / horizon / ground of its own, else the sky's), as the scene's
environment texture. Without it a metal surface has nothing to reflect and draws near black (an interior has no sky for it). intensity scales both
the reflection and the light the map adds to every surface (default 1; interiors want 0.3-0.6).
With sky the map is the sky dome itself, drawn once into a cube of size pixels (default 128) when the dome's shader is ready: the gloss of wet ground and the
metal of a hall reflect the clouds, the horizon's glow and the sun as the sky shows them. It only reflects: the light surfaces take from the sky stays the ambient's. |
post?: { bloom?: number; threshold?: number } | post-processing of the picture: bloom is the source engine's bloom intensity (Unreal's post process volume: 0.675 default, a glowing interior
3-4); bright parts (lamps, windows) glow around. A tier for weak GPUs leaves it out. threshold is the brightness that starts to glow (default 0.95). |
probes?: ProbeVolumeDef | baked global illumination (tools/ue-export/bake-gi): when present it lights every surface instead of the flat ambient light |
roomReflection?: RoomReflectionDef | an interior's reflections: the room drawn once into a cube map after loading (see room-reflection.ts); glass, glaze, metal and polished floors reflect it |
effects?: { name?: string; kind?: 'fire'; template?: string; position: Vec3; scale?: number; /** an effect of the vfx catalogue (`fire.torch`, `fire.candle`, `fire.hearth` ...): drawn by the world's vfx service when it has one (else the simple fire); still near the camera only */ vfx?: string; params?: Record<string, number> }[] | fixed effects placed in the level |
motes?: AmbientParticlesDef[] | motes in boxes of air (dust, pollen), see ambient-particles.ts |
effectsRadius?: number | metres: 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?: FoliageWindDef | wind in the foliage, bending grass, swaying trees and cloth, as Unreal's materials do it (see foliage-wind.ts) |
lights?: LightBudgetDef | hundreds of lamps and flames under a budget: the nearest few are real lights, the rest glow (see light-budget.ts) |
packages/levels/src/environment.ts:24
EnvironmentVfx interface
interface EnvironmentVfxAn effect of the vfx catalogue placed by the environment: it is made out (no particles) and started and stopped as the camera comes near and goes.
start(): void | |
stop(): void | |
dispose(): void |
packages/levels/src/environment.ts:283
FmdlLoadOptions interface
interface FmdlLoadOptionstier?: ModelTier | the device tier: which levels are loaded (default desktop) |
texture?: (ref: string, srgb: boolean) => Promise<BABYLON.Texture> | a texture of the library by its ferret:// reference (default: the file of the dependency package, read through the resolved model's reader; a model's own maps are read from its packages) |
variant?: string | the 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 FocusA place the player (or a camera) is, with the way it faces: cells ahead are fetched first.
position: BABYLON.Vector3 | |
forward?: BABYLON.Vector3 |
packages/levels/src/streaming.ts:26
FogVeilDef interface
interface FogVeilDefextinctionScale: number | Unreal's VolumetricFogExtinctionScale: the veil's density is the height fog's density at the camera times this |
distance: number | Unreal's VolumetricFogDistance, metres: the veil's depth |
albedo?: [number, number, number] | Unreal's VolumetricFogAlbedo (linear, 0..1): the veil's colour is the fog's colour times this (default white) |
packages/levels/src/fog-veil.ts:6
FoliageFlowMap interface
interface FoliageFlowMapa local flow map the foliage reads on top of the wind (FlowMap of
readonly size: number | |
readonly cell: number | |
readonly originX: number | |
readonly originZ: number | |
readonly data: Float32Array | |
readonly active: boolean | |
readonly version: number | |
readonly lowHeight?: number | |
readonly highHeight?: number |
packages/levels/src/foliage-wind.ts:235
FoliageWindDef interface
interface FoliageWindDefwind: { intensity: number; direction: [number, number] } | Unreal's Wind_intensity and Wind_direction (X, Y) |
rules: FoliageWindRule[] | |
fromMaterials?: boolean | the library materials that carry a grassWind (their master's SimpleGrassWind inputs) flutter by it, with no rule of their own to write; rules may then be empty |
packages/levels/src/foliage-wind.ts:31
FoliageWindHandle interface
interface FoliageWindHandlereadonly materials: number | how many materials took a rule |
bendAt(p: { x: number; y: number; z: number } | null, radius?: number): void | the player's position in the engine's metres (grass bends away from it); null: nobody |
setWind(w: { intensity?: number; direction?: [number, number] }): void | change the wind at run time |
readonly current: { intensity: number; direction: [number, number] } | the wind now (the same object every call: do not keep it across a change) |
dispose(): void |
packages/levels/src/foliage-wind.ts:237
FoliageWindRule interface
interface FoliageWindRuleWind 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: string | a regular expression over the glTF material name |
flutter?: { influence: number; speed?: number; weight?: number; weightFromUV?: boolean; directional?: number; useVertexColor?: boolean; alphaWeight?: { multiplier: number; offset: number }; /** the influence is not scaled by the level's wind and the added offset is `push` centimetres on all three axes: a leaf master's own SimpleGrassWind (see `GrassWindDef` of @ferret/assets) */ absolute?: boolean; push?: number; /** the whole flutter is scaled by one channel (0 r .. 3 a) of a picture the material carries (`levelMaterial.grassWindWeight`), read at the vertex's first texture coordinates */ weightMap?: { channel: number } } | |
bend?: { distance: number; strength: number } | |
sway?: { intensity: number } | |
swing?: { droop: number; speed: number; vertexColorDistortion: number; uvTimeDistortion: number; angleAlongWind: number; againstWind: number; windMultiplier: number; flutterWeight: number; flutterSpeed: number } |
packages/levels/src/foliage-wind.ts:19
FormBridgeLike interface
interface FormBridgeLikedefine(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => unknown): unknown | |
lasting(name: string, sig: { args: string[]; min?: number; rest?: string; returns?: string }, fn: (ctx: any, ...args: any[]) => { done(): boolean; result?: unknown }): unknown |
packages/levels/src/fmdl-motion.ts:480
FreezeOptions interface
interface FreezeOptionsroot: string | the 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 | null | finds 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) => boolean | meshes under the root that a name test keeps live (a game's own rule) |
packages/levels/src/static-freeze.ts:10
GlbIndex interface
interface GlbIndexwhat the scene glb says about its names: which glTF mesh each node name draws, and how many meshes carry a name
nodeMesh: Map<string, string | null> | node name → glTF mesh name (null: nodes of that name draw meshes of different names) |
meshCount: Map<string, number> | glTF mesh name → how many glTF meshes carry it |
packages/levels/src/material-look.ts:106
GroundSource interface
interface GroundSourceThe baked ground (colour in rgb, ground height in a; and surface: normal and roughness) of a landscape with a virtual texture, over its rectangle, as materials that blend with the ground read it.
texture: BABYLON.BaseTexture | |
rect: [number, number, number, number] | |
toLandscape: () => BABYLON.Matrix | |
surface?: BABYLON.BaseTexture | the second baked picture: the ground normal's x and z in the landscape's frame (its y is rebuilt: sqrt(1 - x^2 - z^2)) in r and g, the ground roughness in b; absent when the ground has none |
packages/levels/src/landscape.ts:581
HairFibreOptions interface
interface HairFibreOptionsexposure?: number | Overall 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 HeightFogDefdensity: number | |
heightFalloff: number | |
height: number | height of the fog actor, metres |
second?: HeightFogLayer | |
exact?: boolean | the rays take Unreal's factor exactly (height-fog-material.ts): 2^-integral |
maxOpacity?: number | with exact: the most the fog may cover, 0..1 (default 1) |
packages/levels/src/height-fog.ts:10
HeightFogLayer interface
interface HeightFogLayerdensity: 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 LandscapeDefname: string | |
mesh?: string | regex 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?: boolean | the far backdrop: no collision, never picked, always drawn; layers and weights are optional for it |
virtualTexture?: VirtualTextureDef | |
packed?: boolean | Keep every picture of the landscape in two texture arrays (colour with roughness in alpha; normal with occlusion in alpha) instead of one sampler each: a material then needs the weightmaps, two array samplers and the macro picture, however many layers, far pictures and world aligned pictures there are. Pictures of one array share a size. |
packages/levels/src/landscape.ts:119
LandscapeFar interface
interface LandscapeFartile: number | |
albedo?: string | |
nao?: string |
packages/levels/src/landscape.ts:65
LandscapeLayerDef interface
interface LandscapeLayerDefname: string | |
albedo: string | colour image (sRGB); with heightBlend its alpha channel is the layer's height map. '' for a layer that has only a colour |
colour?: Vec3 | a constant colour (linear) instead of a picture: Unreal's far plane master blends vector parameters, not pictures |
normal?: string | optional tangent-space normal image |
nao?: string | a packed image of the near picture's normal map (rgb, as stored) and ambient occlusion (alpha), read at the layer's tiling; needs LandscapeDef.packed |
flatten?: number | Unreal's FlattenNormal on the layer's normal: the normal moves toward (0, 0, 1) by this fraction (negative: the relief is exaggerated); the layer function's Normal_Intensity |
roughness?: string | optional roughness image (data, its red channel), read at the layer's tiling: Unreal's layer function multiplies it by roughnessScale |
roughnessScale?: number | the layer's roughness multiplier (the function's scalar parameter); with no roughness image the layer's roughness is this number (default 1 when either is given) |
tile: number | metres of one repeat of the layer's textures (Unreal: 100 / the material's UV scale) |
tint?: Vec3 | multiplies the albedo (linear) |
heightBlend?: number | 0 = plain weight blend; above 0 = Unreal's height blend, the layer's height (albedo alpha) times this decides who wins where weights overlap |
slope?: LandscapeSlope | Unreal's slope-driven automatic layer (WorldAlignedBlend on the ground normal): see LandscapeSlope |
far?: LandscapeFar | the picture for far distances: another tile size (and image); tile 0 is the one texel at uv 0 (a layer whose far scale is 0). Mixed with the near picture by blend |
blend?: DistanceBlend | the camera-depth mix of the near and the far picture (Unreal's Distance_Blend); without it the near picture is always used |
roughnessAlpha?: boolean | the albedo image's alpha channel is the layer's roughness (data), packed so that the layer needs no sampler of its own for it |
saturation?: number | Unreal's Desaturation node: the colour moves toward its luminance by this fraction (negative: more saturated) |
power?: number | Unreal's Power node on the colour (the picture's colour, linear) |
hue?: number | Unreal's HueShift function: the colour plus the colour turned about the grey axis by this many revolutions (0 turns nothing, so the colour comes out doubled, as the graph's Add does) |
world?: LandscapeWorldAligned | a world aligned layer: its own picture is the one on steep faces, projected along the axes; see LandscapeWorldAligned |
packages/levels/src/landscape.ts:25
LandscapePicture interface
interface LandscapePictureone picture of a world aligned layer
albedo: string | colour image, or the same file as another layer's albedo (it then shares that layer's sampler) |
tile: number | |
far?: LandscapeFar | |
blend?: DistanceBlend | |
roughnessAlpha?: boolean | |
roughnessScale?: number | |
saturation?: number | |
power?: number | |
hue?: number | |
nao?: string | |
flatten?: number |
packages/levels/src/landscape.ts:70
LandscapeSlope interface
interface LandscapeSlopeThe 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.
packages/levels/src/landscape.ts:106
LandscapeTextures interface
interface LandscapeTexturesarrays?: { albedo: BABYLON.BaseTexture; nao?: BABYLON.BaseTexture } | |
weights: BABYLON.BaseTexture[] | |
albedo: (BABYLON.BaseTexture | undefined)[] | |
normal: (BABYLON.BaseTexture | undefined)[] | |
roughness?: (BABYLON.BaseTexture | undefined)[] | |
extra?: BABYLON.BaseTexture[] |
packages/levels/src/landscape.ts:464
LandscapeView interface
interface LandscapeViewdef: LandscapeDef | |
meshes: BABYLON.AbstractMesh[] | |
virtualTexture?: BABYLON.BaseTexture | the baked virtual texture (colour in rgb, ground height in a), when the landscape has one |
virtualSurface?: BABYLON.BaseTexture | its second picture: the ground normal (x, z in the landscape's frame) and the roughness (see GroundSource.surface) |
requiredMaxZ?: number | camera depth (maxZ) a far landscape needs to be seen whole: the rectangle's diagonal plus the camera's height over it, rounded up |
warnings: string[] | |
dispose(): void |
packages/levels/src/landscape.ts:678
LandscapeWorldAligned interface
interface LandscapeWorldAlignedUnreal's MF_Rock_Cliff: three world aligned pictures stacked by the slope of the ground. The layer's own picture is on steep faces; flat takes over where the up component of the
ground normal rises over flatRamp ([from, to]: 0 below from, 1 above to), top (grass) over topRamp. macro multiplies the colour by powers of a large scale variation picture
(Unreal's Micro_Variation inputs): the colour times prod(pow(texture(uv / tiles[k]).rgb, powers[k])); the picture is data, not colour.
flat: LandscapePicture | |
flatRamp: [number, number] | |
top?: LandscapePicture | |
topRamp?: [number, number] | |
macro?: { albedo: string; tiles: [number, number, number]; powers: [number, number, number] } |
packages/levels/src/landscape.ts:90
LevelContext interface
interface LevelContextWhat 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 }): void | declare where the player may start |
progress(p: number): void | report progress 0..1 to the loading screen |
packages/levels/src/levels.ts:11
LevelDef interface
interface LevelDefOne entry of the level registry (the equivalent of a row of UE's DT_LevelInfo).
id: string | |
name?: string | |
url?: string | a 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?: string | the spawn used when the level is entered without naming one (default: the first declared) |
data?: Record<string, unknown> | anything the game wants to keep with the level: music, weather, display name |
tags?: string[] | free tags (a theme, a chapter): handed to the game's choices, never read by the engine |
environment?: { skip?: EnvironmentPart[] } | parts of the level's environment the game draws itself (its own sky, its own water): the loader leaves them out; the rest is as the manifest says |
prepare?(progress: (p: number) => void, signal?: AbortSignal): Promise<void> | Get what the level needs ready before the old level is touched (a remote level opens its package here). If it throws the
travel fails and the player stays in the current level. progress takes 0..1 of this step. |
plan?(): Promise<LevelPlan> | What fetching the level will download, known after prepare: bytes and files not held yet, and whether everything is already on the device. |
fetch?(ctx: { signal: AbortSignal; progress(loaded: number, total: number, files: number): void; /** files read at once (default: the level's own choice; a background prefetch asks for 1) */ concurrency?: number }): Promise<void> | Step 4 of a travel: bring the core set of the level to the device. progress takes bytes. A failure or a cancel leaves the old level in place. |
packages/levels/src/levels.ts:22
LevelFiles interface
interface LevelFilesWhat the level materials read the package through (the package loader's own fetch, never the library).
json(path: string): Promise<any> | |
blobUrl(path: string): Promise<string> | a URL the engine can load the file from (a blob URL of the fetched bytes) |
packages/levels/src/level-materials.ts:146
LevelManifest interface
interface LevelManifestversion: number | |
name?: string | |
scene?: string | file 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?: string | a mesh of simple collision shapes (invisible, solid). When present, the visible meshes of the scene do not collide |
collisionChunks?: CollisionChunksDef | the 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?: string | the spawn used when the level is entered without naming one |
environment?: EnvironmentDef | sun, ambient light, fog, sky and fixed effects (see EnvironmentDef) |
materialLooks?: MaterialLooks | the look of the scene's glTF materials, by TYPE (a model: its uid, all instances) and by INSTANCE (one object: its uid, over the type's look), then by the glTF material name inside the model (see material-look.ts): colour, metallic, roughness, emissive, normal scale, alpha mode, maps; set live by the editor (edit.material.set) |
tags?: string[] | free tags and data for the game (a theme, a chapter, a mood): handed to the game's choices (LevelDef.tags / data), never read by the engine |
data?: Record<string, unknown> | |
placements?: string[] | placement lists (*.placements.json, see placements.ts) loaded with the core: library models placed with GPU instancing, material overrides per actor |
levelMaterials?: LevelMaterialsRef | the level's own materials (level-materials.ts): materials a file of definitions (ferret-materials/1) or them inline, textures the catalogue of the level's KTX2 files (a file or inline), codec the one policy that picks UASTC or ETC1S (best, light, chosen; default best). A mesh slot of a placed model takes the material of its name; no library is asked |
streaming?: StreamingBlock | streaming inside the level: scene is then the core (what is visible and solid at the spawn) and the rest arrives by cell |
visibility?: VisibilityBlock | precomputed visibility for a level of rooms: what is not in sight from the player's grid cell is not drawn (see VisibilityBlock) |
snapshot?: boolean | the 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?: RelevanceBlock | the level's own values for the relevance service: per camera mode the largest turn rate omega (rad/s) and the horizon (s), and the tuning; they win over what the engine reads from the camera |
packages/levels/src/manifest.ts:84
LevelMaterialOverride interface
interface LevelMaterialOverrideA material of the level (level-materials.ts) standing in for a material of the model, by the name it has in the level's definitions.
material: string |
packages/levels/src/placements.ts:39
LevelMaterialsFile interface
interface LevelMaterialsFileformat: typeof LEVEL_MATERIALS_FORMAT | |
materials: Record<string, MaterialDef> |
packages/levels/src/level-materials.ts:42
LevelMaterialsOptions interface
interface LevelMaterialsOptionspolicy?: LevelCodecPolicy | the file policy of two-codec textures (default best) |
warn?: (message: string) => void | |
makeTexture?: (path: string, o: { srgb: boolean; scene: BABYLON.Scene }) => BABYLON.BaseTexture | Promise<BABYLON.BaseTexture> | make a texture from a file of the level (default: a Babylon texture from the blob URL, resolved when loaded; tests pass their own) |
anisotropy?: number | the anisotropy of the textures (default 8, Unreal's default texture filter) |
programTextureBudget?: number | How many pictures a program (a master carried whole) may read one by one (default 8: a fragment shader has 16 texture units and Babylon's own lighting, shadows, reflection and
the level's decal buffer and distance field take some). A program with more has its pictures put into texture arrays by size and format (texture-array.ts): one unit per array.
Not used with makeTexture (a test's own pictures are not KTX2 files). |
readyTimeoutMs?: number | the longest ready() waits for the transcoding of textures already read (default 20000 ms; a texture still not decoded is a warning) |
video?: (mediaTexture: string, scene: BABYLON.Scene) => BABYLON.BaseTexture | undefined | Promise<BABYLON.BaseTexture | undefined> | the picture of a video material (an unlit master whose colour is a media texture): the level's assembly hands the video source; none given, the surface stays its base colour |
packages/levels/src/level-materials.ts:169
LevelMaterialsRef interface
interface LevelMaterialsRefWhere the level's own materials come from: file names (read through the loader) or definitions inline, the texture catalogue likewise, and the codec policy (default best).
materials?: string | Record<string, MaterialDef> | |
textures?: string | Record<string, unknown> | unknown[] | |
codec?: LevelCodecPolicy | |
distanceField?: string | the header of the level's distance field (distance-field.ts), for the materials that read it |
screenDecals?: string | the file of the level's projected decals (screen-decals.ts): { decals: ScreenDecalSpec[] }, each naming one of the level's materials |
packages/levels/src/placements.ts:41
LevelOptions interface
interface LevelOptionsMinimum time the loading screen stays up, so it does not flash (ms; 0 in tests).
minLoadingMs?: number | |
slowMs?: number | no new bytes for this long while the target downloads: travel:slow {slow: true} (default 5000) |
holdMs?: number | the 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?: boolean | true on devices with room: a failed travel rebuilds the old level and returns the player to the spot; false (console): to the hub |
transitionEnterMs?: number | how 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 LevelPlanbytes: number | |
files: number | |
cached: boolean |
packages/levels/src/levels.ts:51
LevelReport interface
interface LevelReportwarnings: string[] | things the manifest asked for that the level could not provide: missing nodes, unknown behaviours ... |
packages/levels/src/levels.ts:80
LevelTextureCatalogue interface
interface LevelTextureCataloguetextures: Map<string, LevelTextureEntry> |
packages/levels/src/level-materials.ts:40
LevelTextureEntry interface
interface LevelTextureEntrystem: string | |
srgb?: boolean | |
codec?: LevelCodec | |
files: Partial<Record<LevelCodec, string>> |
packages/levels/src/level-materials.ts:39
LibraryCard interface
interface LibraryCarda candidate as the AI that asks reads it
id: string | |
uid?: string | |
type: string | |
name: string | |
tags: string[] | |
rubric?: string | |
description?: string | |
preview?: string | |
size?: number | |
versions?: string[] |
packages/levels/src/library.ts:81
LibraryCharacter interface
interface LibraryCharacterreadonly id: string | |
readonly item: CharacterItem | |
readonly model: ModelHandle | |
readonly clips: ClipRef[] | the clip sets of the character, resolved from the catalog |
dispose(): void |
packages/levels/src/library.ts:113
LibraryContext interface
interface LibraryContextWhat install gets.
world: World | |
ferret: any | the 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): unknown | the exports of a declared dependency's code (already loaded before this one) |
packages/levels/src/code.ts:20
LibraryEntry interface
interface LibraryEntry extends CatalogAssetid: string | |
version?: string | the library version this entry was resolved to (the reference's, or 1.0.0); set by entry(), absent from list() |
versions?: string[] | every version of the asset (the server's numbers, oldest first); set by list() |
packages/levels/src/library.ts:71
LibraryFind interface
interface LibraryFinda request to the library service: keywords (English), narrowed by exact type, rubric (and everything beneath it) and tags
q?: string | |
type?: string | |
rubric?: string | |
tags?: string[] | |
limit?: number | |
offset?: number |
packages/levels/src/library.ts:79
LibraryModel interface
interface LibraryModelA static library model on its way (a tree, a rock): model is the handle, item its file (bounds, collision).
readonly id: string | |
readonly item: ModelItem | |
readonly model: ModelHandle | |
dispose(): void |
packages/levels/src/library.ts:100
LibraryModule interface
interface LibraryModuleWhat a package's code module exports. install may return { dispose } or a promise of it.
install?(ctx: LibraryContext): unknown | |
[name: string]: unknown |
packages/levels/src/code.ts:34
LibraryQuery interface
interface LibraryQuerytype?: LibraryItem['type'] | |
tags?: string[] | |
text?: string | |
rubric?: string |
packages/levels/src/library.ts:70
LibrarySound interface
interface LibrarySoundreadonly id: string | |
readonly name: string | |
readonly item: SoundItem | |
readonly format: 'wav' | 'mp3' |
packages/levels/src/library.ts:148
LightBudgetDef interface
interface LightBudgetDefbudget: number | how 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?: number | how 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?: number | seconds between two re-rankings (default 0.25) |
fade?: number | seconds a light takes to fade out of / into a real light (default 0.35) |
hysteresis?: number | a 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?: number | lights 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?: string | a 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?: boolean | every 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 LightBudgetOptionsname?: string | |
viewer?: () => Vec3 | undefined | where the viewer is, in the level's metres; default the active camera |
materials?: boolean | raise 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 LightBudgetStatsitems: number | |
budget: number | |
real: number | |
glowing: number | |
reranks: number | |
soundsOn: number |
packages/levels/src/light-budget.ts:155
LoadableModel interface
interface LoadableModelwhat load takes: a resolved model with the reader of its chain's files (FmdlModel.stageModel(), a ResolveResult)
resolved?: ResolvedModel | |
read?: (qualified: string) => Promise<Uint8Array> |
packages/levels/src/fmdl-code.ts:66
LoadedCode interface
interface LoadedCodeid: string | |
version: string | |
exports: LibraryModule | null | the module's exports; null for a package without code (only its dependencies were loaded) |
commands: string[] | commands and behaviours that appeared while install ran |
behaviours: string[] |
packages/levels/src/code.ts:39
LookDef interface
interface LookDefcolourLayers?: ColourLayersDef | |
macro?: MacroVariationDef[] | |
groundBlend?: GroundBlendDef | |
vertexMasks?: VertexMasksDef | |
aoOnIndirect?: boolean | |
pixelDepth?: PixelDepthDef | |
detailNormal?: DetailNormalDef | |
patternLayer?: PatternLayerDef | |
flatten?: number | Unreal's FlattenNormal of the material's own normal map: n' = normalize(vec3(n.xy * s, 1 - (1 - n.z) * s)); a level material's normalScale (not 1) |
opacityGradient?: OpacityGradientDef | |
depthFade?: DepthFadeDef | |
opacity?: number | |
graph?: GraphDef | |
srgb?: readonly string[] | names of the pictures of masks that are sRGB colour |
packages/levels/src/material-models.ts:145
LookStructure interface
interface LookStructureWhat the shader is built from: part of the define's name, so two materials of one structure share a program and two of different structure never do. Fields that are off are absent.
base: 'albedo' | 'colour' | 'graph' | 'none' | |
layers: { mask: string; channel: MaskChannel; uv?: true; invert?: true }[] | uv: its mask is read at a scale of its own; invert: the colour is painted where the mask is 0 |
macro: { mask: string }[] | |
ground: boolean | |
vc?: { ao: boolean; opacity: boolean } | vertex colours read as masks: the red channel as occlusion, the alpha as a factor of the opacity mask |
depth?: true | pixel depth offset |
flat?: true | the material's own normal is flattened exactly as Unreal's FlattenNormal (the tilt and the z term scaled) |
detail?: { map: string } | the detail normal's picture |
pattern?: { mask: string; channel: MaskChannel; normal?: string; occlusion?: string; occlusionChannel: 'r' | 'g' | 'b' | 'a' } | a pattern's normal and occlusion over the material's own by a mask |
fade?: { gradient?: { axis: 'u' | 'v'; invert: boolean }; opacity?: true; depth?: true } | the opacity: a gradient along u or v, a constant, the depth behind the surface |
gview?: true | the graph reads the pixel's depth: the view matrix is bound |
graph?: GraphDef | the master as an expression tree (which outputs it sets is read off the tree) |
srgb?: string[] | names of the pictures that are colour (sRGB), decoded in the shader |
aoIndirect?: true | the material's occlusion dims indirect light only |
packages/levels/src/material-models.ts:117
LookTarget interface
interface LookTargetan 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: number | meshes (placed actors count once each) it covers |
materials: string[] | the glTF material names found on them |
ambiguous?: string | why a write on it is refused (absent: it is one thing) |
packages/levels/src/material-look.ts:152
MacroBlend interface
interface MacroBlendexponentX: number | |
multX: number | |
exponentYZ: number | |
multYZ: number |
packages/levels/src/material-models.ts:61
ManifestEntity interface
interface ManifestEntityid: string | |
behaviour?: string | a 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?: string | the 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?: string | the id of a streaming bundle this entity depends on: it is created once the bundle is in, and a placeholder stands at its position until then. It may also be the id of a streaming cell: the entity wraps a node of that cell, is made whenever the cell is resident and destroyed when the cell is released (no placeholder) |
packages/levels/src/manifest.ts:16
ManifestIssue interface
interface ManifestIssuepath: string | |
message: string |
packages/levels/src/manifest.ts:163
ManifestSpawn interface
interface ManifestSpawnid: string | |
position: [number, number, number] | |
yaw?: number | |
human?: string |
packages/levels/src/manifest.ts:82
MaterialInfo interface
interface MaterialInfoname: string | |
meshes: number | |
look: boolean | |
baseColor: [number, number, number, number] | |
metallic: number | null | |
roughness: number | null | |
emissive: [number, number, number] | |
emissiveStrength: number | |
normalScale: number | null | |
alphaMode: 'opaque' | 'mask' | 'blend' | |
doubleSided: boolean | |
maps: Partial<Record<MaterialMapSlot, boolean>> |
packages/levels/src/material-look.ts:145
MaterialLookDef interface
interface MaterialLookDefbaseColor?: [number, number, number] | [number, number, number, number] | |
metallic?: number | |
roughness?: number | |
emissive?: [number, number, number] | |
emissiveStrength?: number | |
normalScale?: number | |
alpha?: { mode: 'opaque' | 'mask' | 'blend'; cutoff?: number } | |
doubleSided?: boolean | |
maps?: Partial<Record<MaterialMapSlot, string>> |
packages/levels/src/material-look.ts:30
MaterialLooks interface
interface MaterialLookspackages/levels/src/material-look.ts:43
MaterialLooksHandle interface
interface MaterialLooksHandleupdate(looks: MaterialLooks | undefined): void | replace 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 | null | the 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(): void | takes every look off and stops watching |
packages/levels/src/material-look.ts:164
MaterialLooksOptions interface
interface MaterialLooksOptionstextureUrl?: (ref: string) => Promise<string> | string | the 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) => void | a problem to report (a map that could not be read, an ambiguous address) |
glbIndex?: () => Promise<GlbIndex | null> | the names of the scene glb (for the type fallback by glTF mesh name); read only when a look or a listing needs it |
packages/levels/src/material-look.ts:136
MaterialOptions interface
interface MaterialOptionsvariant?: string | |
name?: string | |
scene?: BABYLON.Scene |
packages/levels/src/library.ts:132
MaterialOverride interface
interface MaterialOverrideA library material standing in for a material of the model.
library: string | |
variant?: string |
packages/levels/src/placements.ts:37
MaterialScaleDef interface
interface MaterialScaleDefRepair of baked materials that came out wrong from the Unreal export.
match is a regular expression over the glTF material name; then
- flat: [r, g, b] (0..255, sRGB) replaces the albedo picture by one colour (the picture's average over its painted texels, kept in the build config).
The exporter bakes some materials over the lightmap UVs, so the picture is an atlas of islands on a black background while the mesh reads it through
its first UV set: part of the surface lands on black. The surface turns matte (the bake's metal/roughness picture is the same wrong atlas); the normal map stays;
- flatLinear: [r, g, b] (0..1, LINEAR, as a material parameter of the original gives it) does the same with the colour as the shader takes it: flat divides
its sRGB numbers by 255 and hands them to the shader as they are, so it draws lighter than the picture it was read from (kept as it is for the levels built on it);
- albedo is a LINEAR multiplier of the albedo (the light the surface returns): 2 makes it twice as bright;
- noVertexColors: true stops the meshes of the material from tinting it with their vertex colours. Unreal's painted vertex colours are masks the
material blends with (moss, dirt), already baked into the picture, but glTF viewers multiply the albedo by them: violet and cyan blotches on the walls.
(An InstancedMesh draws with its source mesh's flag, so the source is the one switched.)
It covers the materials that exist now and every one a streamed cell adds later (they are handled once their picture or mesh is set, at most 300 frames later).
match: string | |
flat?: [number, number, number] | |
flatLinear?: [number, number, number] | |
albedo?: number | |
noVertexColors?: boolean |
packages/levels/src/material-scale.ts:18
ModelCodeGame interface
interface ModelCodeGamethe part of the game language's binding the code gives its functions to (installGame)
provide(functions: Record<string, (...args: any[]) => unknown>, declarations?: Array<{ name: string; kind: ModelFunctionKind; args?: ModelValueType[] | null; returns?: ModelValueType | null }>): () => void |
packages/levels/src/fmdl-code.ts:68
ModelCodeOptions interface
interface ModelCodeOptionsworld?: World | the world: its physics host runs the step hooks, and it gets the commands model.functions and model.call |
origin?: (pkg: string, manifest: PackageManifest) => boolean | does this package come from where the game does (shipped with it, its own site)? Then its code is the game's |
trusted?: () => Iterable<string> | undefined | key ids whose signatures are trusted; without them any valid signature is enough |
sharedEngine?: () => Iterable<string> | the parent ships its engine inside its bundle (shareEngine): the names of the packages it holds |
importModule?: (bytes: Uint8Array, path: string) => Promise<ModuleExports> | import a module from its checked bytes (default: a blob URL and import()) |
packages/levels/src/fmdl-code.ts:53
ModelDescribed interface
interface ModelDescribedid: string | |
abstract: boolean | |
lineage: string[] | |
description: ModelDescription | |
markdown: string |
packages/levels/src/fmdl-catalogue.ts:21
ModelFunctionInfo interface
interface ModelFunctionInfoname: string | |
kind: ModelFunctionKind | |
params: NonNullable<ModelFunction['params']> | |
returns?: ModelValueType | |
description: string | |
model: string |
packages/levels/src/fmdl-code.ts:71
ModelHandle interface
interface ModelHandleA model on its way. node is the placeholder until the model is in, then the model's root.
readonly ref: string | |
readonly state: ModelState | |
readonly node: BABYLON.TransformNode | null | |
readonly ready: Promise<{ root: BABYLON.TransformNode; dispose(): void } | null> | resolves with the instance, or null when it failed or was disposed (the reason is in error and the asset:failed event) |
readonly error?: StreamError | |
dispose(): void |
packages/levels/src/runtime.ts:37
ModelInstance interface
interface ModelInstanceWhat a function and a hook of a model's code get first: the instance it works on.
readonly name: string | the name of the actor on the stage |
readonly model: string | the id of its model, and of the chain it comes from (the root ancestor first) |
readonly lineage: string[] | |
readonly data: ModelJson | the merged model.json: the model's own data is in its physics and in its x- fields |
readonly actor: Actor | |
readonly root: Actor['root'] | |
readonly rig: PartRig | |
readonly stage: ModelStage | |
readonly world: World | undefined | |
readonly time: number | the stage's time, seconds of fixed steps |
readonly state: Record<string, any> | what this instance keeps between calls and steps |
call(fn: string, ...args: unknown[]): unknown | a function of this instance |
other(name: string): ModelInstance | undefined | another instance that has code |
read(path: string): Promise<Uint8Array> | a file of the model by the path data names it with |
packages/levels/src/fmdl-code.ts:27
ModelListing interface
interface ModelListingid: 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?: PlaceholderSpec | shown at once, replaced by the model (default: a small box); 'none' shows nothing until the model is in |
parent?: BABYLON.TransformNode | the node the model hangs from (an entity's node): the placeholder and then the model are its children |
position?: [number, number, number] | |
name?: string |
packages/levels/src/runtime.ts:25
ModelPlacement interface
interface ModelPlacement extends Omit<ModelOptions, 'pkg'>tier?: LibraryTier | |
yaw?: number |
packages/levels/src/library.ts:97
MountAssets interface
interface MountAssets extends PackageAssetsWhat 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 MountOptionspackages?: PackageSet | the 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 OcclusionOptionsOcclusion 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: string | the level root's name: only meshes named <root>/... get queries |
minRadius?: number | bounding sphere radius a mesh needs, metres (default 3) |
minIndices?: number | indices 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 OceanOptionsname?: string | |
radius?: number | how 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) => number | metres of water under (x, z), negative on land; omitted: deep everywhere |
far?: number | the 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?: number | rows of a depth texture baked per frame once it has to move (default 24) |
fog?: 'exp' | 'exp2' | the fog: 'exp' (density per metre) or 'exp2' |
packages/levels/src/ocean.ts:17
OceanWave interface
interface OceanWavewavelength: number | |
amplitude: number | |
steepness?: number | |
direction?: number |
packages/levels/src/ocean.ts:16
OpenedDependency interface
interface OpenedDependencyA dependency that was opened: which catalog it came from and the URL of the file that was read.
id: string | |
version: string | |
range: string | |
catalog: string | |
url: string | |
pkg: FerretPackage | |
libraryVersion?: string |
packages/levels/src/dependencies.ts:24
PackageAssets interface
interface PackageAssetsWhat the loader needs from @ferret/assets (an AssetCache fits).
load(url: string): Promise<void> | |
instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }> | |
release(url: string): void |
packages/levels/src/package.ts:27
PackageCommandHooks interface
interface PackageCommandHooksresolve?: (url: string) => PackageInput | Promise<PackageInput> | turn a url or name into something FerretPackage.open reads (default: the url itself) |
opened?: (pkg: FerretPackage, url: string) => void | told 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> | undefined | key ids the reader trusts (for \pkg.verify\ and the code check) |
packages/levels/src/commands.ts:8
PackageLoaderOptions interface
interface PackageLoaderOptionsassets: PackageAssets | |
fetch?: (url: string) => Promise<{ ok: boolean; status: number; json(): Promise<any>; arrayBuffer(): Promise<ArrayBuffer> }> | replace fetch (tests, a Platform file API) |
collisions?: boolean | make the level's meshes collide (default true) |
manifest?: (def: LevelDef) => LevelManifest | undefined | a manifest to use instead of the one in the package: the editor's draft (return undefined to load the file) |
streamingRadiusScale?: number | scale the streaming radii of every streamed level (a tier may ask for less) |
forceNavBuild?: (def: LevelDef) => boolean | build the NavMesh from navBuild even if navmesh.bin exists (the editor, after a rebuild) |
placements?: PlacementResolver | finds library models and materials by id for placement lists (*.placements.json; an AssetLibrary gives it: placementResolver()); lists that name only ferret:// files need none |
packages/levels/src/package.ts:33
Placement interface
interface Placementactor: string | |
model: string | a key of models |
position: Vec3 | |
rotation?: Quat | |
scale?: number | Vec3 | |
materials?: Record<string, MaterialOverride | LevelMaterialOverride> | |
node?: string | Draw this actor on its own, not as a thin instance: a node of this name (Actor>Component: a node Actor with a child Component, as an entity's node names it) that a behaviour can move (a door
that swings). Actor holds the actor's position and rotation, Component is the part that is turned (identity), and the model's meshes hang under it with the actor's scale; the cell that holds the list
is the needs of the entity. Without a > the single node holds position and rotation. |
packages/levels/src/placements.ts:46
PlacementBuildOptions interface
interface PlacementBuildOptionsscene: BABYLON.Scene | |
instantiate(url: string, name?: string): Promise<{ root: BABYLON.TransformNode; dispose(): void }> | make an instance of a loaded model file (an asset cache's instantiate) |
urls: Map<string, string> | the file reference of each model name of the placement list (resolved before; see PlacementSource.load) |
resolver?: PlacementResolver | |
materials?: Map<string, Promise<BABYLON.Material>> | library materials already made, by id#variant (shared by the cells of one level: a material is made once, the library owns it) |
levelMaterials?: LevelMaterials | the level's own materials: a mesh slot named like one of them takes it, and { material } overrides pick one by name |
warn?: PlacementWarnings | |
name?: string | the root of the new nodes is named so (default placements) |
packages/levels/src/placements.ts:170
PlacementFile interface
interface PlacementFileformat: typeof PLACEMENTS_FORMAT | |
models: Record<string, PlacementModel> | |
actors: Placement[] | |
levelMaterials?: LevelMaterialsRef |
packages/levels/src/placements.ts:59
PlacementGroup interface
interface PlacementGroupkey: string | |
model: string | |
mirrored?: boolean | |
materials?: Record<string, MaterialOverride | LevelMaterialOverride> | |
actors: Placement[] | |
node?: string |
packages/levels/src/placements.ts:133
PlacementInstance interface
interface PlacementInstanceroot: 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: number | instances drawn |
dispose(): void |
packages/levels/src/placements.ts:161
PlacementModel interface
interface PlacementModelA model by library item id, or by a file reference of a package.
library?: string | |
ref?: string | |
tier?: LibraryTier |
packages/levels/src/placements.ts:35
PlacementResolver interface
interface PlacementResolverWhat the placement needs to find models and materials of the library by id (an AssetLibrary gives it: placementResolver()).
modelRef(m: PlacementModel): Promise<string> | string | the ferret:// file of a library model (its tier chosen) |
material(o: MaterialOverride): Promise<BABYLON.Material> | a library material to put on the model's meshes |
packages/levels/src/placements.ts:62
PlacementWarnings interface
interface PlacementWarnings(message: string): void |
packages/levels/src/placements.ts:160
PrefetchOptions interface
interface PrefetchOptionssettleMs?: number | wait this long after a level is ready before the first background download (the level's own first seconds come first) |
margin?: number | safety factor on the estimate: start early enough to finish in eta * margin (default 1.5) |
assumedRate?: number | assumed 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 PreviewOptionsseconds?: number | how long the fake download lasts |
bytes?: number | |
files?: number | |
fail?: boolean | end with a failure instead of readiness (to see the game's failure screen) |
cached?: boolean | cached: plan says the wait is short |
signal?: AbortSignal |
packages/levels/src/transitions.ts:147
ProbeVolumeDef interface
interface ProbeVolumeDefBaked 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: string | the baked grid, relative to the package: probes.bin |
origin: [number, number, number] | the position of the first probe, metres |
spacing: number | metres between probes |
dims: [number, number, number] | probes along x, y, z |
gain?: number | scale of the baked light (default 1) |
fill?: number | how 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?: number | the share of the baked light that faces turned down (ceilings) get, 0..1 (default 1: all of it) |
specular?: number | the baked light mirrored by every surface, 0 and more (default 0: none; 1: as much as arrives). What Unreal's SkyLight and reflection captures give: the radiance the grid holds toward the reflection (the sky outdoors, the dim room indoors), blurred with the roughness, times the surface's F0 and the split sum's environment BRDF (Karis' fit), dimmed by the ambient occlusion as Unreal's specular occlusion does. Wet planks and stone seen at a low angle lose their saturation to it. |
packages/levels/src/probe-volume.ts:7
ProgramBridgeLike interface
interface ProgramBridgeLikelasting(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 ProgramHostrun(program: string, o: { target?: string; params: Record<string, Value> }): Program | start a program text with its parameters on a target (the runtime's: the actuators' cap.run) |
knows(name: string): boolean | is name a word of the language |
packages/levels/src/fmdl-programs.ts:24
ProgramUses interface
interface ProgramUsesWhat the shader of a program reads from the surface and the scene.
uv0: boolean | |
uv1: boolean | |
uv2: boolean | |
vertexColor: boolean | |
matrix: boolean | |
local: boolean | |
bounds: boolean | |
near: boolean | |
time: boolean | |
view: boolean | |
depth: boolean | |
screen: boolean | |
tangent: boolean |
packages/levels/src/material-program.ts:16
PropellerViewOptions interface
interface PropellerViewOptionsThe 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?: number | blades on the propeller (default 3) |
radius?: number | the disc's radius, m (default: read off the blades' bounds, else 1.6) |
blurFrom?: number | the 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 PropulsorBindOptionsfield: FlowField | |
actuator?: (name: string) => { force: V3; on: boolean } | undefined | the state of a named actuator: its force (N) and whether it is running; undefined when the physics does not run |
surface?: SurfaceQuery | |
scale?: number | the 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 RelevanceBlockmodes?: Record<string, { omega?: number; horizon?: number; floorOmega?: number }> | |
hold?: number | seconds a thing stays in a finer class before it may go to a coarser one |
gonePx?: number | below this many pixels a thing is not drawn at all |
packages/levels/src/manifest.ts:136
RiverDef interface
interface RiverDefpoints: 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: number | metres per second the surface moves downstream (the first point to the last) |
packages/levels/src/water.ts:80
RoomReflection interface
interface RoomReflectionreadonly 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(): void | draw the room again (after a change of light or furniture) |
dispose(): void |
packages/levels/src/room-reflection.ts:42
RoomReflectionDef interface
interface RoomReflectionDefWhat 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?: Vec3 | where 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?: number | side of a cube face in pixels (default 256: 6 x 256 x 256 half floats, about 3 MB with its mip levels) |
intensity?: number | scale 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 RunOptionsenterTimeoutMs?: number | |
log?: (event: string, detail: Record<string, unknown>) => void |
packages/levels/src/transitions.ts:85
RuntimeAssetsOptions interface
interface RuntimeAssetsOptionsstore: AssetStore | |
models: MountAssets | loads and instantiates glTF (an AssetCache, or mount.assets when packages are in use) |
mount?: PackageMount | needed for ferret:// references |
packages/levels/src/runtime.ts:47
SamplerPlan interface
interface SamplerPlanThe samplers beyond the layers' own albedo images: far images, the pictures of world aligned layers, the macro variation picture (a file a layer already has as its albedo shares that layer's sampler).
packed: the pictures are layers of two texture arrays instead (albedoArray, naoArray: their files in order); a sampler is then "#<index>" (colour) or "@<index>" (normal and occlusion), and only the macro picture is a sampler.
extras: { file: string; srgb: boolean }[] | |
sampler(file: string): string | |
albedoArray: string[] | |
naoArray: string[] | |
nao(file: string): string |
packages/levels/src/landscape.ts:269
ScreenDecalSpec interface
interface ScreenDecalSpecOne decal of a level, in the engine's frame (metres): the box's centre, its three unit axes (x is the projection's), and half extents along them.
material: string | the level material (a master carried whole, decal: true) the box projects |
position: [number, number, number] | |
axes: [[number, number, number], [number, number, number], [number, number, number]] | the decal's local x (the projection axis), y and z in the engine's frame |
half: [number, number, number] | half extents along the axes, m |
sortOrder?: number |
packages/levels/src/screen-decals.ts:21
SequenceDef interface
interface SequenceDefname: 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 SequenceTracktarget: string | { camera: true } | |
position?: Key<[number, number, number]>[] | |
positionAxes?: [boolean, boolean, boolean] | which of x, y, z the position keys animate (default all); the others keep the node's own value (Unreal: a transform track with only some channels keyed) |
scaleAxes?: [boolean, boolean, boolean] | the same for scale |
rotation?: Key<[number, number, number, number]>[] | |
scale?: Key<[number, number, number]>[] | |
fov?: Key<number>[] |
packages/levels/src/sequence.ts:17
SettleOptions interface
interface SettleOptionsmeshes: BABYLON.AbstractMesh[] | the meshes the level draws (the thin-instance groups of the placements and the level's own) |
materials?: LevelMaterials[] | the level's materials: their textures are awaited |
shadows?: BABYLON.ShadowGenerator[] | shadow generators whose depth programs are compiled too |
warn?: (message: string) => void | |
timeoutMs?: number | the longest the final readiness check polls (default 15000 ms) |
parallel?: number | how many programs compile at once (default 12: the driver compiles them in parallel, and a job mostly waits) |
packages/levels/src/level-ready.ts:11
SettleReport interface
interface SettleReportmeshes: number | |
programs: number | |
notReady: string[] | |
ms: number |
packages/levels/src/level-ready.ts:25
ShadowRoleOptions interface
interface ShadowRoleOptionscasts?: (m: BABYLON.AbstractMesh) => boolean | which of the meshes that take shadows also cast them; default: all of them. A game names its casters by what they are (a node's name, a parent, a material's name) |
includeDescendants?: boolean | casters keep their children out of the shadow generator's includeDescendants (default false: the mesh alone, as the group's other meshes are visited too) |
packages/levels/src/sun-shadows.ts:103
ShadowRoleResult interface
interface ShadowRoleResultcasters: number | |
receivers: number | |
skipped: number |
packages/levels/src/sun-shadows.ts:110
ShipWakeOptions interface
interface ShipWakeOptionsThe 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: number | how far astern the track runs, m (a destroyer: 2500; a submarine: 450) |
beam: number | the hull's beam, m |
speed: number | the ship's speed, m/s: the time a row of the track is behind the ship is its distance over this |
sternBack?: number | where the track starts behind the ship's reference point (its stern), m |
rows?: number | rows along the track (default 72) |
height?: number | the height over the water, m (default 1.8: above the waves of a fresh sea) |
packages/levels/src/wake.ts:8
ShoreDef interface
interface ShoreDefoutline: [number, number][] | |
width?: number | metres of foam inside the edge (default 1.5) |
packages/levels/src/water.ts:60
SlopeRamp interface
interface SlopeRampUnreal's WorldAlignedBlend parameters (Blend Sharpness, Blend Bias), as the material instance has them: slopeAlpha(up, ramp).
sharpness: number | |
bias: number |
packages/levels/src/landscape.ts:99
SnapshotOptions interface
interface SnapshotOptionsSnapshot 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?: number | frames drawn normally after a change before a new snapshot is recorded (default 20) |
mode?: 'standard' | 'fast' | 'standard' (default) or 'fast' |
auto?: boolean | when 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 SoundOptionsaudio: SoundSink | |
name?: string | the name to play it by (default the item id) |
format?: 'wav' | 'mp3' | the file to use; default by tier: the MP3 (smaller) on mobile and low, the WAV on desktop, whichever there is when only one is |
tier?: LibraryTier |
packages/levels/src/library.ts:140
SoundSink interface
interface SoundSinkWhat AssetLibrary.sound needs of the audio service (AudioService of @ferret/media is one): take the bytes of a file and define a sound over them.
addFile(key: string, data: Uint8Array): unknown | |
define(name: string, def: Record<string, unknown>): unknown | |
has(name: string): boolean |
packages/levels/src/library.ts:135
SpawnPoint interface
interface SpawnPointid: string | |
position: BABYLON.Vector3 | |
yaw: number | |
human?: string |
packages/levels/src/levels.ts:8
StageModel interface
interface StageModelwhat the stage can place by id: the loader's FmdlModel is one (stage.addModel), a test gives its own
id: string | |
resolved?: ResolvedModel | the resolved model and a reader of its files by qualified path: what its motions are found and read from (ModelPrograms) |
read?: (qualified: string) => Promise<Uint8Array> | |
make(level: number, name: string): { root: Node; plan: AssemblyPlan } | the nodes of a level, not parented, and the plan they were made from |
packages/levels/src/fmdl-motion.ts:289
StageOptions interface
interface StageOptionsscene?: BABYLON.Scene | |
emit?: (name: string, payload: unknown) => void | the events of the world (world.events.emit); none in a plain test |
packages/levels/src/fmdl-motion.ts:311
StageWatcher interface
interface StageWatcherWho is told of the models of a stage (the code of models).
appearing?(model: StageModel): void | a model is about to appear: throwing refuses it, and nothing is built |
appeared?(actor: Actor): void | an actor has appeared, placed; throwing takes it away again |
vanishing?(name: string): void | an actor is about to go (its nodes are still there) |
step?(dt: number): void | a fixed step of the stage |
packages/levels/src/fmdl-motion.ts:318
StreamCellDef interface
interface StreamCellDefOne 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?: boolean | always resident (the play area round the spawn): fetched first, part of the ready gate, never released and never evicted for memory |
layer?: string | a key of layers: the cell uses that layer's radii instead of the block's (foliage is wanted closer than houses) |
memory?: number | bytes the cell takes once resident (geometry plus decoded textures); counted against memoryBudget. Default: size |
lod?: string | a low-poly stand-in shown while the cell is farther than loadRadius but within lodRadius (a few percent of the cell's triangles, no textures worth the name) |
details?: StreamDetailDef[] | Lighter variants of the same cell (fewer triangles, smaller textures), nearest first: the cell is made of its file within fullRadius of the player and of the first
variant whose radius reaches it farther out (the last one up to loadRadius). A variant has the cell's mesh names for what it keeps but may leave small things out,
so an entity that needs the cell exists only while the full file is the resident one. |
packages/levels/src/manifest.ts:34
StreamDetailDef interface
interface StreamDetailDefOne lighter variant of a streamed cell (StreamCellDef.details): radius is the distance from the player up to which it is wanted (increasing along the list, at most loadRadius); size / memory are what it takes once resident.
file: string | |
radius: number | |
size?: number | |
memory?: number |
packages/levels/src/manifest.ts:51
StreamingBlock interface
interface StreamingBlockThe streaming block. A level without it loads whole, as before.
cell: number | the grid size in metres the cells were cut with (informational for tools) |
cells: Record<string, StreamCellDef> | |
loadRadius: number | metres from the player: cells inside are loaded (and are part of the ready gate at the spawn) |
unloadRadius: number | cells 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?: number | metres from the player within which a cell's lod stand-in is shown; at least loadRadius (default: unloadRadius) |
fullRadius?: number | metres 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?: number | metres 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?: number | bytes 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?: number | pacing 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?: boolean | reserved: low mips first, upgrade later; nothing acts on it yet |
packages/levels/src/manifest.ts:54
StreamingOptions interface
interface StreamingOptionsat(file: string): string | where 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?: number | scale both radii (a tier may ask for less) |
memoryBudget?: number | bytes of resident cells, over the block's memoryBudget (a tier or a device may ask for less) |
maxPerFrame?: number | most cells instantiated in one update |
budgetMs?: number | milliseconds of instantiation work per update; at least one cell is always added when something waits, so streaming cannot starve |
concurrency?: number | most cells fetched at once |
now?: () => number |
packages/levels/src/streaming.ts:28
SunShadows interface
interface SunShadowsreadonly generator: BABYLON.CascadedShadowGenerator | |
add(meshes: Iterable<BABYLON.AbstractMesh>): void | let these meshes (and their thin instances) cast and receive the sun's shadows |
dispose(): void |
packages/levels/src/sun-shadows.ts:49
SunShadowsDef interface
interface SunShadowsDefcascades?: number | number of cascades, 2 to 4 (default 4) |
distance?: number | how far from the camera the sun's shadows are drawn, metres (default 200) |
mapSize?: number | side of each cascade's depth map, texels (default 2048) |
bias?: number | depth bias of the map (default 0.0005) |
normalBias?: number | bias along the normal, metres (default 0.05) |
blend?: number | the share of a cascade over which it blends into the next (default 0.1) |
lambda?: number | 0 = evenly spaced cascades, 1 = logarithmic: near cascades finer (default 0.95) |
filter?: 'pcf' | 'hard' | the edge: pcf (soft, the default) or hard |
packages/levels/src/sun-shadows.ts:14
SwarmDef interface
interface SwarmDefA 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: number | the 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?: number | 1/s |
speedLimit?: number | m/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?: number | m/s^2 added along x/z of the level's wind, times this (default 0) |
seed?: number | |
distance?: number | the swarm runs only while the camera is within this many metres (default 40) |
packages/levels/src/swarm.ts:10
Transition interface
interface Transitionenter(ctx: TransitionContext): Promise<void> | void | The travel starts. Show something at once. Resolve when it is on screen (after 2 s the engine's bar takes over). |
update(p: TransitionProgress): void | The target's progress, many times a second. |
ready(ctx: TransitionContext): Promise<void> | void | The 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 TransitionContextfrom: LevelDef | null | |
to: LevelDef | |
plan: LevelPlan | what the travel will download; cached means a short wait is expected |
world: World | |
events: EventBus | |
ui?: UIService | the 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?: SceneHost | the 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: AbortSignal | the player cancelled |
packages/levels/src/transitions.ts:16
TransitionProgress interface
interface TransitionProgressWhat 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 TravelOptionsspawn?: string | |
keep?: Entity[] | keep these entities: they move to the new level's spawn instead of being removed (the player) |
keepOld?: boolean | Keep 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?: AbortSignal | Cancel from a menu: before the old level is released the player simply stays; later they are put back. |
transition?: string | The 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 ValidateOptionspackages?: PackageSet | the 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?: boolean | check the sha256 of every file (default true) |
engine?: EngineVersions | false | the engine that is running; default this build's (FERRET_VERSION, BABYLON_VERSION); false skips the check of the manifest's engine |
tierView?: boolean | set when pkg is already one tier's view of a game (its own call for each tier) |
fetched?: boolean | a build: a dependency that is not open need not be, when the package names catalogs (the player fetches it from there and checks it before the start) |
packages/levels/src/ferret.ts:182
VirtualTextureDef interface
interface VirtualTextureDefresolution?: number | texels along the longer side of the rectangle (default 2048) |
blendHeight?: number | metres above the ground over which a prop's albedo fades from the ground colour to its own (default 1.5) |
strength?: number | 0..1, how much of the ground colour a prop takes at its foot (default 1) |
meshes: string | regex source: the meshes (by name, anywhere in the level) whose materials sample the virtual texture |
packages/levels/src/landscape.ts:108
VisibilityBlock interface
interface VisibilityBlockThe visibility block: a level of many rooms (a castle) draws only what can be seen from where the player stands. The level's nodes are
split into named groups (a room, a corridor); the floor plan is cut by a grid of cell metres in x and z (origin 0, key "ix_iz" with
ix = floor(x / cell)); see[key] lists the groups that can be seen from anywhere in that grid cell. A tool computes the lists (rays against
the level's collision, tools/visibility.mjs). The player in a cell that has no entry sees everything: a gap in the table is never a hole.
cell: number | |
groups: Record<string, { nodes: string[] }> | group id -> the glTF node names that make it up (each node with all it carries) |
always?: string[] | groups that are always drawn (a landmark seen from everywhere) |
see: Record<string, string[]> | |
mode?: 'visible' | 'enable' | 'visible' (default): meshes of an unseen group are not drawn but keep their collision; 'enable': the nodes are disabled (cheapest; collision goes too) |
packages/levels/src/manifest.ts:150
VisibilityOptions interface
interface VisibilityOptionsfocus?: () => { x: number; z: number } | null | where the viewer stands; default the camera |
packages/levels/src/visibility.ts:5
Waitable interface
interface Waitabledone(): boolean | |
result?: unknown |
packages/levels/src/fmdl-motion.ts:36
WakeRow interface
interface WakeRowdist: number | |
tau: number | |
coreHalf: number | |
coreAlpha: number | |
armOffset: number | |
armHalf: number | |
armAlpha: number |
packages/levels/src/wake.ts:22
WaterDef interface
interface WaterDeflevel: number | y of the surface at rest |
centre?: [number, number] | centre (x, z) and size (x, z) of the surface, metres |
size?: [number, number] | |
absorption?: Vec3 | the 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?: number | a 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?: number | 0..1 (default 0.02) |
specular?: number | 0..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?: number | 0..1, how opaque the surface draws (default 0.92) |
foam?: number | 0..1, how strongly breaking crests turn to white water (default 0.8; a gentle sea has none whatever this is) |
meso?: number | 0..1: patches, wind streaks and whitecaps that show from high above, where real waves are smaller than a pixel (default 0: off) |
river?: RiverDef | a 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?: ShoreDef | a 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 WaterResponseMapa 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 WaterSurfaceViewmesh: 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 WaterWavewavelength: number | metres crest to crest |
amplitude: number | metres, crest above the rest level |
steepness?: number | 0..1: how sharp the crests are (Gerstner Q) |
direction?: number | degrees about the vertical, the way the wave travels (0 = +x) |
packages/levels/src/water.ts:10
Types
EnvironmentPart type
type EnvironmentPart = 'sun' | 'ambient' | 'fog' | 'sky' | 'water'a part of a level's environment a game may leave out (LevelDef.environment.skip)
packages/levels/src/levels.ts:49
FileReader type
type FileReader = (qualified: string) => Promise<Uint8Array>packages/levels/src/fmdl.ts:16
Interp type
type Interp = 'linear' | 'cubic' | 'step'A level sequence (Unreal's LevelSequence): tracks that move nodes and the camera over time, played once or looped, on level begin or on a trigger. The JSON is what the exporter (vschool_ferret export/ue/probe_sequences.py, tools/sequences.mjs) writes for each sequence; lengths are metres, angles are quaternions in the engine's frame (the exporter converts from Unreal's cm / Z-up), time is seconds.
{ name, length, loop?, play: 'begin' | 'trigger' | 'manual', trigger?: string (a trigger volume's id), rate?: 1,
tracks: [ { target: string | { camera: true }, position?: Key3[], rotation?: Key4[], scale?: Key3[], fov?: Key1[] } ],
events?: [ { t, name } ] }
Key = { t, v, interp?: 'linear' | 'cubic' | 'step' } (v: number | [x,y,z] | [x,y,z,w])
target is a scene node ("Actor>Component" or a name); { camera: true } drives the active camera. Events are emitted on the world bus as sequence:event.
packages/levels/src/sequence.ts:15
LevelCodec type
type LevelCodec = 'etc1s' | 'uastc'packages/levels/src/level-materials.ts:33
LevelCodecPolicy type
type LevelCodecPolicy = 'best' | 'light' | 'chosen'which file of a texture that exists in both codecs is read: best UASTC, light ETC1S, chosen the one the encoder's check chose
packages/levels/src/level-materials.ts:36
LookScope type
type LookScope = 'type' | 'instance'packages/levels/src/material-look.ts:44
LookTable type
type LookTable = Record<string, Record<string, MaterialLookDef>>uid → glTF material name → look
packages/levels/src/material-look.ts:42
MaterialMapSlot type
type MaterialMapSlot = 'baseColor' | 'normal' | 'orm' | 'emissive' | 'opacity'The look of the glTF materials of a level, set in the manifest (materialLooks) and changed live by the editor (edit.material.*).
A material is never addressed by its name across the whole scene (the same name stands in twenty places). Two scopes:
- types[typeUid][materialName]: the TYPE, the model as an asset: the look goes to the named material of that model in ALL its instances ("all boards");
- instances[instanceUid][materialName]: ONE concrete object (a node and what hangs on it, an entity, one placed actor): it goes over the type's look ("this board").
Inside a model the material is named by its glTF material name.
Where a uid comes from (the first that the scene offers wins, the others are fallbacks, so an old level without any extras still works):
- type: glTF node extras.ferret.uid.type (the exporter writes the Unreal asset path) | the key of a placement list's models | the library id of that model | the glTF MESH name;
- instance: glTF node extras.ferret.uid.instance (the exporter writes the actor name) | the manifest entity id | the placement actor | the node path (names from the scene root, joined with "/").
An address that more than one thing answers to (two glTF meshes of one name, two nodes of one path) is AMBIGUOUS: it still applies on load to everything it matches,
edit.material.list shows it, and the editor refuses to write on it (give the object a uid in the export instead).
The values are the ones of a library material (MaterialDef of
packages/levels/src/material-look.ts:27
ModelState type
type ModelState = 'loading' | 'ready' | 'failed'packages/levels/src/runtime.ts:34
PlaceholderSpec type
type PlaceholderSpec = 'box' | 'none' | { size?: number | [number, number, number]; color?: [number, number, number] } | ((scene: BABYLON.Scene) => BABYLON.TransformNode)packages/levels/src/runtime.ts:23
ProgramType type
type ProgramType = 1 | 2 | 3 | 4packages/levels/src/material-program.ts:13
RefKind type
type RefKind = 'package' | 'remote' | 'relative'packages/levels/src/runtime.ts:14
RegisterFn type
type RegisterFn = (name: string, description: string, fn: (args: any) => unknown) => voidpackages/levels/src/fmdl-docks.ts:262
ResolvedAtmosphere type
type ResolvedAtmosphere = Required<AtmosphereDef>packages/levels/src/atmosphere.ts:59
TextureCodecPolicy type
type TextureCodecPolicy = 'chosen' | 'best' | 'light'packages/levels/src/library.ts:34
TransitionChooser type
type TransitionChooser = (from: LevelDef | null, to: LevelDef, plan: LevelPlan) => string | undefined | nullpackages/levels/src/transitions.ts:53
Constants
ARM_REACH const
const ARM_REACH: 200packages/levels/src/wake.ts:28
ARM_STRENGTH const
const ARM_STRENGTH: 0.14The 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: 30packages/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: Transitionpackages/levels/src/transitions.ts:51
COLOUR_ATTRIBUTE const
const COLOUR_ATTRIBUTE: "#if !defined(VERTEXCOLOR) && !defined(FERRET_COLOR_ATTR)\n#define FERRET_COLOR_ATTR\nattribute vec4 color;\n#endif"the color attribute, declared once however many plugins (this and the foliage wind) read it; a mesh that uses vertex colours has it declared by Babylon already
packages/levels/src/material-models.ts:409
DEFAULT_LIBRARY_URL const
const DEFAULT_LIBRARY_URL: "/lib/ferret-assets/catalog.json"packages/levels/src/library.ts:32
DISTANCE_FIELD_GLSL const
const DISTANCE_FIELD_GLSL: "uniform highp sampler3D ferretMpDfTable;\nuniform highp sampler3D ferretMpDfValues;\nfloat ferretMpDfByte(vec3 w) {\n vec3 v = (w - ferretMpDfOrigin.xyz) / ferretMpDfOrigin.w, b = floor(v / ferretMpDfAtlas.w);\n if (any(lessThan(b, vec3(0.0))) || any(greaterThanEqual(b, ferretMpDfGrid.xyz))) return 1.0;\n vec4 e = texelFetch(ferretMpDfTable, ivec3(b), 0);\n if (e.a < 0.5) return 1.0;\n vec3 …the lookup: ferretMpDfByte(world metres) is the stored value 0..1 (1: far), ferretMpDfMetres the distance
packages/levels/src/distance-field.ts:104
ENGINE_GLOBAL const
const ENGINE_GLOBAL: "__ferretEngine"The engine a docked level's code shares with its parent. A level's code is built like a game's: an ES module that imports @ferret/*. A parent whose engine
is ES modules with an import map needs nothing more. A parent that ships its engine inside its own bundle (Ilion) publishes the packages it holds in globalThis.__ferretEngine
(shareEngine) and the code loader rewrites the imports of the module's text to read from there (useSharedEngine), so the level and the parent are one engine: one World, one set of
registries, one scheduler. A package the parent does not hold is an error that names it; a level that needs one carries it inside its own code (the converter and the scene builder inline it).
packages/levels/src/dock-engine.ts:8
HEIGHT_TRANSITION const
const HEIGHT_TRANSITION: 0.2how much height a height-blended layer needs to beat the others (score units), as a transition width
packages/levels/src/landscape.ts:142
LEVEL_CODEC_POLICIES const
const LEVEL_CODEC_POLICIES: readonly LevelCodecPolicy[]packages/levels/src/level-materials.ts:37
LEVEL_CODECS const
const LEVEL_CODECS: readonly LevelCodec[]packages/levels/src/level-materials.ts:34
LEVEL_MATERIALS_FORMAT const
const LEVEL_MATERIALS_FORMAT: "ferret-materials/1"packages/levels/src/level-materials.ts:30
LEVEL_TEXTURES_FORMAT const
const LEVEL_TEXTURES_FORMAT: "ferret-textures/1"packages/levels/src/level-materials.ts:31
LOOK_SCOPES const
const LOOK_SCOPES: readonly LookScope[]packages/levels/src/material-look.ts:45
LUT_SIZE const
const LUT_SIZE: 24packages/levels/src/atmosphere.ts:49
MACRO_BLEND_DEFAULT const
const MACRO_BLEND_DEFAULT: 1.5WorldCoordinate3Way's own default of its four blend inputs (Blend Exponent X / Y Z, Blend Mult X / Y Z): all 1.5 in the exported function
packages/levels/src/material-models.ts:40
MANIFEST_VERSION const
const MANIFEST_VERSION: 1packages/levels/src/manifest.ts:14
MATERIAL_MAP_SLOTS const
const MATERIAL_MAP_SLOTS: readonly MaterialMapSlot[]packages/levels/src/material-look.ts:28
MAX_LANDSCAPE_LAYERS const
const MAX_LANDSCAPE_LAYERS: 8packages/levels/src/landscape.ts:138
MAX_LANDSCAPE_SAMPLERS const
const MAX_LANDSCAPE_SAMPLERS: 13WebGL guarantees 16 texture units; the PBR material uses a few, so layers + normals + weightmaps stay under this
packages/levels/src/landscape.ts:140
MAX_MATERIAL_LIGHTS const
const MAX_MATERIAL_LIGHTS: 8most lights one material may light with (uniform-block limit of D3D11 through ANGLE, 12 vertex blocks, 4 taken by scene/material/mesh/bones)
packages/levels/src/light-budget.ts:166
MOVEMENT_KEYS const
const MOVEMENT_KEYS: readonly ["radius", "height", "crouchHeight", "eyeHeight", "walkSpeed", "runSpeed", "crouchSpeed", "jumpVelocity", "gravity", "maxStepHeight", "walkableAngle", "acceleration", "braking", "airControl", "swimSpeed", "buoyancy", "swimAcceleration", "outOfWaterZ", "jumpOutOfWaterPitch", "maxOutOfWaterStepHeight"]packages/levels/src/manifest.ts:161
MULTI_SCATTER const
const MULTI_SCATTER: 0.3packages/levels/src/atmosphere.ts:48
PIXEL_DEPTH_THRESHOLD const
const PIXEL_DEPTH_THRESHOLD: 0.5DitherTemporalAA's Alpha Threshold input default
packages/levels/src/material-models.ts:42
PLACEMENTS_FORMAT const
const PLACEMENTS_FORMAT: "ferret-placements/1"packages/levels/src/placements.ts:26
programTime const
const programTime: { now: () => number; }seconds since the module was loaded: the Time of every program (one clock, so equal materials blink together as in the original)
packages/levels/src/material-program.ts:270
RELIEF_DECAL_LAYER const
const RELIEF_DECAL_LAYER: 268435456the layer of the relief decals: outside a camera's default mask (0x0FFFFFFF)
packages/levels/src/decal-buffer.ts:13
SCREEN_DECAL_LAYER const
const SCREEN_DECAL_LAYER: 536870912the layer of the decal boxes: outside a camera's default mask (0x0FFFFFFF) and the relief decals' (0x10000000)
packages/levels/src/screen-decals.ts:15
SCREEN_DECAL_PASS const
const SCREEN_DECAL_PASS: { readonly colour: 0; readonly surface: 1; }the two passes a decal's shader draws: its colour and opacity, then its roughness and metallic
packages/levels/src/screen-decals.ts:18
UE_UNITS_PER_METRE const
const UE_UNITS_PER_METRE: 100packages/levels/src/material-models.ts:38
UNREAL_FILM_GLSL const
const UNREAL_FILM_GLSL: stringGLSL: vec3 ferretUnrealFilm(vec3 linearSRGB) -> linear sRGB in 0..1 (the caller encodes the gamma)
packages/levels/src/unreal-film.ts:20
UNREAL_FILM_TONEMAPPING const
const UNREAL_FILM_TONEMAPPING: 2the Babylon tone mapping type that draws Unreal's film curve once installUnrealFilm() has run (it takes the place of the unused glTF PBR Neutral type)
packages/levels/src/unreal-film.ts:71