# @ferret/core: API

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

69 exports. Generated from the source (`packages/core/src`), so it matches the code.

## Classes

### CommandChannel

*class* · `packages/core/src/commands.ts:10`

```ts
class CommandChannel
```

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

### Component

*class* · `packages/core/src/component.ts:10`

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

### Entity

*class* · `packages/core/src/entity.ts:8`

```ts
class Entity
```

An entity wraps a Babylon TransformNode and carries components.

- `readonly id: string`
- `readonly components: Component[]`
- `readonly tags: Set<string>`
- `timeDilation: number` — Per-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`

### EventBus

*class* · `packages/core/src/events.ts:5`

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

### FrameProfiler

*class* · `packages/core/src/perf.ts:36`

```ts
class FrameProfiler
```

- `enabled: boolean`
- `window: number` — the window, in frames, over which the worst value is kept (the previous window's worst stays shown until the new one has one)
- `external: boolean` — true when the game calls `endFrame` itself (it runs its own loop); the world then leaves it alone
- `frames: number`
- `frameMs: number` — the whole frame, ms (wall clock between two `endFrame` calls), as a moving average and the worst
- `frameWorst: number`
- `time<T>(name: string, fn: () => T): T` — time `fn` into slot `name`
- `begin(): number` — start a span: pass the result to `end`
- `end(name: string, t0: number): void`
- `add(name: string, ms: number): void` — add a measured span (ms) to the slot's frame total
- `probe(name: string, read: () => number): void` — a number read at the end of every frame and kept like a span (a probe may return NaN to say "not available")
- `endFrame(): void` — close the frame: every slot's total goes into its average and worst, the probes are read, the totals reset
- `bound(): FrameBound` — which 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): void` — Record 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): void` — a moment worth seeing in the trace (only while a trace runs)
- `stopTrace(): void`
- `trace(): PerfTrace | null` — the 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): string` — the report as aligned text, with the frame line first
- `reset(): void`

### JobPool

*class* · `packages/core/src/job-pool.ts:66`

```ts
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): T` — make (or fetch) a shared array every job can read and write by `name`
- `map(phase: string, n: number, args?: unknown): void` — run `phase` over items 0..n-1; returns when every item is done
- `async dispose(): Promise<void>`

### Logger

*class* · `packages/core/src/log.ts:5`

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

### QualityService

*class* · `packages/core/src/quality.ts:89`

```ts
class QualityService implements Service
```

- `readonly name: "quality"`
- `auto: boolean`
- `readonly log: QualityDecision[]`
- `constructor(private o: QualityOptions = {})`
- `init(world: World): void`
- `register(knob: QualityKnob): void` — add 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): void` — nothing 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): void` — every knob at a share of its range (0 the richest, 1 the cheapest); the regulator goes on from there when it is on
- `targetHz(): number` — the frame rate being held now
- `update(): void` — Called once per rendered frame.
- `report(): QualityReport`
- `text(): string` — one line for the `?perf` overlay
- `dispose(): void`

### Registry

*class* · `packages/core/src/registry.ts:3`

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

### Replica

*class* · `packages/core/src/snapshot.ts:142`

```ts
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): void` — Rebuild the objects from `cur`; with `prev` and `alpha` the interpolated fields are between the two (0 is `prev`, 1 is `cur`).

### RowLayout

*class* · `packages/core/src/snapshot.ts:29`

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

### SceneHost

*class* · `packages/core/src/host.ts:16`

```ts
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(): World` — The world the level service builds into and the game normally plays in.
- `get active(): World` — The world that is advanced and rendered now.
- `worlds(): World[]`
- `get(name: string): World | undefined`
- `nameOf(w: World): string | undefined`
- `create(name: string, opts: HostWorldOptions = {}): World` — A 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): void` — Show a world: from the next frame it is the one advanced and rendered. The one that was shown is not advanced any more.
- `showMain(): void` — Show the main world again (a travel does this when the player is let in, and when a transition fails).
- `dispose(world?: World): void` — Dispose 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): void` — One real frame: advance the main world, and the active one if it is another.
- `render(): void` — Render the active world's scene.

### SimHost

*class* · `packages/core/src/sim-host.ts:196`

```ts
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: number` — the 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): void` — Call 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): number` — the renderer's alpha between the previous and the current snapshot at `now`
- `async dispose(): Promise<void>`

### SnapshotCodec

*class* · `packages/core/src/snapshot.ts:70`

```ts
class SnapshotCodec
```

