FERRETGame engine over Babylon.js
Ferret

@ferret/view

Presentation views of a scene: section (cutaway) planes cut meshes on the GPU, with hatched caps on the cut faces; camera limits: keep off things, stay in a region, over a floor.

27 exports · source in packages/view/src

Classes

CameraLimits class

class CameraLimits

A set of limits and the rule that resolves a move against them.

readonly limits: CameraLimit[]
readonly o: Required<CameraLimitsOptions>
last: LimitReport
constructor(limits: CameraLimit[] = [], o: CameraLimitsOptions = {})
add(l: CameraLimit): CameraLimit
remove(name: string): void
get(name: string): CameraLimit | undefined
enable(name: string, on: boolean): void
margin(l: CameraLimit, p: P3, reach = this.o.maxStep): { g: number; n: P3 }How far p is inside what a limit allows (>= 0 allowed) and the way back in (unit). A keepOff limit answers for its nearest shape; reach is how far from p a shape may be to count (the step being resolved).
allows(p: P3): booleanIs p allowed by every enabled limit?
resolve(from: P3, to: P3): P3Where a camera that is at from ends up when asked to go to to. The move is cut into steps of at most maxStep; in each step a limit the camera was clear of turns the step to slide along its boundary, and a limit the world has moved into lets the camera only away (or pushes it out, push).
jump(p: P3): P3The nearest allowed place to p (for a camera put somewhere by a script, a teleport, a cut): every limit pushes, whatever its intrusion.

packages/view/src/camera-limits.ts:107

RelevanceService class

class RelevanceService implements Service
readonly name: "relevance"
observedOmega: numberthe camera's peak turn rate, rad/s, observed (decays with a time constant of 8 s)
camVel: [number, number, number]the camera's velocity, m/s, differenced between frames
readonly counts: Record<RelClass, number>the things in each class at the last refresh
changed: numberhow many classes changed at the last refresh
constructor(readonly opts: RelevanceOptions)
init(world: World): void
get mode(): stringthe mode in force (a camera mode of the game: 'cockpit', 'chase', 'free'...)
set mode(name: string)the mode in force (a camera mode of the game: 'cockpit', 'chase', 'free'...)
setMode(name: string, cfg: ModeConfig): thisoverride a mode's values (the game's own): undefined keeps what is there, null-like clearing is clearMode
clearMode(name: string): this
configure(block: { modes?: Record<string, ModeConfig>; hold?: number; gonePx?: number }): thismany modes and the tuning, in the shape of the manifest's relevance block: { modes: { cockpit: { omega, horizon } }, hold?, gonePx? }
inUse(name = this.cur): ModeInUseomega and the horizon in force for a mode (the current one by default)
track(id: string, x = 0, y = 0, z = 0, r = 1): thisput a thing under watch (its class starts view, the finest, so nothing is coarse before it has been looked at)
untrack(id: string): void
set(id: string, x: number, y: number, z: number, r: number, vx = 0, vy = 0, vz = 0): voidthe thing's place and size now (and its velocity, m/s, which can only make it come into the frame sooner)
has(id: string): boolean
get size(): number
of(id: string): RelClassthe class of a tracked thing (view for one not tracked: unknown things are drawn fully)
tViewOf(id: string): number
atLeast(id: string, cls: RelClass): booleanat least as fine as cls: view is finer than soon...
each(cls: RelClass, fn: (id: string) => void): void
classify(x: number, y: number, z: number, r: number, v: readonly [number, number, number] = [0, 0, 0]): { cls: RelClass; tView: number; px: number }the class of a sphere now, with no state and no hold (for a module that keeps its own list)
refresh(dt: number): voidOnce per rendered frame, after the camera has moved and before the modules draw: read the camera, observe its turn rate and velocity, classify the tracked things. Idempotent within a frame (update, the service hook, calls it too).
update(dt: number): voidCalled once per rendered frame.
report(): { mode: ModeInUse; counts: Record<RelClass, number>; tracked: number; observedOmega: number; camVel: number; changed: number }
dispose(): void

packages/view/src/relevance.ts:84

SectionView class

class SectionView

A section (cutaway) view: meshes are cut by up to six planes in the material, on the GPU, and the cut faces are filled with a flat, hatched colour (the inside faces of a closed solid show through the cut, and they are drawn as the cap). Works with standard and PBR materials, instances and skinned meshes. The cut materials are copies, so a material shared with meshes that are not cut stays as it was; dispose() gives every mesh its own material back. Shadows and picking still see the whole mesh.

