# @ferret/perspective: API

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. Generated from the source (`packages/perspective/src`), so it matches the code.

## Classes

### BabylonBackend

*class* · `packages/perspective/src/view.ts:172`

```ts
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): Representation` — Gives 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): LazyMeshRepresentation` — A 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): void` — The 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): Sphere` — the bounding sphere of an entity in world space
- `frame(entity: Entity, frame: number): void` — show frame `frame` of an animated impostor of the entity
- `upOf(entity: Entity): Point3` — the entity's up axis in the world, for the glint of a point
- `apply(entity: Entity, ladder: readonly PerspectiveLevel[], f: Fade): void` — show 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[]): void` — the entities at the point level this frame, in one batch (one draw call)
- `frameMs(): number` — the real time of the last frame, ms, if the backend can measure it
- `debug(on: boolean): void` — tint every level a colour (debug)
- `dispose(): void`

### CoherenceState

*class* · `packages/perspective/src/coherence.ts:51`

```ts
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): void` — buffers for `n` items
- `list(): number[]` — an empty list from the pool (all given back by `reset`)
- `reset(): void`

### FrameGovernor

*class* · `packages/perspective/src/select.ts:93`

```ts
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 | undefined` — Records a frame; returns the new scale when it changed.

### ImpostorSet

*class* · `packages/perspective/src/impostor.ts:224`

```ts
class ImpostorSet
```

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

- `readonly mesh: BABYLON.Mesh`
- `readonly material: BABYLON.ShaderMaterial`
- `domHit: boolean` — a hit by the nearest view alone counts (thin parts survive); on by default after measurement
- `coverMin: number`
- `surfaceEps: number` — how 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: number` — how 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: number` — the strength of the hemispheric light's specular lobe (1: as Babylon's PBR) (read when a set is made)
- `fogPower: number` — the 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(): boolean` — Is every texture loaded (a mesh that uses them draws nothing before).
- `add(node: BABYLON.TransformNode): Representation`
- `get active(): number` — Instances shown now.
- `dispose(): void`

### LazyMeshRepresentation

*class* · `packages/perspective/src/view.ts:100`

```ts
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: number` — how 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): void` — debug: tint the representation (null: remove the tint)

### MeshRepresentation

*class* · `packages/perspective/src/view.ts:65`

```ts
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): void` — debug: tint the representation (null: remove the tint)

### PartCuller

*class* · `packages/perspective/src/parts.ts:26`

```ts
class PartCuller
```

- `get count(): number` — parts that carry a far level now
- `minPx: number`
- `constructor(private scene: BABYLON.Scene, private o: PartCullOptions = {})`
- `add(root: BABYLON.Node): number` — Give 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): void` — set 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').QualityKnob` — The 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(): void` — take the levels off again and stop following the view

### Perspective

*class* · `packages/perspective/src/component.ts:37`

```ts
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: number` — the rung shown now (the one fading in while a fade runs)
- `fadeFrom: number` — the rung fading out, or -1 when no fade runs
- `mix: number` — 0..1 while a fade runs
- `px: number` — the size in pixels, last frame
- `forced: number` — a rung held by `perspective.force`, or -1
- `phase: number` — frames since the service counted this entity, for `poseEvery`
- `animateNow: boolean` — set by the service: true when this frame should pose the bones / refresh the presentation at this entity's rate
- `gated: boolean` — the service has hooked this entity's Animator
- `get level(): PerspectiveLevel`
- `onAttach()`
- `onDetach()`

### PerspectiveService

*class* · `packages/perspective/src/service.ts:29`

```ts
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: boolean` — coherent detail on (the constructor's `coherent`, `?coherent=0` in a game turns it off)
- `constructor(private readonly o: PerspectiveOptions)`
- `get backend(): PerspectiveBackend`
- `get scale(): number` — the 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): boolean` — True 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): void` — Called once per rendered frame.
- `dispose(): void`

### PointsPass

*class* · `packages/perspective/src/points.ts:122`

```ts
class PointsPass
```

- `readonly mesh: BABYLON.Mesh`
- `readonly material: BABYLON.ShaderMaterial`
- `drawn: number`
- `fogPower: number` — the 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(): SceneLight` — The light the scene gives a surface, as the point colour needs it.
- `update(list: readonly PointInstance[], eye: Point3, viewport: [number, number]): void` — Draws these points this frame (an empty list hides the pass).
- `dispose(): void`

### RecordingBackend

