N3: Client prediction, reconciliation and interpolation

The client's side of a networked match, in src/net/:

- ClientGame takes the server's notices and snapshots, generates the island
  from the seed and answers with commands. It works on packets, so it runs
  over a NetClient or a test's simulated link.
- ClientClock decides which tick the next command is for, from the server's
  echo of the newest command tick it has received, holding three commands
  waiting at the server.
- ClientPrediction runs each command on a copy of the client's own player
  with the server's movement code, and compares every snapshot with what it
  predicted. A difference is replayed from the server's state and eased in.
- SnapshotInterpolator draws everyone else four ticks in the past, between
  snapshots, on a clock steered gently by arrivals.

Snapshots now carry the client's own block: exact position and velocity,
the water around the player, stamina and state flags, so a prediction can
match the server to the bit. The command echo is now the newest tick
received rather than taken. Protocol version 2.

Snapshots go out every second tick. The interval was three ticks, which is
10 a second, not the 20 the documents claimed; 15 a second is the nearest
even spacing and what interpolation is tuned for.

Drop.ride() holds the barge ride for the server and the client alike, and
NetGame's joining, input and snapshot steps can be called without a socket.

Measured in test/net/test_prediction_link.gd over a simulated link with
100 ms each way, 20 ms jitter and 2% loss: no corrections to own movement
in about 1,400 snapshots per client, and the other player drawn 0.4 mm on
average from where a perfect link would draw them.