- `readonly layouts: Map<string, { layout: RowLayout; cap: number; record: boolean; }>`
- `constructor(readonly spec: SnapshotSpec)`
- `static size(cap: number, stride: number): number` — numbers 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): SnapshotView` — Pack 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).

### World

*class* · `packages/core/src/world.ts:31`

```ts
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: FrameProfiler` — where the time of a frame goes (off until `perf.enabled`; see perf.ts)
- `readonly maxFrame: number`
- `timeScale: number` — Global time scale (slow motion < 1).
- `time: number` — Simulated seconds since the world was created (affected by timeScale, not by entity dilation).
- `tickCount: number` — Number 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): void` — every service, in the order they were added
- `get alpha(): number` — How 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[] } = {}): Entity` — Make 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): number` — Advance by a real frame time: runs as many fixed steps as fit, then the per-frame updates.
- `step(): void` — Exactly one fixed step (also the way tests drive the world).
- `run(seconds: number): void` — Run the world headless for `seconds` of simulated time.
- `dispose(): void`

## Functions

### canShareMemory

*function* · `packages/core/src/sim-host.ts:191`

```ts
function canShareMemory(): boolean
```

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

### defaultPoolSize

*function* · `packages/core/src/job-pool.ts:60`

```ts
function defaultPoolSize: () => number
```

### ensureBabylon

*function* · `packages/core/src/babylon.ts:23`

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

### frameWork

*function* · `packages/core/src/quality.ts:325`

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

### gpuTimer

*function* · `packages/core/src/perf.ts:177`

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

### guardFrame

*function* · `packages/core/src/frame-guard.ts:47`

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

### hasBabylonPart

*function* · `packages/core/src/babylon.ts:14`

```ts
function hasBabylonPart(part: string): boolean
```

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

### instrumentScene

*function* · `packages/core/src/perf.ts:150`

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

### nodePort

*function* · `packages/core/src/node-workers.ts:23`

```ts
function nodePort(): WorkerPort
```

the worker end, inside a Node worker script

### nodeWorker

*function* · `packages/core/src/node-workers.ts:13`

```ts
function nodeWorker(script: string | URL): WorkerLike
```

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

### perfOverlay

*function* · `packages/core/src/perf.ts:191`

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

### registerSnapshotCommands

*function* · `packages/core/src/snapshot.ts:232`

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

### reportLine

*function* · `packages/core/src/frame-guard.ts:34`

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

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

### runJobWorker

*function* · `packages/core/src/job-pool.ts:33`

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

### runSimWorker

*function* · `packages/core/src/sim-host.ts:138`

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

### watchHangs

*function* · `packages/core/src/frame-guard.ts:62`

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

### webPort

*function* · `packages/core/src/sim-host.ts:135`

```ts
function webPort: () => WorkerPort
```

### webWorker

*function* · `packages/core/src/web-workers.ts:5`

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

## Interfaces

### CollectionSpec

*interface* · `packages/core/src/snapshot.ts:18`

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

### CommandInfo

*interface* · `packages/core/src/commands.ts:8`

```ts
interface CommandInfo
```

- `name: string`
- `description: string`

### FrameBound

*interface* · `packages/core/src/perf.ts:17`

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

### GuardOptions

*interface* · `packages/core/src/frame-guard.ts:16`

```ts
interface GuardOptions
```

- `game?: string` — the game's name in the reports
- `report?: (line: string) => void` — where a report line goes besides the console and local storage (default: the server's log on https)

### HostWorldOptions

*interface* · `packages/core/src/host.ts:5`

```ts
interface HostWorldOptions extends WorldOptions
```

- `clearColor?: [number, number, number]`

### JobContext

*interface* · `packages/core/src/job-pool.ts:18`

```ts
interface JobContext
```

- `shared: Record<string, SharedArray>`
- `args: any`

### JobPoolOptions

*interface* · `packages/core/src/job-pool.ts:49`

```ts
interface JobPoolOptions
```

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

### PerfRow

*interface* · `packages/core/src/perf.ts:14`

```ts
interface PerfRow
```

- `name: string`
- `avgMs: number`
- `worstMs: number`
- `lastMs: number`
- `callsPerFrame: number`

### PerfTrace

*interface* · `packages/core/src/perf.ts:21`

```ts
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: boolean` — the trace has run its time

### QualityDecision

*interface* · `packages/core/src/quality.ts:68`

```ts
interface QualityDecision
```

- `t: number`
- `id: string`
- `from: number`
- `to: number`
- `why: string`

### QualityKnob

*interface* · `packages/core/src/quality.ts:25`

```ts
interface QualityKnob
```

- `readonly id: string` — unique id, `module.what` ('render.scale', 'perspective.distance', 'crowd.near')
- `readonly load: QualityLoad` — which side of the frame a step down relieves
- `readonly steps: number` — number 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): void` — put the knob at `level`
- `ready?(): boolean` — may the knob change now (a framebuffer change only behind a fade, say); default yes
- `active?(): boolean` — is the knob in play now (a headset knob only during a session); default yes
- `label?: string`

### QualityOptions

*interface* · `packages/core/src/quality.ts:43`

```ts
interface QualityOptions
```

- `targetHz?: number | (() => number)` — the frame rate to hold on a flat screen (default 60). A function is read every decision
- `xrHz?: () => number` — the headset's display rate while a session runs (the XR service sets it); a positive value wins over `targetHz`
- `floorHz?: number` — a flat screen may settle at this lower steady rate when every knob is spent (never a headset); default none
- `gpuMs?: () => number` — GPU time of the last frame in ms, NaN when unknown (see `gpuTimer`)
- `workMs?: () => number` — CPU work of the last frame in ms (see `frameWork`); without it the wall time stands for it
- `every?: number` — seconds 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?: number` — a 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 } | false` — remember the levels between runs: `load` gives what `save` was given; default: the browser's local storage under `key`
- `key?: string` — the name the levels are remembered under (a game name and a device class are good: 'dunkirk:desktop')
- `auto?: boolean` — start regulating at once (default true); `quality.auto` switches it
- `busy?: () => boolean` — something loads now (besides the services' own `qualityBusy()` and the scene's waiting items): the frames are not judged meanwhile

### QualityReport

*interface* · `packages/core/src/quality.ts:69`

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

### ReplicaHooks

*interface* · `packages/core/src/snapshot.ts:131`

```ts
interface ReplicaHooks
```

- `audit?: boolean` — dev 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): any` — an object for a key that is new (default `{}`): a game can give it methods or a class
- `remove?(collection: string, key: number, obj: any): void` — an object whose key is no longer in the snapshots

