Skip to content

196 netplay 2 save and restore

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

196. Netplay 2: save and restore of the match (N1, issue #149)

Question: rollback netplay runs ahead on guessed input words, then goes back to the last tick whose words were all known and runs the ticks again with the real ones (document 195). That needs a copy of the whole simulation state after a tick, and a way to put it back. Does putting it back and running the ticks again give exactly the state the straight run reaches? What does a copy cost? And what do the views, sounds and explosions do when the match jumps back (issue #149, stage N1; tracking #43)?

The netplay series: document 195 is the plan (stages N1 to N8). This document is N1, save and restore. It needs no network: everything here runs in one process.

Glossary

Term Meaning
snapshot SimSnapshot: a copy of the match's sim state after a tick.
restore Writing a snapshot back into the match, into the same objects.
guess, re-run The ticks run on guessed words after a snapshot; the same ticks run again after the restore, on the real words.
straight run The same words with no rollback at all. A rollback run must give its hash after every tick.
view resync What the level scene does after a restore: drop the views of objects that are gone, make the views of objects that came back.
presented event A sound or an explosion the view already played for a tick (PresentedEvents). A re-run tick does not play it again.

The answer, up front

  1. SimSnapshot copies what SimHash hashes (document 160): the match's variables and every sim object they reach, with the same classes skipped (the pack, the controls, the computer players' brains, the views). For each object: its script variables, with arrays and dictionaries copied and the objects in them kept as references, and its signal connections.
  2. Restore writes back into the same objects. A vehicle stays the same object, so whatever holds it still holds it. An object made after the snapshot drops out of the lists it is in; one removed since comes back (the snapshot held it alive), and its connections, which removal cuts, are reconnected. An array or dictionary goes back into the container the variable holds now, so a container shared with a view stays shared.
  3. Order matters once: the float views of the integer state (Vehicle.position and the like) are properties, and some setters write the integers they view, rounded. They are put back first and the integers after them, exactly. Without that, a soldier's pos_fx came back off by one (found by the check on its 8th tick).
  4. It is exact. On the engine fixture, 1500 ticks with a rollback every 7 ticks onto random words (214 rollbacks, 213 of which reached another state while guessing) give the straight run's hash after every tick. On the game's own four-player match (openfire-nettest, MAP01) all 4000 ticks agree through 571 rollbacks.
  5. It is cheap enough. On the desktop a snapshot of the fixture's match (26 objects) takes about 1.2 ms and a restore about 1.2 ms; the game's four-player match (33 objects) about 1.0 ms each. The web is measured in N2, with the session.
  6. A bug the views hid: the level view changed the sim. A destroyed or crushed tile's new state (its coastal id and art) was set by the 3D view, when its explosion's drawing reached the script's TILE_STATE: on the frame clock, with Godot's own dice. So a match with a view was not the same match as one without (every check runs without one), and two peers with different frame rates would part. The match now runs that part of the explosion's script itself (TileCollapse), on its ticks, with the game's dice, which is what the original does (FUN_0042e600 rolls FUN_0041d3d0, traced below). The view only draws the explosion.
  7. The views follow a restore. The match emits restored; the level scene drops each view whose object is gone, makes one for each object that came back, does the same for gates, and redraws the tiles changed lately. Sounds and explosions are keyed by tick: a re-run tick plays only what it did not play the first time.

How a rollback uses it

A snapshot after tick t; ticks t+1 to t+k run on guesses; the real words differ, so the snapshot is restored, the views resync, and the same ticks run again on the real words

Mermaid source
flowchart LR
  S["after tick t<br/>SimSnapshot.take"] --> G["ticks t+1 .. t+k<br/>on guessed words<br/>(sounds, explosions played)"]
  G --> W{"a real word<br/>differs"}
  W --> R["snapshot.restore<br/>same objects, values back"]
  R --> V["restored signal<br/>views resync"]
  V --> E["ticks t+1 .. t+k again<br/>on the real words<br/>(only new events played)"]
Loading

N1 provides the take, the restore and the presentation's half. When to take one and when to roll back is the session's, in N2.

Taking a snapshot

The walk starts at the match and saves each sim object it meets once.

# addons/openfire_engine/game/sim/sim_snapshot.gd
static func take(mc: MatchController) -> SimSnapshot:
	var s := SimSnapshot.new()
	s.tick = mc.sim_tick
	s._seen[mc.get_instance_id()] = true
	s._save(mc, false)
	return s


func _save(o: Object, links: bool) -> void:
	var names := _vars(o)
	var values := []
	values.resize(names.size())
	for i in names.size():
		values[i] = _copy(o.get(names[i]), true)
	_entries.append([o, names, values])
	if links:
		var conns := []
		for sig in _signals(o):
			for c in o.get_signal_connection_list(sig):
				conns.append([sig, c["callable"], c["flags"]])
		_links.append([o, conns])

The variables come in an order: the float views first. SimHash skips them; the snapshot saves them too, so that what is drawn after a restore matches what is simulated, but puts the integers back after them.

# addons/openfire_engine/game/sim/sim_snapshot.gd: _vars
	var views: Array = SimHash.SKIP_VARS.get(cls, [])
	var first: Array = []   # the float views (SimHash skips them): some are properties whose setters write the integers they view, rounded,
	var names: Array = []   # so they are put back first and the integers after them, exactly
	for p in o.get_property_list():
		if p["usage"] & PROPERTY_USAGE_SCRIPT_VARIABLE and not skip.has(p["name"]):
			(first if views.has(p["name"]) else names).append(p["name"])
	first.append_array(names)

Restoring it

# addons/openfire_engine/game/sim/sim_snapshot.gd
func restore(mc: MatchController) -> void:
	for e in _entries:
		var o: Object = e[0]
		var names: Array = e[1]
		var values: Array = e[2]
		for i in names.size():
			var v: Variant = values[i]
			if typeof(v) == TYPE_OBJECT and v != null and not is_instance_valid(v):
				continue   # a view or sound node freed since: not sim state, and nothing to put back
			var cur: Variant = o.get(names[i])
			if typeof(v) == TYPE_ARRAY and typeof(cur) == TYPE_ARRAY and not (cur as Array).is_read_only():
				(cur as Array).assign(_copy(v, false))   # into the same array: whatever shares it (a view's reference) sees the restored one
			elif typeof(v) == TYPE_DICTIONARY and typeof(cur) == TYPE_DICTIONARY and not (cur as Dictionary).is_read_only():
				(cur as Dictionary).clear()
				(cur as Dictionary).merge(_copy(v, false))
			else:
				o.set(names[i], _copy(v, false))
	for l in _links:
		var o: Object = l[0]
		for sig in _signals(o):
			for c in o.get_signal_connection_list(sig):
				o.disconnect(sig, c["callable"])
		for c in l[1]:
			var cb: Callable = c[1]
			if cb.is_valid() and not o.is_connected(c[0], cb):
				o.connect(c[0], cb, c[2])
	mc.restored.emit()

Each restore copies from the snapshot afresh, so one snapshot can be restored any number of times (N2 restores the same one again when a second late word arrives). The controls are not sim state (SimHash.SKIP_CLASSES): the session keeps the words it handed out, and N2's NetControls are indexed by tick, so they need nothing back.

The tile's new state moves into the match

Before N1, TerrainView3D connected a destroyed tile's ExplosionEffect3D.tile_state to its own _apply_tile_destroyed, which changed the level's coastal id and art and rolled randi(). The effect advanced on _process(delta). The match reads those coastal ids (collisions, road assist, hit points), so the view changed the game. The variation's dice, traced:

// RFIRE.BIN FUN_0042e600 (Ghidra), the tile's destroyed state
  if ((*(uint *)(param_2 + 0xc) & 4) == 0) {
    uVar1 = 0;
    if ((*(uint *)(param_2 + 0xc) & 2) == 0) goto LAB_0042e626;
    iVar3 = 2;
  }
  else {
    iVar3 = 4;
  }
  uVar1 = FUN_0041d3d0(iVar3);   // the game's dice: CrtRand.below (document 168)
  uVar1 = uVar1 & 0xff;

So the match runs the explosion's script for the tile (TileCollapse, a sim object), with the timing the effect had: op 21's timers count down, the progress grows by the record's rate, the explosion ends at its duration, else the script runs.

# addons/openfire_engine/game/tile_collapse.gd
func sim_step(mc: MatchController) -> void:
	var rec := record(mc.pack)
	var i := timers.size() - 1
	while i >= 0:
		timers[i] -= 1
		if timers[i] <= 0:
			timers.remove_at(i)
			mc.apply_tile_state(tile, coastal_id)
		i -= 1
	if ended:
		finished = timers.is_empty()
		return
	progress_fx += Pack.fx_of(rec, "rate_per_tick", Fx.ONE >> 2)
	if progress_fx >= Pack.fx_of(rec, "duration", Fx.ONE):
		ended = true   # the explosion is gone; op 21's delayed change was scheduled apart from it (FUN_004146d0), so it still comes
		finished = timers.is_empty()
		return
	var ops: Array = rec.get("script", [])
	while not script_done and pc < ops.size():
		var op: Array = ops[pc]
		match op[0]:
			"END":
				script_done = true
			"STOP":
				pc += 1
				return
			"WAIT":
				if progress_fx < Pack.fx(op[1]):
					return
				pc += 1
			"TILE_STATE":
				mc.apply_tile_state(tile, coastal_id)
				pc += 1
			"SHATTER":
				mc.tile_shattered.emit(int(op[1]), tile, coastal_id)
				pc += 1
			"OP21":
				mc.clear_tile_decoration(tile)
				timers.append(int(op[1]))
				pc += 1
			_:
				pc += 1

MatchController.apply_tile_state is the view's old code with rng.below(2) / rng.below(4) in place of randi(), then tile_changed. The match starts a collapse where it emits target_hit, tile_destroyed and tile_crushed, with the coastal id read before any listener hears of it; a crush record first sets the tile's variant to 1 (also the view's job until now). The collapses step with the world objects, after the debris (_update_collapses in step); the original's place for explosion objects in its update order is not traced, a port choice marked in the code.

One difference from the old view, on purpose: op 21's delayed state change outlives the explosion. In the view it was a timer inside the effect node, lost if the drawing ended first; in the original it is scheduled apart from the explosion (FUN_004146d0 → FUN_0042da50), as the effect's own header says.

SHATTER (the flying pieces) stays presentation (DebrisPiece is out of the sim, document 170): the match only emits tile_shattered, and the view hands it to MatchController.shatter_tile as before.

What it changes: a headless match (every check, CI's recordings) now changes destroyed tiles, as the game always did on screen. openfire's AI harnesses (ai_match_harness.gd, ai_jeep_gun_check.gd, playthrough_rfmap001.gd) played the view's part by hand; they no longer do.

The views after a restore

# addons/openfire_engine/game/terrain_view_3d.gd
func _on_restored() -> void:
	_events.restart()
	var live := _live_objects()
	for o in _object_views.keys():
		var v: Node = _object_views[o]
		if not is_instance_valid(v) or v.is_queued_for_deletion():
			_object_views.erase(o)
		elif not live.has(o):
			v.queue_free()
			_object_views.erase(o)
	for o in live:
		if not _object_views.has(o):
			(live[o] as Callable).call(o)

_live_objects lists the match's shots, mines, flags, wrecks, pieces, soldiers, Drones, awake turrets, marks and edge guard that are not gone, each with the call that makes its view. Gates are resynced the same way by tile, the tiles the match changed in the last 600 ticks are redrawn from the restored level, and the Drone's hum stops if no Drone is left. A homing shot's smoke connection is not made again: the snapshot restores it with the shot's other connections.

Sounds and explosions are asked first:

# addons/openfire_engine/game/presented_events.gd
func first(tick: int, key: String) -> bool:
	if tick != _tick:
		_tick = tick
		_counts.clear()
	var n: int = _counts.get(key, 0)
	_counts[key] = n + 1
	var k := "%d|%s|%d" % [tick, key, n]
	if _seen.has(k):
		return false
	_seen[k] = tick
	if tick - _pruned_at > KEEP_TICKS:
		_prune(tick - KEEP_TICKS)
	return true

The key holds the n-th time in that tick, so two identical explosions on one tick both play, and a re-run plays a third one that only the real words made. The level view asks it for every explosion it spawns (impacts, mines, tiles shot or crushed, drownings, missile smoke); SoundManager asks it for every one-shot (play, play_at). Loops (engines, the Drone's hum) follow state and are not keyed. What a wrong guess played and the real run does not repeat has been heard; rollback games accept that.

How it was checked

Check What it proves
engine tests/snapshot_check.gd The determinism match replayed with a rollback every 7 ticks, 1 to 8 ticks ahead on random words: all 1500 hashes equal the straight run's (214 rollbacks, 213 guessed runs reached another state); a snapshot restores twice; the vehicles are the same objects
engine tests/restore_view_check.gd The level scene on the fixture, armed vehicles on scripted words, a rollback every 5 ticks: after all 239 restores every live object has exactly one view; with right guesses, the explosions and sounds played equal the straight run's (with the key check switched off it plays 3 explosions for 1, so the check bites)
engine tests/tile_collapse_check.gd A building's state comes on its script's tick (the 8th), SHATTER on the same tick, the art from the match's dice, the same in a second match; a crushed bush: variant at once, op 21 on the 2nd tick, its state 6 ticks later after the explosion ended; a restore mid-collapse ends the same
openfire-nettest tests/rollback_check.gd The game's four-player match on MAP01: all 4000 hashes through 571 rollbacks
engine CI snapshot_check and tile_collapse_check on Linux and Windows, restore_view_check on Linux

Where the code is (today)

What Where
Snapshot and restore addons/openfire_engine/game/sim/sim_snapshot.gd (SimSnapshot)
The tile's explosion script in the match game/tile_collapse.gd (TileCollapse); MatchController._start_collapse, apply_tile_state, clear_tile_decoration, signals tile_changed, tile_shattered, restored
The views after a restore game/terrain_view_3d.gd (_on_restored, _live_objects, _fresh), game/presented_events.gd, game/sound_manager.gd (events)
The checks engine tests/snapshot_check.gd, restore_view_check.gd, tile_collapse_check.gd; openfire-nettest tests/rollback_check.gd

Next: N2, #150: the rollback session (NetSession, NetControls), peers joined by a fake transport that delays, reorders and drops, the snapshot cost measured on the web, and a rollback replay in the game's CI. Done in document 197.

Clone this wiki locally