# Networking and accounts

# Networking and accounts

`net` is built on one idea: **the game owns its backend**; the engine owns the mechanism. Everything that talks to a server sits behind an interface the game implements.

## Transports and replication

A `Transport` moves entity state between clients: `MemoryTransport` (tests and local, with rooms), `WebSocketTransport` (a relay such as `tools/relay`: every message goes to the other clients of the room), `HttpPollTransport` (a key-value server: every client sets one record of Ferret's own shape and reads the others'), `RecordPresenceTransport` (the presence server of the Unreal games, see below) and `LiveKitTransport` (a data channel in a LiveKit room). A `Replicated` entity lists the `fields` that travel; `bodyField` replicates a physics body, and a body at rest sends only its pose. Remote players appear as avatars driven by the received state.

`NetService` is the mechanism: entities, events, messages (`send(name, data, to?)`, to everyone or to one player), join and leave of peers. A game with other players needs more than that, and every such game builds the same things over it; `Multiplayer` is that layer.

## Multiplayer

`Multiplayer` sits on a `NetService` and knows **players**, not only peers: their names, their **scope** (where they are: a level, a zone, any string the game gives; null while travelling) and their seniority. Everything is opt-in, and a game without `@ferret/net` stays single-player.

```ts
const net = world.addService(new NetService(new WebSocketTransport({ url, token: room => tokenFor(room) }), { id: me, tickRate: 15 }));
const mp = world.addService(new Multiplayer(net, {
  name: () => account.user()?.name ?? me,
  scope: () => levels.current?.id ?? null,
  ready: () => !levels.travelling,
  rooms: level => `school:${level}`,
  avatar: {
    entity: hero,
    create: (w, owner) => w.spawn(`player-${owner}`, { tags: ['remote-player'] }),
    keep: e => levels.exempt(e),
    look: { get: () => preset, apply: (e, p) => kit.dress(e, p as Preset), byName: n => pickByName(n, PRESETS) },
  },
}));
void mp.start();                              // connecting never holds the game back
```

- **The avatar.** The player's entity is published; the game's `create` makes the copy of another player's (its body, its animator), and `Multiplayer` adds the replication, the shown name, the scope and the look. A look is put on once per change, and tried again with the next update if `apply` rejects; until a player's look is known (or for a client that never sends one) it is the one `pickByName` gives, the same on every machine. A copy is not made while `ready()` is false (during a level travel, what is made would be taken for part of the level); `keep` is called with each copy.
- **Scopes.** A copy is shown only while its player is in this player's scope. With `rooms`, the transport changes room when the scope changes (`setRoom`; the relay's room is a query parameter), so players of other levels send nothing at all; the players of the old room are forgotten at once (`net:leave` for each). While travelling (scope null) the player stays in the room it was in. A transport without rooms is refused for this option.
- **Admission.** `WebSocketTransport` asks `token(room)` before each connection and puts it on the URL; with no token it stays out, without a retry loop, until `reconnect()`. `Multiplayer` calls that after `account:login` (`reconnectOn`), so a guest joins the room the moment they sign in. `tools/relay` with a secret (`startRelay(port, { secret })`, or `RELAY_SECRET`) admits a client only with `roomToken(secret, room)`, the hex HMAC-SHA256 of the room; the game's server gives it to the players it admits.
- **Channels.** `mp.channel(name)` is a small value each player keeps (a laser pointer's spot, a held tool, a status): `set` it every frame; it is sent when it changes, at most every `interval`, repeated every `keepalive` while it lasts, cleared once when set to null. Another player's value goes when they leave, when it is not repeated in time (`expire`), and (scoped, by default) while they are in another scope. `get`, `entries` and `on` read it; values that arrive before the channel is opened here are kept for it.
- **Locks.** `mp.lock(name)` is a thing only one player (of the scope, by default) may have: `acquire` succeeds when nobody else has it; two claims at the same moment are settled the same way on every machine (the earlier claim, then the smaller id), and the loser gives its claim up. The holder leaving frees it.
- **Authority.** `mp.authority(scope)` is the player who has been in that scope longest (by the wall-clock time each one says it arrived, then by id); `authority(null)`, of the whole room. Every machine computes the same answer from the same messages, and it passes on by itself when the authority leaves. A player who has just arrived does not count itself for `settle` seconds, time to hear the others. Use it wherever one machine must decide: the weather of `netFlow` (`authority: mp.isAuthority()`), an NPC's roaming, a match's score. Event `mp:authority`.
- **Latecomers.** `mp.share(name, { snapshot, restore })` registers a state a player finds on arrival: the authority of a scope sends its snapshot to a player who enters that scope (`scoped: false`: the room's authority, to a player who joins the room). `restore` runs as if the change came from another player, so the shared events it raises (a door opening) are not sent out again. Event `mp:synced`.

World events: `mp:join`, `mp:leave`, `mp:player` (name or scope changed), `mp:authority`, `mp:synced`, `mp:lock`, `mp:room`.

## Unreal clients: the presence wire

The Unreal games (`USchoolMultiplayerSubsystem` and its Go PresenceServer) keep one record per player on a presence server: `POST {op:'set', ...record}` every second, `{op:'list'}` for the names (`{names:[...]}`), `{op:'get', name}` for each record (or `{error}`); a record not set for about three seconds is forgotten. `RecordPresenceTransport` speaks that wire, so browser players and Unreal players share one world as players of `Multiplayer`: an Unreal player has a name, a scope and an avatar that walks (the records carry no velocity, so it is the way the player went since the last record), and never takes part in authority, since it does not speak the protocol. The net id must be the record's name.

What the record holds is a codec's: `unrealStudentCodec` writes `FStudentData` as the Unreal client does (centimetres, Unreal axes, the capsule's centre, yaw turned by 90 degrees; `level` is the scope, `userName` the shown name) and reads it back; `extra` maps further record fields to avatar fields (`{ preset: 'look' }`), and `extras: true` carries Ferret's events and channels in one more field, `ferret`, for servers that keep fields they do not know (the Go server's struct drops them: positions and names still travel, events do not). It polls, so it is about a second behind: use the relay for anything quicker, and this to share a world with the original engine's clients. A server that cannot be reached is tried again after 1, 2, 4 and up to 30 seconds.

Besides entity state, a transport's presence server can hold **named records**: `PresenceRecordStore` sets and reads a record by name (`set` / `get` over the same wire), the server forgets one that nobody posts for about three seconds, and a client that cannot reach the server keeps its own posts for that long, so a player alone and offline still drives the state. `ProximityTransform` in gameplay packages (skill `ferret`) uses it.

## Gateways

`Gateways` holds the game's backends, each behind an interface (`GatewaySet`): account and currency, dialogue, zone occupancy, voice. `call(name, fn, fallback)` runs a backend call safely, so a game without a backend, or with one that is down, falls back instead of failing. The Camerlengo link (`CamerlengoClient`, `CamerlengoOccupancy`, `CamerlengoVoice`) is one implementation: a single endpoint, a command and its parameters.

## Voice

Voice rooms follow zones: entering a zone joins its room, leaving it leaves the room (`LiveKitVoice`). The LiveKit client is passed in, so the engine does not bundle it.

## Accounts

`AccountService` is the player's account in the game's own process: sign-in, a session kept between page loads, balances, and a gateway for `net`. `signInCard` is a ready sign-in form, with text a game can translate (`SignInStrings`).
