@ferret/net
Replication over pluggable transports; multiplayer: players, scopes and rooms, avatars with looks, channels, locks, authority, state for latecomers; the Unreal presence wire; gateways to a game's backend, the Camerlengo link.
Classes
CamerlengoClient class
class CamerlengoClientconstructor(readonly opts: CamerlengoOptions) | |
async call(command: string, params: Record<string, unknown> = {}): Promise<Record<string, any>> | |
async login(path: string, user: string, password: string): Promise<string> | Signs in; resolves with the session token. |
packages/net/src/camerlengo.ts:24
CamerlengoError class
class CamerlengoError extends Errorconstructor(readonly command: string, readonly code: string, reason: string) |
packages/net/src/camerlengo.ts:20
CamerlengoOccupancy class
class CamerlengoOccupancy implements OccupancyGatewayZone occupancy for the backend's registry (zone:setActive): a zone with players is active, one that emptied is set inactive. Uses a service key, so it belongs on the game server (or a trusted host); level is the registry's level id.
constructor(private client: CamerlengoClient, private opts: { key: string; level: string }) | |
async report(occupancy: Record<string, number>) | zone hash -> number of players there |
packages/net/src/camerlengo.ts:62
CamerlengoVoice class
class CamerlengoVoice implements VoiceGatewayThe voice room of a zone for the signed-in player. session is read on every call, so it can change (sign-in, refresh).
constructor(private client: CamerlengoClient, private session: () => string | null) | |
async roomFor(zoneHash: string) | a token and URL for the LiveKit room of a zone (zoneHash, never the zone's name) |
packages/net/src/camerlengo.ts:47
Gateways class
class Gateways implements ServiceHolds the gateways and calls them safely. call(name, fn, fallback) runs fn(gateway) and returns fallback if the gateway is absent, switched off, down (inside its cooldown) or the call fails or times out. Events: gateway:down { name, error }, gateway:up { name }.
readonly name: "gateways" | |
constructor(readonly set: GatewaySet = {}, readonly opts: GatewayOptions = {}) | |
init(world: World) | |
has(name: GatewayName): boolean | Is there a gateway of that name, switched on? (Not whether it is reachable.) |
isDown(name: GatewayName): boolean | |
async call<K extends GatewayName, R>(name: K, fn: (g: NonNullable<GatewaySet[K]>) => Promise<R>, fallback: R): Promise<R> | |
user() | |
balance() | |
change(amount: number, reason: string): Promise<number | null> | Earn or spend. Resolves with the new balance, or null when it did not happen (no account, backend down, refused). |
voiceRoom(zoneHash: string) | |
async reportOccupancy(o: Record<string, number>) | |
dialogue(npc: string, utterance: string, context?: Record<string, unknown>) | The NPC's line from the backend, or null: the caller then says its local line. |
packages/net/src/gateways.ts:56
HttpPollTransport class
class HttpPollTransport implements TransportPresence-server transport: every client sets one record (its entities' latest state and its last events) and lists the records of all. The server needs no change, but this is polling: positions about twice a second, events as soon as the next poll. Enough to see other players walk about; use websocket or livekit for anything quicker. The record is { state, events: [{seq,name,data}], time } under the key = the client's id.
readonly name: "http-poll" | |
healthy: boolean | false while the server cannot be reached |
constructor(readonly opts: HttpPollOptions) | |
connect(selfId: string) | |
disconnect() | |
send(msg: NetMessage, _reliable: boolean) | |
onMessage(fn: (m: NetMessage) => void) | |
update() | Poll when it is time. Call every frame; it does nothing in between. |
packages/net/src/transport.ts:239
LiveKitTransport class
class LiveKitTransport implements Transportreadonly name: "livekit" | |
constructor(private currentRoom: () => DataRoom | null) | |
connect() | |
bind(room: DataRoom) | Call when the room (re)joins: start listening on it. |
disconnect() | |
send(msg: NetMessage, reliable: boolean) | |
onMessage(fn: (m: NetMessage) => void) |
packages/net/src/transport.ts:319
LiveKitVoice class
class LiveKitVoice implements VoiceAdapterJoins and leaves the voice room of a zone. createRoom makes a fresh Room each time (() => new Room() from livekit-client), so the engine does not depend on that package. room is the connected Room, for LiveKitTransport.bind.
room: LiveKitRoomLike | null | |
constructor(private createRoom: () => LiveKitRoomLike, private opts: { microphone?: boolean; onJoin?: (room: LiveKitRoomLike) => void; /** where the audio elements of other players go (default: document.body, when there is a document) */ container?: { appendChild(n: any): unknown } } = {}) | |
async join(r: { url: string; token: string; room: string }) | |
async leave() |
packages/net/src/camerlengo.ts:93
MemoryHub class
class MemoryHublatency: number | artificial one-way delay in ms (0 = delivered at once) |
loss: number | drop this share of unreliable messages |
join(t: MemoryTransport, id: string, room = '') | |
leave(id: string) | |
members(room = ''): string[] | the peers in a room (tests) |
deliver(from: string, msg: NetMessage, reliable: boolean) |
packages/net/src/transport.ts:47
MemoryTransport class
class MemoryTransport implements Transportreadonly name: "memory" | |
constructor(readonly hub: MemoryHub, public room = '') | |
connect(selfId: string) | |
disconnect() | |
send(msg: NetMessage, reliable: boolean) | |
onMessage(fn: (m: NetMessage) => void) | |
onConnect(fn: () => void) | Called each time the transport (re)connects, so a player can say hello again. Returns the unsubscribe. |
async setRoom(room: string) | Transports with rooms: leave the room and join another (the peers of the old room are gone for this player). |
receive(m: NetMessage) |
packages/net/src/transport.ts:71
Multiplayer class
class Multiplayer implements Servicereadonly name: "multiplayer" | |
world: World | |
readonly now: () => number | |
readonly wall: () => number | |
readonly scoped: boolean | true when the game has scopes (the scope option) |
constructor(readonly net: NetService, readonly opts: MultiplayerOptions = {}) | |
get id(): string | |
get scope(): string | null | this player's scope as last seen |
init(world: World) | |
players(): PlayerInfo[] | The other players. |
player(id: string): PlayerInfo | undefined | |
get self(): PlayerInfo | |
near(): PlayerInfo[] | The other players in this player's scope. |
authority(scope: string | null | undefined = this.myScope): string | null | The authority of a scope (default: this player's; null: of the whole room): the player who has been there longest, by the time each one says it arrived (then by id). Every machine computes the same answer from the same messages. Null while there is none known: a player who has just arrived does not count itself until it has had time to hear the others. |
isAuthority(scope?: string | null): boolean | |
share(name: string, state: SharedState): this | Register a state a player gets on arrival from the authority (the doors of a level, the score of a match). |
channel<T>(name: string, opts?: ChannelOptions): PlayerChannel<T> | A small value each player keeps (a pointer's spot, a held tool); one per name. |
lock(name: string, opts?: { scoped?: boolean }): NetLock | A thing only one player (of the scope, by default) has at a time. |
sendChannel(c: string, v: unknown) | |
async start(): Promise<void> | Join: the room of the current scope, then the transport. Connecting never holds the game back. |
get settled(): Promise<void> | Resolves when a room change asked for is done (tests). |
update() | Called once per rendered frame. |
dispose() |
packages/net/src/multiplayer.ts:247
NetLock class
class NetLockA thing only one player has at a time; the first claim wins (by the claim's time, then the player's id). See Multiplayer.lock.
constructor(readonly name: string, private mp: Multiplayer, opts: { scoped?: boolean } = {}) | |
holder(): string | null | Who has it now (a player id), or null. |
get held(): boolean | |
acquire(): boolean | Take it, if nobody else has it. True when this player holds it now (a claim made at the same moment elsewhere may still win). |
release(): void | |
on(fn: (holder: string | null) => void): () => void | Called when the holder changes (null: free). |
tick() |
packages/net/src/multiplayer.ts:203
NetService class
class NetService implements ServiceReplication: publishes the state of the entities this machine owns, creates and moves copies of the others', carries
events (a door opened, an item taken), tells when players come and go. The transport underneath is a setting.
Game code does not know about it: it marks entities (replicate), says which events are shared (replicateEvent) and
how a copy is made (spawnable); with NetService left out the same game is a single-player game.
Events on the world: net:join { peer }, net:leave { peer }, net:event { from, name, data }.
readonly name: "net" | |
readonly id: string | |
readonly tickRate: number | |
readonly delay: number | |
constructor(readonly transport: Transport, readonly opts: NetOptions = {}) | |
init(world: World) | |
isInTransit(e: Entity): boolean | True while the entity is travelling and is not published. |
async start(): Promise<void> | Connect the transport. A transport that cannot connect leaves the game playing alone. |
get peerIds(): string[] | |
copies(): Entity[] | the copies of other players' entities |
spawnable(kind: string, factory: Factory): this | How to make the copy of an entity of this kind. It returns the entity (node, look, animator); the service adds the rest. |
replicate(e: Entity, params: ReplicatedParams): Replicated | Publish an entity this machine owns. |
replicateEvent(name: string, rule: EventRule): this | Share a world event: when it happens here, others get it; when it comes from others, apply does it here. |
send(name: string, data: unknown, to?: string): void | A message of your own to everyone else (reliable); with to, to that one player only. |
asRemote<R>(fn: () => R): R | Run fn as if it came from another player: the shared events it emits are not sent out again (applying a snapshot). |
clock(): number | The service's clock, seconds (the one the interpolation and the timeouts use). |
forget(): void | Forget every other player at once (net:leave for each, their copies go): this player has left the room they were in. |
on(name: string, fn: (data: any, from: string) => void): () => void | Listen for a message of that name from other players. |
fixedUpdate(dt: number) | Called before the components' fixed update, at the fixed rate. |
update() | Called once per rendered frame. |
dispose() |
packages/net/src/net.ts:68
OccupancyReporter class
class OccupancyReporter implements ServiceReports the zone occupancy (hashed names) to the occupancy gateway every few seconds, when it changes.
readonly name: "occupancy-reporter" | |
constructor(readonly opts: { interval?: number } = {}) | |
init(world: World) | |
update(dt: number) | Called once per rendered frame. |
packages/net/src/gateways.ts:154
PlayerChannel class
class PlayerChannel<T>A small value each player keeps; see Multiplayer.channel.
readonly interval: number | |
readonly keepalive: number | |
readonly expire: number | |
readonly scoped: boolean | |
constructor(readonly name: string, private mp: Multiplayer, opts: ChannelOptions = {}) | |
set(value: T | null): void | This player's value; null clears it (the others are told once). |
get own(): T | null | |
get(peer: string): T | null | Another player's value, if it is there and visible from here. |
entries(): Array<[string, T]> | The other players' visible values. |
on(fn: (peer: string, value: T | null) => void): () => void | Called when another player's visible value arrives or goes (null). |
receive(peer: string, v: T | null, s: string | null, at = this.mp.now()) | |
drop(peer: string) | |
rescope() | |
hurry() | |
tick(now: number) |
packages/net/src/multiplayer.ts:113
PresenceRecordStore class
class PresenceRecordStoreNamed records on the presence server, speaking the original game's wire: POST {op:"set", name, x, y, z, yaw, model} to assert one and POST {op:"get", name} to read it; a reply with an error field means missing or stale. The server forgets a record that nobody posts for ~3 s, so "nobody is near" needs no message. read is synchronous: it returns the last answer and starts the next poll in the background (one in flight per name), so a caller that ticks reads the state one tick late, as the original does. When the server cannot be reached the client's own posts are kept for stale seconds so a player alone, offline, still drives the state. Structurally a RecordStore of @ferret/transform.
offline: boolean | true after a failed request, false after a successful one |
constructor(readonly opts: PresenceRecordStoreOptions) | |
post(name: string, record: NamedRecord) | |
read(name: string): NamedRecord | null |
packages/net/src/records.ts:28
RecordPresenceTransport class
class RecordPresenceTransport implements Transportreadonly name: "presence" | |
healthy: boolean | false while the server cannot be reached |
failures: number | consecutive failed rounds; the pause between rounds grows with them (up to 30 s) |
constructor(readonly opts: RecordPresenceOptions) | |
connect(selfId: string) | |
disconnect() | The record is simply no longer set: the server forgets it within seconds, and the others take that for leaving. |
send(msg: NetMessage, _reliable: boolean) | |
onMessage(fn: (m: NetMessage) => void) | |
update() | Start a round when it is time; call every frame. |
async round(now = (this.opts.now ?? Date.now)()): Promise<void> | One round: set this player's record, list the names, get each other record (exposed for tests). |
packages/net/src/presence.ts:40
RemoteMotion class
class RemoteMotion extends ComponentGives a remote copy a motion for the Animator (walk/run by the speed the owner reported).
velocity: Vector3 | |
grounded: boolean | |
motionState() |
packages/net/src/net.ts:29
Replicated class
class Replicated extends Component<ReplicatedParams>Marks an entity whose state is published (when this machine owns it) or received (when it is somebody else's copy).
owner: string | the owner's id: the player who publishes it |
remote: boolean | |
netId: string | network id |
packages/net/src/net.ts:20
UnrealRecordStore class
class UnrealRecordStore implements FerretRecordStoreAdapts a store that speaks the original game's units (Unreal axes: x mirrored, y = Ferret z, z up, centimetres, location = the capsule's centre; yaw turned by 90 degrees as the level exporter turns it) to Ferret's, so Ferret and Unreal clients share records such as an NPC's state. half is half the capsule's height in metres (default 0.44, the animals' 34 x 88 cm capsule).
constructor(private inner: FerretRecordStore, private half = 0.44) | |
post(name: string, r: NamedRecord) | |
read(name: string): NamedRecord | null |
packages/net/src/records.ts:87
WebSocketTransport class
class WebSocketTransport implements Transportreadonly name: "websocket" | |
connected: boolean | false while the socket is down; messages sent then are dropped (state) or kept for the reconnect (events) |
unauthorized: boolean | true when the last attempt had no token: the transport waits for reconnect() |
room: string | the room joined, for transports with rooms |
constructor(readonly opts: WebSocketOptions) | |
async connect(selfId: string): Promise<void> | |
disconnect() | |
async setRoom(room: string): Promise<void> | Leave this room (a bye to its players) and join another; events not yet sent wait for the new room. |
async reconnect(): Promise<void> | Try to connect now, if not connected (a token that was missing may be there now: the player has signed in). |
send(msg: NetMessage, reliable: boolean) | |
onMessage(fn: (m: NetMessage) => void) | |
onConnect(fn: () => void) | Called each time the transport (re)connects, so a player can say hello again. Returns the unsubscribe. |
packages/net/src/transport.ts:122
ZoneVoice class
class ZoneVoice implements ServiceZone voice: when the player enters a zone, join the voice room of that zone (through the gateway's token); leaving the zone leaves the room. No gateway or no adapter: the zones stay silent.
readonly name: "zone-voice" | |
current: string | null | |
constructor(readonly adapter: VoiceAdapter, readonly opts: { tag?: string } = {}) | |
init(world: World) | |
get settled(): Promise<void> | Resolves when the joins and leaves asked for so far are done (tests). |
enterZone(zone: string) | Join the voice room of a zone now (also for a player who is already in it when the gateway comes online, e.g. after sign-in). |
dispose() |
packages/net/src/gateways.ts:114
Functions
bodyField function
function bodyField(): ReplicatedFieldThe replicated field for a body: add it to a Replicated entity's fields ({ body: bodyField() }). The owner publishes the snapshot; a copy turns its node to it and, if the copy has a body, gives it the velocities (so a kinematic copy carries on in the direction it was going between two updates). Position and the interpolation already come with the entity's state.
packages/net/src/bodies.ts:32
pickByName function
function pickByName<T>(name: string, list: readonly T[]): TOne of a list chosen by a name, the same on every machine (a character for a player who did not choose one).
packages/net/src/multiplayer.ts:104
replicateBreaks function
function replicateBreaks(net: NetService, strengthOf: (world: World) => { breakNow(e: Entity, point?: [number, number, number], seed?: number): void } | undefined): voidShare breaks: when a replicated body breaks here, the others break its copy with the same seed, so the pieces and their scatter are the same (the strength capability takes the seed, breakNow(entity, point, seed)). A break of an entity that is not replicated stays on this machine.
packages/net/src/bodies.ts:59
snapshotBody function
function snapshotBody(b: BodyLike): BodySnapshotRound and pack a body's state: millimetres, 1e-4 in a unit quaternion, one flag when it sleeps.
packages/net/src/bodies.ts:22
unrealStudentCodec function
function unrealStudentCodec(o: UnrealStudentCodecOptions = {}): PresenceRecordCodecFStudentData both ways. Ferret (x, y, z) are Unreal (-X, Z, Y) / 100; the location is lifted by half to the capsule's centre; the yaw turned by yawOffset degrees. Numbers are rounded to 0.01 as the Unreal client writes them; timestamp is in seconds. The record's name is the player's id (the presence key), userName the shown name.
packages/net/src/presence.ts:172
Interfaces
AccountGateway interface
interface AccountGatewayThe game's backends, each behind an interface the game implements (§4.7): account and currency, the voice room of a zone, zone occupancy, NPC dialogue. All are optional. A missing or unreachable gateway never throws into the game: calls return their fallback and the gateway is marked down until it works again.
user(): Promise<{ id: string; name: string } | null> | the signed-in player, or null for a guest |
balance(): Promise<number> | |
change(amount: number, reason: string): Promise<number> | earn (positive) or spend (negative); resolves with the new balance, rejects when the backend refuses |
packages/net/src/gateways.ts:9
AvatarLook interface
interface AvatarLookget(): unknown | this player's look (a character preset, a colour): published with the avatar |
apply(copy: Entity, look: unknown, owner: string): void | Promise<unknown> | put a look on a copy; called when it changes. A promise that rejects lets the same look be tried again with the next update |
byName?(name: string): unknown | the look of a player whose look is not known (yet, or ever: a client that does not send one); the same on every machine |
packages/net/src/multiplayer.ts:35
AvatarOptions interface
interface AvatarOptionsentity: Entity | this player's entity |
kind?: string | the replication kind (default 'avatar') and key (default 'hero') |
key?: string | |
create(world: World, owner: string, state: EntityState): Entity | null | makes the copy of another player's avatar (node, body, animator); Multiplayer adds replication, look and visibility |
look?: AvatarLook | |
fields?: Record<string, ReplicatedField> | more fields to carry on the avatar |
keep?(copy: Entity): void | called with each copy made (a level service's exempt, so that a level change does not take it away) |
packages/net/src/multiplayer.ts:44
BodySnapshot interface
interface BodySnapshotWhat a snapshot of a body holds. A body at rest sends its pose only (z): no velocities to apply, no change to send.
q: [number, number, number, number] | |
v?: [number, number, number] | |
w?: [number, number, number] | |
z?: 1 |
packages/net/src/bodies.ts:15
CamerlengoOptions interface
interface CamerlengoOptionsThe Camerlengo backend (ReForce API v2): one endpoint, POST /, body { command, ...params }, answer { ".status": "ok"|"error", ... }. Commands the game uses:
user:verify {key, path, user, password} -> {session} sign a player in (`key`: the app's public key, scope user:verify only)
livekit:userToken {session, room: "zone:<hash>"} -> {token, url, room} the voice room of a zone, for that player
zone:setActive {key, room, level, cellX, cellY, active} zone occupancy (a service key: keep it on the game server, never in a page)fetch is injected so tests and non-browser hosts can supply their own.
url: string | the backend: https://squirrelwisdom.com/ (the proxy to Camerlengo; clients always go through it) |
appKey?: string | the app's public key for user:verify (a key with that one scope; it ships in the page, so it can do nothing else) |
fetch?: typeof fetch |
packages/net/src/camerlengo.ts:12
ChannelOptions interface
interface ChannelOptionsinterval?: number | seconds between two sends of a changing value (default 0.1) |
keepalive?: number | seconds between repeats of an unchanged value (default 1) |
expire?: number | seconds without news after which another player's value is gone (default 3 x keepalive) |
scoped?: boolean | only players in the same scope see the value (default true) |
packages/net/src/multiplayer.ts:88
DataRoom interface
interface DataRoomThe part of a LiveKit Room this needs; pass the real one (livekit-client) or a fake.
publishData(data: Uint8Array, opts: { reliable: boolean }): Promise<void> | void | |
onData(fn: (data: Uint8Array, from?: string) => void): () => void |
packages/net/src/transport.ts:314
DialogueGateway interface
interface DialogueGatewaysay(npc: string, utterance: string, context?: Record<string, unknown>): Promise<string | null> | what an NPC says to the player; null when it has nothing (the game then uses its local lines) |
packages/net/src/gateways.ts:27
EntityState interface
interface EntityStateid: string | network id, unique in the game (the owner's id + the entity's key) |
kind: string | which factory makes the remote copy |
p: [number, number, number] | position |
r: number | yaw, radians |
v?: [number, number, number] | velocity, for the remote copy's animation |
g?: boolean | |
f?: Record<string, unknown> | custom replicated fields |
packages/net/src/transport.ts:8
FerretRecordStore interface
interface FerretRecordStoreA store of records in Ferret's units: metres, feet, yaw in degrees (@ferret/transform's SharedRecord).
post(name: string, record: NamedRecord): void | |
read(name: string): NamedRecord | null |
packages/net/src/records.ts:77
GatewayOptions interface
interface GatewayOptionsenabled?: Partial<Record<GatewayName, boolean>> | each can be switched off whatever is supplied (configuration) |
timeout?: number | seconds before a call counts as failed (default 5) |
cooldown?: number | seconds a gateway that failed is left alone before the next try (default 15) |
now?: () => number |
packages/net/src/gateways.ts:41
GatewaySet interface
interface GatewaySetaccount?: AccountGateway | |
voice?: VoiceGateway | |
occupancy?: OccupancyGateway | |
dialogue?: DialogueGateway |
packages/net/src/gateways.ts:32
HttpPollOptions interface
interface HttpPollOptionsurl: string | the presence server's URL |
interval?: number | seconds between polls (default 0.5) |
eventRing?: number | how many recent events a client keeps in its record for others to read (default 20) |
fetch?: (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; json(): Promise<any> }> | |
now?: () => number |
packages/net/src/transport.ts:222
LiveKitRoomLike interface
interface LiveKitRoomLikeThe part of a livekit-client Room that voice needs; pass the real class's instances or a fake.
connect(url: string, token: string): Promise<unknown> | |
disconnect(): unknown | |
localParticipant?: { setMicrophoneEnabled(on: boolean): Promise<unknown> } | |
on?(event: string, fn: (...args: any[]) => void): unknown | livekit-client's event emitter; used to play other players' audio |
startAudio?(): Promise<unknown> |
packages/net/src/camerlengo.ts:80
MultiplayerOptions interface
interface MultiplayerOptionsname?: () => string | this player's shown name (default: the net id) |
scope?: () => string | null | where this player is now; null while travelling. Without it there is one scope and everybody is shown |
avatar?: AvatarOptions | |
ready?: () => boolean | false while copies must not be made (a level is loading); default always ready |
rooms?: boolean | ((scope: string) => string) | one transport room per scope: true (the room is the scope) or a function scope -> room. Needs a transport with rooms |
reconnectOn?: string[] | world events after which a transport that was not admitted tries again (default ['account:login']) |
settle?: number | seconds a player waits after arriving before it may count itself the authority: time to hear the others (default 1) |
now?: () => number | seconds; default the net's clock |
wall?: () => number | wall-clock ms for seniority; default Date.now |
packages/net/src/multiplayer.ts:68
NamedRecord interface
interface NamedRecordA shared record about one named thing (an NPC): the fields of the original game's presence-server record (FStudentData).
location: [number, number, number] | |
yaw: number | degrees |
model: string |
packages/net/src/records.ts:3
NetOptions interface
interface NetOptionsid?: string | this player's id (default: a random one) |
tickRate?: number | state messages per second (default 10) |
delay?: number | remote copies are shown this far in the past, seconds: room to interpolate between two updates (default 0.15) |
timeout?: number | seconds without news before a player counts as gone (default 6) |
now?: () => number | replace the clock (tests); seconds |
packages/net/src/net.ts:35
OccupancyGateway interface
interface OccupancyGatewayreport(occupancy: Record<string, number>): Promise<void> | zone hash -> number of players there |
packages/net/src/gateways.ts:22
PlayerInfo interface
interface PlayerInfoMultiplayer on top of replication: what every game with other players builds over NetService (the pattern of vschool_ferret and the showcase, made general). It knows players, not only peers: their names, where they are (the scope: a level, a zone, any string), who is the authority of a scope, and it gives a game - the player's avatar: published, its copy made by the game, its look carried and put on with a fallback by name, made only when the
world is ready (not during a level travel), hidden while its player is in another scope;- rooms by scope (optional): the transport changes room when the player changes scope, so other scopes send nothing at all; - an admission token and a reconnect when it can be had (a relay that admits only signed-in players); - player channels: a small value each player keeps (a pointer, a held tool, a status), sent when it changes, at most so often,
repeated while it lasts, gone when the player leaves, stops sending or is elsewhere; - locks: a thing only one player at a time may have (the first to claim it keeps it); - shared state for latecomers: what a player finds when they arrive (doors, levers), sent to them by the authority. Unreal clients on the presence wire (RecordPresenceTransport) are players too: they have a name, a scope and an avatar, but never take part in authority (they do not speak this protocol). World events: mp:join / mp:leave / mp:player { player }, mp:authority { scope, peer, self }, mp:synced { from, scope }, mp:lock { name, holder }, mp:room { room }.
id: string | |
name: string | |
scope: string | null | where the player is; null while unknown or travelling |
since?: number | wall-clock ms when the player entered its scope (seniority within it); undefined for players that do not speak this protocol |
joined?: number | wall-clock ms when the player started (seniority over the whole room) |
self: boolean |
packages/net/src/multiplayer.ts:23
PresenceEvent interface
interface PresenceEventPlayers over a presence server of named records: the wire of the Unreal games (USchoolMultiplayerSubsystem and its Go PresenceServer, vschool_ferret's sample server). One record per player, keyed by its name:
POST {op:'set', ...record} assert this player's record (the server forgets one not set for ~3 s)
POST {op:'list'} -> {names: [...]} (a bare array is taken too)
POST {op:'get', name} -> the record, or {error} when it is missing or stalePolling, so about once a second: enough to see others walk about, and the only way to share a world with clients of the original engine. What the record holds, and in which units, is the codec's business (unrealStudentCodec for FStudentData). The player's avatar is the one replicated entity that travels (by default the first of kind 'avatar'); other entities of this player, and events, travel only if the codec has a place for them (extras) and the server keeps fields it does not know. The peer id of NetService must be the record's name: give the service { id: <player name> }.
seq: number | |
name: string | |
data: unknown | |
to?: string |
packages/net/src/presence.ts:16
PresenceRecordCodec interface
interface PresenceRecordCodecencode(own: { id: string; state: EntityState | null; events: PresenceEvent[]; time: number }): Record<string, unknown> | null | this player's avatar state and recent events -> the record to set (without op); null: nothing to publish |
decode(record: Record<string, unknown>): { id: string; state: EntityState | null; events: PresenceEvent[] } | null | a record from get -> whose it is, the avatar's state, its events; null: not a record this game can read |
packages/net/src/presence.ts:18
PresenceRecordStoreOptions interface
interface PresenceRecordStoreOptionsurl: string | the presence server's URL (POST, JSON) |
stale?: number | seconds a record counts as fresh without a new post or a successful read (default 3, the server's own expiry) |
fetch?: (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; json(): Promise<any> }> | |
now?: () => number | seconds, default Date.now() / 1000 |
packages/net/src/records.ts:10
RecordPresenceOptions interface
interface RecordPresenceOptionsurl: string | the presence server's URL (POST, JSON) |
codec: PresenceRecordCodec | |
interval?: number | seconds between two rounds (default 1, as the Unreal client) |
pick?: (ents: EntityState[]) => EntityState | undefined | which of this player's entities is the record (default: the first of kind 'avatar') |
eventRing?: number | how many recent events the record keeps for others to read, when the codec carries them (default 20) |
fetch?: (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; json(): Promise<any> }> | |
now?: () => number | ms; default Date.now |
packages/net/src/presence.ts:25
ReplicatedField interface
interface ReplicatedFieldpackages/net/src/net.ts:5
ReplicatedParams interface
interface ReplicatedParamskind: string | which factory makes this entity's copy on other players' machines |
key?: string | a name that is the same on every machine for this entity (default: the entity's id) |
fields?: Record<string, ReplicatedField> | extra state to carry: a name -> getter and setter (a worn hat, a shown name, a held item) |
packages/net/src/net.ts:10
SocketLike interface
interface SocketLikereadyState: number | |
send(data: string): void | |
close(): void | |
onopen: ((ev?: unknown) => void) | null | |
onmessage: ((ev: { data: unknown }) => void) | null | |
onclose: ((ev?: unknown) => void) | null | |
onerror: ((ev?: unknown) => void) | null |
packages/net/src/transport.ts:94
StudentRecord interface
interface StudentRecordThe Unreal record FStudentData (SchoolBlueprintUtils.h): Unreal axes in centimetres, the capsule's centre, yaw in degrees.
x: number | |
y: number | |
z: number | |
yaw: number | |
name: string | |
userName: string | |
model: string | |
level: string | |
animation: string | |
timestamp: number | |
[extra: string]: unknown |
packages/net/src/presence.ts:143
Transport interface
interface TransportA way to get messages to the other players. send goes to everyone else in the game; the transport never echoes a message back to its sender. Reliable messages (events) must arrive; unreliable ones (state) may be dropped or replaced by newer ones.
readonly name: string | |
connect(selfId: string): Promise<void> | void | |
disconnect(): void | |
send(msg: NetMessage, reliable: boolean): void | |
onMessage(fn: (msg: NetMessage) => void): () => void | |
update?(): void | transports that poll or batch do their work here, called every frame |
setRoom?(room: string): Promise<void> | Transports with rooms: leave the room and join another (the peers of the old room are gone for this player). |
readonly room?: string | the room joined, for transports with rooms |
onConnect?(fn: () => void): () => void | Called each time the transport (re)connects, so a player can say hello again. Returns the unsubscribe. |
reconnect?(): Promise<void> | Try to connect now, if not connected (a token that was missing may be there now: the player has signed in). |
packages/net/src/transport.ts:28
UnrealStudentCodecOptions interface
interface UnrealStudentCodecOptionshalf?: number | half the capsule's height, metres: Unreal's location is the capsule's centre, Ferret's the feet (default 0.8) |
yawOffset?: number | degrees added to Ferret's yaw on the way out (default 90: the exporter turns Unreal's yaw by -90) |
kind?: string | the replication kind of what is decoded (default 'avatar') and its key (default 'hero', the Multiplayer avatar's) |
key?: string | |
fields?: Record<string, string> | record field -> avatar field: the strings of the record (default { level: 'scope', userName: 'name', model: 'model', animation: 'animation' }) |
extra?: Record<string, string> | more record fields (unknown to Unreal clients) -> avatar fields, carried as they are (a chosen character: { preset: 'look' }) |
extras?: boolean | carry Ferret's events and the avatar's other fields in one more field of the record, ferret (servers that keep unknown fields) |
packages/net/src/presence.ts:149
VoiceAdapter interface
interface VoiceAdapterWhat joins a voice room. The LiveKit client is behind this so the engine does not depend on it.
join(room: { url: string; token: string; room: string }): Promise<void> | |
leave(): Promise<void> |
packages/net/src/gateways.ts:105
VoiceGateway interface
interface VoiceGatewayroomFor(zoneHash: string): Promise<{ url: string; token: string; room: string }> | a token and URL for the LiveKit room of a zone (zoneHash, never the zone's name) |
packages/net/src/gateways.ts:17
WebSocketOptions interface
interface WebSocketOptionsurl: string | wss://host/path ; the room is a query parameter the relay understands |
room?: string | |
token?: (room: string) => string | null | undefined | Promise<string | null | undefined> | The room's admission token, asked for before each connection (&token= on the URL; Ferret's relay with a secret wants the hex HMAC-SHA256 of the room under it). Null or undefined: not admitted now, the transport stays out and does not retry by itself; reconnect() asks again (after the player has signed in). A function that throws counts as null. |
create?: (url: string) => SocketLike | replace new WebSocket (tests) |
retry?: number | seconds between reconnect attempts (default 2; 0 = no reconnect) |
connectTimeout?: number | seconds to wait for the connection before giving up on this attempt (default 5) |
packages/net/src/transport.ts:104
Types
EventRule type
type EventRule = { /** event payload -> plain data for the wire (entities become ids); returning undefined keeps the event local */ encode?: (payload: any) => unknown; /** wire data -> the effect here. Must not emit the same event again; if it does, the echo is blocked anyway */ apply: (world: World, data: any, from: string) => void; }packages/net/src/net.ts:48
GatewayName type
type GatewayName = keyof GatewaySetpackages/net/src/gateways.ts:39
NetMessage type
type NetMessage = | { t: 'state'; from: string; time: number; ents: EntityState[] } | { t: 'event'; from: string; seq: number; name: string; data: unknown; /** one player only (the relay still carries it to the room; the others drop it) */ to?: string } | { t: 'bye'; from: string }What goes over the wire. Transports carry these as JSON; they do not look inside.
packages/net/src/transport.ts:3