FERRETGame engine over Babylon.js
Ferret

@ferret/core

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

121 exports · source in packages/core/src

Classes

CommandChannel class

class CommandChannel
register(name: string, description: string, fn: CommandFn): void
has(name: string): boolean
unregister(name: string, restore?: { fn: CommandFn; description: string }): booleanTake a command back; the one it had replaced (a register of the same name overwrites) is given back with it.
entry(name: string): { fn: CommandFn; description: string } | undefinedWhat is registered under the name now (to keep for unregister's restore).
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
onFixedUpdateAsync?(dt: number): Promise<() => void> | nullThe same step for a component whose work can go to the workers: called instead of onFixedUpdate when the world steps asynchronously and wantsAsync is true. It takes what it needs from the component at its place in the step and returns a promise of the function that puts the result back; the world calls those functions in the order of the components when every component has had its turn, so a component after this one sees the result at the next step. It returns null to say that this step cannot go (the component then runs onFixedUpdate in its place).
wantsAsync?(): booleanthe component class has work for the workers now (cheap: the world asks every step); a component that registers itself in world.asyncComponents is asked
onUpdate?(dt: number): void
onDetach?(): void
kernels?: KernelDecl[]kernels this component declares: taken at its first fixed step, dropped when it is detached
schedule?: ModuleDecla module's description: taken at its first fixed step like kernels

packages/core/src/component.ts:11

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

FramePacer class

class FramePacer
k: numberrefreshes per drawn frame
period: numberthe display's refresh period, ms (learnt)
constructor(readonly o: { maxK?: number; minPeriod?: number } = {})
tick(now: number, lastWork = 0): PacerTicka display callback at now (ms); lastWork the ms the previous drawn frame's own work took (its callback)

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

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
own<T>(name: string, fn: () => T): Ttime a function of the game's own into slot own:name: the report of what the game's code costs in the game's thread lists it with its share and what would take it off
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"
get auto(): booleanthe regulator is on (never true for a service made with never)
set auto(v: boolean)the regulator is on (never true for a service made with never)
readonly never: booleanthis service never lowers quality (see QualityOptions.never)
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
scopedView(keep: (undo: () => void) => void): thisThe service as a docked level sees it (Scope.view): the knobs the level registers are taken off with the level.
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:94

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
unregister(name: string): booleanTake a registration back (a docked level's scope does at its end). Returns whether there was one.
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

ResidentLost class

class ResidentLost extends Error

a pinned task lost its worker (and the state the worker kept for its pin); the caller sets the state up again and asks again

constructor(readonly pin: string)

packages/core/src/task-pool.ts:9

Roles class

class Roles implements Service

The roles of a parent game: a mechanism a game has at most once (the player's character, the camera, the input, the net room, the menu ...). The parent provides what it holds; while a level is docked (dock), the engine's own entry points that make a role (spawnCharacter, CameraRig, a service of the same name) ask takeOver first, so code written for a game of its own that makes "its" character or camera gets the parent's instead, unless the level brings that role itself (has). With no parent and no dock nothing here changes anything: takeOver makes what it is asked to make.

readonly name: "roles"
provide(role: string, impl: unknown): () => voidThe parent gives its implementation of a role (an instance). Returns the way to withdraw it.
holds(role: string): boolean
get<T = unknown>(role: string): T | undefined
list(): string[]
dock(level: string, has: Iterable<string> = []): () => voidA level is docked: has are the roles it brings itself. Returns the way to end the dock.
get docked(): string | undefinedthe level docked now, if any
get given(): string[]The roles the docked code asked for and was given the parent's instance of (for the converter's run and the tests).
parentAnswers(role: string): booleanIs the parent's instance of the role the answer now: a level is docked, the parent holds the role and the level does not bring it.
takeOver<T>(role: string, make: () => T): TWhat an engine entry point calls to make a role: the parent's instance when it answers, else make().

packages/core/src/roles.ts:10

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.
async advanceAsync(realDt: number): Promise<void>advance with the worlds' declared step kernels in the scheduler's workers (the same as advance when no world needs it)
get pooled(): booleantrue when a world's step waits for kernels in workers: the loop then calls advanceAsync
render(): voidRender the active world's scene.

packages/core/src/host.ts:16

Scheduler class

class Scheduler
stats: { runs: number; inWorkers: number; applied: number; lost: number; }counts: kernel runs in all, in workers, and of frame kernels the answers applied
constructor(private readonly world: World)
start(o: SchedulerStart): voidstart the pools (a game does it in createGame); before it, and with no spawn, kernels run here
startLike(o: Scheduler): voidstart with the options another scheduler was started with (a second world of the same game)
stop(): void
respawn(): voiddrop the workers that run kernels and start new ones when a kernel next needs them (the spawn of the page changed: a docked level's kernels came or went); resident state is lost, as when a worker dies
get threads(): numberworkers that run kernels now (plain and Babylon)
get pooled(): booleantrue when the step must be asynchronous: step kernels are declared and workers run them
readonly MIN_PIECE_MS: 0.15a piece cheaper than this is not worth a message
readonly PIECES_PER_WORKER: 4pieces per worker when a kernel is worth cutting: more pieces than workers, so a worker that is done takes the next (the pool's queue)
pieces(name: string, n: number, threads: number): numberhow many pieces a split kernel of n items is cut into: by its measured cost (one piece when the whole is cheap), the first time by the workers' number
workerStats(): { cls: KernelWorker; threads: number; workers: { tasks: number; ms: number }[] }[]per class of worker: how many workers and what each did (tasks finished, ms spent in them)
costOf(name: string): number | undefinedthe measured cost per item of a split kernel, ms (undefined before its first run)
declare(d: KernelDecl, owner?: unknown): () => voiddeclare a kernel; owner lets dropOwner take all of an owner's kernels away. Returns the undeclare
task<I, O>(spec: { name: string; gather(world: World, dt: number): I | null; apply(world: World, out: O): void; sync?: 'step' | 'frame'; each?: boolean; reads?: string[]; writes?: string[]; every?: number }, owner?: unknown): () => voidThe author's short form: a task whose function is registered by defineTask(name, fn) in the game's src/kernels.ts. gather takes plain data out of the world (null: nothing to do), apply puts the answer back. each says the data is a list of independent items (the answer a list of as many): it is cut over the cores and put together in order. frame instead of step lets the page go on and applies the answer a step later. When the data is not plain (a node, a world, a function) the task runs in the game's thread and Scheduler.stays() / scheduler.info say why.
stays(): { task: string; why: string }[]the tasks that stay in the game's thread, and why (in words an author can act on)
dropOwner(owner: unknown): void
refresh(name: string): voidthe resident state of a kernel is sent again before its next run (the world it holds changed)
module(m: ModuleDecl, owner?: unknown): () => voiddeclare a module: all its parts, under the module's name; one undeclare for all
modules(): { name: string; stays?: string; parts: { name: string; sync: string; reads: string[]; writes: string[]; split: boolean; resident: boolean }[] }[]the declared modules: their parts (reads, writes, how each runs) and what stays in the game's thread
list(): { name: string; sync: string; owner: string; module?: string; resident?: string }[]the declared kernels
main: Scheduler | undefinedthe scheduler of the game's main world (the first one started, with workers or without): what views and loaders use when they are given none
shared(key: string, init: { kernel: string; payload: () => unknown }, o: { replicas?: number } = {}): SharedStateA state kept in workers and asked by calls outside the step (a land to build chunks of, a collision world to sweep in): init is the kernel that sets it up from payload(), update adds to it (every copy, also those made later, gets every update in order). Calls go to the least loaded worker, each of which holds its own copy (at most replicas, default all), and to this thread when there are no workers. A copy lost with its worker is made again.
spent(kernel: string): { calls: number; ms: number }the worker time (ms) all finished calls of a kernel took so far, and how many calls: what a service measures its cost by
call<O = unknown>(name: string, input: unknown, transfer: Transferable[] = [], pin?: string): Promise<O>one call of a kernel outside the step (loading work): in a worker when there is one, here otherwise; never blocks the page
stepHere(dt: number): voidthe step kernels of this step, here, in waves (the synchronous step: tests, world.step, a world with no workers)
async stepPooled(dt: number): Promise<void>the step kernels of this step in the workers: each wave gathers, runs at the same time, applies in declaration order
endStep(dt: number): voidthe frame kernels at the end of a step: answers that came are applied (in declaration order), idle due ones are started. With no workers they run here at once and are applied at the next step, so the answer is one step late either way
dispose(): void

packages/core/src/scheduler.ts:113

Scope class

class Scope
readonly entities: Set<Entity>the entities spawned while the scope was open: those still alive are destroyed with it
constructor(readonly world: World, readonly namespace: string)
get closed(): boolean
get size(): numberhow many takings-back wait
add(undo: Undo): UndoKeep undo for the end of the scope (run at once when the scope is closed already). Returns a function that runs it now and forgets it.
on<T = any>(event: string, fn: Handler<T>): UndoAn event handler on the world's bus.
command(name: string, description: string, fn: CommandFn): UndoA command; the one it replaced is given back.
component(name: string, cls: ComponentClass): UndoA component class under a name of the manifests.
behaviour(name: string, cls: ComponentClass): UndoA behaviour class under a name of the manifests.
service<S extends Service>(s: S): SA service; it is disposed and removed with the scope. A service the parent already has under that name is the parent's role: it is given back (seen through the scope, view) and left alone.
view<S>(service: S): SA service of the parent as the scope's code sees it: its scopedView when it has one (what the code adds to it is then taken back with the scope), else the service itself.
observe<T, O>(obs: ObservableLike<T, O>, fn: (e: T) => void): OAn observer of a Babylon observable (scene.onBeforeRenderObservable); removed with the scope.
listen(target: EventTarget, type: string, fn: EventListenerOrEventListenerObject, opts?: boolean | AddEventListenerOptions): UndoA DOM listener; removed with the scope.
interval(fn: () => void, ms: number): UndosetInterval, stopped with the scope.
async capture<R>(fn: () => R | Promise<R>): Promise<R>Run fn and take back every DOM listener and interval that the code it runs adds meanwhile (EventTarget.prototype.addEventListener, setInterval): the code of an example that was written for its own page reaches for window and document itself. Only for the span of the call (the promise it returns is awaited), so what the parent's own code adds at the same time would be caught too: dock while the parent has nothing to add (under the transition video). A worker, a message port and a channel are their maker's own and their listeners stay: the engine's pools make their workers the first time one is needed, which may be while a level installs, and they live on after it.
dispose(): voidTake everything back, newest first; the entities that are left are destroyed. Safe to call twice.

packages/core/src/scope.ts:19

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:202

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

StateBuffer class

class StateBuffer<T extends TypedArray = Float64Array>
readonly id: number
readonly array: T
readonly shared: booleantrue: the array is in shared memory (slices are windows); false: slices are copies
constructor(ctor: new (n: number) => T, length: number, mode: 'auto' | 'shared' | 'copy' = 'auto')
slice(from = 0, to = this.array.length, access: Access = 'rw'): StateSlicethe range [from, to) for a kernel: access says whether the kernel reads it, writes it or both (a copy is made only for what is read)
write(from: number, data: TypedArray): voidthe answer's writes arrive here (copy mode)
dispose(): void

packages/core/src/state-buffer.ts:24

TaskPool class

class TaskPool
readonly threads: number
done: numbertasks finished, in total, and how many ran in a worker
inWorkers: number
readonly worked: { tasks: number; ms: number }[]per worker: tasks it finished and the time it spent in them (ms, as the worker measured)
constructor(private readonly o: TaskPoolOptions)
get capacity(): number
get pending(): number
spentOn(task: string): { calls: number; ms: number }the worker time (ms) all finished calls of a task took so far, and how many calls
alive(): { at: number; load: number }[]the workers that run (their indices) and the tasks each has in hand
pinTo(pin: string, at: number): voidtie a pin to one worker (-1: this thread) before its first task; a pin already tied keeps its worker
pinGeneration(pin: string): numberthe generation of a pin: it changes when the worker that kept the pin's state is gone (0 before the pin's first task)
run<T = unknown>(task: string, payload: unknown, transfer: Transferable[] = [], pin?: string): Promise<T>run a task; transfer hands buffers of the payload over to the worker (they are empty here after). Tasks with the same pin run in one worker, in order, and share a state object there (the second argument of the task); if that worker dies they reject with ResidentLost and the pin moves on
dispose(): void

packages/core/src/task-pool.ts:52

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 scheduler: Schedulerthe system scheduler: declared kernels of services and components, run in the workers it was started with (scheduler.start), here otherwise
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
removeService(name: string): booleanTake a service out of the world: its scheduled work is dropped and it is disposed (a docked level's scope does it at its end). Returns whether there was one.
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
expose(name: string, get: () => unknown): () => voidShow a named value of the game to tests and tools: world.expose('rpm', () => car.rpm). Returns the function that takes it back.
exposed(name: string): unknownThe current value of an exposed name; throws with the names there are when the game does not expose it.
exposedNames(): string[]The names the game exposes.
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.
async advanceAsync(realDt: number): Promise<number>advance with the declared step kernels run in the scheduler's workers (the step waits for them without blocking the page); the same as advance when there are none
step(): voidExactly one fixed step (also the way tests drive the world); declared step kernels run here, with the same result as in workers.
get stepsAsync(): booleantrue when the step has work in workers that it must wait for: declared step kernels, or a service whose asynchronous step wants to run
readonly asyncComponents: Set<Component<Record<string, any>>>components that may step in the workers (they add themselves when attached and take themselves out when detached)
run(seconds: number): voidRun the world headless for seconds of simulated time.
dispose(): void

packages/core/src/world.ts:42

Functions

addPackageWorkers function

function addPackageWorkers(urls: Record<string, string>): () => void

a docked level's workers: added to the game's own while the level is current; the returned function takes them away

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

buildKernelSpawn function

async function buildKernelSpawn(kernels: { path: string; text: string }[]): Promise<{ spawn: ((cls: KernelWorker) => WorkerLike) | null; urls: string[] }>

The kernel workers of a game (or a docked level) played from a package: module workers that load the release's kernel module (kernels/plain.js, or after Babylon kernels/babylon.js), then the game's own kernels from its package (entry.kernels, their @ferret/* imports pointed at that module, so they register where the worker runs them), then run. Messages that come while it loads wait. Without the release folder (FERRET_LIB) the page's own scripts stay.

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

callWithSlices function

function callWithSlices(fn: (input: any, st: Record<string, unknown>) => unknown, input: unknown, st: Record<string, unknown>): unknown

Runs a kernel function with the slices of its input turned into typed arrays (the input's own properties, one level deep). With no slices it is a plain call. With copies, the arrays asked for writing come back in the answer (finishWrites on the game's side puts them into their StateBuffers).

packages/core/src/state-buffer.ts:65

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:197

defaultPoolSize function

function defaultPoolSize: () => number

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

defineTask function

function defineTask<I, O>(name: string, run: (input: I) => O): void

the function of a task: plain data in, plain data out. Put it in the game's src/kernels.ts (the build puts that file in the workers too)

packages/core/src/task.ts:8

ensureBabylon function

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

Make sure the named parts of Babylon are loaded (core, gltf with the PBR materials, shadows, particles, pipeline, video, debug; tools/babylon/parts.mjs): 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

finishWrites function

function finishWrites(out: unknown): unknown

the game's side of a kernel's answer: the writes of copies go into their buffers, the kernel's own result comes out

packages/core/src/state-buffer.ts:80

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:364

gameWorker function

function gameWorker(name: string): WorkerLike

Starts one of the game's own workers by its script name (gameWorker('sim-worker.js')): from the game's package when the player runs it, else the script of that name beside the page (a sample's own page, where tools/build.mjs puts it next to main.js).

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

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:180

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:49

hangWatcherSource function

function hangWatcherSource(base: string, hangMs: number): string

The watcher's code (it runs in a Web Worker, as a string). Messages in: { v } the page's visibility (a hidden page has no frames and runs its timers rarely: not a hang; a change starts both clocks again), { a: 1 } the main thread's timer, { b: 1 } a finished frame (also proof that the thread runs). Each second: no answer from the main thread for hangMs is a stuck thread; an answering thread with no frame for hangMs after the first frame is a frame waiting forever. The first goes to the server's log at once (the main thread cannot send it), and when the stall ends its length goes back to the page (postMessage). Exported for the unit test, which runs it with a fake clock.

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

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

hasKernel function

function hasKernel(name: string): boolean

packages/core/src/scheduler.ts:30

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:153

isSlice function

function isSlice: (v: unknown) => v is StateSlice

packages/core/src/state-buffer.ts:18

kernelNames function

function kernelNames(): { name: string; worker: KernelWorker; resident: boolean }[]

the registered kernels (names and worker classes)

packages/core/src/scheduler.ts:29

kernelWorkerSpawn function

function kernelWorkerSpawn(): typeof kernelSpawn

the kernel worker spawn now in force (or null: the page's own scripts)

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

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

notPlain function

function notPlain(v: unknown): string | null

what in v is not plain data (so it cannot go to a worker), as a path and a reason; null when it is all plain. Looks at most at a few thousand values

packages/core/src/task.ts:23

ownReport function

function ownReport(perf: FrameProfiler, scheduler: Scheduler, extra: (slot: string) => string | undefined = () => undefined): { frameMs: number; rows: OwnRow[] }

the rows of a profiler that are at least 2% of the frame (and 0.3 ms), with what takes each off the game's thread. Needs perf.enabled and a few frames

packages/core/src/perf-advice.ts:23

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:194

pointImports function

function pointImports(text: string, to: (name: string) => string): string

@ferret/* imports of a packaged script pointed at to(name) (a worker has no import map)

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

registerKernels function

function registerKernels(kernels: Record<string, KernelFn | { run: KernelFn; init?: KernelEntry['init'] }>, o: { worker?: KernelWorker } = {}): void

register kernels by name (a package's src/kernels.ts does it at its top level; the page and the worker bundle both import that file)

packages/core/src/scheduler.ts:21

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:36

rolesOf function

function rolesOf(world: World): Roles | undefined

The roles service of a world, if the parent made one (a world with no dock has none).

packages/core/src/roles.ts:54

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

runKernelWorker function

function runKernelWorker(port: WorkerPortLike): void

the worker bundle's entry: runKernelWorker(webPort()) after importing every kernels.ts

packages/core/src/scheduler.ts:45

runSimWorker function

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

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

runTaskWorker function

function runTaskWorker(tasks: Record<string, TaskFn>, port: WorkerPortLike): void

the worker's script: runTaskWorker({ analyseTree }, webPort())

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

scopedGame function

function scopedGame<G extends { world: World; scene: object; input?: any }>(game: G, scope: Scope, _roles?: Roles): G

game seen by the code of a docked level: its world, scene and input are the scoped views; anything else is the parent's own

packages/core/src/scoped-view.ts:94

scopedInput function

function scopedInput<I extends { dispose(): void; attach(canvas: any, o?: any): void; setPointerLock?(on: boolean): void; pointerLock?: boolean }>(input: I, scope: Scope): I

the input as a docked level sees it: the parent's service, which the level may not dispose; attach changes only what the level asks (the pointer lock) and is undone with the scope

packages/core/src/scoped-view.ts:78

scopedScene function

function scopedScene<S extends object>(scene: S, scope: Scope): S

scene seen by the code of a docked level: its observables (onBeforeRenderObservable ...) record the observers they get

packages/core/src/scoped-view.ts:51

scopedWorld function

function scopedWorld<W extends World>(world: W, scope: Scope): W

world seen by the code of a docked level

packages/core/src/scoped-view.ts:14

setKernelWorkerSpawn function

function setKernelWorkerSpawn(spawn: ((cls: 'plain' | 'babylon') => WorkerLike) | null): void

The player: how this page starts the kernel workers instead of ferret-worker.js beside it (a game played from a package has none there): the engine's kernel module of the release with the game's own kernels from its package. null gives the page's own scripts back.

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

setPackageWorkers function

function setPackageWorkers(urls: Record<string, string> | Map<string, string>): void

the player: the game's packaged workers, by their script name (sim-worker.js), each a URL a module worker starts from

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

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:64

webKernelWorker function

function webKernelWorker(cls: 'plain' | 'babylon'): WorkerLike

the engine's kernel workers of a page: ferret-worker.js, or ferret-worker-babylon.js for kernels that need Babylon, beside the page; for world.scheduler.start

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

webPort function

function webPort: () => WorkerPort

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

webWorker function

function webWorker(url: string | URL, name?: string, type?: 'classic' | 'module'): 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; type 'module' for an ES module script

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

withSlices function

function withSlices(tasks: Record<string, TaskFn>): Record<string, TaskFn>

wrap a registry's tasks so slices in their input work (the worker bundle and the page's fallback use it)

packages/core/src/state-buffer.ts:87

workersParam function

function workersParam(): number | undefined

the page's ?workers=N (0: every kernel here), or undefined

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

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

Gathered interface

interface Gathered<I>

what a gather gives: the input, and the buffers to hand over (they are not used here after)

input: I
transfer: Transferable[]

packages/core/src/scheduler.ts:48

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:18

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

KernelDecl interface

interface KernelDecl<I = any, O = any>
name: stringthe kernel's name in the registry
inline?: booleana part its service runs itself at its place in the step (a kernel's step between a service's own phases): listed in the module, left out of the waves
module?: stringthe module this part belongs to (set by Scheduler.module)
sync: 'step' | 'frame'step: the step waits for it (gameplay, physics; deterministic); frame: the page does not wait, the answer is applied at a later step (the view)
reads?: string[]names of the resources it reads and writes: kernels that do not touch the same resources (one writing what the other reads or writes) run at the same time
writes?: string[]
every?: numberrun it every n-th step (default 1)
resident?: { key: string; init(world: World): unknown | Gathered<unknown> }a state the kernel keeps in its worker (a collision world, a surface): sent by init once, again when the worker is lost or refresh asks
split?: { count(input: I): number; slice(input: I, from: number, to: number): I; merge(outs: O[], input: I): O }independent items: cut into one range per worker, each range a kernel call, the answers merged in index order (the result is the same for any number of workers)
author?: booleanset by the author's short form (Scheduler.task): what it is given is looked at, and when it is not plain data the task runs in the game's thread and the engine says why
gather(world: World, dt: number): I | Gathered<I> | nulltake the input out of the world here (null: nothing to do at this step)
apply(world: World, out: O): voidwrite the answer back here

packages/core/src/scheduler.ts:50

KernelEntry interface

interface KernelEntry
run: KernelFn
init?: (payload: any, state: Record<string, unknown>) => void
worker: KernelWorker

packages/core/src/scheduler.ts:16

ModuleDecl interface

interface ModuleDecl

A module's description, written once by the engine's developers: its parts (kernels with what each reads and writes, step or frame, and how its data splits), and in words what stays in the game's thread. The step of 9.2 follows from it: parts that touch nothing in common run at the same time, a part that reads what another writes waits, a split part runs as many pieces as there are workers, the step ends at a barrier.

name: string
parts: KernelDecl[]
stays?: string

packages/core/src/scheduler.ts:103

ObservableLike interface

interface ObservableLike<T = unknown, O = unknown>

a Babylon Observable, as far as the scope needs it

add(fn: (e: T) => void, ...rest: any[]): O
remove(o: O): unknown

packages/core/src/scope.ts:17

OwnRow interface

interface OwnRow
name: stringthe slot: own:name (a function of the game, timed by its author), component:Class.onFixedUpdate, fixed:service, update:service
ms: numberms in the game's thread per frame, and its share of the frame
share: number
kind: 'own' | 'engine' | 'code'own: the author's function; engine: a module of the engine that is declared to the scheduler; code: a component or service no module is declared for
say: stringwhat the engine says about this row: where it runs and why it is the narrow place

packages/core/src/perf-advice.ts:9

PacerTick interface

interface PacerTick

Even frame pacing. A frame that takes a little more than one refresh of the display is shown after two, the next after one, then two: the pictures come at uneven intervals and the motion jerks although the average rate is fair. The pacer draws every k-th refresh instead, k the smallest that the frames keep without being late, and gives the world exactly k refreshes of time a frame, so things move the same distance every picture.

- the refresh period is learnt from the callbacks that come after one that drew nothing (60 Hz until there are some, less if callbacks come faster); - a drawn frame that comes later than its slot by more than half a refresh is a miss; misses in more than 4% of the last two seconds of frames raise k at once; - after four seconds without a miss, k is lowered by one if the frame's own work fits the shorter step with a third to spare; when that brings misses back

  within ten seconds, the shorter step is not tried again for half a minute (the work a frame gives the GPU is not in its own work);

- the time given to the world is k periods while on schedule; a frame really late gets the time that really passed (the world never falls behind the clock). Pure: no Babylon. tick(now, work) is called on every display callback; it says whether to draw and with how much time.

draw: boolean
dt: number

packages/core/src/frame-pacer.ts:14

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:73

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
never?: booleanNever lower quality (a game that holds its picture before its frame rate): the regulator is off and cannot be switched on, the levels remembered from earlier runs are not loaded and nothing is saved, every knob stays at its richest (level 0). The commands quality.set and quality.preset still work by hand.
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:74

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

SchedulerStart interface

interface SchedulerStart
spawn?: (cls: KernelWorker) => WorkerLikestarts a worker of a class (webKernelWorker on a page); without it every kernel runs here
threads?: numberplain workers (default: the cores less two, 1 to 7)
babylonThreads?: numberBabylon workers, started when a kernel needs one (default 1)

packages/core/src/scheduler.ts:76

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
readonly kernels?: KernelDecl[]kernels this service declares: taken when the service is added
readonly schedule?: ModuleDecla module's description: its parts, what splits, what stays in the game's thread; taken when the service is added
fixedUpdateAsync?(dt: number): Promise<void>the same step, asynchronous, for a service whose work goes to workers at its place in the step: used by advanceAsync when wantsAsync says yes
wantsAsync?(): boolean
whyHere?(): string | undefinedwhy its work stays in the game's thread right now (in words), or undefined when it goes to the cores: what perf.report tells the author

packages/core/src/world.ts:12

SharedState interface

interface SharedState

a state kept in workers (see Scheduler.shared)

call<O = unknown>(kernel: string, input: unknown, transfer?: Transferable[], slot?: number): Promise<O>a kernel on the state, in the least loaded worker that holds a copy (or makes one); with a slot, in the slot's own worker (slot 0 is the first worker that runs, slot 1 the next, and so on round), which keeps what the kernel left in that worker's copy for the slot's next call
update(kernel: string, payload: unknown): voidchange every copy (and those made later) by a kernel
readonly copies: numberhow many copies were made
drop(): voidlet the workers forget the state (the copies are made again at the next call); for a state that is replaced by a new one

packages/core/src/scheduler.ts:86

SimEmitter interface

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

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

SimHostOptions interface

interface SimHostOptions
mode?: 'worker' | 'thread'where the simulation runs; default: in a worker when spawn is given and the platform has workers, else in this thread (program needed)
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
paused?: booleanCreated paused: game time does not run until start() (thread mode: pump does not step; worker mode: the worker does not free-run). A game made so that nothing happens before Ready creates its host paused and starts it when the splash leaves. Default false (thread mode steps from the first pump).

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

StateSlice interface

interface StateSlice

what travels in a kernel's input in place of a typed array

$slice: 1
id: number
ctor: string
from: number
to: number
access: Access
buffer?: SharedArrayBuffer
byteOffset?: number
data?: TypedArray

packages/core/src/state-buffer.ts:14

TaskPoolOptions interface

interface TaskPoolOptions
spawn?: () => WorkerLikestarts a worker (() => webWorker(new URL('task-worker.js', document.baseURI))); without it, or with threads 0, tasks run in this thread, one per turn of the event loop
threads?: numberhow many workers (default: the cores less two, 1 to 4)
tasks: Record<string, TaskFn>the same functions the worker's script has: the fallback in this thread

packages/core/src/task-pool.ts:43

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

WorkerPortLike interface

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

packages/core/src/task-pool.ts:10

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:31

Types

Access type

type Access = 'r' | 'w' | 'rw'

packages/core/src/state-buffer.ts:12

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:41

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

KernelFn type

type KernelFn<I = any, O = any> = (input: I, state: Record<string, unknown>) => O | { result: O; transfer: Transferable[] }

a kernel: pure, on plain data (typed arrays, numbers, strings, plain objects); state is the resident state of its pin in the worker that runs it

packages/core/src/scheduler.ts:13

KernelWorker type

type KernelWorker = 'plain' | 'babylon'

the class of worker a kernel needs: plain (no Babylon), or one that loads Babylon first (ferret-worker-babylon.js)

packages/core/src/scheduler.ts:15

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

TaskFn type

type TaskFn = (payload: any, state: Record<string, unknown>) => unknown | { result: unknown; transfer: Transferable[] }

a task: the result, or { result, transfer } to hand typed arrays' buffers back without a copy

packages/core/src/task-pool.ts:7

TypedArray type

type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array

packages/core/src/state-buffer.ts:8

Undo type

type Undo = () => void

Scoped registration: a view of the world that records what a docked level adds and takes all of it back when the level goes. Commands, components, behaviours, services, event handlers, entities, Babylon observers, DOM listeners and intervals made through the scope are undone by dispose, newest first. A game that is not docked never makes one, so nothing changes for it. A name clash with the parent is the level's own error and is thrown as it is without a scope (Registry.register); a command of the same name replaces the parent's for the time of the level and is given back after it.

packages/core/src/scope.ts:14

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