mode: 'any' | 'all'
capColor: [number, number, number] | null
hatch: number
worldPlanes: [number, number, number, number][]the current plane equations in world space (refreshed every frame when the planes follow a frame)
constructor(readonly scene: BABYLON.Scene, private readonly o: SectionOptions)
get active()
set active(on: boolean)
get meshes(): BABYLON.AbstractMesh[]The meshes now cut.
setPlanes(planes: SectionPlane[], mode?: 'any' | 'all')
isCut(p: V3): booleanWhether a world point is cut away now (for picking, labels, or placing things in the open part).
add(targets: (BABYLON.AbstractMesh | BABYLON.TransformNode)[])Cut more meshes (or every mesh under a node).
remove(meshes: BABYLON.AbstractMesh[])Stop cutting these meshes: they get their own material back.
dispose()

packages/view/src/section.ts:114

Functions

attachCameraLimits function

function attachCameraLimits(scene: BABYLON.Scene, camera: BABYLON.Camera, limits: CameraLimits): AttachedLimits

Applies the limits to a Babylon camera before each render: whatever moved the camera since the last frame, the move is resolved from where it was. A camera with a target (ArcRotate) is moved by setPosition, so its radius and angles follow.

packages/view/src/camera-limits.ts:216

camStateOf function

function camStateOf(camera: BABYLON.Camera, engine: { getRenderHeight(): number; getRenderWidth(): number }): CamState

the camera of a Babylon scene as the maths needs it (engine gives the viewport)

packages/view/src/relevance.ts:252

isCut function

function isCut(planes: [number, number, number, number][], mode: 'any' | 'all', p: V3): boolean

Whether a world point is cut away by these plane equations in this mode (the same test as the shader).

packages/view/src/section.ts:45

planeEquation function

function planeEquation(p: SectionPlane, frame?: BABYLON.Matrix): [number, number, number, number]

The plane equation (a, b, c, d) with a x + b y + c z + d > 0 on the side that is cut away.

packages/view/src/section.ts:35

shapeDistance function

function shapeDistance(s: LimitShape, p: P3): { d: number; n: P3 }

The signed distance from p to the shape's surface (negative inside) and the outward unit normal there.

packages/view/src/camera-limits.ts:62

shapeReach function

function shapeReach(s: LimitShape): number

how far a shape reaches from its centre (for asking a provider only for what is near)

packages/view/src/camera-limits.ts:97

viewTime function

function viewTime(cam: CamState, p: readonly [number, number, number], r: number, v: readonly [number, number, number], camV: readonly [number, number, number], omega: number): RelResult

Time to the frame of a sphere (p, radius r, velocity v) for a camera at cam that moves with camV and turns at most omega rad/s. Pure: no state, no hysteresis.

packages/view/src/relevance.ts:36

Interfaces

AttachedLimits interface

interface AttachedLimits

What attachCameraLimits gives back.

limits: CameraLimits
jump(p: P3): voidput the camera at p (out of every limit) and take that as its last allowed place: for scripted cuts and teleports
detach(): voidstop applying the limits

packages/view/src/camera-limits.ts:204

CameraLimitsOptions interface

interface CameraLimitsOptions
maxStep?: numberthe longest step a move is cut into, metres (default 1): smaller than the thinnest thing kept off plus its distance
passes?: numberpasses over the limits per step (default 4): a corner between two limits needs more than one

packages/view/src/camera-limits.ts:45

CamState interface

interface CamState

the camera as the maths needs it: place, the three axes (unit), vertical field of view (rad), aspect (width / height), height in pixels

pos: readonly [number, number, number]
fwd: readonly [number, number, number]
right: readonly [number, number, number]
up: readonly [number, number, number]
fov: number
aspect: number
heightPx: number

packages/view/src/relevance.ts:26

LimitReport interface

interface LimitReport

what the last move did: which limits stopped it, and how far the camera got of the way it was asked to go

blocked: string[]
asked: number
moved: number

packages/view/src/camera-limits.ts:53

ModeConfig interface