### Service

*interface* · `packages/core/src/world.ts:10`

```ts
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): void` — Called before the components' fixed update, at the fixed rate.
- `update?(dt: number): void` — Called once per rendered frame.
- `dispose?(): void`

### SimEmitter

*interface* · `packages/core/src/sim-host.ts:15`

```ts
interface SimEmitter
```

- `emit(name: string, data?: unknown): void`

### SimHostOptions

*interface* · `packages/core/src/sim-host.ts:161`

```ts
interface SimHostOptions
```

- `mode: 'worker' | 'thread'`
- `spawn?: () => WorkerLike` — worker mode: makes the worker (the entry calls `runSimWorker`)
- `program?: () => SimProgram` — thread mode: the program itself
- `spec: SnapshotSpec`
- `dt?: number`
- `opts?: unknown` — options for `SimProgram.init`
- `shared?: boolean` — share 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?: boolean` — thread mode: reuse the snapshot buffers (default true)
- `interpDelay?: number` — Worker 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`

### SimProgram

*interface* · `packages/core/src/sim-host.ts:17`

```ts
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): unknown` — a command from the render side, applied at a step boundary; its result goes back to the caller
- `step(dt: number): void` — one fixed step
- `source(): SnapshotSource` — the objects to show now
- `readonly time: number` — simulation seconds so far
- `snapshotDue?(): boolean` — Is 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`

### SnapshotSource

*interface* · `packages/core/src/snapshot.ts:57`

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

### SnapshotSpec

*interface* · `packages/core/src/snapshot.ts:19`

```ts
interface SnapshotSpec
```

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

### SnapshotView

*interface* · `packages/core/src/snapshot.ts:63`

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

### TraceFrame

*interface* · `packages/core/src/perf.ts:20`

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

### WorkerLike

*interface* · `packages/core/src/sim-host.ts:38`

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

### WorkerPort

*interface* · `packages/core/src/sim-host.ts:134`

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

### WorldOptions

*interface* · `packages/core/src/world.ts:20`

```ts
interface WorldOptions
```

- `fixedStep?: number` — Fixed simulation step in seconds (default 1/60).
- `maxFrame?: number` — Longest real frame time that is simulated, in seconds; a stall is not a jump (default 0.1).

## Types

### CommandFn

*type* · `packages/core/src/commands.ts:6`

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

### ComponentClass

*type* · `packages/core/src/component.ts:27`

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

### Handler

*type* · `packages/core/src/events.ts:2`

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

### JobFn

*type* · `packages/core/src/job-pool.ts:19`

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

### LogLevel

*type* · `packages/core/src/log.ts:2`

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

### QualityLoad

*type* · `packages/core/src/quality.ts:23`

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

### SharedArray

*type* · `packages/core/src/job-pool.ts:16`

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

## Constants

### BABYLON_VERSION

*const* · `packages/core/src/version.ts:11`

```ts
const BABYLON_VERSION: "9.33.1"
```

the Babylon version this engine was built and tested with

### FERRET_BUILD

*const* · `packages/core/src/version.ts:13`

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

### FERRET_VERSION

*const* · `packages/core/src/version.ts:9`

```ts
const FERRET_VERSION: "0.1.0"
```

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

### FERRET_VERSION_FULL

*const* · `packages/core/src/version.ts:15`

```ts
const FERRET_VERSION_FULL: string
```

what to show a person: `0.1.0+202611051430`