*class* · `packages/perspective/src/backend.ts:52`

```ts
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): Sphere` — the bounding sphere of an entity in world space
- `apply(e: Entity, _l: readonly PerspectiveLevel[], f: Fade): void` — show 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[]): void` — the entities at the point level this frame, in one batch (one draw call)
- `frame(e: Entity, frame: number): void` — show frame `frame` of an animated impostor of the entity
- `frameMs(): number | undefined` — the real time of the last frame, ms, if the backend can measure it
- `debug(on: boolean): void` — tint every level a colour (debug)

## Functions

### applyBudget

*function* · `packages/perspective/src/select.ts:60`

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

### atlasSize

*function* · `packages/perspective/src/bake-spec.ts:57`

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

### bakeImpostor

*function* · `packages/perspective/src/bake.ts:95`

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

### bakeKey

*function* · `packages/perspective/src/bake-spec.ts:60`

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

### blurError

*function* · `packages/perspective/src/compare.ts:56`

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

### checkLadder

*function* · `packages/perspective/src/select.ts:17`

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

### chooseLevel

*function* · `packages/perspective/src/select.ts:36`

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

### clipFrame

*function* · `packages/perspective/src/octa.ts:56`

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

### coherentLevels

*function* · `packages/perspective/src/coherence.ts:84`

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

### decodePng

*function* · `packages/perspective/src/png.ts:34`

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

### dilate

*function* · `packages/perspective/src/bake.ts:250`

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

### distance

*function* · `packages/perspective/src/projection.ts:59`

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

### distanceForPx

*function* · `packages/perspective/src/projection.ts:81`

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

### encodePng

*function* · `packages/perspective/src/png.ts:12`

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

### firstLevel

*function* · `packages/perspective/src/select.ts:44`

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

The rung with no hysteresis, for a first choice.

### inView

*function* · `packages/perspective/src/projection.ts:24`

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

### ladderFromThresholds

*function* · `packages/perspective/src/thresholds.ts:29`

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

### ladderOfModel

*function* · `packages/perspective/src/model-ladder.ts:34`

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

### largestPx

*function* · `packages/perspective/src/projection.ts:74`

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

### luminance

*function* · `packages/perspective/src/compare.ts:10`

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

relative luminance of an sRGB byte triple, as linear light

### measureThreshold

*function* · `packages/perspective/src/bake-spec.ts:72`

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

### measureThresholdAsync

*function* · `packages/perspective/src/bake-spec.ts:84`

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

### measureThresholds

*function* · `packages/perspective/src/measure.ts:151`

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

### octaDecode

*function* · `packages/perspective/src/octa.ts:19`

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

The inverse of `octaEncode`.

### octaEncode

*function* · `packages/perspective/src/octa.ts:8`

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

### openMeasureRig

*function* · `packages/perspective/src/measure.ts:71`

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

### orderThresholds

*function* · `packages/perspective/src/thresholds.ts:13`

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

### packAtlas

*function* · `packages/perspective/src/atlas-file.ts:26`

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

### packBaked

*function* · `packages/perspective/src/bake.ts:280`

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

### pointColor

*function* · `packages/perspective/src/points.ts:107`

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

### poseEveryOf

*function* · `packages/perspective/src/select.ts:29`

```ts
function poseEveryOf(l: PerspectiveLevel): number
```

### projectedPx

*function* · `packages/perspective/src/projection.ts:66`

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

### resolveBake

*function* · `packages/perspective/src/bake-spec.ts:38`

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

### sceneLight

*function* · `packages/perspective/src/points.ts:72`

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

### screenHeightPx

*function* · `packages/perspective/src/projection.ts:38`

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

### skyOfBorder

*function* · `packages/perspective/src/compare.ts:32`

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

### unpackAtlas

*function* · `packages/perspective/src/atlas-file.ts:39`

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

### viewBlend

*function* · `packages/perspective/src/octa.ts:46`

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

### viewDirection

*function* · `packages/perspective/src/octa.ts:34`

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

### viewRect

*function* · `packages/perspective/src/bake-spec.ts:53`

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

## Interfaces

### AtlasMeta

*interface* · `packages/perspective/src/atlas-file.ts:7`

```ts
interface AtlasMeta
```

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

### BabylonBackendOptions

*interface* · `packages/perspective/src/view.ts:165`

```ts
interface BabylonBackendOptions
```

- `points?: boolean` — draw the point level (default true)
- `fogPower?: number` — the power of the fog factor of the points: 2.2 matches PBR meshes (default), 1 matches standard materials

### BakeAnimation

*interface* · `packages/perspective/src/bake.ts:247`

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

### BakedAtlas

*interface* · `packages/perspective/src/bake.ts:13`

```ts
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: number` — the bounding sphere radius the views were framed with, metres
- `centre: Point3` — the 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)

### BlurError

*interface* · `packages/perspective/src/compare.ts:41`

```ts
interface BlurError
```

- `err: number` — the 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: number` — the blurred "mass" (the sum of the distance from the sky) of the second over the first: 1 is the same brightness overall
- `shift: number` — the distance in pixels between the two centres of mass
- `contrast: number` — the 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)

