# @ferret/levels: API (continued)

### levelTextureStem

*function* · `packages/levels/src/level-materials.ts:80`

```ts
function levelTextureStem(ref: string): string | undefined
```

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

### loadLandscapeTexture

*function* · `packages/levels/src/landscape.ts:703`

```ts
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

### loadLandscapeTextureArray

*function* · `packages/levels/src/landscape.ts:717`

```ts
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.

### lookCompositionGlsl

*function* · `packages/levels/src/material-models.ts:366`

```ts
function lookCompositionGlsl(s: LookStructure): string
```

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

### lookDefine

*function* · `packages/levels/src/material-models.ts:209`

```ts
function lookDefine: (s: LookStructure) => string
```

### lookDepthGlsl

*function* · `packages/levels/src/material-models.ts:393`

```ts
function lookDepthGlsl(s: LookStructure): string
```

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

### lookFadeGlsl

*function* · `packages/levels/src/material-models.ts:374`

```ts
function lookFadeGlsl(s: LookStructure): string
```

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

### lookGlsl

*function* · `packages/levels/src/material-models.ts:274`

```ts
function lookGlsl(s: LookStructure): string
```

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

### lookMasks

*function* · `packages/levels/src/material-models.ts:193`

```ts
function lookMasks(s: LookStructure): string[]
```

the pictures of a structure in the order samplers are numbered

### lookPictures

*function* · `packages/levels/src/material-models.ts:202`

```ts
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)

### lookReflectionGlsl

*function* · `packages/levels/src/material-models.ts:352`

```ts
function lookReflectionGlsl(s: LookStructure): string
```

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

### lookReflectivityGlsl

*function* · `packages/levels/src/material-models.ts:343`

```ts
function lookReflectivityGlsl(s: LookStructure): string
```

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

### lookStructure

*function* · `packages/levels/src/material-models.ts:167`

```ts
function lookStructure(look: LookDef): LookStructure
```

### lutElevation

*function* · `packages/levels/src/atmosphere.ts:80`

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

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

### macroBlendAlphas

*function* · `packages/levels/src/material-models.ts:73`

```ts
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|).

### macroBlendOf

*function* · `packages/levels/src/material-models.ts:64`

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

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

### macroMix

*function* · `packages/levels/src/material-models.ts:78`

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

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

### maskSample

*function* · `packages/levels/src/material-models.ts:105`

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

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

### miePhase

*function* · `packages/levels/src/atmosphere.ts:83`

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

### mixLayer

*function* · `packages/levels/src/material-models.ts:100`

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

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

### modelClips

*function* · `packages/levels/src/fmdl-motion.ts:266`

```ts
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.

### movingNodes

*function* · `packages/levels/src/static-freeze.ts:26`

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

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

### parseLevelTextures

*function* · `packages/levels/src/level-materials.ts:48`

```ts
function parseLevelTextures(json: unknown): LevelTextureCatalogue
```

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

### patchImageProcessing

*function* · `packages/levels/src/unreal-film.ts:78`

```ts
function patchImageProcessing(code: string): string
```

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

### pickCodecFile

*function* · `packages/levels/src/library.ts:37`

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

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

### pickLevelTextureFile

*function* · `packages/levels/src/level-materials.ts:72`

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

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

### pickTier

*function* · `packages/levels/src/library.ts:153`

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

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

### pixelDepthPush

*function* · `packages/levels/src/material-models.ts:95`

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

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

### planCollisionChunks

*function* · `packages/levels/src/collision-chunks.ts:20`

```ts
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`.

### previewTransition

*function* · `packages/levels/src/transitions.ts:163`

```ts
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.

### projectionUvs

*function* · `packages/levels/src/material-models.ts:84`

```ts
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.

### propellerBlur

*function* · `packages/levels/src/propeller.ts:22`

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

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

### propulsorsOf

*function* · `packages/levels/src/fmdl-propulsors.ts:21`

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

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

### rankNearest

*function* · `packages/levels/src/light-budget.ts:116`

```ts
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.

### rayleighPhase

*function* · `packages/levels/src/atmosphere.ts:82`

```ts
function rayleighPhase(c: number): number
```

### refKind

*function* · `packages/levels/src/runtime.ts:17`

```ts
function refKind(ref: string): RefKind
```

Which scheme a reference uses.

### registerCatalogueCommands

*function* · `packages/levels/src/fmdl-catalogue.ts:70`

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

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

### registerDockCommands

*function* · `packages/levels/src/fmdl-docks.ts:265`

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

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

### registerGroundSource

*function* · `packages/levels/src/landscape.ts:591`

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

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

### relativeTo

*function* · `packages/levels/src/placements.ts:70`

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

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

### releaseDepthRenderer

*function* · `packages/levels/src/material-models.ts:445`

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

### resolveAtmosphere

*function* · `packages/levels/src/atmosphere.ts:60`

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