interface ModeConfig
omega?: numberthe largest turn rate of the camera in this mode, rad/s: given (a game's own value) it wins over what is observed
horizon?: numberthe horizon, s: given it wins over the half turn at omega
floorOmega?: numberthe floor of the turn rate when it is read from the camera, rad/s (the rig's own limit when it has one)

packages/view/src/relevance.ts:55

ModeInUse interface

interface ModeInUse

a mode's values in force and where they came from

mode: string
omega: number
horizon: number
omegaFrom: 'game' | 'camera'
horizonFrom: 'game' | 'omega'

packages/view/src/relevance.ts:82

RelevanceOptions interface

interface RelevanceOptions
camera: () => CamState | nullthe camera and the viewport, read once a frame
hold?: numberseconds a thing stays in a finer class before it may go to a coarser one (default 0.5)
gonePx?: numberbelow this many pixels a thing is gone (default 0.5)
perFrame?: numberat most this many tracked things are classified in a frame; the rest wait their turn (default 4000)
minHorizon?: numberthe horizon is the half turn at omega, between these (s; default 0.6 and 4)
maxHorizon?: number
defaultOmega?: numberthe floor of the observed turn rate for a mode that names none, rad/s (default 2.5, a half turn in 1.3 s)

packages/view/src/relevance.ts:64

RelResult interface

interface RelResult
tView: number
px: number
dist: number
excess: number

packages/view/src/relevance.ts:28

SectionOptions interface

interface SectionOptions
targets: (BABYLON.AbstractMesh | BABYLON.TransformNode)[]what is cut: these meshes, or every mesh under these nodes (a model's root)
exclude?: (mesh: BABYLON.AbstractMesh) => booleanmeshes under the targets that stay whole (a part shown in full inside a cut housing)
planes: SectionPlane[]1 to 6 planes
mode?: 'any' | 'all'any: cut away what is beyond any plane (a slice, a box); all: cut away only what is beyond every plane (one plane is a half cut; two planes take out a quarter, the classic cutaway). Default all.
frame?: BABYLON.TransformNodethe planes are in this node's frame and move with it (default: world space)
capColor?: [number, number, number] | nullcolour of the cut faces, linear RGB 0..1 (default a light grey); null leaves the inside faces as they are
hatch?: numberhatch of the cut faces: line spacing in pixels, 0 for none (default 8)
active?: booleanstart cutting at once (default true)

packages/view/src/section.ts:10

SectionPlane interface

interface SectionPlane

A cutting plane: through point, normal pointing to the side that is cut away.

point: V3
normal: V3

packages/view/src/section.ts:5

Types

CameraLimit type

type CameraLimit = LimitBase & ( /** keep at least `distance` metres off the shapes; `shapes` may be a function asked each step for the shapes near p (within `reach` of it) */ | { type: 'keepOff'; distance: number; shapes: LimitShape[] | ((p: P3, reach: number) => LimitShape[]) } /** stay inside the shape, `margin` metres from its boundary */ | { type: 'keepIn'; shape: LimitShape; margin?: number } /** stay at least `clearance` over `height(x, z)` (the ground, the sea, a deck: whatever is highest there) */ | { type: 'floor'; height: number | ((x: number, z: number) => number); clearance?: number } /** stay at least `clearance` under `height(x, z)` */ | { type: 'ceiling'; height: number | ((x: number, z: number) => number); clearance?: number } /** a rule of the game's own: how far p is inside the allowed space (>= 0 allowed, < 0 by how much it is out) and which way is back in (unit vector) */ | { type: 'custom'; margin: (p: P3) => { g: number; n: P3 } } )

packages/view/src/camera-limits.ts:32

Intrusion type

type Intrusion = 'stay' | 'push'

what a limit does when the world has moved into it (the camera did not move there): stay lets it (the camera may only move away), push moves the camera out

packages/view/src/camera-limits.ts:24

LimitShape type

type LimitShape = | { kind: 'sphere'; c: P3; r: number } /** a rod from a to b with radius r (a man, a hull, a mole, a lorry) */ | { kind: 'capsule'; a: P3; b: P3; r: number } /** a box of half sizes `half`, centred on c, turned by `yaw` about y */ | { kind: 'box'; c: P3; half: P3; yaw?: number } /** an upright cylinder: centre of its base c, radius r, height h */ | { kind: 'cylinder'; c: P3; r: number; h: number }

A body the camera keeps off or stays in. Boxes and cylinders are upright (turned about y only).

packages/view/src/camera-limits.ts:14

P3 type

type P3 = [number, number, number]

Limits on where a camera may go: keep off things (a ship, a man, a wall) by a distance, stay inside a region, stay over a floor (the ground, the sea, a deck) and under a ceiling, or any rule of the game's own. The limits act on the camera's movement, not on its place: a move that would break a limit slides along the limit's boundary, a fast move is cut into short steps so it cannot jump across a thin thing, and a limit can let the world come to the camera (a ship that steams up to it) without the camera being shoved aside (intrusion: 'stay': the camera then only may not go nearer), or push the camera out ('push').

The core is pure (numbers in, numbers out; tested without a scene); attachCameraLimits applies it to a Babylon camera every frame, whatever moved it (keys, mouse, a script, the headset rig), and jump puts a camera somewhere and out of every limit.

packages/view/src/camera-limits.ts:11

RelClass type

type RelClass = 'view' | 'soon' | 'away' | 'gone'

packages/view/src/relevance.ts:21

V3 type

type V3 = [number, number, number] | BABYLON.Vector3

packages/view/src/section.ts:2

Constants

REL_CLASSES const

const REL_CLASSES: readonly RelClass[]

packages/view/src/relevance.ts:22