### BudgetLimits

*interface* · `packages/perspective/src/select.ts:52`

```ts
interface BudgetLimits
```

- `maxFull?: number`
- `maxMesh?: number`

### CameraView

*interface* · `packages/perspective/src/projection.ts:7`

```ts
interface CameraView
```

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

- `position: Point3`
- `fovY: number` — vertical field of view, radians (perspective)
- `heightPx: number` — height of the render target in pixels, render scale included
- `orthoHeight?: number` — orthographic cameras: the height of the view in world units (then `fovY` is ignored)
- `forward?: Point3` — where 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`

### Candidate

*interface* · `packages/perspective/src/select.ts:54`

```ts
interface Candidate
```

- `id: string`
- `px: number`
- `ladder: readonly PerspectiveLevel[]`
- `want: number`

### CoherentGroup

*interface* · `packages/perspective/src/coherence.ts:41`

```ts
interface CoherentGroup
```

- `kind: string`
- `members: number[]` — the members, as indexes into the `items` given
- `px: number` — screen size of the largest member, pixels
- `level: number`

### CoherentItem

*interface* · `packages/perspective/src/coherence.ts:21`

```ts
interface CoherentItem
```

- `id: string`
- `kind: string` — what 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: number` — the level shown now, -1 before the first choice

### CoherentResult

*interface* · `packages/perspective/src/coherence.ts:68`

```ts
interface CoherentResult
```

- `levelAt: Int16Array` — the level of item `i` (in the order of `items`); valid until the next call with the same state
- `pxAt: Float64Array` — the 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)

### Fade

*interface* · `packages/perspective/src/select.ts:50`

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

### GovernorConfig

*interface* · `packages/perspective/src/select.ts:79`

```ts
interface GovernorConfig
```

- `budgetMs: number` — the frame time that is too long, ms
- `window?: number` — frames in a window (default 60)
- `down?: number` — windows 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?: number` — the largest scale (default 4) and the step ratio (default 1.25)
- `step?: number`

### ImpostorBakeOptions

*interface* · `packages/perspective/src/bake-spec.ts:11`

```ts
interface ImpostorBakeOptions
```

- `views?: number` — views per side of the octahedral grid (default 12)
- `cell?: number` — pixels per view side (default 128)
- `mode?: OctaMode` — a 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?: number` — bounding 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?: boolean` — drawn 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)

### ImpostorResult

*interface* · `packages/perspective/src/view.ts:163`

```ts
interface ImpostorResult
```

- `set: ImpostorSet`
- `meta: AtlasMeta`
- `fromCache: boolean`
- `key: string | null`

### ImpostorSource

*interface* · `packages/perspective/src/view.ts:146`

```ts
interface ImpostorSource
```

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

- `bytes?: Uint8Array` — packed atlas bytes (atlas-file.ts): used as they are
- `root?: BABYLON.TransformNode` — the loaded model to bake when there are no bytes (or the cache has none)
- `options?: ImpostorBakeOptions`
- `modelKey?: string` — a 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?: CacheBackend` — the persistent cache (@ferret/assets): read before baking, written after
- `anim?: BakeAnimation` — an 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.TransformNode` — the 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

### KindRule

*interface* · `packages/perspective/src/coherence.ts:32`

```ts
interface KindRule
```

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

### LadderModel

*interface* · `packages/perspective/src/model-ladder.ts:8`

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

### MeasuredError

*interface* · `packages/perspective/src/measure.ts:47`

```ts
interface MeasuredError
```

- `rel: number` — blurError.err: relative to the full image
- `contrast: number` — the full image's contrast, in pixels of sky brightness
- `judged: number` — what 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: number` — the 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

### MeasuredThresholds

*interface* · `packages/perspective/src/thresholds.ts:6`

```ts
interface MeasuredThresholds
```

