FERRETGame engine over Babylon.js
Ferret

@ferret/core

World, fixed-step loop, entities and components, services, event bus, logging and the debug command channel.

69 exports · source in packages/core/src

Classes

CommandChannel class

class CommandChannel
register(name: string, description: string, fn: CommandFn): void
has(name: string): boolean
list(): CommandInfo[]
async execute(name: string, args: any = {}): Promise<unknown>

packages/core/src/commands.ts:10

Component class

abstract class Component<P extends object = Record<string, any>>

A component is a plain class attached to an entity. Parameters come from the manifest (params). Hooks: onAttach (attached), onStart (first fixed step after attach), onFixedUpdate(dt) at the fixed rate, onUpdate(dt) once per rendered frame, onDetach (removed or entity destroyed).

entity: Entity
started: boolean
enabled: boolean
constructor(public params: P = {} as P)
get world(): World
get scene(): BABYLON.Scene
get node(): BABYLON.TransformNode
onAttach?(): void
onStart?(): void
onFixedUpdate?(dt: number): void
onUpdate?(dt: number): void
onDetach?(): void

packages/core/src/component.ts:10

Entity class

class Entity

An entity wraps a Babylon TransformNode and carries components.

readonly id: string
readonly components: Component[]
readonly tags: Set<string>
timeDilation: numberPer-entity time dilation (a game may slow its NPCs). 1 = normal.
destroyed: boolean
data: Record<string, any>
constructor(readonly world: World, readonly node: BABYLON.TransformNode, id?: string)
get name(): string
get position(): BABYLON.Vector3
add<C extends Component>(cls: ComponentClass<C> | string, params?: any): C
get<C extends Component>(cls: ComponentClass<C> | string): C | undefined
require<C extends Component>(cls: ComponentClass<C> | string): C
remove(c: Component): void
destroy(): void

packages/core/src/entity.ts:8

EventBus class

class EventBus

Small event bus. emit calls handlers synchronously, in subscription order.

on<T = any>(name: string, fn: Handler<T>): () => void
once<T = any>(name: string, fn: Handler<T>): () => void
off(name: string, fn: Handler): void
emit<T = any>(name: string, payload?: T): void
clear(): void

packages/core/src/events.ts:5

FrameProfiler class