Closes #34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 11:30:00 -05:00
co-authored by Claude Opus 5.5
parent b4548d91f5
commit 4111a285f0
32 changed files with 1932 additions and 89 deletions
+89
View File
@@ -0,0 +1,89 @@
## Decides which tick a client's next command is for.
##
## Commands have to reach the server before the tick they name runs, so the client's
## tick runs ahead of the server's by the trip there plus a small margin. Nobody tells
## the client how long the trip is. Instead every snapshot echoes the newest command
## tick the server had received when it was built, next to the tick the server was on:
## the difference is how many commands were waiting. The clock holds that at
## Tuning.NET_COMMAND_MARGIN_TICKS. If commands arrive late two snapshots running it
## jumps ahead (once is more likely a burst of lost packets, which no clock can fix);
## if far too early it waits; small errors are worked off by running a little fast or
## slow.
class_name ClientClock
extends RefCounted
## More than this many commands waiting beyond the margin, and the clock waits for
## the server instead of drifting back.
const FAR_AHEAD_TICKS: float = 6.0
## How much of each new measurement goes into the smoothed margin.
const SMOOTHING: float = 0.1
## The clock runs at most this much fast or slow.
const MAX_RATE_CHANGE: float = 0.02
var running: bool = false
## Commands waiting at the server, smoothed over recent snapshots.
var margin: float = Tuning.NET_COMMAND_MARGIN_TICKS
## Times the clock had to jump, for tests and the network graph.
var jumps: int = 0
var _time: float = 0.0
var _rate: float = 1.0
## Echoes of commands older than this were sent before the last jump and say nothing
## about the clock as it is now.
var _settle_tick: int = 0
## Snapshots in a row that said commands were arriving late.
var _late: int = 0
## Starts the clock from the first snapshot of a match the client plays in.
func start(sim_tick: int) -> void:
running = true
_time = float(sim_tick + Tuning.NET_COMMAND_LEAD_START_TICKS)
_rate = 1.0
margin = Tuning.NET_COMMAND_MARGIN_TICKS
_settle_tick = tick()
_late = 0
jumps = 0
func stop() -> void:
running = false
func advance(delta: float) -> void:
if running:
_time += delta * Tuning.TICK_RATE_HZ * _rate
## The newest tick a command should exist for by now.
func tick() -> int:
return floori(_time)
## How far the clock is into the tick after tick(), from 0 to 1.
func fraction() -> float:
return _time - floorf(_time)
## Takes a snapshot's word on how the clock is doing: the server was about to run
## `sim_tick`, and the newest command it had from this client was for `command_tick`
## (-1 if it had none).
func observe(sim_tick: int, command_tick: int) -> void:
if not running or command_tick < _settle_tick:
return
var waiting: float = float(command_tick - sim_tick + 1)
var wanted: float = Tuning.NET_COMMAND_MARGIN_TICKS
_late = _late + 1 if waiting <= 0.0 else 0
if _late == 1:
return
if _late > 1 or waiting > wanted + FAR_AHEAD_TICKS:
var before: int = tick()
_time += wanted - waiting
_settle_tick = maxi(before + 1, tick())
_rate = 1.0
_late = 0
margin = wanted
jumps += 1
return
margin = lerpf(margin, waiting, SMOOTHING)
_rate = 1.0 + clampf((wanted - margin) * 0.01, -MAX_RATE_CHANGE, MAX_RATE_CHANGE)
+1
View File
@@ -0,0 +1 @@
uid://doxshcsxdscyc
+170
View File
@@ -0,0 +1,170 @@
## A client's side of a networked match: takes the server's notices and snapshots,
## predicts its own player, draws everyone else from the recent past, and answers with
## commands.
##
## It works on packets, so it doesn't care where they come from. With a NetClient
## attached, poll() and advance() do the carrying; without one, the owner passes
## packets to receive() and sends whatever advance() leaves in `outbox`.
##
## The client generates the match's island itself from the seed in the MATCH notice
## (`world`, a Simulation that is never stepped) and plans the same barge route, so it
## can run the same movement code as the server on the same ground.
class_name ClientGame
extends RefCounted
## The most ticks predicted in one advance(). Further behind than this, the ticks in
## between go without commands.
const MAX_CATCH_UP_TICKS: int = 12
var receiver: SnapshotReceiver = SnapshotReceiver.new()
var prediction: ClientPrediction = ClientPrediction.new()
var clock: ClientClock = ClientClock.new()
## Everyone and everything else, drawn in the past.
var remote: SnapshotInterpolator = SnapshotInterpolator.new()
## The match's island, points of interest and props, generated here. Null until the
## first MATCH notice.
var world: Simulation = null
var world_seed: int = 0
## From the last MATCH notice; the phase is also kept up to date by snapshots.
var match_phase: int = Match.LOBBY
var match_index: int = -1
## Asked for the player's input once per tick: func(tick: int) -> PlayerCommand. The
## command's tick is filled in here. Null sends commands that do nothing.
var sample_input: Callable = Callable()
## Makes the world for a seed: func(seed: int) -> Simulation. Tests replace it.
var make_world: Callable = func(match_seed: int) -> Simulation: return Simulation.new(match_seed)
## INPUT packets to send on the state channel, unreliably, oldest first. advance()
## fills it; with a NetClient attached it is sent and emptied there.
var outbox: Array[PackedByteArray] = []
var net: NetClient = null
## Packets that made no sense, so far.
var bad_packets: int = 0
var _recent: Array[PlayerCommand] = []
var _ack_due: bool = false
var _last_sim_tick: int = -1
var _last_yaw: int = 0
var _last_pitch: int = 0
func attach(client: NetClient) -> void:
net = client
## Services the attached NetClient and takes every packet that arrived.
func poll(now_msec: int = -1) -> void:
if net == null:
return
net.poll(now_msec)
for packet: Dictionary in net.packets:
receive(int(packet["channel"]), packet["bytes"])
## Takes one packet from the server.
func receive(channel: int, bytes: PackedByteArray) -> void:
if channel == NetProtocol.CHANNEL_CONTROL:
var notice: Dictionary = NetSnapshot.decode_match(bytes)
if notice.is_empty():
bad_packets += 1
return
_take_notice(notice)
elif receiver.apply(bytes):
_take_snapshot()
## Runs the client for `delta` seconds: makes and predicts the commands that are due,
## and moves the drawing clocks on. Call once a frame.
func advance(delta: float) -> void:
remote.advance(delta)
prediction.smooth(delta)
if prediction.active:
clock.advance(delta)
var target: int = clock.tick()
if target - prediction.next_tick >= MAX_CATCH_UP_TICKS:
prediction.skip_to(target - MAX_CATCH_UP_TICKS + 1)
while prediction.next_tick <= target:
var command: PlayerCommand = _input_for(prediction.next_tick)
prediction.predict(command)
_recent.append(command)
while _recent.size() > Tuning.NET_INPUT_REDUNDANCY:
_recent.pop_front()
outbox.append(NetSnapshot.encode_input(receiver.ack_tick(), _recent))
elif _ack_due:
# Not playing: still say which snapshot is held, so the server can send changes.
outbox.append(NetSnapshot.encode_input(receiver.ack_tick(), []))
_ack_due = false
if net != null:
for bytes: PackedByteArray in outbox:
net.send(NetProtocol.CHANNEL_STATE, bytes, false)
outbox.clear()
## True while this client's own player is in the match and being predicted.
func playing() -> bool:
return prediction.active
## Where to draw this client's own player now.
func own_position() -> Vector3:
return prediction.view_position(clock.fraction())
func _take_notice(notice: Dictionary) -> void:
var new_match: bool = int(notice["index"]) != match_index
match_phase = notice["phase"]
match_index = notice["index"]
if world == null or int(notice["seed"]) != world_seed:
world_seed = notice["seed"]
world = make_world.call(world_seed)
new_match = true
if new_match:
_reset_match()
func _reset_match() -> void:
prediction.stop()
clock.stop()
remote.reset()
_recent.clear()
_last_sim_tick = -1
func _take_snapshot() -> void:
_ack_due = true
match_phase = receiver.match_phase
if receiver.sim_tick < _last_sim_tick:
# The simulation's clock went back: a new match began.
_reset_match()
_last_sim_tick = receiver.sim_tick
if receiver.own_id == 0:
remote.reset()
else:
remote.push(receiver.sim_tick, receiver.entities)
if receiver.own.is_empty() or world == null:
if prediction.active:
prediction.stop()
clock.stop()
_recent.clear()
return
if not prediction.active:
# The barge's route is drawn from the seed alone, at the match's first tick.
prediction.begin(world.ground, Drop.plan(world.ground, SimRng.new(world_seed), 0))
clock.start(receiver.sim_tick)
clock.observe(receiver.sim_tick, receiver.command_tick)
var record: PackedInt32Array = receiver.entities.get(receiver.own_id, PackedInt32Array())
prediction.reconcile(receiver.own_id, receiver.own, record, receiver.sim_tick)
func _input_for(tick: int) -> PlayerCommand:
var command: PlayerCommand = null
if sample_input.is_valid():
command = sample_input.call(tick)
if command == null:
# Nothing pressed, still looking the same way.
command = PlayerCommand.new()
command.yaw = _last_yaw
command.pitch = _last_pitch
command.tick = tick
_last_yaw = command.yaw
_last_pitch = command.pitch
return command
+1
View File
@@ -0,0 +1 @@
uid://ptifged8edme
+207
View File
@@ -0,0 +1,207 @@
## Moves the client's own player the moment a command is made, without waiting for the
## server, and puts right whatever the server then says happened differently.
##
## Each command runs the same movement code the server will run, on the client's copy
## of the player, and is kept. Every snapshot carries the player's exact state before
## some tick (NetSnapshot's own block). If that is what was predicted before that tick,
## nothing happens. If not, the copy is put where the server says and every command
## since is run again; how far that moves the player's present position is the
## correction. A correction isn't shown at once: the difference is carried as an offset
## on the drawn position and fades out.
##
## What isn't predicted: built pieces and broken props, which aren't replicated yet,
## and the flood beyond the cells around the player. Near those the server corrects.
class_name ClientPrediction
extends RefCounted
## The flags movement reads and changes.
const _MOVEMENT_FLAGS: int = NetSnapshot.FLAG_ON_GROUND | NetSnapshot.FLAG_SWIMMING | NetSnapshot.FLAG_ELIMINATED | (3 << NetSnapshot.FLAG_DROP_SHIFT)
## Predicted ticks kept to compare with the server: four seconds.
const HISTORY_TICKS: int = 120
## The client's copy of its own player.
var player: SimEntity = SimEntity.new(0, SimEntity.ARCHETYPE_PLAYER)
var active: bool = false
## The next tick to predict.
var next_tick: int = 0
## Snapshots compared, and those where the server's state wasn't the predicted one.
var reconciles: int = 0
var mispredictions: int = 0
## How far the last, and the largest, correction moved the player's present position.
var last_correction: float = 0.0
var max_correction: float = 0.0
## Corrections too large to blend, shown at once.
var snaps: int = 0
var _ground: SimGround = null
var _drop: Drop = null
## The water around the player as of the last snapshot: its level, the flood cell the
## player was in, and which of the nine cells around that one it reaches.
var _water: float = Flood.NO_WATER
var _water_cell: Vector2i = Vector2i.ZERO
var _water_mask: int = 0
## Tick -> the command predicted for it.
var _commands: Dictionary = {}
## Tick -> the player's state before that tick ran, as _state() lists it.
var _states: Dictionary = {}
## Where the player was before the newest predicted tick, for drawing between ticks.
var _previous: Vector3 = Vector3.ZERO
var _offset: Vector3 = Vector3.ZERO
## Starts predicting on `ground`, with the match's `drop` if it has one.
func begin(ground: SimGround, drop: Drop) -> void:
stop()
_ground = ground
_drop = drop
reconciles = 0
mispredictions = 0
last_correction = 0.0
max_correction = 0.0
snaps = 0
func stop() -> void:
active = false
_commands.clear()
_states.clear()
_offset = Vector3.ZERO
## Runs `command`, which must be for next_tick, on the client's copy of the player.
func predict(command: PlayerCommand) -> void:
if not active or command.tick != next_tick:
return
_commands[next_tick] = command
_run(next_tick)
next_tick += 1
_commands.erase(next_tick - HISTORY_TICKS)
_states.erase(next_tick - HISTORY_TICKS)
## Gives up on every tick before `tick`: no commands were made for them.
func skip_to(tick: int) -> void:
next_tick = maxi(next_tick, tick)
## Takes the server's word: `own` is the player's own block and `record` its record
## from a snapshot whose simulation tick is `sim_tick`, so both describe the player
## before that tick ran. Returns how far the player's present position moved.
func reconcile(entity_id: int, own: Dictionary, record: PackedInt32Array, sim_tick: int) -> float:
reconciles += 1
last_correction = 0.0
player.id = entity_id
_water = own["water"]
_water_mask = own["water_mask"]
_water_cell = _cell_of(own["position"])
# The own block is only sent for a living player.
player.health = 1
if not record.is_empty():
player.health = maxi(record[NetSnapshot.R_HEALTH], 1)
player.armor = record[NetSnapshot.R_ARMOR]
if not active or sim_tick >= next_tick:
# Nothing predicted from here on: start from what the server says.
active = true
_adopt(own, record)
next_tick = sim_tick
_previous = player.position
_forget_before(sim_tick)
return 0.0
var predicted: Array = _states.get(sim_tick, [])
_forget_before(sim_tick)
if predicted == _state_of(own):
return 0.0
var before: Vector3 = player.position
_adopt(own, record)
for tick: int in range(sim_tick, next_tick):
_run(tick)
var moved: Vector3 = player.position - before
last_correction = moved.length()
if last_correction > 0.0:
mispredictions += 1
max_correction = maxf(max_correction, last_correction)
_offset -= moved
if _offset.length() > Tuning.NET_CORRECTION_SNAP_METRES:
_offset = Vector3.ZERO
snaps += 1
return last_correction
## Fades out whatever correction is still being hidden. Call once a frame.
func smooth(delta: float) -> void:
_offset *= exp(-delta * Tuning.NET_CORRECTION_SMOOTH_RATE)
if _offset.length_squared() < 0.000001:
_offset = Vector3.ZERO
## Where to draw the player: `fraction` of the way from the tick before to the newest
## predicted one, plus whatever correction is still fading.
func view_position(fraction: float = 1.0) -> Vector3:
return _previous.lerp(player.position, clampf(fraction, 0.0, 1.0)) + _offset
## The correction still being hidden, in metres.
func hidden_correction() -> float:
return _offset.length()
## One tick of the player, as Simulation.step() does it.
func _run(tick: int) -> void:
_states[tick] = _state()
_previous = player.position
if player.eliminated:
return
var command: PlayerCommand = _commands.get(tick)
if player.drop_state == Drop.ABOARD:
if _drop == null:
return
_drop.ride(player, command, tick)
if player.drop_state == Drop.ABOARD and _drop.is_over(tick + 1):
_drop.leap(player, tick + 1)
return
var water: float = _water_at(player.position)
Movement.step(player, command, _ground, water)
var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT)
# Stamina matters to swimming. Drowning is the server's to decide.
Water.update(player, _water_at(player.position), 0, sprinting)
func _adopt(own: Dictionary, record: PackedInt32Array) -> void:
NetSnapshot.apply_self(player, own)
if not record.is_empty():
player.yaw = record[NetSnapshot.R_YAW]
## Everything movement reads from the player, for comparing with the server.
func _state() -> Array:
return [player.position, player.velocity, player.stamina_ticks, NetSnapshot.flags_of(player) & _MOVEMENT_FLAGS]
func _state_of(own: Dictionary) -> Array:
return [own["position"], own["velocity"], own["stamina"], int(own["flags"]) & _MOVEMENT_FLAGS]
func _forget_before(tick: int) -> void:
for kept: int in _states.keys():
if kept < tick:
_states.erase(kept)
for kept: int in _commands.keys():
if kept < tick:
_commands.erase(kept)
func _cell_of(position: Vector3) -> Vector2i:
var last: int = ceili(Tuning.WORLD_SIZE_METRES / Tuning.FLOOD_CELL_METRES) - 1
return Vector2i(
clampi(floori(position.x / Tuning.FLOOD_CELL_METRES), 0, last),
clampi(floori(position.z / Tuning.FLOOD_CELL_METRES), 0, last),
)
## The water level over a point, from the nine cells the last snapshot described.
## Further away than that, the nearest of them stands in.
func _water_at(position: Vector3) -> float:
var away: Vector2i = (_cell_of(position) - _water_cell).clampi(-1, 1)
if _water_mask & (1 << ((away.y + 1) * 3 + away.x + 1)) != 0:
return _water
return Flood.NO_WATER
+1
View File
@@ -0,0 +1 @@
uid://uqlw27by0lsx
+1 -1
View File
@@ -16,7 +16,7 @@ class_name NetProtocol
extends RefCounted
## Raised whenever the wire format changes in a way old clients can't read.
const VERSION: int = 1
const VERSION: int = 2
const MAGIC: String = "TDWL"
const CHANNEL_CONTROL: int = 0
## Unreliable game traffic: commands up, snapshots down.
+93 -24
View File
@@ -8,9 +8,10 @@
##
## server -> SNAPSHOT (channel 1, unreliable)
## u8 type, u32 server tick, u32 baseline tick (0 = none), u32 simulation tick,
## u32 last command tick taken from this client, varint the entity the client is
## watching (its own player, or the one it spectates; 0 = none), u8 match
## phase, u8 tide phase, s16 sea level in centimetres,
## u32 newest command tick received from this client plus one (0 = none yet),
## varint the entity the client is watching (its own player, or the one it
## spectates; 0 = none), u8 match phase, u8 tide phase, s16 sea level in centimetres,
## u8 1 if the client's own block follows, then that block (see SELF_BYTES),
## u8 removed count, then entity IDs as varints,
## u16 record count, then per record: varint ID, u8 (archetype << 5 | group mask),
## then the fields of each group in the mask
@@ -32,6 +33,14 @@ const MSG_INPUT: int = 17
## orders snapshots across matches. The simulation tick is the one commands name.
const HEADER_BYTES: int = 17
const MATCH_BYTES: int = 14
## The client's own block: what it needs to predict its own player and nobody else is
## told. Exact, not quantized, so a prediction made from it matches the server's to the
## bit: position and velocity (three f32 each, which is all a Vector3 holds), the water
## level around the player (f64), which of the nine flood cells around the player that
## water reaches (u16), swimming stamina in ticks (u16) and the player's FLAG_ bits (u8).
const SELF_BYTES: int = 37
## Every bit of the nine-cell water mask.
const WATER_EVERYWHERE: int = 0x1FF
## The most commands one INPUT may carry. Clients send fewer; see Tuning.
const MAX_INPUT_COMMANDS: int = 8
@@ -117,20 +126,7 @@ static func record_of(entity: SimEntity) -> PackedInt32Array:
record[R_PITCH] = clampi(roundi(float(entity.pitch) / PlayerCommand.PITCH_MAX * 127.0), -127, 127)
record[R_HEALTH] = clampi(entity.health, 0, 255)
record[R_ARMOR] = clampi(entity.armor, 0, 255)
var flags: int = (entity.drop_state & 3) << FLAG_DROP_SHIFT
if entity.on_ground:
flags |= FLAG_ON_GROUND
if entity.crouching:
flags |= FLAG_CROUCHING
if entity.swimming:
flags |= FLAG_SWIMMING
if entity.eliminated:
flags |= FLAG_ELIMINATED
if entity.reload_ticks > 0:
flags |= FLAG_RELOADING
if entity.use_ticks > 0:
flags |= FLAG_USING
record[R_FLAGS] = flags
record[R_FLAGS] = flags_of(entity)
var held: int = -1
if entity.selected >= 1 and entity.selected <= entity.slot_items.size():
held = entity.slot_items[entity.selected - 1]
@@ -145,6 +141,47 @@ static func record_of(entity: SimEntity) -> PackedInt32Array:
return record
## A player's FLAG_ bits.
static func flags_of(entity: SimEntity) -> int:
var flags: int = (entity.drop_state & 3) << FLAG_DROP_SHIFT
if entity.on_ground:
flags |= FLAG_ON_GROUND
if entity.crouching:
flags |= FLAG_CROUCHING
if entity.swimming:
flags |= FLAG_SWIMMING
if entity.eliminated:
flags |= FLAG_ELIMINATED
if entity.reload_ticks > 0:
flags |= FLAG_RELOADING
if entity.use_ticks > 0:
flags |= FLAG_USING
return flags
## The client's own block for `player`. `water` is the level of the water around it and
## `water_mask` says which of the nine flood cells around it that water reaches: bit
## (dz + 1) * 3 + (dx + 1) for the cell dx, dz away from the player's.
static func self_of(player: SimEntity, water: float, water_mask: int) -> Dictionary:
return {
"position": player.position, "velocity": player.velocity, "water": water,
"water_mask": water_mask, "stamina": player.stamina_ticks, "flags": flags_of(player),
}
## Puts a client's own block into `player`: everything movement depends on.
static func apply_self(player: SimEntity, own: Dictionary) -> void:
var flags: int = own["flags"]
player.position = own["position"]
player.velocity = own["velocity"]
player.stamina_ticks = own["stamina"]
player.on_ground = flags & FLAG_ON_GROUND != 0
player.crouching = flags & FLAG_CROUCHING != 0
player.swimming = flags & FLAG_SWIMMING != 0
player.eliminated = flags & FLAG_ELIMINATED != 0
player.drop_state = (flags >> FLAG_DROP_SHIFT) & 3
## Where a record's entity is, to the nearest 1/64 m.
static func position_of(record: PackedInt32Array) -> Vector3:
return Vector3(
@@ -203,11 +240,22 @@ static func encode_snapshot(header: Dictionary, removed: PackedInt32Array, recor
out.put_u32(int(header["tick"]) & 0xFFFFFFFF)
out.put_u32(int(header.get("baseline", 0)) & 0xFFFFFFFF)
out.put_u32(int(header.get("sim_tick", 0)) & 0xFFFFFFFF)
out.put_u32(int(header.get("command_tick", 0)) & 0xFFFFFFFF)
out.put_u32((int(header.get("command_tick", -1)) + 1) & 0xFFFFFFFF)
_put_varint(out, int(header.get("own_id", 0)))
out.put_u8(int(header.get("match_phase", 0)))
out.put_u8(int(header.get("tide_phase", 0)))
out.put_16(clampi(int(header.get("sea_cm", 0)), -32768, 32767))
var own: Dictionary = header.get("self", {})
out.put_u8(0 if own.is_empty() else 1)
if not own.is_empty():
for vector: Vector3 in [own["position"], own["velocity"]]:
out.put_float(vector.x)
out.put_float(vector.y)
out.put_float(vector.z)
out.put_double(own["water"])
out.put_u16(int(own["water_mask"]) & WATER_EVERYWHERE)
out.put_u16(clampi(int(own["stamina"]), 0, 65535))
out.put_u8(int(own["flags"]) & 0xFF)
out.put_u8(removed.size())
for entity_id: int in removed:
_put_varint(out, entity_id)
@@ -237,24 +285,45 @@ static func encode_snapshot(header: Dictionary, removed: PackedInt32Array, recor
## Reads a SNAPSHOT's header and lists, without applying them: {"tick", "baseline",
## "sim_tick", "command_tick", "own_id", "match_phase", "tide_phase", "sea_cm", "removed":
## "sim_tick", "command_tick" (-1 = none yet), "own_id", "match_phase", "tide_phase",
## "sea_cm", "self": the client's own block as self_of() made it, or empty, "removed":
## PackedInt32Array, "records": [[entity ID, archetype, mask, values]]}, where `values`
## holds the fields present, in record order. Empty if malformed.
static func decode_snapshot(bytes: PackedByteArray) -> Dictionary:
if bytes.size() < HEADER_BYTES + 7 or bytes[0] != MSG_SNAPSHOT:
if bytes.size() < HEADER_BYTES + 8 or bytes[0] != MSG_SNAPSHOT:
return {}
var cursor: Array[int] = [HEADER_BYTES]
var own_id: int = _read_varint(bytes, cursor)
if own_id < 0 or cursor[0] + 5 > bytes.size():
if own_id < 0 or cursor[0] + 6 > bytes.size():
return {}
var at: int = cursor[0]
var result: Dictionary = {
"tick": bytes.decode_u32(1), "baseline": bytes.decode_u32(5), "sim_tick": bytes.decode_u32(9),
"command_tick": bytes.decode_u32(13),
"command_tick": bytes.decode_u32(13) - 1,
"own_id": own_id, "match_phase": bytes[at], "tide_phase": bytes[at + 1], "sea_cm": bytes.decode_s16(at + 2),
}
var removed_count: int = bytes[at + 4]
cursor[0] = at + 5
var own: Dictionary = {}
at += 5
if bytes[at - 1] > 1:
return {}
if bytes[at - 1] == 1:
if at + SELF_BYTES + 1 > bytes.size():
return {}
own = {
"position": Vector3(bytes.decode_float(at), bytes.decode_float(at + 4), bytes.decode_float(at + 8)),
"velocity": Vector3(bytes.decode_float(at + 12), bytes.decode_float(at + 16), bytes.decode_float(at + 20)),
"water": bytes.decode_double(at + 24),
"water_mask": bytes.decode_u16(at + 32) & WATER_EVERYWHERE,
"stamina": bytes.decode_u16(at + 34),
"flags": bytes[at + 36],
}
for value: float in [own["position"].x, own["position"].y, own["position"].z, own["velocity"].x, own["velocity"].y, own["velocity"].z, own["water"]]:
if not is_finite(value):
return {}
at += SELF_BYTES
result["self"] = own
var removed_count: int = bytes[at]
cursor[0] = at + 1
var removed: PackedInt32Array = PackedInt32Array()
for _index: int in removed_count:
var entity_id: int = _read_varint(bytes, cursor)
+158
View File
@@ -0,0 +1,158 @@
## Draws everyone else a little in the past, between the snapshots on either side of
## that moment, so they move evenly however unevenly snapshots arrive.
##
## The moment drawn is a clock of its own, Tuning.NET_INTERP_DELAY_TICKS behind the
## newest snapshot. It runs with the frame clock and is steered gently towards where
## the snapshots say it should be, so a late packet doesn't jerk everyone at once. If
## it runs past the newest snapshot (a packet lost), entities carry on along their last
## heading for a few ticks and then wait. When the missing news arrives and the guess
## was off, the difference is blended away over a few frames rather than shown at once.
class_name SnapshotInterpolator
extends RefCounted
## Snapshots kept per entity.
const SAMPLES: int = 16
## Further than this from where it should be, the clock is simply set.
const RESET_TICKS: float = 10.0
## The moment being drawn, in simulation ticks.
var time: float = 0.0
var started: bool = false
## Samples asked for beyond the newest snapshot, and those beyond what extrapolation
## covers, for tests and the network graph.
var extrapolated: int = 0
var held: int = 0
## Entity ID -> its samples, oldest first: [tick, position, yaw, pitch] with the angles
## in radians.
var _tracks: Dictionary = {}
var _newest: int = 0
## How far the clock is from where it should be, smoothed.
var _error: float = 0.0
## Entity ID -> what is still being blended away after a wrong guess.
var _offsets: Dictionary = {}
func reset() -> void:
_tracks.clear()
_offsets.clear()
started = false
_error = 0.0
extrapolated = 0
held = 0
## Takes the picture of a snapshot (SnapshotReceiver.entities) at `sim_tick`.
func push(sim_tick: int, entities: Dictionary) -> void:
if started and sim_tick <= _newest:
return
for entity_id: int in entities:
var record: PackedInt32Array = entities[entity_id]
var track: Array = _tracks.get_or_add(entity_id, [])
# If this entity was being drawn on a guess, remember where.
var guessing: bool = started and track.size() >= 2 and time > float(track[track.size() - 1][0])
var guessed: Vector3 = _at(track, false)["position"] + _offsets.get(entity_id, Vector3.ZERO) if guessing else Vector3.ZERO
var yaw: float = 0.0
var pitch: float = 0.0
if record[NetSnapshot.R_ARCHETYPE] == SimEntity.ARCHETYPE_PLAYER:
yaw = NetSnapshot.yaw_radians_of(record)
pitch = NetSnapshot.pitch_radians_of(record)
track.append([sim_tick, NetSnapshot.position_of(record), yaw, pitch])
if track.size() > SAMPLES:
track.pop_front()
if guessing:
var offset: Vector3 = guessed - _at(track, false)["position"]
if offset.length() > Tuning.NET_CORRECTION_SNAP_METRES:
_offsets.erase(entity_id)
else:
_offsets[entity_id] = offset
for entity_id: int in _tracks.keys():
if not entities.has(entity_id):
_tracks.erase(entity_id)
_offsets.erase(entity_id)
_newest = sim_tick
var wanted: float = float(sim_tick) - Tuning.NET_INTERP_DELAY_TICKS
if not started or absf(wanted - time) > RESET_TICKS:
time = wanted
_error = 0.0
started = true
else:
_error = lerpf(_error, wanted - time, 0.2)
func advance(delta: float) -> void:
if not started:
return
time += delta * Tuning.TICK_RATE_HZ * (1.0 + clampf(_error * 0.05, -0.1, 0.1))
var keep: float = exp(-delta * Tuning.NET_CORRECTION_SMOOTH_RATE)
for entity_id: int in _offsets.keys():
var offset: Vector3 = _offsets[entity_id] * keep
if offset.length_squared() < 0.000001:
_offsets.erase(entity_id)
else:
_offsets[entity_id] = offset
func has(entity_id: int) -> bool:
return _tracks.has(entity_id)
func ids() -> Array:
return _tracks.keys()
## Where an entity is at the moment being drawn: {"position", "yaw", "pitch"}, or
## empty if nothing is known of it.
func sample(entity_id: int) -> Dictionary:
var track: Array = _tracks.get(entity_id, [])
if track.is_empty():
return {}
var shown: Dictionary = _at(track, true)
if _offsets.has(entity_id):
shown["position"] += _offsets[entity_id]
return shown
## An entity's place on its track at the moment being drawn.
func _at(track: Array, count: bool) -> Dictionary:
var last: Array = track[track.size() - 1]
if time >= float(last[0]):
if track.size() < 2 or time == float(last[0]):
return _shown(last[1], last[2], last[3])
var before: Array = track[track.size() - 2]
var span: float = float(last[0] - before[0])
var ahead: float = time - float(last[0])
if count:
extrapolated += 1
if ahead > Tuning.NET_INTERP_EXTRAPOLATE_TICKS:
held += 1
ahead = minf(ahead, Tuning.NET_INTERP_EXTRAPOLATE_TICKS)
var step: Vector3 = last[1] - before[1]
if _teleported(step, span):
return _shown(last[1], last[2], last[3])
return _shown(last[1] + step * (ahead / span), last[2], last[3])
for index: int in range(track.size() - 1, 0, -1):
var from: Array = track[index - 1]
if time < float(from[0]):
continue
var to: Array = track[index]
var span: float = float(to[0] - from[0])
if _teleported(to[1] - from[1], span):
return _shown(to[1], to[2], to[3])
var weight: float = (time - float(from[0])) / span
return _shown((from[1] as Vector3).lerp(to[1], weight), lerp_angle(from[2], to[2], weight), lerpf(from[3], to[3], weight))
var first: Array = track[0]
return _shown(first[1], first[2], first[3])
func position_of(entity_id: int) -> Vector3:
var shown: Dictionary = sample(entity_id)
return shown["position"] if not shown.is_empty() else Vector3.ZERO
func _teleported(step: Vector3, ticks: float) -> bool:
return step.length() > Tuning.NET_INTERP_TELEPORT_METRES_PER_SECOND * ticks / Tuning.TICK_RATE_HZ
func _shown(position: Vector3, yaw: float, pitch: float) -> Dictionary:
return {"position": position, "yaw": yaw, "pitch": pitch}
+1
View File
@@ -0,0 +1 @@
uid://c16j5ts8po816
+6 -2
View File
@@ -19,8 +19,11 @@ var tick: int = 0
var sim_tick: int = 0
## This client's own entity, or the one it is spectating; 0 outside a match.
var own_id: int = 0
## The newest of this client's command ticks the server had taken.
var command_tick: int = 0
## The newest of this client's command ticks the server had received, or -1.
var command_tick: int = -1
## This client's own block from that picture (see NetSnapshot.self_of), or empty when
## it isn't playing: in the lobby, eliminated or watching someone else.
var own: Dictionary = {}
var match_phase: int = 0
var tide_phase: int = 0
var sea_level: float = 0.0
@@ -85,6 +88,7 @@ func apply(bytes: PackedByteArray) -> bool:
sim_tick = snapshot["sim_tick"]
own_id = snapshot["own_id"]
command_tick = snapshot["command_tick"]
own = snapshot["self"]
match_phase = snapshot["match_phase"]
tide_phase = snapshot["tide_phase"]
sea_level = int(snapshot["sea_cm"]) / 100.0
+30 -6
View File
@@ -28,7 +28,7 @@ var _entities: Array[SimEntity] = []
func add_client(handle: int) -> void:
_clients[handle] = {
"acked": 0, "history": {}, "last_sent": {}, "command_tick": 0,
"acked": 0, "history": {}, "last_sent": {}, "command_tick": -1,
"bytes": 0, "snapshots": 0, "full": 0, "deferred": 0,
}
@@ -50,7 +50,8 @@ func acknowledge(handle: int, tick: int) -> void:
client["acked"] = tick
## Notes the newest command tick taken from a client, echoed in its snapshots.
## Notes the newest command tick received from a client, echoed in its snapshots so
## the client can tell how early its commands arrive.
func note_command(handle: int, command_tick: int) -> void:
if _clients.has(handle):
var client: Dictionary = _clients[handle]
@@ -65,7 +66,7 @@ func reset() -> void:
client["acked"] = 0
client["history"] = {}
client["last_sent"] = {}
client["command_tick"] = 0
client["command_tick"] = -1
_records.clear()
_entities.clear()
_records_tick = -1
@@ -106,8 +107,9 @@ static func interest(sim: Simulation, viewer: SimEntity, among: Array[SimEntity]
## Builds the snapshot for a client at the simulation's current tick. `viewer_id` is
## the entity the client is watching (its own player, or the one it spectates), or 0
## outside a match. `tick` is the server's own tick count, which must grow with every
## call for the same client.
func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase: int) -> PackedByteArray:
## call for the same client. `own_id` is the client's own player, or 0: while that is
## who it watches and they are still in the match, the snapshot carries their own block.
func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase: int, own_id: int = 0) -> PackedByteArray:
if not _clients.has(handle):
return PackedByteArray()
var client: Dictionary = _clients[handle]
@@ -128,6 +130,10 @@ func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase:
"tide_phase": sim.tide.phase_at(sim.tick) if sim.tide != null else 0,
"sea_cm": roundi(sim.sea_level * 100.0),
}
var own_bytes: int = 0
if viewer != null and viewer.id == own_id and not viewer.eliminated:
header["self"] = own_block(sim, viewer)
own_bytes = NetSnapshot.SELF_BYTES
var visible: Dictionary = {}
# [score, entity ID, mask, record]: the lowest score travels first.
var changed: Array = []
@@ -149,7 +155,7 @@ func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase:
changed.sort_custom(func(a: Array, b: Array) -> bool: return a[0] < b[0] if a[0] != b[0] else a[1] < b[1])
var state: Dictionary = base.duplicate()
var budget: int = Tuning.NET_SNAPSHOT_MAX_BYTES - NetSnapshot.HEADER_BYTES - NetSnapshot.varint_bytes(int(header["own_id"])) - 7
var budget: int = Tuning.NET_SNAPSHOT_MAX_BYTES - NetSnapshot.HEADER_BYTES - NetSnapshot.varint_bytes(int(header["own_id"])) - 8 - own_bytes
var removed: PackedInt32Array = PackedInt32Array()
for entity_id: int in base:
if visible.has(entity_id):
@@ -187,6 +193,24 @@ func build(handle: int, sim: Simulation, viewer_id: int, tick: int, match_phase:
return bytes
## A player's own block: its exact state, and the water in the flood cells around it.
## A cell still filling after a breach counts as dry until it stands level with the sea.
static func own_block(sim: Simulation, player: SimEntity) -> Dictionary:
var flood: Flood = sim.flood
if flood == null:
return NetSnapshot.self_of(player, sim.sea_level, NetSnapshot.WATER_EVERYWHERE)
var cx: int = clampi(floori(player.position.x / flood.cell), 0, flood.side - 1)
var cz: int = clampi(floori(player.position.z / flood.cell), 0, flood.side - 1)
var mask: int = 0
for dz: int in range(-1, 2):
for dx: int in range(-1, 2):
var x: int = clampi(cx + dx, 0, flood.side - 1)
var z: int = clampi(cz + dz, 0, flood.side - 1)
if flood.level_of_cell(z * flood.side + x) >= flood.sea_level - 0.05:
mask |= 1 << ((dz + 1) * 3 + dx + 1)
return NetSnapshot.self_of(player, flood.sea_level, mask)
func _record(sim: Simulation, entity_id: int) -> PackedInt32Array:
if not _records.has(entity_id):
_records[entity_id] = NetSnapshot.record_of(sim.entities.find(entity_id))
+57 -30
View File
@@ -1,6 +1,6 @@
## Joins the transport to the match: people who connect become participants, their
## input packets become commands through ServerLoop.submit(), and everyone is sent
## snapshots of what they may see, 20 times a second.
## snapshots of what they may see, 15 times a second.
##
## Call poll() once a frame before running ticks, and after_tick() after each tick.
class_name NetGame
@@ -15,7 +15,7 @@ var events: Array[Dictionary] = []
## Input packets that couldn't be read, so far.
var bad_inputs: int = 0
## Handle -> the newest command tick taken from them this match.
## Handle -> the newest command tick received from them this match.
var _last_command: Dictionary = {}
@@ -35,8 +35,7 @@ func poll() -> void:
var handle: int = int(event.get("handle", 0))
if event["type"] == "joined":
if loop.match_flow.join(handle):
sender.add_client(handle)
_last_command[handle] = -1
adopt(handle)
_send_match(handle)
events.append(event)
else:
@@ -47,24 +46,36 @@ func poll() -> void:
_last_command.erase(handle)
events.append(event)
for packet: Dictionary in net.packets:
var handle: int = packet["handle"]
if not sender.has_client(handle):
take_input(packet["handle"], packet["bytes"])
## Starts sending snapshots to a participant who is already in the match flow, and
## taking their input. poll() does this for everyone who joins over the network.
func adopt(handle: int) -> void:
sender.add_client(handle)
_last_command[handle] = -1
## Takes one INPUT packet from a participant: the snapshot they hold, and commands.
func take_input(handle: int, bytes: PackedByteArray) -> void:
if not sender.has_client(handle):
return
var input: Dictionary = NetSnapshot.decode_input(bytes)
if input.is_empty():
bad_inputs += 1
return
sender.acknowledge(handle, int(input["ack"]))
if not loop.match_flow.in_match():
return
# Packets repeat recent commands; each tick's command is offered once, whether
# or not the simulation takes it. The newest tick received is echoed either way,
# so a client whose commands come too late or too early can tell.
for command: PlayerCommand in input["commands"]:
if command.tick <= int(_last_command[handle]):
continue
var input: Dictionary = NetSnapshot.decode_input(packet["bytes"])
if input.is_empty():
bad_inputs += 1
continue
sender.acknowledge(handle, int(input["ack"]))
if not loop.match_flow.in_match():
continue
# Packets repeat recent commands; each tick's command is offered once, whether
# or not the simulation takes it.
for command: PlayerCommand in input["commands"]:
if command.tick <= int(_last_command[handle]):
continue
_last_command[handle] = command.tick
if loop.submit(handle, command):
sender.note_command(handle, command.tick)
_last_command[handle] = command.tick
sender.note_command(handle, command.tick)
loop.submit(handle, command)
## Tells everyone about a change of phase, and sends snapshots when one is due.
@@ -83,13 +94,32 @@ func after_tick() -> void:
if changed:
for handle: int in net.handles():
_send_match(handle)
if loop.ticks % Tuning.NET_SNAPSHOT_INTERVAL_TICKS != 0:
if not snapshot_due():
return
for handle: int in net.handles():
if not sender.has_client(handle):
continue
var bytes: PackedByteArray = sender.build(handle, loop.sim, viewer_of(handle), loop.ticks, flow.phase)
net.send(handle, NetProtocol.CHANNEL_STATE, bytes, false)
if sender.has_client(handle):
net.send(handle, NetProtocol.CHANNEL_STATE, snapshot_for(handle), false)
## True on the ticks a snapshot goes out.
func snapshot_due() -> bool:
return loop.ticks % Tuning.NET_SNAPSHOT_INTERVAL_TICKS == 0
## The snapshot for a participant as things stand: what they may see, and their own
## block while they are playing.
func snapshot_for(handle: int) -> PackedByteArray:
var flow: Match = loop.match_flow
var own_id: int = int(flow.entity_of.get(handle, 0)) if flow.in_match() else 0
return sender.build(handle, loop.sim, viewer_of(handle), loop.ticks, flow.phase, own_id)
## The MATCH notice as things stand: the phase, and the match's index and seed.
func match_notice() -> PackedByteArray:
var flow: Match = loop.match_flow
var started: bool = flow.in_match() or flow.phase == Match.RESULTS
var index: int = flow.matches_started - 1 if started else flow.matches_started
return NetSnapshot.encode_match(flow.phase, index, flow.current_seed())
## The entity a participant is watching: their own player, the player they spectate
@@ -105,7 +135,4 @@ func viewer_of(handle: int) -> int:
func _send_match(handle: int) -> void:
var flow: Match = loop.match_flow
var started: bool = flow.in_match() or flow.phase == Match.RESULTS
var index: int = flow.matches_started - 1 if started else flow.matches_started
net.send(handle, NetProtocol.CHANNEL_CONTROL, NetSnapshot.encode_match(flow.phase, index, flow.current_seed()), true)
net.send(handle, NetProtocol.CHANNEL_CONTROL, match_notice(), true)
+12
View File
@@ -101,6 +101,18 @@ func leap(player: SimEntity, tick: int) -> void:
player.on_ground = false
## A tick aboard the barge: jump leaps off, anything else rides along. The server and a
## client predicting its own player both come through here.
func ride(player: SimEntity, command: PlayerCommand, tick: int) -> void:
if command != null:
player.yaw = command.yaw
player.pitch = command.pitch
if command.is_pressed(PlayerCommand.BUTTON_JUMP):
leap(player, tick)
return
player.position = barge_position(tick + 1)
## Distance from `from` along unit `direction` to the square [margin, size - margin].
static func _distance_to_edge(from: Vector2, direction: Vector2, margin: float, size: float) -> float:
var best: float = INF
+1 -12
View File
@@ -180,7 +180,7 @@ func step() -> void:
if player.eliminated:
continue
if player.drop_state == Drop.ABOARD:
_ride(player, command)
drop.ride(player, command, tick)
else:
_apply_command(player, command)
Weapons.advance_projectiles(self)
@@ -196,17 +196,6 @@ func step() -> void:
tick += 1
## A tick aboard the barge: jump leaps off, anything else rides along.
func _ride(player: SimEntity, command: PlayerCommand) -> void:
if command != null:
player.yaw = command.yaw
player.pitch = command.pitch
if command.is_pressed(PlayerCommand.BUTTON_JUMP):
drop.leap(player, tick)
return
player.position = drop.barge_position(tick + 1)
func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
var water: float = water_level_at(player.position)
Movement.step(player, command, ground, water)
+23 -3
View File
@@ -11,10 +11,10 @@ const MAX_COMMAND_LEAD_TICKS: int = 60
const WORLD_SIZE_METRES: float = 1024.0
# Network. See docs/ARCHITECTURE.md, "Snapshot format".
## Server ticks between snapshots: 20 a second.
const NET_SNAPSHOT_INTERVAL_TICKS: int = 3
## Server ticks between snapshots: 15 a second.
const NET_SNAPSHOT_INTERVAL_TICKS: int = 2
## The most bytes in one snapshot. Keeps a packet inside one UDP datagram on any
## ordinary link, and a client under 24 KB/s before packet headers.
## ordinary link, and a client under 18 KB/s before packet headers.
const NET_SNAPSHOT_MAX_BYTES: int = 1200
## A client is sent other players and shots within this many metres on the map of the
## player it is watching: a little further than the longest weapon reaches.
@@ -28,6 +28,26 @@ const NET_SNAPSHOT_HISTORY: int = 40
const NET_STALE_METRES_PER_SNAPSHOT: float = 6.0
## Commands a client repeats in each input packet, so a lost packet costs nothing.
const NET_INPUT_REDUNDANCY: int = 3
## Commands a client aims to have waiting at the server when each tick runs. Enough
## that ordinary jitter, or a lost packet whose commands the next one repeats, still
## gets every command there in time.
const NET_COMMAND_MARGIN_TICKS: int = 3
## How far ahead of the first snapshot's tick a client starts stamping commands, before
## the server's echo tells it how early they really arrive.
const NET_COMMAND_LEAD_START_TICKS: int = 6
## How far in the past a client draws other players, in ticks: two snapshots, so there
## is nearly always one on each side of the moment drawn.
const NET_INTERP_DELAY_TICKS: float = 4.0
## When snapshots are late or lost, others carry on along their last heading for at
## most this many ticks, then wait.
const NET_INTERP_EXTRAPOLATE_TICKS: float = 3.0
## Something that moved faster than this between two snapshots was put somewhere new,
## and is drawn there at once rather than sliding across.
const NET_INTERP_TELEPORT_METRES_PER_SECOND: float = 80.0
## A correction to the client's own predicted position is blended away at this rate
## (per second), and one larger than the snap distance is shown at once.
const NET_CORRECTION_SMOOTH_RATE: float = 10.0
const NET_CORRECTION_SNAP_METRES: float = 3.0
# Match sizes
const SOLO_PLAYERS: int = 24