18. A browser multiplayer protocol
Chapter 8 described how the original's computers talk on a 1993 office network, and chapter 13 sketched how browsers could do the same over the internet. This chapter turns that sketch into a complete specification: every identifier and who hands it out, how connections are set up, how players agree on slots, every message byte by byte, how each message is applied, what happens in every step, and how much bandwidth it costs. Two implementations written from this chapter alone should be able to play together.
Nothing in this chapter exists in NetWars 2.06. The original has no ids, no handshake, no acknowledgements and no server (chapter 8). Where this protocol behaves differently from the original, the text says so and says what the original did. The game rules themselves (what a hit costs, what a satellite gives) are not changed here; chapters 4 to 8 and 14 to 17 define them. The choice between the original's behaviour and a fix is made per room by the preset of chapter 20: Modern and Custom rooms use the protocol of this chapter; Authentic rooms use the variant at the end ("Authentic rooms").
- WebSocket: a long-lived two-way connection from a page to a server.
- WebRTC: the browser's way to connect two browsers directly. An RTCPeerConnection is one such connection; a data channel carries our own bytes over it.
- SDP offer / answer: the two descriptions the browsers exchange (through a server) to set up a connection; one side offers, the other answers.
- ICE: the procedure that tries pairs of network addresses (candidates) until one pair works. Trickle ICE: candidates are sent one by one as they are found, after the offer. ICE restart: running that search again on an existing connection, when its path broke.
- STUN server: tells a browser its public address. TURN server: relays the encrypted
traffic when no direct path works. mDNS candidate: a local address hidden behind a random
….localname; it works only where the local network passes multicast. - DTLS: the encryption of WebRTC traffic. SCTP: the protocol inside it that carries data channel messages; it numbers and acknowledges packets (SACK = its acknowledgement packet), retransmits on reliable channels, and does not on ours marked unreliable.
- bfcache: the browser's back/forward cache, which can freeze a whole page and bring it back later.
The pieces
- Peers: the browsers. Each runs the whole game for its own ship (chapter 8: each computer is the authority for its ship, shots, satellite, score and status; the shooter decides hits; each side decides its own collisions).
- The signalling service: a small server reached over a WebSocket. It keeps, per room, the list of members and the slot table, hands out ids, and relays connection set-up messages. It runs no game logic and never sees a game message. It is the only authority for who holds which slot.
- STUN and TURN servers, whose addresses and credentials the service hands out.
- Two data channels per connected pair:
ev(reliable and ordered: every message arrives, in order) andst(unordered and never retransmitted: a lost message stays lost, and the next one replaces it anyway).
Every page in a room has one of three roles: lobby (connected to the service only, sees the slot table), player (holds a slot, connected to every other player and every spectator), spectator (no slot, connected to every player, never to another spectator; sends no game state). A room has at most 4 players and 4 spectators; lobby pages are limited only by the service (16 is a sensible cap).
Identifiers
| Name | Type | Assigned by, when | Start | Rules |
|---|---|---|---|---|
| room id | 16 random bytes, 22 characters of base64url | the inviter's browser
(crypto.getRandomValues), once | — | In the link's fragment:
https://example.org/netwars#room=k7Qx2mZp9aLw4f0NqT1v8w. A fragment never reaches the web
server; the page passes it to the service in join. Anyone with the link can join. |
| session id | 16 random bytes, base64url | the tab, the first time it opens the
room; kept in sessionStorage | — | Survives a reload of that tab. A secret
between the tab and the service ("I am the tab that held slot 2"); never sent to peers. A
duplicated tab copies sessionStorage, so a page must check that no other tab uses its
session id (service rules below). |
| peer id | u32 | the service, at random, at each join of a new page
(a reload gets a new one) | never 0 | Unique among the room's present members and those of the last 10 minutes. Names a peer in every game message. Compared as unsigned numbers (who is "polite", tie-breaks); the comparison says nothing about who came first. |
| slot | u8 0..3 (PLAYER 1..4) | the service, on claim | — | Fixes ship model, start corner, radar colour and collision push (chapter 8). |
| slot generation (gen) | u16, wraps | the service: +1 each time the slot gets a new holder | 0; first holder gets 1 | (slot, gen) names one holding of a slot. |
| grant number | u32 | the service: +1 per grant in the room | 0; first grant 1 | Orders holdings in time: larger = newer. |
| roster version | u32 | the service: +1 per change of the slot table | first roster 1 | Pages apply rosters in increasing version only; the roster inside welcome always replaces
the page's roster, whatever its version (after an empty restart the numbers start again). |
| life id | u16, wraps | the slot holder: +1 when it enters flight from the name screen and at each respawn | 0 = no life yet; first life 1 | Hits name the victim's life. |
| step | u32 | each page, its own counter, +1 per simulation step | 0 at join; first step 1 | Not shared, not synchronised: it orders one sender's messages and dates its events. |
| satellite id | u16, wraps | the owner: +1 at every spawn | 0 = never had one; first spawn 1 | (owner peer id, satellite id) names one satellite. Never reset while the page lives. |
| shot id | u16, wraps | the shooter: +1 at every shot fired | first shot 1 | (shooter peer id, shot id) names one laser shot. At most 8 of a peer's shots exist at a time, so wrapping never makes two live shots share an id. |
| event number | u32 | each sender, one counter for all its HIT and SAT messages | first event 1 | (sender, event number) names one event. Never wraps in practice (60 events per second for 2 years). |
For every sender a receiver keeps lastStep and lastEvent, both 0 until the
first message. Wrapping u16 counters are compared with serial-number arithmetic: a is
newer than b when (a − b) mod 65,536 is between 1 and 32,767.
Clock and step rate
- Each page steps on its own fixed clock: it accumulates
performance.now()time and runs one step per step period. Modern and Custom rooms: 1/70 s (14,285,714 ns; the multiplayer speed of the original in our recordings, chapter 20 Part 2) or 1,193,182 ÷ 65,536 per second (54,925,401 ns, single-player speed). The period is a room setting. - The steps are driven from the animation frame callback while the page is visible, at most 5 steps per callback; if more are due (the tab stalled), the excess is dropped: the step counter does not jump, the world skips that time. A hidden page leaves flight ("Away", below); its network work (PING, PONG, events) runs from timers and message handlers, never from the animation frame.
- My step time = my step counter + (now − time of my last step) ÷ step period: a fractional step number on my own clock.
- There is no lockstep and no shared step: no page ever waits for another. Each page decides only for its own objects, so no shared random numbers are needed either.
The signalling service
Messages to and from the service are JSON text, one object per WebSocket message, field
t = type. The service handles all messages of a room one at a time, in arrival order, and
sends to each page in order (one WebSocket per page keeps that order). Integers are JSON numbers;
peer ids, slots and counters are as in the identifier table.
Page to service
| t | Fields (type) | Meaning |
|---|---|---|
join | room (string), session (string), proto
([major, minor]), optional settings ({preset: "authentic" | "modern" | "custom", periodNs: int,
rules: 8 lowercase hex digits}), name (string), optional resume ({peer: int, role:
"player" | "spectator" | "lobby", slot: int or null, gen: int, grant: int, rosterV: int, reload:
bool}) | Enter the room. The first page of an empty room fixes its settings (its own, or the
defaults). A page opening a link sends settings only if the link carries them; without it,
it follows the room's settings from welcome. |
claim | slot (int) | Ask for a slot. |
spectate | — | Ask to become a spectator. |
release | — | Give up slot or spectator place; back to lobby. |
signal | to (int), data: either {description:
{type: "offer" | "answer", sdp: string}} or {candidate: RTCIceCandidateInit or null} | Relay
set-up to one peer. candidate: null = end of candidates. |
links | live ([int]) | The peers this page's links to are
live (definition under "Liveness"), plus peers whose last message had the away flag, for up to
10 minutes. Sent right after every welcome and resumed, then on change (at most once
per second) and every 10 s. |
name | name (string) | Name changed. |
ice | — | Ask for fresh STUN/TURN servers. |
ping | — | Every 10 s. A page that has received nothing from the service (pong or anything else) for 5 s after a ping considers the WebSocket dead, closes it and reconnects: a page notices a dead service within 15 s. |
Service to page
| t | Fields (type) | Meaning |
|---|---|---|
welcome | peer (int), settings, roster,
members ([{peer, role, name}]), ice ([RTCIceServer: {urls: string or [string],
username?, credential?}]), iceTtl (int, seconds), recovering (bool) | Joined. |
resumed | ok (bool), role, slot,
gen, grant, reason ("conflict" | "expired") if not ok | Answer to a
resume, right after welcome. |
member | peer, event ("joined" | "left" | "role"),
role, name | Someone joined, left, or changed role. |
roster | v (int), slots (4 entries, each null or {peer,
gen, grant, name, state: "held" | "reserved"}), spectators ([int]) | The slot table, to every page after each change. |
claimed | slot (int or null for spectate), gen,
grant | Claim or spectate granted. |
denied | slot, reason ("taken" | "reserved" | "full" |
"recovering" | "unreachable") | Claim or spectate refused. |
revoked | slot, reason ("unreachable" | "conflict"),
partner (int, for unreachable) | The service took the slot back. |
signal | from (int), data | Relayed set-up message. |
ice | ice, iceTtl | Fresh STUN/TURN servers. |
error | code ("version" | "settings" | "room-full" |
"session-in-use" | "recovering" | "no-peer" | "peer-away" | "bad-message"), peer (for no-peer) | The first four end
the join (the WebSocket is closed); "no-peer" answers a signal to a peer that is gone (the
page then closes its connection to it). |
pong | — | Answer to ping. |
- Liveness of a page: a WebSocket that has sent nothing for 25 s (pages ping every 10 s) or
closed is dead. A page is present while its WebSocket is live or some player's
latest
linksreport lists it as live (a page that alone lost the service but still plays is present). - Taking over a session: a
joinwith aresumethat names the peer id the service currently has for this session id takes the session over, even if the old WebSocket still looks live (it is usually half-open after a network change): the service closes the old socket and continues with the same peer id, slot and gen. - Duplicate session: any other
joinwhose session id belongs to a page with a live WebSocket is refused withsession-in-use; that page creates a new session id and joins again, as a different member. (Pages also check this themselves: each holds the Web Lock"netwars:" + session id; if it cannot get it, another tab has it, and it makes a new session id before joining.) - A slot is free when it has no holder and no reservation.
claimis granted when the slot is free, the page holds no slot, and the room is not recovering: gen := gen + 1, grant := ++grant counter, state held; replyclaimed, then the roster (version + 1) to all. Otherwisedenied. Because claims are handled one at a time, two pages can never get the same slot.spectatelikewise, while fewer than 4 spectators are present.release: slot or spectator place free at once; roster to all.- Reservation: when a holder's WebSocket dies without
release, its slot becomes reserved for its session id. The reservation's 60 s run only while the holder is not present (no WebSocket and no player reporting a live link to it): a page that lost only the service keeps its slot for as long as it keeps playing. 60 s is longer than the page's reconnect back-off, whose longest gap is 18 s. The roster keeps the same peer id and gen with state reserved. Ajoinwith that session id andresumewithin 60 s:reload: false(same page, only the WebSocket broke) keeps peer id and gen;reload: true(a new page) gets a new peer id and gen + 1. After 60 s the slot is free. A service that was unreachable for a while but kept its state restarts all reservation timers when pages reach it again, so its own outage does not use up the 60 s. - Restart with empty memory: for 45 s after it starts, the service is recovering. 45 s
covers a page's detection of the dead service (at most 15 s) plus its longest retry gap (18 s) plus
margin. While recovering it accepts only joins with
resume(others geterror recoveringand retry after 45 s), so new peer ids can never collide with ids named in resumes; it refuses claims and spectates (denied recovering), suspends the partial-mesh rule, and adopts every resumed slot with its peer id, gen and grant (a resume withreload: truegets a new peer id and gen + 1, as above). It sets its grant counter above the largest reported grant and its roster version above the largest reportedrosterV. Two resumes for the same slot: the higher gen wins, then the lower peer id. If the loser arrives second it getsresumed ok: false, conflict; if it was adopted first (and already gotresumed ok), it getsrevoked(conflict)when the winner's resume arrives. Either way it returns to the lobby. When the window ends, slots nobody resumed are free. resumed ok: false, expired: the reservation ran out and the slot has a new holder, or is free (the page may claim again).- A page that gets no answer to
claimorspectatewithin 10 s treats it as denied. - Signals for a peer that is neither present nor reserved are answered with
error no-peer(the sender closes its connection to that peer). Signals for a reserved holder are answered witherror peer-away: the sender keeps its connection (it may still be live, or an ICE restart may be running) and retries later. Nothing is stored. member leftfor a holder whose slot is now reserved does not end anything at the peers: they keep the connection while it is live.
Connections
Who connects to whom
- Required pairs: player–player and player–spectator. Never spectator–spectator, never a lobby page.
- The newcomer offers. When a page becomes a player or spectator, it creates a connection to
each required partner that is present and sends the offer. A page already present does not create
a connection for a newcomer in advance: it creates the RTCPeerConnection and both data channels in
the handler of the newcomer's first offer, synchronously, before calling
setRemoteDescription. - Both channels are created by both sides with
negotiated: trueand fixed ids, so nobody waits for the other to create them:
ev = pc.createDataChannel("ev", {negotiated: true, id: 0})
st = pc.createDataChannel("st", {negotiated: true, id: 1, ordered: false, maxRetransmits: 0})
both withbinaryType = "arraybuffer". - A link is up when both channels are open and HELLO has arrived on
ev. - One connection per peer. Before a page accepts or makes a new connection to a peer id it
already has a connection to (meshing again after a failure, or the peer's offer on a fresh
connection), it closes the old one. Events still in flight on the old
evare lost with it (events are never re-sent), so the new HELLO's nextEvent can never overtake an event that will still arrive. An ICE restart keeps the same connection and is not affected. - Outgoing signals are queued while the page's WebSocket is reconnecting, in order, for up to 30 s; older ones are discarded and the attempt they belonged to counts as failed.
STUN, TURN and candidates
- Use the
icelist fromwelcome. The service should issue TURN credentials valid longer than any session (12 hours). With shorter ones, a page asks forice60 s beforeiceTtlends, callspc.setConfiguration({iceServers})on each connection and thenrestartIce(). Whether a TURN server keeps an existing relay after the credential that created it has expired differs between servers H; the restart makes it independent of that. - Offer TURN over TLS on port 443 (
turns:URLs) for strict networks that allow only web traffic. Over a TCP or TLS relay, the unreliable channel is no longer unreliable on that hop: a lost packet holds up the ones behind it (head-of-line blocking), so states arrive in bursts. That is acceptable; liveness and interpolation tolerate it. - Browsers hide local addresses behind mDNS names. On networks that block multicast or isolate clients (many Wi-Fi networks), two browsers in the same room of a building may fail to connect directly and fall back to STUN or TURN candidates.
Glare: perfect negotiation
"Glare" is when both sides send an offer at the same time (two newcomers who find each other at once, or a renegotiation). Every connection uses the standard perfect negotiation pattern; in each pair the peer with the larger peer id is polite (it gives way), the other is impolite.
makingOffer = false; ignoreOffer = false; isSettingRemoteAnswerPending = false
pc.onnegotiationneeded = async () =>
try:
makingOffer = true
await pc.setLocalDescription() // creates an offer
signal(to, {description: pc.localDescription})
catch e: log(e)
finally: makingOffer = false
pc.onicecandidate = (e) => signal(to, {candidate: e.candidate}) // null at the end
on signal from the peer, data:
try:
if data.description:
d = data.description
readyForOffer = not makingOffer and
(pc.signalingState == "stable" or isSettingRemoteAnswerPending)
offerCollision = d.type == "offer" and not readyForOffer
ignoreOffer = (not polite) and offerCollision
if ignoreOffer: return
isSettingRemoteAnswerPending = (d.type == "answer")
await pc.setRemoteDescription(d) // the polite side rolls back here
isSettingRemoteAnswerPending = false
if d.type == "offer":
await pc.setLocalDescription() // creates the answer
signal(from, {description: pc.localDescription})
else if "candidate" in data:
try:
if data.candidate == null: await pc.addIceCandidate() // end of candidates
else: await pc.addIceCandidate(data.candidate)
catch e: if not ignoreOffer: log(e)
catch e: log(e)
negotiation timeout: if signalingState stays "have-local-offer" for 10 s,
await pc.setLocalDescription({type: "rollback"}) and count a failed attempt
ICE restart, giving up, and meshing again
- When
iceConnectionStatehas been "disconnected" for 2 s, or becomes "failed", the impolite side callspc.restartIce(). The polite side calls it only if no new offer has arrived 5 s after its own detection (a fallback, so normally only one side starts). - At most 3 restarts within 30 s. Then close the connection.
- Meshing again never stops. Whenever the roster shows both pages of a required pair as present and their link is not up and no attempt is running, the page with the smaller peer id creates a new connection and offers, after 2 s; after each failed attempt the wait doubles, up to 60 s; it returns to 2 s once a link has stayed up for 60 s.
- While the service is unreachable, no offer can be delivered: repairs wait for it.
Slots
The service sees every page in the room, handles one claim at a time and answers each claim itself. That makes it the natural authority for slots: whatever order messages arrive in at the peers, there is never more than one granted holder per slot.
- A lobby page shows the roster: each slot with its name, "Free" or "reconnecting".
- Enter on a Free slot sends
claim. Ondeniednothing happens. - On
claimed: connect to the required partners; show the name screen (status "not in play", as in the original). Enter flight when every player link is up, or after 5 s at the latest. - Accepting a player's messages: a page accepts STATE from peer p for slot s when its latest roster lists p as holder of s (held or reserved) with the STATE's gen. A STATE with a newer gen than the roster shows is kept as pending for up to 1 s and used when the roster arrives. A STATE from a peer whose link is live but who is missing from the roster (the service is recovering or briefly lost it) is still accepted, as long as no roster names another holder of that slot.
- While the service is unreachable no slot changes hands. Holders keep their slots, spectators and lobby pages wait, newcomers cannot join.
- Changing role: player → lobby: BYE (reason 1) on all links,
release, close all connections. Player → spectator: BYE (reason 1) to spectators and close those links,release,spectate, then a new HELLO (role spectator) on the remaining player links. Spectator → player:release,claim; onclaimeda new HELLO (role player, slot, gen) on the player links and new connections, as newcomer, to the spectators. A second HELLO on a link replaces the role, slot and gen of the first.
Why "the lowest peer id wins" is not enough
Chapter 13 mentioned a simpler idea: every page announces its claim to the others, and if two claim the same slot, the lower peer id keeps it. That works only if every claimer hears every other claimer, and in a mesh that is not guaranteed. Example: Ann (peer id 5) and Cid (peer id 9) both claim slot 2. Bo is connected to both; Ann and Cid cannot reach each other. Bo hears both claims and decides "Ann holds slot 2". Ann never hears Cid's claim and flies as slot 2; Cid never hears Ann's and also flies as slot 2. Bo ignores Cid's ship and Cid's hits, but Cid believes they count. Three pages, three different pictures, and no rule applied locally can fix it, because a page can never know whether there is a claim it has not heard. Agreement needs one place that hears every claim: the service.
Partial mesh
"Partial mesh" means some required pair has no live link: A sees B, B sees C, A not C. Players cannot play with a missing link (A's hits on C would never arrive, A would not see C), so one player must go. Care is needed not to evict healthy players because of the one whose network broke.
- The pair X–Y (both holders) is down while either X's or Y's latest
linksreport does not list the other as live. The service evaluates a pair only when it has alinksreport from both sent after their latestwelcomeorresumed, and never while recovering. - The service counts how long a pair has been down, starting no earlier than the roster that first listed both as holders, and only while both are present. (A partner that silently died is not present: nobody yields to it; its WebSocket times out after 25 s, its slot is reserved for 60 s and then freed.)
- When some pairs have been down for 20 s (longer than a negotiation timeout of 10 s plus the first
retry), the service revokes one holder: the one that is in the most such pairs; on a tie, the
newer grant. It sends that page
revoked(unreachable, partner)and frees its slot; the page sends BYE (reason 4) and returns to the lobby with "Could not connect to name". Then it evaluates again. Example: A has lost all its links but keeps its WebSocket; A–B and A–C are down, B–C is up; A is in two pairs, B and C in one each: A is revoked, B and C play on. - Against loops: for 60 s, while the partner is still present, the service answers that page's
claimwithdenied unreachable(it may spectate). - While the service is unreachable nobody is revoked; the game simply goes on with the missing link.
- A spectator without a live link to some player shows "no connection" for that slot; nobody else is affected.
Data channel messages
All game messages are binary, little-endian (like the original packet), one message per data
channel message, byte 0 = type. Types below 0x80 go on ev, 0x80 and above on
st. A receiver ignores unknown types and the bytes after the length it knows (this is how
minor versions extend messages). A message shorter than its known length is dropped and logged.
Every drop of any message is logged with its reason.
| Type | Name | Channel | Bytes | Sender → receiver | When |
|---|---|---|---|---|---|
| 0x01 | HELLO | ev | 48 | both ways | first message on a new link; again after a role change |
| 0x02 | BYE | ev | 4 | leaver → its links | leaving, changing role, revoked, refusing |
| 0x03 | NAME | ev | 18 | player → its links | right after each HELLO, and when the name changes |
| 0x10 | HIT | ev | 20 | shooter → victim only | my shot hit a player |
| 0x20 | SAT | ev | 20 | collector or shooter → owner only | I collected or shot a satellite |
| 0x80 | STATE | st | 111 + 44·n | player → its links | after every step (to spectators after every 2nd) |
| 0x81 | PING | st | 20 | everyone → its links | every 500 ms, from a timer |
| 0x82 | PONG | st | 20 | answer to PING | at once, in the message handler |
A STATE, PING or event that arrives on a link before its HELLO is dropped.
HELLO (0x01), 48 bytes
| Offset | Type | Field | Meaning |
|---|---|---|---|
| 0 | u8 | type | 0x01 |
| 1 | u8 | protoMajor | 1 |
| 2 | u8 | protoMinor | 0 |
| 3 | u8 | role | 1 player, 2 spectator |
| 4 | u32 | periodNs | the room's step period |
| 8 | u8 | preset | 0 Authentic, 1 Modern, 2 Custom |
| 9 | u8 | reserved | 0 |
| 10 | u16 | reserved | 0 |
| 12 | u32 | rulesHash | see "Versions and settings" |
| 16 | u32 | peerId | sender's peer id |
| 20 | i8 | slot | 0..3, or −1 for a spectator |
| 21 | i8 | status | as in STATE |
| 22 | u16 | gen | slot generation (0 for a spectator) |
| 24 | u16 | lifeId | current life (0 if none yet) |
| 26 | u16 | satId | id of the current or last satellite (0 if none yet) |
| 28 | u32 | step | sender's current step |
| 32 | u32 | nextEvent | the event number it will use next (≥ 1) |
| 36 | i32 | score | its score |
| 40 | u8 × 8 | reserved | 0 |
Applying HELLO: if protoMajor, periodNs, preset or rulesHash differ from mine, send BYE (reason 3), close the connection and show "This player runs a different version or settings". If peerId is not the peer the service introduced on this connection, close it. Otherwise: lastStep := max(lastStep, step − 1), lastEvent := max(lastEvent, nextEvent − 1) (a second link from the same peer id must not reopen old numbers), and take role, slot, gen, life, satellite id and score.
BYE (0x02), 4 bytes
0 u8 type 0x02; 1 u8 reason (0 leaving the room, 1 changing role or back to the lobby, 3 incompatible, 4 revoked); 2 u16 reserved. Applying: remove the sender's ship, shot copies and satellite copy at once (no explosion). Its name and last score stay in the score table until the slot gets a new holder.
NAME (0x03), 18 bytes
0 u8 type 0x03; 1 u8 length (0..15); 2 u8 × 16 the name in UTF-8, zero-padded. At most 15 bytes,
like the original's 15 characters, cut only between whole characters. The game draws names with the
original 8×8 font: 256 glyphs in the order of the PC character set (code page 437, as far as we can
tell H; assets/fonts/font8x8.txt). Map each character to that code
page; characters it does not have are drawn as ?.
STATE (0x80), 111 + 44·n bytes
The successor of the original's 130-byte packet (chapter 8): the same fields in the same units, plus ids.
| Offset | Type | Field | Meaning |
|---|---|---|---|
| 0 | u8 | type | 0x80 |
| 1 | u8 | slot | 0..3 |
| 2 | u16 | gen | slot generation |
| 4 | u32 | step | the sender's step after which this state was taken |
| 8 | u16 | lifeId | current life |
| 10 | i8 | status | 0 alive, −1 cloaked, 1 killed, 2 not in play (the original's status word) |
| 11 | u8 | flags | bit 0 away (below); other bits 0 |
| 12 | i64 × 3 | position | x, y, z: world units × 65,536 (the original's 64-bit coordinate, middle word = world unit) |
| 36 | i64 × 3 | velocity | per step, same format |
| 60 | i16 × 9 | axes | a (forward), b (right), c (the game's "up" arrow, which points to the bottom of the screen, chapter 3), each x, y, z in Q14 (16,384 = 1.0) |
| 78 | i32 | score | the sender's score |
| 82 | u16 | satId | id of the sender's satellite |
| 84 | i8 | satKind | 0 none, 1 shields, 2 cloak, 3 thrust, 4 fire power, −1 exploding |
| 85 | u8 | recordSize | bytes per shot record: 44 in version 1.0; receivers read the 44 bytes they know and skip the rest |
| 86 | i64 × 3 | satPosition | as position |
| 110 | u8 | n | number of shot records, 0..8 |
| 111 | recordSize × n | shot records | below; fields added by later minor versions go after the records |
Shot record, 44 bytes
| Offset | Type | Field | Meaning |
|---|---|---|---|
| 0 | u16 | shotId | shooter's shot id |
| 2 | u32 | fireStep | the shooter's step in which it was fired |
| 6 | u8 | flags | bit 0 powered, bit 1 exploded |
| 7 | u8 | hitMove | if exploded: the move (0..23) after which it hit; else 0 |
| 8 | i64 × 3 | start | position before its first move: ship position + axis c × 64 world units (so the
shot appears just below the centre of the view; player_fire, src/shots.c) |
| 32 | i32 × 3 | velocity | per step, world units × 65,536: ship velocity + axis a × 1,024 (always fits 32 bits) |
The original sent 8 flags (none, flying, flying powered, exploding), and the receiver started its copy from the sender's position when it first saw the flag, so a lost or late packet started the copy in the wrong place and a newcomer never knew when a shot began. Here each shot record goes into the next 4 STATE messages actually sent on each link after the shot was fired, and into the next 4 after it exploded (with bit 1 set). Four copies make a single lost message harmless; a shot whose copies are all lost is simply not drawn, which costs nothing because copies of other players' shots are pictures only (chapter 8).
senderStepNow(p) = r_p * (myStepTime - o_p) // p's current step as I estimate it ("Showing other peers")
t_p = the sender step at which I draw p's ship now (fractional)
on a shot record r from peer p:
c = copy (p, r.shotId)
if c exists and r.flags has "exploded": c.hitMove = r.hitMove, c.exploded = true
if c does not exist:
k = floor(t_p) - r.fireStep
finished = (not exploded and k > 23) or (exploded and k > r.hitMove + 7)
if not finished: create c from r
drawing copy c at t = t_p: k = floor(t) - c.fireStep, m = t - c.fireStep + 1 (moves done)
k < 0 : not drawn yet
not exploded and k <= 23 : flying at c.start + min(m, 24) * c.velocity
exploded and k <= c.hitMove : flying at c.start + min(m, c.hitMove + 1) * c.velocity
exploded and c.hitMove < k <= hitMove+7 : explosion at c.start + (c.hitMove + 1) * c.velocity
otherwise : delete c
also delete every copy with fireStep < senderStepNow(p) - 64
24 moves and 7 explosion steps match the shooter's own shot (lifetime 0x18; explosion state 0xFFF8 counted up to 0 and drawn while negative, src/shots.c). A copy already drawn past its hit point jumps back to the explosion when the exploded record arrives late. Copies never hit anything.
HIT (0x10), 20 bytes
| Offset | Type | Field | Meaning |
|---|---|---|---|
| 0 | u8 | type | 0x10 |
| 1 | u8 | flags | bit 0 powered (costs 2 shields instead of 1) |
| 2 | u16 | shotId | the shot that hit |
| 4 | u32 | event | shooter's event number |
| 8 | u32 | victimPeer | victim's peer id |
| 12 | u16 | victimLife | victim's life id in the STATE the shooter drew |
| 14 | u8 | victimSlot | for logs and checks |
| 15 | u8 | reserved | 0 |
| 16 | u32 | step | shooter's step of the hit |
The shooter adds 50 points at once, as the original does, and sends HIT to the victim only; the others see only the shot explode (through its record), as in the original.
- The sender must be an accepted slot holder (the roster names it, with its gen, as a player; or the live-link rule of "Holding a slot" applies). HITs and SATs from anyone else (a spectator, a page that lost its slot) are ignored and logged. The killer, if the hit kills, is the slot the sender holds in my accepted state.
- victimPeer ≠ my peer id, or victimLife ≠ my current life: ignore. (A hit on my previous life, or on the previous holder of my slot, never touches me.)
- I am not in flight (name screen, away) or my shields are 0: ignore (chapter 20, D3). The original
applied hits on the name screen too (
name_entrycallsnet_sync_frame, src/namentry.c). - Excess delay over 1 s: ignore. Excess delay = my step time at arrival − (o_p + step ÷ r_p), i.e. how much later than the shooter's fastest messages this one came. A constant delay, however large, is part of o_p and does not count, so a player with a slow connection is still hit; only a hit held up by a stall (a broken path, a congested queue) is dropped.
- Otherwise apply it exactly as the original applies a hit word (chapter 8, "Exact rules: applying hit reports"): −1 shield (−2 if powered), flash, cloak lost with "Cloak Destroyed!", at 0 shields status killed, killer = the shooter's slot, death countdown 64.
SAT (0x20), 20 bytes
| Offset | Type | Field | Meaning |
|---|---|---|---|
| 0 | u8 | type | 0x20 |
| 1 | u8 | action | 1 collected, 2 shot |
| 2 | u16 | satId | the satellite, as in the owner's STATE |
| 4 | u32 | event | sender's event number |
| 8 | u32 | ownerPeer | owner's peer id |
| 12 | u32 | step | sender's step |
| 16 | u16 | shotId | for action 2, else 0xFFFF |
| 18 | u16 | reserved | 0 |
Who decides a satellite pick-up
In an owner-confirmed design the collector asks the owner and gets the bonus only if the owner answers "yours". In a collector-decides design the collector takes the bonus at once and tells the owner, who removes the satellite; ids make sure each satellite is taken at most once per collector and that a late message cannot remove a newer satellite. This protocol uses collector-decides with ids:
- It is the original's rule (each machine decides about its own ship; the shooter decides hits). Chapter 20 keeps "two players can take the same satellite at once" in Modern (D6) and fixes only the repeats (D4, D5, D5b); this design gives exactly that.
- The bonus comes in the step of the touch, not a round trip later, and does not depend on the owner being reachable at that moment.
- The cost: two players touching the same satellite within about one network delay of each other both get it. On the 1993 LAN that window was 1–2 frames; on the internet it is a few steps.
Owner:
- Spawn as the original: every 128th step of the flight loop (also while dead), only if it has no satellite (an exploding one counts as having one): satId := satId + 1, kind and position as chapter 5.
- Queued SATs are applied at the start of the satellite part of my step, before my own touch test,
as the original handles the event word at the start of
satellite_update(src/satellite.c). So when a remote collect is queued and I touch my own satellite in the same step, the remote collect wins. SAT for me with satId = my satId and my kind > 0: action 1 → kind 0; action 2 → kind −1 (exploding; kind 0 once its age passes 64, as the original). Any other SAT (old id, already gone, already exploding) is ignored. So the first SAT for a satellite wins. - Collecting or shooting my own satellite is local and immediate, as in the original.
- Leaving flight (name screen, away): my satellite becomes kind 0 at once. (The original keeps
sending it from the name screen without handling events, and removes it only when the next life
starts,
satellites_clearin src/main.c; meanwhile others can collect it every frame, chapter 8.)
Everyone else, for each owner's copy (owner, satId, kind, position from its latest STATE):
- A set taken of (owner, satId). A copy in the set is not drawn as a satellite, cannot be touched and cannot be shot. An entry is removed when the owner's STATE shows a different satId, or the owner is gone.
- My shots are tested against copies with kind > 0, not taken, after the tests against ships (src/shots.c order), in owner slot order, also when the same shot hit a ship in that step (the original does not stop between the two loops). Each copy a shot overlaps in that step: SAT action 2 for it, add it to taken, draw its explosion locally; the shot explodes; no points. (The original tests every copy too, but has one event word, so only the last is reported.)
- Touch (the original's test: close enough to collide and not within 8 steps after a bump), in flight, not spectating, copy kind > 0 and not taken: apply the pick-up of that kind at once (chapter 5, multiplayer values), send SAT action 1, add to taken. So exactly once per (owner, satId).
- A copy whose owner has status 2 is ignored (its owner has removed it anyway).
The original (Authentic): no ids; the event names only the owner's slot; the collector's copy stays until the owner's next packet, so the bonus is applied on 1–2 frames, and on every frame while the owner is on the name screen; two collectors both get it; a late or stale event removes whatever satellite the owner has now (chapter 8, "Satellites between players").
PING (0x81) and PONG (0x82), 20 bytes each
| Offset | Type | Field | Meaning |
|---|---|---|---|
| 0 | u8 | type | 0x81 or 0x82 |
| 1 | u8 | flags | bit 0 away |
| 2 | u16 | reserved | 0 |
| 4 | u32 | nonce | chosen by the PING sender, echoed in PONG |
| 8 | f64 | time | PING: sender's performance.now() in ms; PONG: copied |
| 16 | u32 | step | the sender's current step |
Every page sends PING to each link every 500 ms from setInterval and answers each PING
with a PONG directly in the channel's onmessage handler. Round-trip time: now − time when
the PONG arrives; smoothed rtt := 0.875·rtt + 0.125·sample.
Receiving
- Events are de-duplicated on arrival, in the
onmessagehandler, in arrival order: a HIT or SAT whose event number is not greater than lastEvent of its sender is dropped (and logged); otherwise lastEvent := event and it is queued. Queued SATs are applied at the start of the satellite part of the next step, queued HITs in the hit phase after it, each in arrival order. (De-duplicating at intake keeps a HIT that arrived before a later SAT from being taken for a duplicate.) - The
evchannel itself delivers each message once and in order. A sender never re-sends an event on a new connection: an event that did not get through before its connection closed is lost, and it would be stale anyway. - STATE: accepted under the slot rule above and only if step > lastStep of that sender; otherwise dropped (late or duplicated on the unordered channel). On accept: lastStep := step; the state goes into that sender's history (last 32) for drawing; score and satellite are taken from it; its shot records are applied.
- A STATE with a new lifeId starts a new ship for that sender: no interpolation from the old life.
- Status is a level, applied from the newest accepted STATE: 0 shown, −1 cloaked (drawn as the original draws a cloaked peer), 2 hidden. Status 1 (killed) starts the explosion and "name has been killed" once per (sender, life), and not for a sender's first accepted STATE (a newcomer does not see old deaths). Cloak may toggle any number of times.
- Events and states travel on different channels; an event may arrive before or after the STATE of its step. No rule depends on that order.
Showing other peers
The original drew another ship exactly where its last packet put it. Over the internet messages arrive unevenly and the other page's clock runs at a slightly different rate, so each page maps every sender's steps onto its own clock and draws other ships a little in the past.
- For each STATE accepted from p, record (s = its step, m = my step time at arrival).
- Rate r_p (sender steps per my step): 1 at first; once 5 s of samples exist, the slope of a straight line fitted to the (m, s) pairs of the last 10 s, clamped to 0.5..1.05. This follows a slow device (running at 90 % say) and clock drift (10–100 parts per million) without a sawtooth.
- Offset o_p = the smallest (m − s ÷ r_p) over the last 2 s: the fastest delivery, so jitter does not move it. Without samples in the last 2 s (the sender is away or silent), keep the last o_p and r_p. Before the first STATE from p: r_p = 1 and o_p = (my step time at HELLO) − HELLO's step, and the HIT excess-delay check is skipped (the hit is applied). Lateness of a message = (m − s ÷ r_p) − o_p.
- Delay D = 3 steps + the 90th percentile of the lateness over the last 2 s, at most 10 steps.
- The sender step to draw: t_p = r_p × (myStepTime − o_p − D).
- Position: linear between the two stored states around t_p (in floating point, world units =
value ÷ 65,536). Axes: blend a and b linearly, then a := a ÷ |a|; b := b − (a·b)·a, b := b ÷ |b|; c is
computed from a and b the way the original does it (
vec3_cross(a, b, c), chapter 3). If t_p is beyond the newest state, extrapolate with its velocity for at most 4 steps, then hold. - If a sender's step jumps by more than 35 against senderStepNow, drop its samples and start the fit again.
- Hit tests and collisions use the ship as drawn at t_p, taken at my integer step time (chapter 13: "the shooter decides" means "what the shooter saw").
Worked example. A STATE with step 8,000 from Bob arrives at my step time 9,253.2; over the last 2 s the fastest one gave o = 1,252.9 (r = 1). Lateness of this one: 9,253.2 − 8,000 − 1,252.9 = 0.3 steps. The 90th percentile of the lateness is 1.5, so D = 4.5. At my step time 9,260.0 I draw Bob at t = 9,260.0 − 1,252.9 − 4.5 = 8,002.6: 60 % of the way from his state 8,002 to 8,003. His shot fired in step 8,002 has made m = 8,002.6 − 8,002 + 1 = 1.6 moves.
Liveness
- A link is live when (1) some message (STATE, PING, PONG, event) arrived on it in the last 1,000 ms, or 10,000 ms if the sender's last STATE or PING had the away flag, and (2) once the link is older than 3 s, a PONG to one of my PINGs arrived in the last 3 s (this catches a partner that hears nothing from me while I still hear it).
- Not live: hide that peer's ship, shot copies and satellite copy; stop sending it STATE (keep PING). This replaces the original's 4 frames without a packet (chapter 8), which would be 57 ms at 70 steps per second.
- Live again: show it from its next STATE. A closed connection or a BYE removes it at once.
Away: a hidden tab
- Hidden pages get no animation frames and slow timers (chapter 13). On
visibilitychangeto hidden, a player in flight leaves flight: status 2, its satellite kind 0, the away flag set, and sends one STATE with that. Its score is kept (unlike the original's Esc, which zeroes it, src/main.c). It ignores HIT while away (its ship is hidden, so none should come). - While hidden it keeps sending PING with the away flag whenever its timer runs. Receivers treat a PING with the away flag as status 2 for that sender, even if the STATE was lost, and allow 10 s between its messages.
- A hidden spectator does the same: away flag in its PINGs, the same 10 s allowance.
- Visible again: the name screen; Enter starts a new life (life + 1).
- A page that was frozen (laptop sleep, mobile freeze,
pageshowwithpersistedtrue after the bfcache) and finds that more than 5 s passed: it closes all its connections and joins again withresume {…, reload: true}, like a reload.
Spectators and late joiners
- A spectator connects to every player, sends HELLO, PING and PONG, never STATE, HIT or SAT. It cannot be hit and never collects. Players send it STATE after every second step (35 per second); the interpolation copes with that.
- A late joiner needs no special message. Its first picture comes from: the roster (slots, names, who is reconnecting); one HELLO and NAME per link (life, satellite id, score, status, step, event counter); the next STATE from each player, a complete snapshot of ship, status, score and satellite. Missing: shots fired before the link came up whose 4 records were all sent earlier (pictures only), kill messages of the past, explosions already running.
One step, exactly
every step period (from the accumulator; at most 5 per animation frame):
step := step + 1
1. intake: everything received since the last step, in arrival order
roster from the service -> apply if v > applied version
HELLO, BYE, NAME -> applied in the message handler already
HIT, SAT -> de-duplicated in the handler, waiting in the queue
STATE -> accept or drop (above), into the history
2. simulate my world in the original frame order (chapters 2 and 14), with other ships as
drawn at their t_p:
my ship; my shots (hits on ships -> HIT, +50; hits on satellite copies -> SAT);
other ships (collisions decided locally); shot copies;
satellites: first the queued SATs for my satellite, in arrival order; then spawn
(every 128th step) and touches (-> pick-up + SAT)
every HIT and SAT is sent on ev when created, to its one receiver
3. hit phase: queued HITs for me, in arrival order
4. liveness of every link
5. for each live link to a player, and to a spectator when step is even:
if st.bufferedAmount > 1,024 or the link is congested: skip it this step
else build and send STATE (the state after this step, with the shot records due)
6. draw (independently of the steps, interpolated)
Difference from the original's order: the original sends at the start of a frame the state of the
end of the previous frame. Sending after the step is the same state one step earlier. Satellite
events and hits are applied where the original applies them: satellite events at the start of
satellite_update, hits in net_sync_frame after drawing.
Congestion
- State: the check above (
st.bufferedAmountover 1,024 bytes, about 5 messages) replaces the original's "send only if the previous send has finished". A skipped STATE costs nothing: the next one replaces it. Build a STATE only when sending it, never queue one. - Events are never skipped. When
ev.bufferedAmountexceeds 65,536 bytes the link is congested: no STATE on it until the amount is below 16,384. Congested for more than 5 s: close the connection (repair rules above).
Bandwidth
Overhead per data channel message: IPv4 20 + UDP 8 + DTLS record 13 + AES-GCM nonce and tag 24 + SCTP common header 12 + SCTP data chunk 16 = 93 bytes (113 over IPv6). SCTP acknowledges every second packet with a SACK, also on the unreliable channel; a SACK packet is about 93 bytes too.
| Case | STATE payload | On the wire | Per link at 70/s |
|---|---|---|---|
| not firing (typical) | 111 B | 204 B | 114 kbit/s |
| holding fire (one shot every 3rd step), missing | 111 + 44 × 1.33 = 170 B | 263 B | 147 kbit/s |
| worst case: 8 records in every message | 463 B | 556 B | 311 kbit/s |
- Why 8 records can happen: holding the trigger fires every 3rd step, but releasing it clears the cooldown (src/control.c), so tapping can fire in every step. The real limit is the 8 shot slots. A missed shot keeps its slot 24 steps; one that hits at its first move frees it 9 steps after firing (explosion included), so at point-blank range about 8 ÷ 9 × 70 ≈ 62 shots and HITs per second are possible.
- A player with 3 other players: typical 3 × (114 + 26 SACKs) ≈ 0.42 Mbit/s up and down; worst 3 × (311 + 26) ≈ 1.0 Mbit/s. Each spectator adds 57 kbit/s typical, 156 worst (35 per second).
- A spectator watching 4 players: download 0.23–0.62 Mbit/s; upload only SACKs (about 13 kbit/s per link) and PINGs.
- PING and PONG: under 4 kbit/s per link. HIT and SAT: 113 bytes each on the wire, at most about 60 per second.
- The largest message (463 bytes) fits one packet; nothing is fragmented.
- A relayed link costs its traffic twice on the TURN server.
Versions and settings
- protoMajor changes when a message changes incompatibly; different majors never play
together: the service refuses the join (
error version), and HELLO refuses the link. The page shows "Reload the page to get the current version". - protoMinor grows when a message gets new bytes at its end (STATE: after the shot records), a shot record grows (through recordSize), or a new type appears. Different minors play together; each side ignores what it does not know.
- Settings: preset, step period and rulesHash are fixed per room by its first page and carried in
welcome; the link may carry them as a hint (#room=…&preset=modern&rate=70):presetis authentic, modern or custom;rate=70means periodNs 14,285,714 andrate=18.2means 54,925,401 (Authentic always uses 14,268,123); a Custom link addsrules=and the 8 hex digits. A link without hints creates a Modern room at 70 steps per second with no changed options (rulesHash 811c9dc5). A mismatch is refused like a major version (chapter 20: preset, rule options and step rate are room settings). - rulesHash: take every rule option of chapter 20 whose value differs from the preset's
default; write each as
id=value(the option's identifier, values as decimal integers, booleans 0 and 1) followed by a line feed; sort the lines by bytes; hash the ASCII bytes with FNV-1a 32 (start 2,166,136,261; for each byte: xor, then multiply by 16,777,619 modulo 232). No changed options: the hash of nothing, 2,166,136,261. Because options at their default are left out, a newer minor version that adds an option still matches older pages as long as the option stays at its default. In JSON it is written as 8 lowercase hex digits.
Authentic rooms
An Authentic room must reproduce the original's network behaviour, bugs included (chapter 20). It
uses the same service, connections, HELLO, NAME, BYE and PING, with periodNs 14,268,123 (the VGA
refresh of the 640 × 350 mode: 25.175 MHz ÷ (800 × 449) = 70.086 per second, chapter 20's 70.09), and
replaces STATE, HIT and SAT by one message on st:
| Offset | Type | Field | Meaning |
|---|---|---|---|
| 0 | u8 | type | 0x84 STATE_A |
| 1 | u8 | slot | 0..3 |
| 2 | u16 | gen | slot generation |
| 4 | u32 | step | sender's step |
| 8 | u8 × 130 | packet | bytes 30..159 of the original packet (chapter 8: name, orientation, position, velocity, event record, score, satellite, 8 shot flags) |
- Step order as the original (chapter 17): re-arm the receive buffers, send STATE_A with the state
of the end of the previous step (only if
st.bufferedAmountis 0, like "previous send finished"), simulate and draw, then wait. - Players send STATE_A to spectators too, in every step (the original's spectators heard every broadcast).
- The page keeps one 130-byte buffer per peer. The first STATE_A from that peer arriving after the
re-arm is copied in; later ones in the same step are dropped. Only live peers are re-armed each step;
an inactive peer's buffer stays armed across steps and takes the first STATE_A that arrives whenever
it comes, which makes that peer live again (
net_post_peer_listens,net_sync_frame). One deviation: a STATE_A whose step is not greater than the last one latched is dropped too, because the unordered channel reorders far more often than the original's LAN did, and the original would latch the old packet. - Waiting: a browser cannot busy-wait. The step's end is deferred: the page keeps checking (on each message and each animation frame) and finishes the step when every live peer's buffer has been filled this step, or when the original's limit has passed: the 5th tick of the 18.2-per-second timer after the step began, 219.7–274.6 ms depending on where in a tick it began (chapter 20). The next step starts no earlier than one period after this one began.
- Liveness is the original's counter (4, −1 per step without a message, 0 = not waited for); the event words in the buffers are applied every step, as the original does, repeats and all.
- Speed: each step needs the other peers' messages, so the step rate is about 1 ÷ max(14.27 ms, one-way delay to the slowest peer). At 40 ms one way that is 25 steps per second, 36 % of the original speed, and every lost message stalls everyone for up to 275 ms. Authentic rooms are for a LAN or players in the same city.
- Known difference: slots come from the service, so "two players in one slot" (chapter 20, D7) cannot happen.
Timers and limits at a glance
| What | Value |
|---|---|
| step period | 14,285,714 ns (70/s) or 54,925,401 ns; Authentic 14,268,123 ns |
| steps per animation frame, at most | 5 |
| STATE to players / spectators | after every step / every 2nd step |
| shot record repeats | next 4 STATEs sent per link after firing, next 4 after exploding |
| PING interval; PONG needed within | 500 ms; 3 s |
| link not live after | 1,000 ms without a message (10,000 ms when away) |
| HIT excess delay, at most | 1 s |
| pending STATE with an unknown gen | 1 s |
| enter flight after claiming, at the latest | 5 s |
| claim or spectate without an answer | 10 s, then treated as denied |
| partial mesh: revoke after; re-claim refused for | 20 s down while both present; 60 s |
| ICE: "disconnected" before restart; polite fallback; restarts | 2 s; 5 s; 3 within 30 s |
| meshing again: first wait, doubling up to | 2 s, 60 s |
| negotiation timeout; queued signals kept | 10 s; 30 s |
| page ping to the service; service declares a page dead after | 10 s; 25 s |
| reservation after a dead WebSocket | 60 s |
| service recovery window after an empty restart | 45 s |
| service reconnect back-off | 1, 2, 4, 8, 15, 15 … s, each ±20 % random |
| frozen page: rejoin if more than | 5 s passed |
| st buffered limit; ev congested / clear / give up | 1,024 B; 65,536 B / 16,384 B / 5 s |
| interpolation delay D | 3 steps + jitter, at most 10 steps |
| TURN credential lifetime (recommended) | 12 hours |
A whole session, in one picture
- Build it in this order: STATE and HELLO between two tabs through
BroadcastChannel(no service); then the service with join, claim and signal; then HIT and SAT; then liveness, the step mapping and the congestion checks; then repairs, reservations and the partial-mesh rule. - Write the codec (encode and decode of every message) as one small module with tests that round-trip each message and check its length against this chapter.
- Log every dropped message with its reason (old step, wrong gen, duplicate event, old life, unknown satellite, before HELLO). Chapter 19 walks through the failures these rules handle.