FERRETGame engine over Babylon.js
Ferret

@ferret/perspective

Drawing and animating by size on the screen: a ladder of full model, simpler mesh, baked impostor, dot and nothing, with cross-fades, a budget, a frame-time governor, animated impostors and measured thresholds.

99 exports · source in packages/perspective/src

Classes

BabylonBackend class

class BabylonBackend implements PerspectiveBackend
constructor(readonly scene: BABYLON.Scene, private readonly o: BabylonBackendOptions = {})
get pointsPass(): PointsPass | undefined
represent(entity: Entity, rung: number | string, what: BABYLON.TransformNode | BABYLON.AbstractMesh[] | Representation): RepresentationGives a rung its representation: a node with its meshes, a list of meshes, or any Representation (the impostor). The rung is an index into the entity's ladder or the name / kind of a level. A full rung with none given is the entity's own meshes that no other rung claims.
representLazy(entity: Entity, rung: number | string, make: () => BABYLON.TransformNode | BABYLON.AbstractMesh[], keepFrames?: number): LazyMeshRepresentationA rung whose meshes are made by make when it is first shown and disposed after keepFrames frames unused (see LazyMeshRepresentation). Because the entity may then have no meshes at all, give its size with setBounds (the impostor's addImpostor does this by itself from the atlas).
setBounds(entity: Entity, centre: Point3, radius: number): voidThe entity's bounding sphere in its own node's frame, when it cannot be measured from meshes that may not exist.
async addImpostor(entity: Entity, rung: number | string, src: ImpostorSource): Promise<ImpostorResult>Gives the entity an impostor at rung. The atlas is the packed bytes if given; else the cache's for this model and options if it has them and they are of this bake version; else the model is baked now (and the result is written to the cache). Entities with the same modelKey and options share one atlas and one draw call.
cameras(): CameraView[]the cameras that render this frame
sphereOf(entity: Entity): Spherethe bounding sphere of an entity in world space
frame(entity: Entity, frame: number): voidshow frame frame of an animated impostor of the entity
upOf(entity: Entity): Point3the entity's up axis in the world, for the glint of a point
apply(entity: Entity, ladder: readonly PerspectiveLevel[], f: Fade): voidshow the rungs of fade (from fading out, to fading in) for an entity; mix is 1 when the change is over and only to is drawn
points(list: readonly PointInstance[]): voidthe entities at the point level this frame, in one batch (one draw call)
frameMs(): numberthe real time of the last frame, ms, if the backend can measure it
debug(on: boolean): voidtint every level a colour (debug)
dispose(): void

packages/perspective/src/view.ts:172

CoherenceState class

class CoherenceState

What is carried from one frame to the next: the boundaries chosen per kind, and the scratch buffers (grown once, then reused).

readonly splits: Map<string, number[]>
px: Float64Array<ArrayBuffer>
seen: Uint8Array<ArrayBuffer>
level: Int16Array<ArrayBuffer>
parent: Int32Array<ArrayBuffer>
gidx: Int32Array<ArrayBuffer>
readonly cells: Map<number, number[]>
readonly byKind: Map<string, number[]>
ensure(n: number): voidbuffers for n items
list(): number[]an empty list from the pool (all given back by reset)
reset(): void

packages/perspective/src/coherence.ts:51

FrameGovernor class

class FrameGovernor

Watches frame times and scales the thresholds: over budget, less detail at the same size; well under, it comes back.

scale: number
constructor(readonly cfg: GovernorConfig)
record(ms: number): number | undefinedRecords a frame; returns the new scale when it changed.

packages/perspective/src/select.ts:93

ImpostorSet class

class ImpostorSet

All the objects of one baked model: one mesh, one material, thin instances.

readonly mesh: BABYLON.Mesh
readonly material: BABYLON.ShaderMaterial
domHit: booleana hit by the nearest view alone counts (thin parts survive); on by default after measurement
coverMin: number
surfaceEps: numberhow far, in radii of the sphere, the depth a view stored may be from a point of the eye ray for the point to be on the surface that view saw (read when a set is made)
metalDarken: numberhow much of the metalness darkens the diffuse term: 1 is the physical model (a metal has none), which is what Babylon's PBR does (read when a set is made)
hemiSpecular: numberthe strength of the hemispheric light's specular lobe (1: as Babylon's PBR) (read when a set is made)
fogPower: numberthe power the fog factor is raised to (see PointsPass.fogPower)
lightScale: [number, number]
debugTint: [number, number, number]
constructor(readonly scene: BABYLON.Scene, readonly meta: AtlasMeta, png: Record<string, Uint8Array>)
isReady(): booleanIs every texture loaded (a mesh that uses them draws nothing before).
add(node: BABYLON.TransformNode): Representation
get active(): numberInstances shown now.
dispose(): void

packages/perspective/src/impostor.ts:224

LazyMeshRepresentation class

class LazyMeshRepresentation implements Representation

A rung whose meshes do not exist until it is first shown, and are disposed again after keepFrames frames off (default 120, so a rung at the edge of a threshold does not churn). The scene then never walks the meshes of rungs nobody sees: a far aircraft has no full model at all.

