Skip to content

198 netplay 4 webrtc and link codes

Alex Diakovsky edited this page Dec 3, 2026 · 2 revisions

198. Netplay 4: WebRTC and link codes (N3, issue #151)

Question: document 197's session runs peers in one process over a fake network. How do two real machines connect, with no server of our own? What does a player do to link up, how does the other machine learn which match to play, and does a real link keep every peer's match identical? Can CI prove that, with two browser pages on one runner (issue #151, stage N3; tracking #43)?

The netplay series: document 195 is the plan (stages N1 to N8); document 196 is N1, save and restore; document 197 is N2, the rollback session. This document is N3, the real transport.

Glossary

Term Meaning
transport NetTransport: what a session sends its packets through. LoopbackNet (the fake network) and WebRtcTransport (the real one) are two of them.
WebRTC The browser's peer-to-peer link: two pages talk directly, once each knows the other's description and addresses.
SDP A connection's description (what it offers, its keys). Each side makes one; the other must be told it.
ICE candidate One address a side can be reached on (its own on the local network, or its public one as a STUN server sees it).
STUN A public server that tells a machine its public address. It carries none of the game's traffic. N3 uses Google's public one.
signalling Getting each side's SDP and candidates to the other. N6 brings a server for it; N3 has the players do it by copy and paste.
link code One side's SDP and candidates packed into a text to paste: OF1- and then base64.
words channel The data channel for the session's packets: unordered, never resent (a lost packet is replaced by the next one, which repeats it).
room channel The data channel for messages that must arrive, in order: the start message now, the handshake and the room later.

The answer, up front

  1. A transport is an interface with two channels: send(to, data, reliable) and receive(reliable), plus poll(), connected_peers() and the signals peer_connected and peer_disconnected. The session uses the words channel; the menus use the room channel. LoopbackNet now has both (its room channel loses nothing and keeps order), so every check of N2 still runs on it.
  2. WebRtcTransport is the real one, in the browser only. Each link to a peer is one WebRTCPeerConnection with two negotiated data channels: words (id 1, unordered, no retransmits) and room (id 2, reliable and ordered). A desktop build has no WebRTC without the extension, so there available() is false and the menu hides Link play.
  3. Link codes, no server. The host's game makes an offer and shows its code. The joiner pastes it, and their game shows an answer code. The host pastes that back, and the link opens. A code carries the SDP and every ICE candidate gathered, deflated: 600 to 750 characters. Gathering counts as done when the browser says so, or when 1.5 s pass with no new candidate, or after 8 s at most.
  4. The host starts the match. Once linked, the host picks a map and presses Start. The host's game sends the MatchSetup over the room channel (which person is on which side, which machine owns each row, the host's seed) and starts. The joiner's game starts when the message arrives. Both level scenes then run the match under a NetSession. Each shows only its own person, and the other machine's person gets no keys. The host runs the computers.
  5. It is exact over a real link. In CI, two headless Chromium pages on one runner link by their codes and play the game's recorded match for 600 ticks, each typing two players' recorded words. Both pages' confirmed hashes equal the recording's on every tick.
  6. Found on the way: a snapshot held the session. NetSession.start took its first snapshot before setting MatchController.session, and the snapshot restored every script variable of the match. The first rollback therefore set session back to null, and the match quietly went back to its own clock. N2's checks step the match by hand, so they never saw this. The two-level-scene check found it. The fix: the snapshot skips session, which is not match state, and start sets it before saving.

Linking up

The host's game makes an offer and gathers its addresses, then shows the offer code; the host sends it to the joiner by any means; the joiner pastes it, their game makes an answer and shows the answer code; it goes back to the host, who pastes it; WebRTC opens the two channels directly between the machines, with STUN only telling each its public address; the host picks a map and presses Start, the start message carries the match setup over the room channel, and both games start the level under a NetSession

Mermaid source
sequenceDiagram
  participant H as Host's game
  participant S as STUN (public)
  participant J as Joiner's game
  H->>H: Host: offer(1), gather addresses
  H-->>S: what is my public address?
  H->>H: code_ready: show the offer code
  Note over H,J: the host sends the code to the joiner (chat, mail, anything)
  J->>J: Join: accept(code): answer, gather addresses
  J-->>S: what is my public address?
  J->>J: code_ready: show the answer code
  Note over H,J: the joiner sends the answer code back
  H->>H: Connect: finish(code)
  H->>J: WebRTC opens: words channel + room channel
  H->>H: pick a map, Start
  H->>J: room: {"kind": "start", "setup": MatchSetup}
  par
    H->>H: level scene + NetSession (me 0)
  and
    J->>J: level scene + NetSession (me 1)
  end
  H->>J: words, every frame, both ways
Loading

The transport

The interface, which LoopbackNet and WebRtcTransport both fill in:

# addons/openfire_engine/game/net/net_transport.gd
signal peer_connected(peer: int)
signal peer_disconnected(peer: int)

## Sends `data` to peer `to`: on the words channel (it may never arrive), or with `reliable` on the room channel.
func send(_to: int, _data: PackedByteArray, _reliable := false) -> void:
	pass

## What arrived on one channel since the last call: [[from, data], ...], in arrival order.
func receive(_reliable := false) -> Array:
	return []

## Housekeeping, once a frame: connections, channel states.
func poll() -> void:
	pass

## The peers this one can send to now.
func connected_peers() -> Array:
	return []

Each link is a peer connection with two negotiated channels. Both sides create the channels themselves with the same ids, so no channel has to be announced:

# addons/openfire_engine/game/net/webrtc_transport.gd
func _link(peer: int) -> Link:
	if _links.has(peer):
		(_links[peer] as Link).pc.close()
	var l := Link.new()
	l.started_msec = Time.get_ticks_msec()
	l.pc.initialize({"iceServers": ice_servers})
	l.words = l.pc.create_data_channel("words", {"negotiated": true, "id": WORDS_ID, "ordered": false, "maxRetransmits": 0})
	l.room = l.pc.create_data_channel("room", {"negotiated": true, "id": ROOM_ID})
	...
	l.pc.session_description_created.connect(func(type: String, sdp: String):
		l.pc.set_local_description(type, sdp)
		l.local_sdp = sdp)
	l.pc.ice_candidate_created.connect(func(media: String, index: int, cand: String):
		l.candidates.append([media, index, cand])
		l.last_candidate_msec = Time.get_ticks_msec())
	_links[peer] = l
	error = ""
	return l

poll hands out the code once gathering is done, and turns the channels' states into the two signals:

# addons/openfire_engine/game/net/webrtc_transport.gd
func poll() -> void:
	var now := Time.get_ticks_msec()
	for p in _links:
		var l: Link = _links[p]
		l.pc.poll()
		if l.local_sdp != "" and not l.code_sent:
			var quiet := not l.candidates.is_empty() and now - l.last_candidate_msec >= QUIET_MSEC
			if l.pc.get_gathering_state() == WebRTCPeerConnection.GATHERING_STATE_COMPLETE or quiet or now - l.started_msec >= GATHER_MSEC:
				l.code_sent = true
				code_ready.emit(p, encode({"kind": l.kind, "from": me, "to": p, "sdp": l.local_sdp, "ice": l.candidates}))
		var open := l.open()
		if open and not l.was_open:
			l.was_open = true
			peer_connected.emit(p)
		...

Link codes

A code is the JSON of one side's offer or answer, deflated and in base64. Reading a code drops the spaces and line breaks a chat program may add, and anything that is not a code reads as empty:

# addons/openfire_engine/game/net/webrtc_transport.gd
static func encode(d: Dictionary) -> String:
	var raw := JSON.stringify(d).to_utf8_buffer()
	return CODE_PREFIX + Marshalls.raw_to_base64(raw.compress(FileAccess.COMPRESSION_DEFLATE))

static func decode(code: String) -> Dictionary:
	var c := code.strip_edges().replace(" ", "").replace("\n", "").replace("\r", "").replace("\t", "")
	if not c.begins_with(CODE_PREFIX):
		return {}
	var packed := Marshalls.base64_to_raw(c.substr(CODE_PREFIX.length()))
	if packed.is_empty():
		return {}
	var raw := packed.decompress_dynamic(1 << 20, FileAccess.COMPRESSION_DEFLATE)
	var d: Variant = JSON.parse_string(raw.get_string_from_utf8())
	if not (d is Dictionary) or not d.has_all(["kind", "from", "to", "sdp"]):
		return {}
	return d

The joiner learns its peer number from the offer (to). The host takes only an answer to an offer it made, so pasting your own code back gives a reason rather than a broken link:

# addons/openfire_engine/game/net/webrtc_transport.gd
func accept(code: String) -> bool:
	var d := decode(code)
	if d.is_empty() or d.get("kind") != "offer":
		error = "not_offer" if not d.is_empty() else "bad_code"
		return false
	me = int(d["to"])
	var l := _link(int(d["from"]))
	l.kind = "answer"
	l.pc.set_remote_description("offer", String(d["sdp"]))   # the answer comes through session_description_created
	_add_candidates(l, d)
	return true

func finish(code: String) -> bool:
	var d := decode(code)
	if d.is_empty() or d.get("kind") != "answer" or int(d.get("to", -1)) != me or not _links.has(int(d["from"])):
		error = "not_answer" if not d.is_empty() else "bad_code"
		return false
	...

The Link play screen and the start message

The default menus gain a Link play entry and a screen of the new type net_link (MenuDef). A pack's own menus can place it anywhere, as with every other screen (document 127). The screen offers Host or Join, the code boxes with a Copy button, and on the host's side a map list (maps with at least two sides) and a computers checkbox. The match is fixed for this stage: the host's person on the map's first side, the joiner's on its second, and the host's computers on the rest:

# addons/openfire_engine/game/net_link_screen.gd
func match_setup(level_id: String, with_computers: bool, seed_value: int) -> MatchSetup:
	var lv := LevelData.new()
	lv.load_from(pack.level_dir(level_id), pack.level_override_paths(level_id))
	var ms := MatchSetup.new()
	ms.choose_level(lv, level_id)
	var sides := MatchSetup.level_sides(lv)
	ms.rows = [{"kind": "person", "side": sides[0], "skill": "", "peer": 0}, {"kind": "person", "side": sides[1], "skill": "", "peer": 1}]
	if with_computers:
		for s in sides.slice(2):
			ms.rows.append({"kind": "computer", "side": s, "skill": AIProfile.default_id(pack)})
	ms.match_seed = seed_value
	return ms

func press_start() -> void:
	if role != "host" or not transport.is_connected_to(1) or levels.is_empty() or _started:
		return
	var setup := match_setup(String(levels[level_index][0]), computers, FxRand.new_seed())
	transport.send(1, JSON.stringify({"kind": START_KIND, "setup": setup.to_dict()}).to_utf8_buffer(), true)
	_begin(setup)

The joiner's screen starts the same match when the message arrives, as itself:

# addons/openfire_engine/game/net_link_screen.gd
func _process(_delta: float) -> void:
	if transport == null:
		return
	transport.poll()
	for pkt in transport.receive(true):
		var d: Variant = JSON.parse_string(PackedByteArray(pkt[1]).get_string_from_utf8())
		if role == "join" and d is Dictionary and d.get("kind") == START_KIND and d.get("setup") is Dictionary and not _started:
			var setup := MatchSetup.from_dict(d["setup"])
			setup.me = transport.me
			_begin(setup)
			return

MatchSetup rows may now carry the peer that owns them (none means the host). The setup also carries match_seed and me. to_dict and from_dict carry it over JSON, turning JSON's floats back into integers. apply hands the match the other machine's people:

# addons/openfire_engine/game/match_setup.gd  (apply)
	var own := owners()
	mc.remote_players.clear()
	for i in own.size():
		if own[i] != me and playing[i]["kind"] == "person":
			mc.remote_players.append(i)
	if match_seed >= 0:
		mc.match_seed = match_seed

The match leaves those players out of people(), so they get no view, no ears and no binding set. Their controls are empty, because the session hands their vehicle the words that come over the link:

# addons/openfire_engine/game/match_controller.gd
func people() -> Array[PlayerSlot]:
	var out: Array[PlayerSlot] = []
	for i in slots.size():
		if not slots[i].ai and not remote_players.has(i):
			out.append(slots[i])
	return out
...
	if remote_players.has(slots.find(ps)):
		ps.controls = PlayerControls.new()   # another machine's person: the netplay session hands the vehicle their words
	else:
		ps.controls = AIControls.new(self, ps, AIBrain.new(ai_profile_for(slots.find(ps)))) if ps.ai else PlayerControls.for_player(pack, humans, people().find(ps))

GameFlow passes the screen's transport to the level scene. The level scene starts the session right after the match is set up:

# addons/openfire_engine/game/terrain_view_3d.gd
	if net_transport != null and match_setup != null:
		var owners := match_setup.owners()
		var peers := 1
		for o in owners:
			peers = maxi(peers, int(o) + 1)
		net_session = NetSession.new(controller, net_transport, match_setup.me, peers, owners)
		net_session.start()

SimHash leaves humans and remote_players out: they differ between the two machines by design, and they are not the match.

The snapshot held the session

# addons/openfire_engine/game/sim/sim_snapshot.gd
const SKIP_VARS := {
	"LevelData": ["_jitter", "_facing", "_decoration_lookup"],
	"MatchController": ["_coastal_chains", "session"],   # the NetSession that steps the match is not its state
}

# addons/openfire_engine/game/net/net_session.gd  (start)
	_ran_to = head
	mc.session = self
	_save()

Before the fix, the two linked level scenes in net_link_check stopped at tick 9: the first restore put session = null back, so MatchController._process ran its own clock while the session waited for ticks that never came. A real match would have done the same at its first rollback.

Two browser pages in CI

The game's "Replay" export gains a second mode. With ?net=host or ?net=join in its address, the page runs tests/recorded_match/net_pair.gd instead of the replay. The engine's tools/ci/web_pair.mjs opens both pages in headless Chromium and plays the two players' part: it hands the host's window.ofLinkCode to the joiner's window.ofRemoteCode, and the answer back. The two pages run on one runner, so their own addresses are enough (ice_servers = []). Chromium normally hides local addresses behind mDNS names, which the runner cannot resolve, so the script turns that off (--disable-features=WebRtcHideLocalIpsWithMdns).

# openfire-nettest tests/recorded_match/net_pair.gd
func _start(peer: int) -> void:
	if session != null:
		return
	print("net_pair %s: linked to peer %d" % [role, peer])
	var m := RM.new_match(_pack, self, _ilog, TICKS)
	var mc: MatchController = m[0]
	var me := 0 if role == "host" else 1
	session = NetSession.new(mc, transport, me, 2, OWNERS, [false, false, false, false])
	session.hash_every = 1
	for p in OWNERS.size():
		if OWNERS[p] == me:
			var w: Dictionary = _words[p]
			session.local_input[p] = func(t: int) -> int: return int(w.get(t, 0))
	session.start()   # from here the match's own _process hands the session each frame
	_t0 = Time.get_ticks_msec()

Each page types two of the recording's four players, its words by tick taken from a straight replay (session_replay.gd). The workflow's compare job checks both pages' 600 confirmed hashes against the recording's first 600.

First green run: nettest 881c757. The codes were 628 characters each. Each page confirmed 600 ticks in about 10.6 s (the match runs at 62.5 ticks a second, so it kept pace). The host rolled back 61 times (45 wrong guesses) and the joiner 61 times (49), there were no desyncs, and both pages' 600 hashes equal the recording's.

How it was checked

Check What it proves
engine tests/net_link_check.gd Link codes round-trip and survive line breaks and spaces; non-codes are refused (bad_code), and an offer pasted where the answer goes too (not_answer); a desktop build cannot link and the default menus have the Link play screen. On the four-home test mod: the screen's MatchSetup (owners [0, 1, 0, 0]) survives the start message's JSON. The room channel delivers 30 of 30 in order over a bad loopback network. Two matches set up from it, one per machine, have the right people and remote players, roll the host's seed, and agree on every confirmed tick for 600 ticks. Two whole level scenes, linked the same way and run on real frames, each show only their own person's view, stay stepped by their session through every rollback, and agree on every confirmed tick to 300; the joiner gets the host's computers' words
openfire-nettest CI (web.yml, replay job) Two headless Chromium pages of the Replay export link over WebRTC by their link codes and play the recording's first 600 ticks, two players each: every confirmed hash on both pages equals the recording's
engine CI (determinism.yml) net_link_check on Linux
The try-out The user plays Link play between two machines on the published build

Not done here

  • Two machines only. A link code joins one joiner to the host. Three or four machines need a code per pair, or the room server (N6). MatchSetup and the session already take up to four peers.
  • The start message stands in for the handshake (N4). It does not yet check that both sides run the same build and the same pack, and nothing counts down: the joiner starts a round trip after the host, and the session's input delay and window absorb that.
  • No reconnect. peer_disconnected fires, but nothing acts on it yet. A lost peer stalls the match at its window.
  • A strict network can stop the link. With STUN only (no TURN relay), two machines behind symmetric NATs cannot reach each other. Two machines on the same network, or most home connections, can.
  • Background tabs stop. A browser pauses the frame loop of a tab that is not in front, so a match in a hidden tab stalls the other player. Two players on one machine need two windows side by side, not two tabs.
  • Desktop builds have no WebRTC (the extension is not bundled): Link play is web only for now.

Where the code is (today)

What Where
The transport addons/openfire_engine/game/net/net_transport.gd (NetTransport), game/net/loopback_net.gd (LoopbackNet), game/net/webrtc_transport.gd (WebRtcTransport)
The Link play screen game/net_link_screen.gd (NetLinkScreen), game/menu_def.gd (type net_link, screen link), game/game_flow.gd (_show_net_link_screen)
The match's side game/match_setup.gd (peer per row, match_seed, me, owners, to_dict/from_dict), game/match_controller.gd (remote_players), game/terrain_view_3d.gd (net_transport, net_session)
The checks engine tests/net_link_check.gd, tools/ci/web_pair.mjs; openfire-nettest tests/recorded_match/net_pair.gd, match_web.gd, .github/workflows/web.yml

Next: N4, #152, document 199: the handshake. Both sides check they run the same build and pack, then share the seed, the setup and the settings, and a countdown starts every peer on the same tick.

Clone this wiki locally