### riverRibbon

*function* · `packages/levels/src/water.ts:95`

```ts
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).

### rotateAboutAxis

*function* · `packages/levels/src/foliage-wind.ts:83`

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

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

### sampleDistanceField

*function* · `packages/levels/src/distance-field.ts:56`

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

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

### sampleKeys

*function* · `packages/levels/src/sequence.ts:68`

```ts
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

### samplerPlan

*function* · `packages/levels/src/landscape.ts:270`

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

### scopeKey

*function* · `packages/levels/src/material-look.ts:46`

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

### screenDecalsOf

*function* · `packages/levels/src/screen-decals.ts:105`

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

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

### settleDrawing

*function* · `packages/levels/src/level-ready.ts:36`

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

### shareEngine

*function* · `packages/levels/src/dock-engine.ts:11`

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

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

### shoreDistance

*function* · `packages/levels/src/water.ts:67`

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

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

### simpleGrassWind

*function* · `packages/levels/src/foliage-wind.ts:72`

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

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

### skyRadiance

*function* · `packages/levels/src/atmosphere.ts:175`

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

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

### slopeAlpha

*function* · `packages/levels/src/landscape.ts:228`

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

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

### slopeShares

*function* · `packages/levels/src/landscape.ts:231`

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

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

### smoothTri

*function* · `packages/levels/src/foliage-wind.ts:69`

```ts
function smoothTri: (x: number) => number
```

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

### spawnFromManifest

*function* · `packages/levels/src/levels.ts:449`

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

### sunLightColour

*function* · `packages/levels/src/environment.ts:277`

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

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

### takesShadows

*function* · `packages/levels/src/sun-shadows.ts:97`

```ts
function takesShadows(m: BABYLON.AbstractMesh): boolean
```

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

### tierPath

*function* · `packages/levels/src/dock.ts:211`

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

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

### treeSway

*function* · `packages/levels/src/foliage-wind.ts:101`

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

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

### unfreezeStatic

*function* · `packages/levels/src/static-freeze.ts:48`

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

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

### unrealFalloff

*function* · `packages/levels/src/light-budget.ts:169`

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

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

### useHairFibre

*function* · `packages/levels/src/hair-fibre.ts:99`

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

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

### useSharedEngine

*function* · `packages/levels/src/dock-engine.ts:33`

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

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

### useUnrealFalloff

*function* · `packages/levels/src/light-budget.ts:176`

```ts
function useUnrealFalloff(): boolean
```

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

### validateAmbientParticles

*function* · `packages/levels/src/ambient-particles.ts:32`

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

### validateAtmosphere

*function* · `packages/levels/src/atmosphere.ts:64`

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

### validateEnvironment

*function* · `packages/levels/src/environment.ts:97`

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

### validateFogVeil

*function* · `packages/levels/src/fog-veil.ts:15`

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

### validateFoliageWind

*function* · `packages/levels/src/foliage-wind.ts:39`

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

### validateLandscapes

*function* · `packages/levels/src/landscape.ts:146`

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

### validateLevelMaterials

*function* · `packages/levels/src/level-materials.ts:119`

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

### validateLightBudget

*function* · `packages/levels/src/light-budget.ts:82`

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

### validateLookDef

*function* · `packages/levels/src/material-look.ts:54`

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

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

### validateManifest

*function* · `packages/levels/src/manifest.ts:169`

```ts
function validateManifest(m: unknown): ManifestIssue[]
```

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

### validateMaterialLooks

*function* · `packages/levels/src/material-look.ts:79`

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

### validateMaterialScale

*function* · `packages/levels/src/material-scale.ts:20`

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

### validatePackage

*function* · `packages/levels/src/ferret.ts:202`

```ts
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.

### validatePlacements

*function* · `packages/levels/src/placements.ts:77`

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

### validateProbes

*function* · `packages/levels/src/probe-volume.ts:30`

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

### validateRelevance

*function* · `packages/levels/src/manifest.ts:347`

```ts
function validateRelevance(r: unknown): ManifestIssue[]
```

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

### validateRoomReflection

*function* · `packages/levels/src/room-reflection.ts:28`

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

### validateSequences

*function* · `packages/levels/src/sequence.ts:39`

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

### validateSunShadows

*function* · `packages/levels/src/sun-shadows.ts:33`

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

### validateSwarm

*function* · `packages/levels/src/swarm.ts:38`

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

### validateVisibility

*function* · `packages/levels/src/visibility.ts:117`

```ts
function validateVisibility(v: any): ManifestIssue[]
```

### validateWater

*function* · `packages/levels/src/water.ts:113`

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

### virtualTextureShare

*function* · `packages/levels/src/landscape.ts:237`

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

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

### wakeFade

*function* · `packages/levels/src/wake.ts:30`

```ts
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)

### wakeProfile

*function* · `packages/levels/src/wake.ts:33`