created: numberhow many times the meshes were made (for tests and stats)
constructor(private readonly make: () => BABYLON.TransformNode | BABYLON.AbstractMesh[], readonly keepFrames = 120)
get alive(): boolean
setState(state: RepState, mix: number): void
tint(color: BABYLON.Color3 | null): voiddebug: tint the representation (null: remove the tint)

packages/perspective/src/view.ts:100

MeshRepresentation class

class MeshRepresentation implements Representation

A set of meshes that is one rung. Visibility is isVisible (the game's own enabling is untouched); what a mesh was before is restored when it is shown.

constructor(readonly meshes: BABYLON.AbstractMesh[])
setState(state: RepState, mix: number): void
tint(color: BABYLON.Color3 | null): voiddebug: tint the representation (null: remove the tint)

packages/perspective/src/view.ts:65

PartCuller class

class PartCuller
get count(): numberparts that carry a far level now
minPx: number
constructor(private scene: BABYLON.Scene, private o: PartCullOptions = {})
add(root: BABYLON.Node): numberGive every source mesh under root its far level. A mesh already given one is left as it is. Returns how many parts were added. The bounding sphere is read in the world, so a model's own scale counts; root should be in place (scaled) when this is called.
refit(force: boolean): voidset the distances again when the field of view or the target's height has moved (called each frame by itself; force for a test)
qualityKnob(maxPx = 4.5, steps = 3): import('@ferret/core').QualityKnobThe pixel threshold as a knob of the quality regulator: a larger one leaves more small far parts undrawn, fewer draw calls and active meshes (both sides of the frame). The scene is never broken: the threshold never goes above maxPx (default 4.5 pixels), below which a part is not seen as a part; the steps are the shares of the way from the start to it.
dispose(): voidtake the levels off again and stop following the view

packages/perspective/src/parts.ts:26

Perspective class

class Perspective extends Component<PerspectiveParams>

Marks an entity as drawn by size on the screen. The component holds only the declaration and the state the service writes (index, fade); it has no onFixedUpdate, so nothing here can reach the simulation. The service decides in update, before the components' onUpdate.

index: numberthe rung shown now (the one fading in while a fade runs)
fadeFrom: numberthe rung fading out, or -1 when no fade runs
mix: number0..1 while a fade runs
px: numberthe size in pixels, last frame
forced: numbera rung held by perspective.force, or -1
phase: numberframes since the service counted this entity, for poseEvery
animateNow: booleanset by the service: true when this frame should pose the bones / refresh the presentation at this entity's rate
gated: booleanthe service has hooked this entity's Animator
get level(): PerspectiveLevel
onAttach()
onDetach()

packages/perspective/src/component.ts:37

PerspectiveService class

class PerspectiveService implements Service

the plan to 6. Once per rendered frame, in update (never in the fixed step), it measures every tracked entity on the screen, picks its rung with hysteresis, applies the budget, runs the cross-fades and tells the backend. The simulation does not read anything it writes.

readonly name: "perspective"
coherent: booleancoherent detail on (the constructor's coherent, ?coherent=0 in a game turns it off)
constructor(private readonly o: PerspectiveOptions)
get backend(): PerspectiveBackend
get scale(): numberthe multiplier now applied to every threshold: tier times governor
effectiveLadder(ladder: readonly PerspectiveLevel[]): PerspectiveLevel[]The thresholds in use for a ladder: the tier scales them all; the quality regulator scales only those of the detailed rungs (full, mesh). The threshold where a baked impostor gives way to a point is the one measured at the bake: no regulator moves it, so far things keep their impostors (that is what impostors are made for) and never turn into dots sooner to save a frame.
qualityKnobs(): import('@ferret/core').QualityKnob[]knobs for the quality regulator (QualityService finds them): larger thresholds draw far things simpler sooner (both CPU and GPU)
setTierScale(s: number): void
setBudget(b: BudgetLimits): void
init(world: World): void
track(p: Perspective): void
untrack(p: Perspective): void
get count(): number
list()
stats()
animate(entityId: string): booleanTrue when this frame should refresh the presentation of entityId at its rung's rate (bones, code-driven parts). Entities not tracked animate.
levelOf(entityId: string)
update(dt: number): voidCalled once per rendered frame.
dispose(): void

packages/perspective/src/service.ts:29

PointsPass class

class PointsPass
readonly mesh: BABYLON.Mesh
readonly material: BABYLON.ShaderMaterial
drawn: number
fogPower: numberthe power the fog factor is raised to: 2.2 for PBR meshes (the library's models), 1 for standard materials
constructor(private readonly scene: BABYLON.Scene)
light(): SceneLightThe light the scene gives a surface, as the point colour needs it.
update(list: readonly PointInstance[], eye: Point3, viewport: [number, number]): voidDraws these points this frame (an empty list hides the pass).
dispose(): void

packages/perspective/src/points.ts:122

RecordingBackend class

class RecordingBackend implements PerspectiveBackend

A backend that draws nothing and writes down what it was told. Cameras and spheres are set by the test.

readonly log: Recorded[]
cams: CameraView[]
spheres: Map<string, Sphere>
ms: number | undefined
debugOn: boolean
last: Map<string, Fade>
pointList: PointInstance[]
frames: Map<string, number>
cameras(): CameraView[]the cameras that render this frame
sphereOf(e: Entity): Spherethe bounding sphere of an entity in world space
apply(e: Entity, _l: readonly PerspectiveLevel[], f: Fade): voidshow the rungs of fade (from fading out, to fading in) for an entity; mix is 1 when the change is over and only to is drawn
points(list: readonly PointInstance[]): voidthe entities at the point level this frame, in one batch (one draw call)
frame(e: Entity, frame: number): voidshow frame frame of an animated impostor of the entity
frameMs(): number | undefinedthe real time of the last frame, ms, if the backend can measure it
debug(on: boolean): voidtint every level a colour (debug)

packages/perspective/src/backend.ts:52

Functions

applyBudget function

function applyBudget(cands: readonly Candidate[], lim: BudgetLimits): Map<string, number>

The budget of detail: at most maxFull entities at full and maxMesh at mesh rungs. The largest on screen keep their rung (ties by id, so that the order never shuffles); the rest step down to the next rung that is not over a limit. Returns the rung per id.

packages/perspective/src/select.ts:60

atlasSize function

function atlasSize(b: ResolvedBake, frames = 1): { w: number; h: number }

packages/perspective/src/bake-spec.ts:57

bakeImpostor function

async function bakeImpostor(scene: BABYLON.Scene, root: BABYLON.TransformNode, options: ImpostorBakeOptions = {}, anim?: BakeAnimation): Promise<BakedAtlas>

Bakes the model under root: one render per view per map. The root is moved to the origin, unrotated, for the bake and put back after. Nothing in the scene but the model's meshes is drawn into the maps. hide nodes are left out and replace nodes are shown in place of the ones named (see ImpostorBakeOptions).

packages/perspective/src/bake.ts:95

bakeKey function

function bakeKey(model: Uint8Array, materials: string, o: ImpostorBakeOptions): string

The key an atlas is cached by: the model bytes, what the materials give (any string the caller derives), the options and the bake version.

packages/perspective/src/bake-spec.ts:60

blurError function

function blurError(a: Rgb, b: Rgb, sky: readonly [number, number, number] | 'border', r = 2): BlurError

How far b is from a, with the sky colour sky (sRGB bytes) as the empty picture. Both go through a box blur of radius r first. err is relative to a and so cannot tell a vanishing object from a big one: contrast can.

packages/perspective/src/compare.ts:56

checkLadder function

function checkLadder(ladder: readonly PerspectiveLevel[]): string[]

packages/perspective/src/select.ts:17

chooseLevel function

function chooseLevel(ladder: readonly PerspectiveLevel[], current: number, px: number, scale = 1, margin = 0.1): number

The level for a size, with hysteresis. current is the rung now (an index into the ladder); scale multiplies every threshold (the quality tier and the governor: above 1, detail is given up at larger sizes); margin is the ratio by which a size must pass a threshold to cross it: richer needs px >= minPx * scale * (1 + margin), poorer needs px < minPx * scale * (1 - margin).

packages/perspective/src/select.ts:36

clipFrame function

function clipFrame(t: number, duration: number, frames: number): number

The frame of a looping clip baked as frames frames, at clip time t of a clip of duration seconds.

packages/perspective/src/octa.ts:56

coherentLevels function

function coherentLevels(items: readonly CoherentItem[], cams: readonly CameraView[], rule: (kind: string) => KindRule, scale = 1, state = new CoherenceState(), budget: BudgetLimits = {}, fits?: (members: readonly number[], level: number, kind: string) => boolean): CoherentResult

Levels for items seen by cams, with every threshold times scale, the budget spent per group. state keeps the boundaries between frames (so they do not jump between two gaps of about the same size) and the buffers. fits(members, level, kind) (members as item indexes) lets a drawer with pools of its own refuse a whole group; it is asked only for levels of full and mesh kind, and reserves what it accepts.

packages/perspective/src/coherence.ts:84

decodePng function

async function decodePng(png: Uint8Array): Promise<{ rgba: Uint8Array; width: number; height: number }>

Decodes to RGBA bytes (for tests and for tools; the engine loads PNGs straight into textures and never reads them back).

packages/perspective/src/png.ts:34

dilate function

function dilate(maps: Partial<Record<BakeMap, Uint8Array>>, o: { views: number }, width: number, cell: number, passes: number, frames = 1): void

Fills the RGB of the texels no view covers with that of the covered texels beside them, passes texels deep, in every maps' cell. Coverage is the colour map's alpha and is not changed.

packages/perspective/src/bake.ts:250

distance function

function distance: (a: Point3, b: Point3) => number

packages/perspective/src/projection.ts:59

distanceForPx function

function distanceForPx(r: number, px: number, fovY: number, heightPx: number): number

The distance at which a sphere of radius r covers px pixels (perspective): the inverse of projectedPx.

packages/perspective/src/projection.ts:81

encodePng function

async function encodePng(rgba: Uint8Array, width: number, height: number): Promise<Uint8Array>

A PNG of RGBA bytes written by hand (CompressionStream for the zlib part): a canvas premultiplies, and drops the colour of every texel whose alpha is 0, which is exactly the colour the bake bleeds past the silhouette.

packages/perspective/src/png.ts:12

firstLevel function

function firstLevel(ladder: readonly PerspectiveLevel[], px: number, scale = 1): number

The rung with no hysteresis, for a first choice.

packages/perspective/src/select.ts:44

inView function

function inView(s: Sphere, cam: CameraView): boolean

Is any of the sphere inside the camera's view: within the cone that holds the frame's corners, widened by the sphere's own angle. A camera without forward sees everything (the answer is then always true).

packages/perspective/src/projection.ts:24

ladderFromThresholds function

function ladderFromThresholds(t: MeasuredThresholds, has: { mesh?: boolean } = {}, names: Partial<Record<'full' | 'mesh' | 'impostor' | 'point', string>> = {}): PerspectiveLevel[]

The ladder a model's measured thresholds make. A level that would take over at a size not below the one before it is left out (the impostor is then as good as the simpler mesh up to a size where the mesh is still needed: the mesh rung is dropped). names gives the backend's name of a rung.

packages/perspective/src/thresholds.ts:29

ladderOfModel function

function ladderOfModel(model: LadderModel, o: ModelLadderOptions = {}): ModelRung[]

The ladder of a model. A level other than the last needs its measured threshold (the size below which the next level is within tolerance of it): the packer writes them, they are never made up here, and a model that has not been measured throws, naming the levels that miss it. A rung that would take over at a size not below the one before it is left out. The last rung is used down to 0.

packages/perspective/src/model-ladder.ts:34

largestPx function

function largestPx(s: Sphere, cams: readonly CameraView[]): number

The size for a scene with several cameras (XR eyes, a scope, a mirror): the largest wins, so nothing is drawn thinner than the best view needs.

packages/perspective/src/projection.ts:74

luminance function

function luminance: (r: number, g: number, b: number) => number

relative luminance of an sRGB byte triple, as linear light

packages/perspective/src/compare.ts:10

measureThreshold function

function measureThreshold(error: (px: number) => number, tol: number, lo = 0.25, hi = 2048, steps = 14): number

The threshold of a cheaper level (4.4): the smallest size in pixels at which its image differs from the richer one's by no more than tol. error(px) renders both at that size and returns the difference; it should shrink as px shrinks, which is what makes a cheaper level possible. Found by bisection on a log scale between lo and hi. If even hi is within the error the answer is hi; if lo is not, it is lo.

packages/perspective/src/bake-spec.ts:72

measureThresholdAsync function

async function measureThresholdAsync(error: (px: number) => Promise<number>, tol: number, lo = 0.25, hi = 2048, steps = 14): Promise<number>

measureThreshold for an error that is measured by rendering, which is asynchronous.

packages/perspective/src/bake-spec.ts:84

measureThresholds function

async function measureThresholds(inp: MeasureInput): Promise<MeasuredThresholds>

Measures all the thresholds of a model. The levels the model does not have (no loadMesh) come out absent.

packages/perspective/src/measure.ts:151

octaDecode function

function octaDecode(u: number, v: number, mode: OctaMode): Point3

The inverse of octaEncode.

packages/perspective/src/octa.ts:19

octaEncode function

function octaEncode(d: Point3, mode: OctaMode): [number, number]

A direction (unit, from the object to the viewer) to a point of the unit square. The hemisphere takes y >= 0 only.

packages/perspective/src/octa.ts:8

openMeasureRig function

async function openMeasureRig(inp: MeasureInput): Promise<MeasureRig>

Opens the scene the measurement draws in: the model every way it has, over a sky, under fixed light.

packages/perspective/src/measure.ts:71

orderThresholds function

function orderThresholds(t: MeasuredThresholds): MeasuredThresholds

A cheaper level that takes over at a size not below the one before it adds nothing: the level after it is as good as it from there down. Going from the cheapest up, a level whose threshold does not exceed that of the cheaper level kept is dropped (the point, when the object is already invisible where the point stops being within the tolerance).

packages/perspective/src/thresholds.ts:13

packAtlas function

function packAtlas(a: PackedAtlas): Uint8Array

Writes: magic, u32 meta length, meta as JSON, then per map in the order of meta.options.maps: u32 length and the PNG bytes.

packages/perspective/src/atlas-file.ts:26

packBaked function

async function packBaked(a: BakedAtlas, note?: string): Promise<Uint8Array>

Encodes the maps as PNG and packs them with the meta into the bytes that are cached and shipped (atlas-file.ts).

packages/perspective/src/bake.ts:280

pointColor function

function pointColor(p: PointInstance, light: SceneLight, eye: Point3): Point3

The colour of a lit object seen from afar: its albedo times the light that falls on a surface turned at random (the ambient plus half the sun, which is the mean of max(N.L, 0) over the sphere of normals), plus the sun's glint off the object's up axis where it has one. Pure; light is the scene's.

packages/perspective/src/points.ts:107

poseEveryOf function

function poseEveryOf(l: PerspectiveLevel): number

packages/perspective/src/select.ts:29

projectedPx function

function projectedPx(s: Sphere, cam: CameraView): number

The size in pixels of a sphere on the render target of cam: the tangent of the half angle it subtends over the tangent of half the field of view, times the target's height (so a sphere that fills the view is heightPx); for an orthographic camera its diameter over the view's height. Inside the sphere, or at its surface, it fills the view: Infinity.

packages/perspective/src/projection.ts:66

resolveBake function

function resolveBake(o: ImpostorBakeOptions = {}): ResolvedBake

packages/perspective/src/bake-spec.ts:38

sceneLight function

function sceneLight(scene: BABYLON.Scene): SceneLight

Sums the enabled lights of the scene by kind. Linear colour times intensity, as Babylon's PBR takes them.

packages/perspective/src/points.ts:72

screenHeightPx function

function screenHeightPx(engine: { getRenderHeight(): number; getRenderingCanvas?(): { clientHeight?: number } | null }): number

The height of the screen in its own pixels (the canvas's CSS height times the device pixel ratio), not of the render target: a level of detail is chosen by how big a thing looks, and a lower render scale (the quality regulator's) must not turn far things into dots or drop parts sooner. Falls back to the render height where there is no canvas.

packages/perspective/src/projection.ts:38

skyOfBorder function

function skyOfBorder(img: Rgb): [number, number, number]

The colour of the picture's border (the median of the border pixels, per channel): the sky, when the object is not at the edge.

packages/perspective/src/compare.ts:32

unpackAtlas function

function unpackAtlas(bytes: Uint8Array): PackedAtlas

Reads what packAtlas wrote. A file of another bake version, or a damaged one, is an error that says which.

packages/perspective/src/atlas-file.ts:39

viewBlend function

function viewBlend(d: Point3, n: number, mode: OctaMode): ViewBlend

The three views to blend for a viewing direction, and their weights (a triangle of the grid cell that holds the direction).

packages/perspective/src/octa.ts:46

viewDirection function

function viewDirection(i: number, j: number, n: number, mode: OctaMode): Point3

The direction a view of the N x N grid was baked from: views sit on the grid points (i/(N-1), j/(N-1)), the edges included.

packages/perspective/src/octa.ts:34

viewRect function

function viewRect(b: ResolvedBake, i: number, j: number, frame = 0): { x: number; y: number; w: number; h: number }

Where a view lives in one map's atlas. A still atlas is views x views cells; a clip repeats that block once per frame, side by side.

packages/perspective/src/bake-spec.ts:53

Interfaces

AtlasMeta interface

interface AtlasMeta
version: number
options: ResolvedBake
radius: number
centre: Point3
width: number
height: number
frames: number
look: { color: Point3; fill: number }
note?: stringthe mean of what the colour map covers per view, for tests and the viewer: nothing reads it at run time

packages/perspective/src/atlas-file.ts:7

BabylonBackendOptions interface

interface BabylonBackendOptions
points?: booleandraw the point level (default true)
fogPower?: numberthe power of the fog factor of the points: 2.2 matches PBR meshes (default), 1 matches standard materials

packages/perspective/src/view.ts:165

BakeAnimation interface

interface BakeAnimation

An animated bake: pose(f) puts the model in frame f of its loop (0..frames-1) before that frame's views are drawn.

frames: number
pose(frame: number): void | Promise<void>

packages/perspective/src/bake.ts:247

BakedAtlas interface

interface BakedAtlas

Three maps of RGBA bytes, width x height, rows from the top. color: unlit base colour (sRGB bytes) + coverage; normal: view-space normal x and y * 0.5 + 0.5, and the depth across the sphere (0 near, 1 far) in blue; orm: occlusion, roughness, metallic.

options: ResolvedBake
radius: numberthe bounding sphere radius the views were framed with, metres
centre: Point3the bounding sphere's centre in the root's frame
width: number
height: number
frames: number
maps: Partial<Record<BakeMap, Uint8Array>>
look: { color: Point3; fill: number }mean linear albedo of what the views cover, and the share of the bounding disc they cover (averaged over the views)

packages/perspective/src/bake.ts:13

BlurError interface

interface BlurError
err: numberthe sum of the absolute differences of the blurred luminances over the sum of how far the first one is from the sky: 0 the same, 1 as much as a missing object
massRatio: numberthe blurred "mass" (the sum of the distance from the sky) of the second over the first: 1 is the same brightness overall
shift: numberthe distance in pixels between the two centres of mass
contrast: numberthe first image's mass in units of the sky's own luminance: the size of the object's contrast, whatever it looks like (the absolute measure the "none" level is cut by)

packages/perspective/src/compare.ts:41

BudgetLimits interface

interface BudgetLimits
maxFull?: number
maxMesh?: number

packages/perspective/src/select.ts:52

CameraView interface

interface CameraView

What the rule needs to know about one camera that renders the scene this frame.

position: Point3
fovY: numbervertical field of view, radians (perspective)
heightPx: numberheight of the render target in pixels, render scale included
orthoHeight?: numberorthographic cameras: the height of the view in world units (then fovY is ignored)
forward?: Point3where the camera looks (a unit vector) and the width over the height of its target: with them inView can tell what is in the frame
aspect?: number

packages/perspective/src/projection.ts:7

Candidate interface

interface Candidate
id: string
px: number
ladder: readonly PerspectiveLevel[]
want: number

packages/perspective/src/select.ts:54

CoherentGroup interface

interface CoherentGroup
kind: string
members: number[]the members, as indexes into the items given
px: numberscreen size of the largest member, pixels
level: number

packages/perspective/src/coherence.ts:41

CoherentItem interface

interface CoherentItem
id: string
kind: stringwhat is compared with what: a model id, 'tommy', 'lifeboat'. Items of different kinds never group or snap together
centre: Point3
radius: number
ladder: readonly PerspectiveLevel[]
current: numberthe level shown now, -1 before the first choice

packages/perspective/src/coherence.ts:21

CoherentResult interface

interface CoherentResult
levelAt: Int16Arraythe level of item i (in the order of items); valid until the next call with the same state
pxAt: Float64Arraythe screen size of item i, pixels; valid until the next call with the same state
groups: CoherentGroup[]the groups in the frame (a thing out of the frame stands alone and is not listed)

packages/perspective/src/coherence.ts:68

Fade interface

interface Fade

A cross-fade between two rungs. mix goes 0 to 1: from fades out and to fades in (a dither in screen space).

from: number
to: number
mix: number

packages/perspective/src/select.ts:50

GovernorConfig interface

interface GovernorConfig
budgetMs: numberthe frame time that is too long, ms
window?: numberframes in a window (default 60)
down?: numberwindows over budget in a row before the thresholds go up (default 2), windows well under it before they come back (default 4)
up?: number
maxScale?: numberthe largest scale (default 4) and the step ratio (default 1.25)
step?: number

packages/perspective/src/select.ts:79

ImpostorBakeOptions interface

interface ImpostorBakeOptions
views?: numberviews per side of the octahedral grid (default 12)
cell?: numberpixels per view side (default 128)
mode?: OctaModea model that stays upright is baked over the upper hemisphere only (default 'sphere')
hide?: string[]node names left out of the bake (a spinning propeller)
replace?: Record<string, string>node name -> node name of a substitute drawn in its place (the propeller disc)
radius?: numberbounding sphere radius, metres; default: from the model
maps?: BakeMap[]maps baked (default all three)
clips?: Record<string, number>frames per looping clip for animated impostors: clip name -> frames. Empty: a still impostor
flat?: booleandrawn as flat pictures: the nearest views' pictures blended on the billboard, no depth march (for people and animals, which have no thin parts to find: no holes, a third of the cost)

packages/perspective/src/bake-spec.ts:11

ImpostorResult interface

interface ImpostorResult
set: ImpostorSet
meta: AtlasMeta
fromCache: boolean
key: string | null

packages/perspective/src/view.ts:163

ImpostorSource interface

interface ImpostorSource

Where an impostor's atlas comes from: bytes already packed (a library asset, a .ferret package), or the model to bake.

bytes?: Uint8Arraypacked atlas bytes (atlas-file.ts): used as they are
root?: BABYLON.TransformNodethe loaded model to bake when there are no bytes (or the cache has none)
options?: ImpostorBakeOptions
modelKey?: stringa string that names this model and its content (the file's url and hash): with the options it is the cache key, and entities of the same model share one atlas
cache?: CacheBackendthe persistent cache (@ferret/assets): read before baking, written after
anim?: BakeAnimationan animated impostor: the frames of the looping clip and how to pose the model in each (the frame count is part of the cache key)
node?: BABYLON.TransformNodethe node the impostor follows (default: the entity's): a node placed where the model's own frame is, when the atlas was baked in that frame (a library atlas) and the entity's node holds the model turned or moved

packages/perspective/src/view.ts:146

KindRule interface

interface KindRule
link?: numbermetres: two things of the kind closer than this belong to one group (0: no groups, each thing alone)
gap?: numberthe ratio of screen size around a threshold within which its boundary looks for the largest gap (default 1.4)
margin?: numberthe hysteresis of a lone group's level, as a share of the threshold (default 0.1)

packages/perspective/src/coherence.ts:32

LadderModel interface

interface LadderModel

What the ladder needs of a resolved model (ResolvedModel.model of @ferret/assets is one).

id?: string
levels?: { file: string; maxTier?: ModelTier; thresholds?: { px: number; tolerance: number } }[]
impostors?: Record<string, { thresholds?: { impostor?: number; point?: number; none?: number; tolerance: number } } | null>

packages/perspective/src/model-ladder.ts:8

MeasuredError interface

interface MeasuredError
rel: numberblurError.err: relative to the full image
contrast: numberthe full image's contrast, in pixels of sky brightness
judged: numberwhat the measurement is judged by: rel weighted by how visible the object is (an object too faint to see cannot be wrong in a way anyone sees); for 'none' the contrast of the full image itself, the size of what is left out
massRatio: numberthe blurred mass of the picture over the full one's, and the distance between the two centres of mass, px (means over the directions)
shift: number
perDirection: number[]rel of each direction, in the order of the directions

packages/perspective/src/measure.ts:47

MeasuredThresholds interface

interface MeasuredThresholds
mesh?: number
impostor?: number
point?: number
none?: number
tolerance: number

packages/perspective/src/thresholds.ts:6

MeasureInput interface

interface MeasureInput
engine: BABYLON.AbstractEngine
loadFull(scene: BABYLON.Scene): Promise<BABYLON.TransformNode>a fresh copy of the model's full mesh and of its simpler mesh, in the scene given (the simpler may be absent: then there is no mesh level)
loadMesh?(scene: BABYLON.Scene): Promise<BABYLON.TransformNode>
atlas: Uint8Arraythe packed atlas of the model (atlas-file.ts)
tolerance?: numberthe error a cheaper level may have against the richer image (default 0.05); the none level takes it as an absolute contrast, in pixels of sky brightness
directions?: Array<[number, number] | [number, number, number]>viewing directions: [yaw, pitch] of the model, or [x, y, z] of the direction from the model to the eye in the model's own frame (default eight spread over the sphere)
lights?: { hemi: number; sun: number }the strength of the two lights (default hemispheric 0.55, sun 1.0)
maxPx?: numberthe biggest size measured, px (default 300: the object must fit the window)
onImage?(label: string, dataUrl: string): voidcalled with each rendered picture (a data URL), for looking at what is compared
onCurve?(level: 'mesh' | 'impostor' | 'point' | 'none', samples: Array<[number, number]>): void

packages/perspective/src/measure.ts:14

MeasureRig interface

interface MeasureRig
hasMesh: booleanis there a simpler mesh to measure
shoot(v: Variant, dir: readonly number[], px: number): Promise<Rgb>
error(v: Exclude<Variant, 'full'>, px: number): Promise<MeasuredError>the mean over the directions of how far variant v is from the full model at size px
dispose(): void

packages/perspective/src/measure.ts:61

ModelLadderOptions interface

interface ModelLadderOptions
tier?: ModelTierthe device tier: which levels may be loaded (default desktop)
impostor?: stringthe impostor the far rungs use (default default); none when the model has none of that name

packages/perspective/src/model-ladder.ts:22

ModelRung interface

interface ModelRung extends PerspectiveLevel

A rung of a model's ladder: which level of the model it draws, or which impostor.

level?: numberthe model's level index (the rungs of kind full and mesh)
impostor?: stringthe impostor's name (the rung of kind impostor)

packages/perspective/src/model-ladder.ts:15

PackedAtlas interface

interface PackedAtlas

A packed atlas: the meta and, per map, the PNG bytes.

meta: AtlasMeta
png: Partial<Record<BakeMap, Uint8Array>>

packages/perspective/src/atlas-file.ts:21

PartCullOptions interface

interface PartCullOptions

Small parts of a model are not drawn when they are smaller than a few pixels.

A glTF model of a boat or a gun is dozens of primitives (rails, fittings, gear, detail), each its own draw call however many instances of the model there are. At a few hundred metres every one of them is a speck, and Babylon still submits it. Here each source mesh of a model gets Babylon's own level of detail with nothing as its far level (addLODLevel(distance, null)), the distance being where the part's bounding sphere covers minPx pixels: Babylon then drops it before it evaluates the mesh (instances use their source's levels, each by its own distance).

The distance depends on the field of view and the height of the render target, so it is set again when either moves by more than a twentieth. A part that is skinned, has thin instances or is not a plain mesh is left alone.

minPx?: numbera part smaller than this many pixels is not drawn (default 2)
heightPx?: () => numberthe height of the render target in pixels (default: the engine's render height)
fov?: () => numberthe vertical field of view, rad (default: the active camera's)

packages/perspective/src/parts.ts:15

PerspectiveBackend interface

interface PerspectiveBackend
cameras(): CameraView[]the cameras that render this frame
sphereOf(entity: Entity): Spherethe bounding sphere of an entity in world space
apply(entity: Entity, ladder: readonly PerspectiveLevel[], fade: Fade): voidshow the rungs of fade (from fading out, to fading in) for an entity; mix is 1 when the change is over and only to is drawn
points(list: readonly PointInstance[]): voidthe entities at the point level this frame, in one batch (one draw call)
frame?(entity: Entity, frame: number): voidshow frame frame of an animated impostor of the entity
upOf?(entity: Entity): Point3the entity's up axis in the world, for the glint of a point
frameMs?(): number | undefinedthe real time of the last frame, ms, if the backend can measure it
debug?(on: boolean): voidtint every level a colour (debug)
dispose?(): void

packages/perspective/src/backend.ts:26

PerspectiveLevel interface

interface PerspectiveLevel

One rung of an entity's ladder. The ladder is ordered richest first; a rung is used from minPx up.

kind: LevelKind
name?: stringa name the backend knows it by: the mesh lod1, the impostor atlas ...
minPx: numberused when the projected size is at least this many pixels
poseEvery?: numberthe bones are posed every poseEvery frames (1: every frame); 0: never. Default: 1 at full and mesh, 0 below

packages/perspective/src/select.ts:7

PerspectiveOptions interface

interface PerspectiveOptions
backend: PerspectiveBackend
tierScale?: numbera multiplier of every threshold from the quality tier (default 1); set again with setTierScale
budget?: BudgetLimits
governor?: GovernorConfigthe frame-time governor; without it the thresholds only move with the tier
coherent?: booleancoherent detail: groups and peers drawn alike (default true; false chooses each entity alone, as before)

packages/perspective/src/service.ts:11

PerspectiveParams interface

interface PerspectiveParams
ladder: PerspectiveLevel[]the rungs, richest first (see PerspectiveLevel); the last must have minPx 0
fade?: numberseconds of the cross-fade between two rungs (default 0.25); 0 switches at once
margin?: numberthe ratio by which a size must pass a threshold to cross it (default 0.1)
radius?: numberbounding sphere radius override, metres; default: what the backend measures
color?: [number, number, number]the mean albedo drawn for the object at the point level, linear rgb (default a mid grey)
glint?: numberthe sun's glint on the object at the point level, 0..1 (default 0)
loop?: { duration: number; frames: number }an animated impostor: the looping clip's length in seconds and the frames baked of it. The frame shown is picked from clock (default: the service's own time)
clock?: () => numberthe time in seconds of the clip's loop for this entity (e.g. its Animator's clock); default the service's time, so objects without one all walk in step
fill?: numberthe share of the bounding sphere's disc that the object's silhouette fills, averaged over the directions (0..1, default 1); the bake measures it. The point level draws a disc of the object's own area, not of its bounding sphere's
coherence?: { kind?: string; link?: number; gap?: number }Coherent detail: kind names what this is compared with (things of one kind at about one distance are drawn alike; default: the things with the same ladder), link the metres within which things of the kind stand together as one group with one level (default 0: alone).

packages/perspective/src/component.ts:6

PointInstance interface

interface PointInstance

One thing drawn as a point this frame.

id: string
position: Point3
coverage: numberthe share of its pixel the object covers, 0..1 (below one pixel: the squared size)
px: numberthe diameter in pixels of the disc that has the object's own area (its size times the root of its fill)
alpha: numberthe fade of the point in or out, 0..1
color?: Point3the mean albedo of the object, linear rgb 0..1 (default a mid grey)
glint?: numberhow strongly the sun glints off it, 0..1 (0: never); the flash is strongest when the half vector of the sun and the eye lies along up
up?: Point3the object's up axis in the world, for the glint

packages/perspective/src/backend.ts:9

Representation interface

interface Representation

Something a rung draws. Meshes implement it here; the impostor implements it in impostor.ts.

setState(state: RepState, mix: number): void
setFrame?(f: number): voidan animated impostor: show frame f of the baked loop (a still atlas ignores it)
tint?(color: BABYLON.Color3 | null): voiddebug: tint the representation (null: remove the tint)

packages/perspective/src/view.ts:20

ResolvedBake interface

interface ResolvedBake
views: number
cell: number
mode: OctaMode
hide: string[]
replace: Record<string, string>
radius?: number
maps: BakeMap[]
clips: Record<string, number>
flat?: boolean

packages/perspective/src/bake-spec.ts:32

Rgb interface

interface Rgb

RGB bytes of a w x h image, three per pixel.

data: ArrayLike<number>
width: number
height: number

packages/perspective/src/compare.ts:6

SceneLight interface

interface SceneLight

The scene's light as the impostor and point shaders take it: the hemispheric light as an up and a down colour (mixed by the normal), the directional lights summed as one sun.

ambient: Point3the mean of up and down: what a surface of any orientation gets
ambientUp: Point3
ambientDown: Point3
sun: Point3
toSun: Point3

packages/perspective/src/points.ts:62

Sphere interface

interface Sphere

A bounding sphere in world space.

centre: Point3
radius: number

packages/perspective/src/projection.ts:57

ViewBlend interface

interface ViewBlend
views: [[number, number], [number, number], [number, number]]three views of the grid, each [i, j]
weights: [number, number, number]their weights; they sum to 1

packages/perspective/src/octa.ts:38

Types

BakeMap type

type BakeMap = 'color' | 'normal' | 'orm'

packages/perspective/src/bake-spec.ts:9

LevelKind type

type LevelKind = 'full' | 'mesh' | 'impostor' | 'point' | 'none'

packages/perspective/src/select.ts:4

OctaMode type

type OctaMode = 'sphere' | 'hemisphere'

packages/perspective/src/octa.ts:5

Point3 type

type Point3 = [number, number, number]

packages/perspective/src/projection.ts:4

Recorded type

type Recorded = | { call: 'apply'; id: string; from: number; to: number; mix: number } | { call: 'points'; ids: string[] }

What a backend call was, for tests.

packages/perspective/src/backend.ts:47

RepState type

type RepState = 'off' | 'on' | 'in' | 'out'

How a rung is shown: fully (on), fading in, fading out (with the mix 0..1 of the cross-fade), or not at all.

packages/perspective/src/view.ts:17

Variant type

type Variant = 'full' | 'mesh' | 'impostor' | 'point' | 'none'

packages/perspective/src/measure.ts:42

Constants

AMBIENT_SCALE const

const AMBIENT_SCALE: 1

What a Babylon PBR surface (no environment map) returns of the light it gets, measured on a flat plate of known albedo under each light alone (tools/perspective/check, calibration of 2026-11-10): the hemispheric light comes back whole (albedo x light), the directional light as albedo x light x cos / 3 (the Lambert 1/pi, 0.347 measured); the two add.

packages/perspective/src/points.ts:100

BAKE_VERSION const

const BAKE_VERSION: 2

Bumped when the bake or the atlas format changes: older atlases are then baked again.

packages/perspective/src/bake-spec.ts:7

SUN_SCALE const

const SUN_SCALE: 0.347

packages/perspective/src/points.ts:101

VISIBLE_CONTRAST const

const VISIBLE_CONTRAST: 4

How visible an object has to be for an error in it to count: the object's contrast, in pixels of sky brightness (a black object of 4 px of area has 4).

packages/perspective/src/measure.ts:45