class FrameProfiler
enabled: boolean
window: numberthe window, in frames, over which the worst value is kept (the previous window's worst stays shown until the new one has one)
external: booleantrue when the game calls endFrame itself (it runs its own loop); the world then leaves it alone
frames: number
frameMs: numberthe whole frame, ms (wall clock between two endFrame calls), as a moving average and the worst
frameWorst: number
time<T>(name: string, fn: () => T): Ttime fn into slot name
begin(): numberstart a span: pass the result to end
end(name: string, t0: number): void
add(name: string, ms: number): voidadd a measured span (ms) to the slot's frame total
probe(name: string, read: () => number): voida number read at the end of every frame and kept like a span (a probe may return NaN to say "not available")
endFrame(): voidclose the frame: every slot's total goes into its average and worst, the probes are read, the totals reset
bound(): FrameBoundwhich side holds the frame, from the moving averages (the GPU's frame time comes from the gpu:frame probe of instrumentScene)
startTrace(seconds = 60, minMs = 1): voidRecord every frame for seconds (turns the profiler on): its length and the slots of at least minMs in it, the browser's long tasks, and the game's marks. For the start of a game: where the long frames come from. Read it with trace().
mark(name: string): voida moment worth seeing in the trace (only while a trace runs)
stopTrace(): void
trace(): PerfTrace | nullthe trace so far (null when none was started)
report(prefix?: string): PerfRow[]the slots, the most expensive first (names starting with prefix only, when given)
text(top = 24, prefix?: string): stringthe report as aligned text, with the frame line first
reset(): void

packages/core/src/perf.ts:36

JobPool class

class JobPool
readonly size: number
readonly shared_: Record<string, SharedArray>
stats: { parallel: number; serial: number; }runs counted by how they ran, for the perf report
constructor(private o: JobPoolOptions)
shared<T extends SharedArray>(name: string, ctor: Ctor<T>, length: number): Tmake (or fetch) a shared array every job can read and write by name
map(phase: string, n: number, args?: unknown): voidrun phase over items 0..n-1; returns when every item is done
async dispose(): Promise<void>

packages/core/src/job-pool.ts:66

Logger class

class Logger
level: LogLevel
sinks: Array<(level: LogLevel, scope: string, msg: string) => void>Sinks receive every line at or above level; the OS Beroun platform adds one that posts to the shell's log.
constructor(readonly scope: string)
debug(m: string)
info(m: string)
warn(m: string)
error(m: string)

packages/core/src/log.ts:5

QualityService class

class QualityService implements Service
readonly name: "quality"
auto: boolean
readonly log: QualityDecision[]
constructor(private o: QualityOptions = {})
init(world: World): void
register(knob: QualityKnob): voidadd a knob; a level remembered from an earlier run is put back at once
unregister(id: string): void
has(id: string): boolean
level(id: string): number
hold(reason: string): voidnothing changes while a hold is on (assets loading, a level coming in); the frames meanwhile are not counted
release(reason: string): void
preset(share: number): voidevery knob at a share of its range (0 the richest, 1 the cheapest); the regulator goes on from there when it is on
targetHz(): numberthe frame rate being held now
update(): voidCalled once per rendered frame.
report(): QualityReport
text(): stringone line for the ?perf overlay
dispose(): void

packages/core/src/quality.ts:89

Registry class

class Registry<T>

A name -> constructor registry. A manifest names components and behaviours; games register the classes.

constructor(readonly kind: string)
register(name: string, item: T): this
get(name: string): T
has(name: string): boolean
names(): string[]

packages/core/src/registry.ts:3

Replica class

class Replica

the objects of the last snapshot applied: plain objects with the spec's property paths, the same objects from frame to frame while their key lives

readonly codec: SnapshotCodec
readonly lists: Record<string, any[]>each collection's objects in snapshot order (one array per name, kept and refilled)
readonly byKey: Record<string, Map<number, any>>each collection's objects by key
readonly records: Record<string, any>each record's object
tick: number
time: number
readonly undeclared: Set<string>the reads of undeclared properties seen while audit is on: "collection.path"
constructor(spec: SnapshotSpec | SnapshotCodec, private hooks: ReplicaHooks = {})
apply(cur: SnapshotView, prev?: SnapshotView | null, alpha = 1): voidRebuild the objects from cur; with prev and alpha the interpolated fields are between the two (0 is prev, 1 is cur).

packages/core/src/snapshot.ts:142

RowLayout class

class RowLayout

the layout of one object's fields in a row of numbers (and the strings that go in the meta part)

readonly fields: Field[]
stride: number
metaCount: number
constructor(specs: readonly string[])

packages/core/src/snapshot.ts:29

SceneHost class

class SceneHost implements Service

The scene host: the place for a second World over a second Scene on the same Engine, so a game's interlude can be an ordinary scene with its own lights, camera and behaviours while the target level loads in the main one. Both scenes share the GL context, shaders and texture caches. Only the active world is rendered (rendering both cost 15x in WebKit, S0). The main world always advances (its services - ui, net, input - keep running, and its paused flag still decides whether the simulation steps); another world advances only while it is the active one.

readonly name: "host"
constructor(readonly engine: BABYLON.AbstractEngine)
init(world: World): void
get main(): WorldThe world the level service builds into and the game normally plays in.
get active(): WorldThe world that is advanced and rendered now.
worlds(): World[]
get(name: string): World | undefined
nameOf(w: World): string | undefined
create(name: string, opts: HostWorldOptions = {}): WorldA new world over a new scene on the shared engine. It is not shown until show. The game owns what is in it.
show(world: World): voidShow a world: from the next frame it is the one advanced and rendered. The one that was shown is not advanced any more.
showMain(): voidShow the main world again (a travel does this when the player is let in, and when a transition fails).
dispose(world?: World): voidDispose a world the game created, with its scene (all of them with no argument: the service's own dispose). If it is shown, the main world is shown first.
advance(realDt: number): voidOne real frame: advance the main world, and the active one if it is another.
render(): voidRender the active world's scene.

packages/core/src/host.ts:16

SimHost class

class SimHost
readonly replica: Replica
readonly dt: number
readonly mode: 'worker' | 'thread'
readonly transport: 'ring' | 'transfer' | 'direct'snapshot transport actually in use
paused: boolean
tick: numberthe most recent tick shown and the ticks that passed unseen (the render side was slower than the simulation)
skipped: number
constructor(o: SimHostOptions)
ready(): Promise<void>resolves when the program has initialised
on(name: string, fn: (data: any) => void): () => void
command<T = unknown>(name: string, args?: unknown): Promise<T>send a command; it is applied at the next step boundary, in the order sent. The promise gives the program's answer.
pause(on = true)worker mode: start or stop the free-running simulation. Thread mode: pumped by pump.
start()
step(n = 1)n steps by hand (a paused simulation, a test)
pump(now: number): voidCall once a frame with the time in seconds. Thread mode steps the simulation by the time that passed (at most five steps); worker mode takes the snapshots that came. Then the replica is rebuilt, interpolated by how far into the step the render time is, and events are delivered.
alpha(now: number): numberthe renderer's alpha between the previous and the current snapshot at now
async dispose(): Promise<void>

packages/core/src/sim-host.ts:196

SnapshotCodec class

class SnapshotCodec
readonly layouts: Map<string, { layout: RowLayout; cap: number; record: boolean; }>
constructor(readonly spec: SnapshotSpec)
static size(cap: number, stride: number): numbernumbers in the buffer of one collection of capacity cap and row width stride: the count, the keys, the rows
sizes(): Record<string, number>
encode(src: SnapshotSource, tick: number, time: number, into?: (name: string, size: number) => Float64Array): SnapshotViewPack the objects of src into buffers. into gives the buffer to write for a name (a slot of the shared ring: its length is the full capacity) or nothing (a new array of exactly the rows is made).

packages/core/src/snapshot.ts:70

World class

class World

The World owns the Babylon scene, the fixed-step simulation loop (decoupled from rendering), the clock with time dilation, the event bus, the services and the entities.

readonly events: EventBus
readonly components: Registry<ComponentClass>
readonly behaviours: Registry<ComponentClass>
readonly commands: CommandChannel
readonly entities: Entity[]
readonly fixedStep: number
readonly perf: FrameProfilerwhere the time of a frame goes (off until perf.enabled; see perf.ts)
readonly maxFrame: number
timeScale: numberGlobal time scale (slow motion < 1).
time: numberSimulated seconds since the world was created (affected by timeScale, not by entity dilation).
tickCount: numberNumber of fixed steps run.
paused: boolean
constructor(readonly scene: BABYLON.Scene, opts: WorldOptions = {})
addService<S extends Service>(s: S): S
service<S extends Service = Service>(name: string): S
hasService(name: string): boolean
forEachService(fn: (s: Service) => void): voidevery service, in the order they were added
get alpha(): numberHow far the render frame is between the last two fixed steps (0..1), for interpolating what the camera follows.
spawn(name: string, opts: { node?: BABYLON.TransformNode; position?: BABYLON.Vector3; id?: string; tags?: string[] } = {}): EntityMake an entity over a new TransformNode (or over an existing node of the scene).
removeEntity(e: Entity): void
entity(id: string): Entity | undefined
findByName(name: string): Entity | undefined
findByTag(tag: string): Entity[]
entitiesWith<C extends Component>(cls: ComponentClass<C>): Entity[]
advance(realDt: number): numberAdvance by a real frame time: runs as many fixed steps as fit, then the per-frame updates.
step(): voidExactly one fixed step (also the way tests drive the world).
run(seconds: number): voidRun the world headless for seconds of simulated time.
dispose(): void

packages/core/src/world.ts:31

Functions

canShareMemory function

function canShareMemory(): boolean

can a SharedArrayBuffer ring be used here: the type exists and (in a page) it is cross-origin isolated

packages/core/src/sim-host.ts:191

defaultPoolSize function

function defaultPoolSize: () => number

packages/core/src/job-pool.ts:60

ensureBabylon function

function ensureBabylon(...parts: string[]): Promise<void>

Make sure the named parts of Babylon are loaded (core, gltf, pbr, shadows, particles, pipeline, video, debug): fetched from globalThis.FERRET_BABYLON (the folder of the parts, set by the player or the page) and imported once. Resolves at once when they are there.

packages/core/src/babylon.ts:23

frameWork function

function frameWork(engine: { onBeginFrameObservable: { add(f: () => void): unknown; remove(o: unknown): void }; onEndFrameObservable: { add(f: () => void): unknown; remove(o: unknown): void } }): { read: () => number; stop: () => void }

The CPU work of a frame from a Babylon engine: the time from the start of the frame to the end of its rendering (what the frame's JavaScript cost, without the wait for the next frame). Returns the reader and the function that stops it.

packages/core/src/quality.ts:325

gpuTimer function

async function gpuTimer(engine: BABYLON.AbstractEngine): Promise<{ read: () => number; stop: () => void }>

The GPU time of the last frame (ms), from the browser's timer query (EXT_disjoint_timer_query); NaN where there is none. For the quality regulator, without the whole scene instrumentation. Resolves to the reader and the function that stops it.

packages/core/src/perf.ts:177

guardFrame function

function guardFrame(fn: () => void, o: GuardOptions = {}): () => void

wrap a frame callback: an exception is reported (once per kind, then every 100th time with the count) and the loop goes on

packages/core/src/frame-guard.ts:47

hasBabylonPart function

function hasBabylonPart(part: string): boolean

Is part available now: the full build, or a part already loaded?

packages/core/src/babylon.ts:14

instrumentScene function

async function instrumentScene(profiler: FrameProfiler, scene: BABYLON.Scene, engine?: BABYLON.AbstractEngine): Promise<() => void>

Babylon's own phases as probes (ms of the last frame): the evaluation of the active meshes, the render targets, the scene render, the animations, the particles, the sprites, plus the draw calls and the GPU frame time where the browser has the timer query (gpu is then NaN-free, else it is left out). Loads the Babylon part instrumentation on a host that serves Babylon in parts. Resolves to the function that stops the instrumentation.

packages/core/src/perf.ts:150

nodePort function

function nodePort(): WorkerPort

the worker end, inside a Node worker script

packages/core/src/node-workers.ts:23

nodeWorker function

function nodeWorker(script: string | URL): WorkerLike

the page end of a Node worker started from a script file

packages/core/src/node-workers.ts:13

perfOverlay function

function perfOverlay(profiler: FrameProfiler, opts: { top?: number; parent?: HTMLElement; extra?: () => string } = {}): () => void

A text panel in the corner of the page with the report, refreshed four times a second (a game starts it with ?perf). Returns the stop function. Without a DOM it does nothing.

packages/core/src/perf.ts:191

registerSnapshotCommands function

function registerSnapshotCommands(world: { commands: { register(name: string, description: string, fn: (a?: any) => unknown): void } }, replica: Replica): void

the report of the render side's reads of undeclared fields, for edit.validate (snapshot.audit), and the spec's own check: declared fields that no object had

packages/core/src/snapshot.ts:232

reportLine function

function reportLine(line: string, o: GuardOptions = {}): void

record one report line (console, __ferretErrors, local storage, the server's log)

packages/core/src/frame-guard.ts:34

runJobWorker function

function runJobWorker(jobs: Record<string, JobFn>, port: WorkerPort): void

the worker's end: call in the job worker's entry with the same jobs the pool was made with

packages/core/src/job-pool.ts:33

runSimWorker function

function runSimWorker(make: () => SimProgram | Promise<SimProgram>, port: WorkerPort): void

packages/core/src/sim-host.ts:138

watchHangs function

function watchHangs(o: GuardOptions & { hangMs?: number; onEndFrame?: { add(f: () => void): unknown; remove(x: unknown): void } } = {}): { beat: () => void; stop: () => void }

Watch for a stuck main thread from a Web Worker. beat is called after every finished frame (pass the engine's end-of-frame observable, or call the returned beat yourself). Returns the stop function. Without Web Workers (a test, OS Beroun) it does nothing.

packages/core/src/frame-guard.ts:62

webPort function

function webPort: () => WorkerPort

packages/core/src/sim-host.ts:135

webWorker function

function webWorker(url: string | URL, name?: string): WorkerLike

the page's end of a Web Worker started from a script URL (relative to the page): the same shape as nodeWorker, for SimHost and JobPool

packages/core/src/web-workers.ts:5

Interfaces

CollectionSpec interface

interface CollectionSpec

The snapshot contract: what a simulation shows to whoever draws it, as flat typed arrays, and the replica that rebuilds objects from them.

A snapshot spec says which fields of which objects the render side may read. The simulation side packs them (SnapshotEncoder), the render side unpacks them into plain objects with the same property paths (Replica), so code that reads craft.plane.pos[0] or ship.vessel.q goes on reading it; nothing else of the simulation is visible across the boundary. Values that move are interpolated between two snapshots by alpha, as World.alpha does for the fixed step.

Fields (a path from the object, then a suffix):

  `x`            a number                  `plane.pos:3`   a vector of 3 numbers (any length)
  `plane.pos:3~` interpolated linearly      `plane.q:4~q`   a quaternion (interpolated by normalised lerp)      `heading~a`   an angle in radians (by the short way round)
  `gone?`        a boolean                  `state@idle|walk|board`   one of the listed words (stored as its index)
  `kind$`        a string                   `dmg{}`         any JSON value (a string or JSON field that the source gives as `undefined` is left as it was)

A collection is many objects with the same fields, each with a unique integer key, up to capacity; a record is one object.

fields: string[]
capacity: number

packages/core/src/snapshot.ts:18

CommandInfo interface

interface CommandInfo
name: string
description: string

packages/core/src/commands.ts:8

FrameBound interface

interface FrameBound

which side holds the frame: the GPU when its frame time is most of the frame, else the CPU ('?' without the GPU timer)

by: 'cpu' | 'gpu' | '?'
frameMs: number
gpuMs: number

packages/core/src/perf.ts:17

GuardOptions interface

interface GuardOptions
game?: stringthe game's name in the reports
report?: (line: string) => voidwhere a report line goes besides the console and local storage (default: the server's log on https)

packages/core/src/frame-guard.ts:16

HostWorldOptions interface

interface HostWorldOptions extends WorldOptions
clearColor?: [number, number, number]

packages/core/src/host.ts:5

JobContext interface

interface JobContext
shared: Record<string, SharedArray>
args: any

packages/core/src/job-pool.ts:18

JobPoolOptions interface

interface JobPoolOptions
jobs: Record<string, JobFn>the jobs by phase name (the same registry the worker entry gets)
spawn?: () => WorkerLikemakes one job worker; without it, or with size 0, every phase runs serially
size?: numbernumber of workers (default: hardware threads - 2, between 0 and 8)
minItems?: numbera phase with fewer items than this runs serially (the call overhead is more than the work)

packages/core/src/job-pool.ts:49

PerfRow interface

interface PerfRow
name: string
avgMs: number
worstMs: number
lastMs: number
callsPerFrame: number

packages/core/src/perf.ts:14

PerfTrace interface

interface PerfTrace
frames: TraceFrame[]the frames, in order
longTasks: { t: number; ms: number }[]the main thread's long tasks (over 50 ms) the browser reported, inside frames or between them
marks: { t: number; name: string }[]what the game marked (an asset loaded, a level shown)
done: booleanthe trace has run its time

packages/core/src/perf.ts:21

QualityDecision interface

interface QualityDecision
t: number
id: string
from: number
to: number
why: string

packages/core/src/quality.ts:68

QualityKnob interface

interface QualityKnob
readonly id: stringunique id, module.what ('render.scale', 'perspective.distance', 'crowd.near')
readonly load: QualityLoadwhich side of the frame a step down relieves
readonly steps: numbernumber of steps, 0 the richest, steps - 1 the cheapest
visibility?: number | ((level: number) => number)how visible it is to be at level (the step about to be taken): the least visible is given up first. Default: 1 for every step
apply(level: number): voidput the knob at level
ready?(): booleanmay the knob change now (a framebuffer change only behind a fade, say); default yes
active?(): booleanis the knob in play now (a headset knob only during a session); default yes
label?: string

packages/core/src/quality.ts:25

QualityOptions interface

interface QualityOptions
targetHz?: number | (() => number)the frame rate to hold on a flat screen (default 60). A function is read every decision
xrHz?: () => numberthe headset's display rate while a session runs (the XR service sets it); a positive value wins over targetHz
floorHz?: numbera flat screen may settle at this lower steady rate when every knob is spent (never a headset); default none
gpuMs?: () => numberGPU time of the last frame in ms, NaN when unknown (see gpuTimer)
workMs?: () => numberCPU work of the last frame in ms (see frameWork); without it the wall time stands for it
every?: numberseconds between decisions (0.5), the window measured (1 s), the wait after a change (2 s), the comfort time before a step back (4 s)
window?: number
settle?: number
upAfter?: number
late?: numbera frame is late above this share of the budget (1.08), comfortable below comfort (0.7)
comfort?: number
remember?: { load(): unknown; save(v: unknown): void } | falseremember the levels between runs: load gives what save was given; default: the browser's local storage under key
key?: stringthe name the levels are remembered under (a game name and a device class are good: 'dunkirk:desktop')
auto?: booleanstart regulating at once (default true); quality.auto switches it
busy?: () => booleansomething loads now (besides the services' own qualityBusy() and the scene's waiting items): the frames are not judged meanwhile

packages/core/src/quality.ts:43

QualityReport interface

interface QualityReport
auto: boolean
targetHz: number
budgetMs: number
xr: boolean
frameP95: number
workP95: number
gpuP95: number
by: 'cpu' | 'gpu' | '?'
holds: string[]
knobs: { id: string; load: QualityLoad; level: number; steps: number; pinned: boolean; active: boolean }[]
log: QualityDecision[]

packages/core/src/quality.ts:69

ReplicaHooks interface

interface ReplicaHooks
audit?: booleandev check: every read of a property the spec does not declare is recorded in Replica.undeclared (the objects are proxies); off by default
make?(collection: string, key: number): anyan object for a key that is new (default {}): a game can give it methods or a class
remove?(collection: string, key: number, obj: any): voidan object whose key is no longer in the snapshots

packages/core/src/snapshot.ts:131

Service interface

interface Service

A world-wide singleton (the rough equivalent of a UE subsystem): input, levels, zones, physics, ui ...

readonly name: string
init?(world: World): void
fixedUpdate?(dt: number): voidCalled before the components' fixed update, at the fixed rate.
update?(dt: number): voidCalled once per rendered frame.
dispose?(): void

packages/core/src/world.ts:10

SimEmitter interface

interface SimEmitter
emit(name: string, data?: unknown): void

packages/core/src/sim-host.ts:15

SimHostOptions interface

interface SimHostOptions
mode: 'worker' | 'thread'
spawn?: () => WorkerLikeworker mode: makes the worker (the entry calls runSimWorker)
program?: () => SimProgramthread mode: the program itself
spec: SnapshotSpec
dt?: number
opts?: unknownoptions for SimProgram.init
shared?: booleanshare the ring by SharedArrayBuffer (needs cross-origin isolation); default: when the environment has it
catchUp?: { maxFrame?: number; maxSteps?: number; drop?: number }Thread mode: how the simulation catches up after a long frame. At most maxFrame seconds of a frame count, at most maxSteps steps are taken in one pump, and when more than drop seconds are owed they are dropped (the machine cannot keep up: slow motion, not a spiral). Default: 0.1 s, 0.15 s worth of steps, 0.25 s.
reuse?: booleanthread mode: reuse the snapshot buffers (default true)
interpDelay?: numberWorker mode: the drawing runs this many seconds behind the newest snapshot (default 0.05, never less than 2.5 snapshot spacings), on a clock of its own that is steered gently toward that point (at most 10 % faster or slower) and never goes back; the picture is interpolated between the two snapshots round the clock, so snapshots that arrive unevenly (a slow frame, the worker's own jitter) do not show as jerks.
hooks?: ReplicaHooks

packages/core/src/sim-host.ts:161

SimProgram interface

interface SimProgram
readonly spec: SnapshotSpec
init(opts: unknown, out: SimEmitter): void | Promise<void>called once with the options the host was given, before the first step
command(name: string, args: unknown): unknowna command from the render side, applied at a step boundary; its result goes back to the caller
step(dt: number): voidone fixed step
source(): SnapshotSourcethe objects to show now
readonly time: numbersimulation seconds so far
snapshotDue?(): booleanIs the state worth a snapshot after this step? A program whose world changes only on some steps (a 20 Hz world in 60 Hz steps) says no on the others, so the drawing interpolates between real changes and not between equal snapshots. Default: every step.
dispose?(): void

packages/core/src/sim-host.ts:17

SnapshotSource interface

interface SnapshotSource

what the simulation hands the encoder: where the objects of each collection are, and each object's key

collections?: Record<string, { items: Iterable<any>; key: (item: any) => number }>
records?: Record<string, any>

packages/core/src/snapshot.ts:57

SnapshotSpec interface

interface SnapshotSpec
collections: Record<string, CollectionSpec>
records?: Record<string, string[]>single objects: name -> fields

packages/core/src/snapshot.ts:19

SnapshotView interface

interface SnapshotView

one snapshot: the time of the simulation it shows, one Float64Array per collection or record ([count, keys..., rows...]) and the rest as JSON

tick: number
time: number
data: Record<string, Float64Array>
meta: Record<string, unknown[][]>per collection or record: the rows' strings and JSON values, aligned with the rows

packages/core/src/snapshot.ts:63

TraceFrame interface

interface TraceFrame

one frame of a trace: when it ended (ms, page clock), how long it was, and the slots that took at least minMs in it

t: number
dt: number
slots: Record<string, number>

packages/core/src/perf.ts:20

WorkerLike interface

interface WorkerLike

what a worker and the page's end of it share: the two ends of a Web Worker or a Node worker

postMessage(msg: unknown, transfer?: Transferable[]): void
on(event: 'message', fn: (msg: any) => void): void
terminate(): void | Promise<unknown>

packages/core/src/sim-host.ts:38

WorkerPort interface

interface WorkerPort

The worker's side: call this in the worker's entry with a function that makes the program. port is the worker's end (self of a Web Worker, or parentPort of a Node worker; use nodePort/webPort below).

post(msg: unknown, transfer?: Transferable[]): void
onMessage(fn: (msg: any) => void): void
close(): void

packages/core/src/sim-host.ts:134

WorldOptions interface

interface WorldOptions
fixedStep?: numberFixed simulation step in seconds (default 1/60).
maxFrame?: numberLongest real frame time that is simulated, in seconds; a stall is not a jump (default 0.1).

packages/core/src/world.ts:20

Types

CommandFn type

type CommandFn = (args: any) => unknown | Promise<unknown>

The debug command channel: named commands that a tool (the inspector, the model viewer, an AI agent over MCP) calls to look at and change a running world. Commands are plain JSON in, plain JSON out.

packages/core/src/commands.ts:6

ComponentClass type

type ComponentClass<C extends Component = Component> = new (params?: any) => C

packages/core/src/component.ts:27

Handler type

type Handler<T = any> = (payload: T) => void

packages/core/src/events.ts:2

JobFn type

type JobFn = (from: number, to: number, ctx: JobContext) => void

packages/core/src/job-pool.ts:19

LogLevel type

type LogLevel = 'debug' | 'info' | 'warn' | 'error'

packages/core/src/log.ts:2

QualityLoad type

type QualityLoad = 'cpu' | 'gpu' | 'both'

packages/core/src/quality.ts:23

SharedArray type

type SharedArray = Float64Array | Float32Array | Int32Array | Uint32Array | Uint8Array | Int16Array | Uint16Array

packages/core/src/job-pool.ts:16

Constants

BABYLON_VERSION const

const BABYLON_VERSION: "9.33.1"

the Babylon version this engine was built and tested with

packages/core/src/version.ts:11

FERRET_BUILD const

const FERRET_BUILD: string

the build stamp yyyymmddHHMM in the LOCAL time of the build machine, never UTC; dev when the code runs unbuilt (tests, the repository)

packages/core/src/version.ts:13

FERRET_VERSION const

const FERRET_VERSION: "0.1.0"

the engine's version (semver); every module of a release shares it

packages/core/src/version.ts:9

FERRET_VERSION_FULL const

const FERRET_VERSION_FULL: string

what to show a person: 0.1.0+202611051430

packages/core/src/version.ts:15