```ts
function wakeProfile(o: ShipWakeOptions): WakeRow[]
```

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

### waveHeight

*function* · `packages/levels/src/water.ts:148`

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

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

## Interfaces

### Actor

*interface* · `packages/levels/src/fmdl-motion.ts:297`

```ts
interface Actor
```

- `name: 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>`

### AmbientParticlesDef

*interface* · `packages/levels/src/ambient-particles.ts:10`

```ts
interface AmbientParticlesDef
```

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

- `name?: string`
- `position: [number, number, number]` — the centre of the box
- `size: [number, number, number]` — the box's full size
- `rate: 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)

### ApplyLandscapeOptions

*interface* · `packages/levels/src/landscape.ts:691`

```ts
interface ApplyLandscapeOptions
```

- `at: (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)

### ApplyLookOptions

*interface* · `packages/levels/src/material-models.ts:602`

```ts
interface ApplyLookOptions
```

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

### ApplyProgramOptions

*interface* · `packages/levels/src/material-program.ts:272`

```ts
interface ApplyProgramOptions
```

- `textures: BABYLON.BaseTexture[]` — the pictures of the program's `textures`, by index
- `srgb?: readonly number[]` — indices of the pictures that are colour (sRGB) and must be decoded in the shader
- `arrays?: readonly { texture: BABYLON.BaseTexture; members: readonly number[] }[]` — Pictures read from texture arrays (a fragment shader has 16 texture units, a master may read more): `texture` is the array, `members[k]` the program's picture that is layer k (texture-array.ts). The entry of `textures` at a member's index is not read (give the array itself); the others are bound as before.
- `cutoff?: 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`)

### AssetLibraryOptions

*interface* · `packages/levels/src/library.ts:44`

```ts
interface AssetLibraryOptions
```

- `store: 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.

### AtmosphereDef

*interface* · `packages/levels/src/atmosphere.ts:18`

```ts
interface AtmosphereDef
```

Unreal'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)

### AtmosphereTable

*interface* · `packages/levels/src/atmosphere.ts:88`

```ts
interface AtmosphereTable
```

- `n: number`
- `rayleigh: Vec3[]` — Rayleigh in-scatter per view elevation, phase left out, per channel, in units of the sun's irradiance
- `mie: Vec3[]` — the same for Mie
- `sunTransmittance: 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`

### AttachOptions

*interface* · `packages/levels/src/library.ts:102`

```ts
interface AttachOptions
```

- `socket?: 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

### BindOptions

*interface* · `packages/levels/src/library.ts:122`

```ts
interface BindOptions
```

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

### BlendGlslOptions

*interface* · `packages/levels/src/landscape.ts:294`

```ts
interface BlendGlslOptions
```

- `depth?: 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

### BudgetLight

*interface* · `packages/levels/src/light-budget.ts:13`

```ts
interface BudgetLight
```

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

- `id?: 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

### CatalogOptions

*interface* · `packages/levels/src/catalog.ts:21`

```ts
interface CatalogOptions extends CatalogPolicy
```

- `tier?: 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.

### CatalogRegistration

*interface* · `packages/levels/src/catalog.ts:33`

```ts
interface CatalogRegistration
```

- `readonly 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.

### CellSource

*interface* · `packages/levels/src/streaming.ts:19`

```ts
interface CellSource
```

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

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

### CharacterOptions

*interface* · `packages/levels/src/library.ts:90`

```ts
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`

### ClipRef

*interface* · `packages/levels/src/library.ts:84`

```ts
interface ClipRef
```

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

- `id: string`
- `ref: string`
- `skeleton: string`
- `clips: ClipsItem['clips']`
- `prefix?: 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

### CodeLoaderOptions

*interface* · `packages/levels/src/code.ts:49`

```ts
interface CodeLoaderOptions
```

- `origin?: (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)

### CollisionChunkDef

*interface* · `packages/levels/src/collision-chunks.ts:10`

```ts
interface CollisionChunkDef
```

- `file: string`
- `bounds: [number, number, number, number, number, number]`

### CollisionChunksDef

*interface* · `packages/levels/src/collision-chunks.ts:11`

```ts
interface CollisionChunksDef
```

- `loadRadius: number`
- `unloadRadius: number`
- `chunks: CollisionChunkDef[]`

### CompiledProgram

*interface* · `packages/levels/src/material-program.ts:20`

```ts
interface CompiledProgram
```

- `types: 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

### DecodedKtx2

*interface* · `packages/levels/src/texture-array.ts:9`

```ts
interface DecodedKtx2
```

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

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

### DependencyOptions

*interface* · `packages/levels/src/dependencies.ts:12`

```ts
interface DependencyOptions
```

- `store: 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

### DependencyTarget

*interface* · `packages/levels/src/dependencies.ts:27`

```ts
interface DependencyTarget
```

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

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