- `mesh?: number`
- `impostor?: number`
- `point?: number`
- `none?: number`
- `tolerance: number`

### MeasureInput

*interface* · `packages/perspective/src/measure.ts:14`

```ts
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: Uint8Array` — the packed atlas of the model (atlas-file.ts)
- `tolerance?: number` — the 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?: number` — the biggest size measured, px (default 300: the object must fit the window)
- `onImage?(label: string, dataUrl: string): void` — called with each rendered picture (a data URL), for looking at what is compared
- `onCurve?(level: 'mesh' | 'impostor' | 'point' | 'none', samples: Array<[number, number]>): void`

### MeasureRig

*interface* · `packages/perspective/src/measure.ts:61`

```ts
interface MeasureRig
```

- `hasMesh: boolean` — is 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`

### ModelLadderOptions

*interface* · `packages/perspective/src/model-ladder.ts:22`

```ts
interface ModelLadderOptions
```

- `tier?: ModelTier` — the device tier: which levels may be loaded (default desktop)
- `impostor?: string` — the impostor the far rungs use (default `default`); none when the model has none of that name

### ModelRung

*interface* · `packages/perspective/src/model-ladder.ts:15`

```ts
interface ModelRung extends PerspectiveLevel
```

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

- `level?: number` — the model's level index (the rungs of kind `full` and `mesh`)
- `impostor?: string` — the impostor's name (the rung of kind `impostor`)

### PackedAtlas

*interface* · `packages/perspective/src/atlas-file.ts:21`

```ts
interface PackedAtlas
```

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

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

### PartCullOptions

*interface* · `packages/perspective/src/parts.ts:15`

```ts
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?: number` — a part smaller than this many pixels is not drawn (default 2)
- `heightPx?: () => number` — the height of the render target in pixels (default: the engine's render height)
- `fov?: () => number` — the vertical field of view, rad (default: the active camera's)

### PerspectiveBackend

*interface* · `packages/perspective/src/backend.ts:26`

```ts
interface PerspectiveBackend
```

- `cameras(): CameraView[]` — the cameras that render this frame
- `sphereOf(entity: Entity): Sphere` — the bounding sphere of an entity in world space
- `apply(entity: Entity, ladder: readonly PerspectiveLevel[], fade: Fade): void` — show 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[]): void` — the entities at the point level this frame, in one batch (one draw call)
- `frame?(entity: Entity, frame: number): void` — show frame `frame` of an animated impostor of the entity
- `upOf?(entity: Entity): Point3` — the entity's up axis in the world, for the glint of a point
- `frameMs?(): number | undefined` — the real time of the last frame, ms, if the backend can measure it
- `debug?(on: boolean): void` — tint every level a colour (debug)
- `dispose?(): void`

### PerspectiveLevel

*interface* · `packages/perspective/src/select.ts:7`

```ts
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?: string` — a name the backend knows it by: the mesh `lod1`, the impostor atlas ...
- `minPx: number` — used when the projected size is at least this many pixels
- `poseEvery?: number` — the bones are posed every `poseEvery` frames (1: every frame); 0: never. Default: 1 at full and mesh, 0 below

### PerspectiveOptions

*interface* · `packages/perspective/src/service.ts:11`

```ts
interface PerspectiveOptions
```

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

### PerspectiveParams

*interface* · `packages/perspective/src/component.ts:6`

```ts
interface PerspectiveParams
```

- `ladder: PerspectiveLevel[]` — the rungs, richest first (see `PerspectiveLevel`); the last must have minPx 0
- `fade?: number` — seconds of the cross-fade between two rungs (default 0.25); 0 switches at once
- `margin?: number` — the ratio by which a size must pass a threshold to cross it (default 0.1)
- `radius?: number` — bounding 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?: number` — the 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?: () => number` — the 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?: number` — the 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).

### PointInstance

*interface* · `packages/perspective/src/backend.ts:9`

```ts
interface PointInstance
```

One thing drawn as a point this frame.

- `id: string`
- `position: Point3`
- `coverage: number` — the share of its pixel the object covers, 0..1 (below one pixel: the squared size)
- `px: number` — the diameter in pixels of the disc that has the object's own area (its size times the root of its `fill`)
- `alpha: number` — the fade of the point in or out, 0..1
- `color?: Point3` — the mean albedo of the object, linear rgb 0..1 (default a mid grey)
- `glint?: number` — how 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?: Point3` — the object's up axis in the world, for the glint

