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
+47
View File
@@ -0,0 +1,47 @@
## A one-way network link for tests: every packet is delayed by a fixed latency plus
## or minus some jitter, and some are lost. Packets can overtake each other, as on a
## real link. Seeded, so a test sees the same link every run.
class_name LinkSim
extends RefCounted
var latency_ms: float = 0.0
var jitter_ms: float = 0.0
var loss: float = 0.0
var sent: int = 0
var lost: int = 0
var _rng: RandomNumberGenerator = RandomNumberGenerator.new()
## [due time in ms, bytes]
var _queue: Array = []
func _init(latency: float, jitter: float, loss_fraction: float, link_seed: int) -> void:
latency_ms = latency
jitter_ms = jitter
loss = loss_fraction
_rng.seed = link_seed
func send(bytes: PackedByteArray, now_ms: float) -> void:
sent += 1
if _rng.randf() < loss:
lost += 1
return
_queue.append([now_ms + latency_ms + _rng.randf_range(-jitter_ms, jitter_ms), bytes])
## Every packet that has arrived by `now_ms`, in the order they arrived.
func receive(now_ms: float) -> Array[PackedByteArray]:
var due: Array = []
var waiting: Array = []
for entry: Array in _queue:
if entry[0] <= now_ms:
due.append(entry)
else:
waiting.append(entry)
_queue = waiting
due.sort_custom(func(a: Array, b: Array) -> bool: return a[0] < b[0])
var packets: Array[PackedByteArray] = []
for entry: Array in due:
packets.append(entry[1])
return packets
+1
View File
@@ -0,0 +1 @@
uid://cso2r58v31kai
+94
View File
@@ -0,0 +1,94 @@
extends TestCase
## Issue N3: the clock that decides which tick a client's next command is for.
const MARGIN: int = Tuning.NET_COMMAND_MARGIN_TICKS
const DT: float = 1.0 / Tuning.TICK_RATE_HZ
var clock: ClientClock
func before_each() -> void:
clock = ClientClock.new()
clock.start(100)
func test_it_starts_ahead_of_the_server_and_keeps_time() -> void:
assert_true(clock.running)
assert_eq(clock.tick(), 100 + Tuning.NET_COMMAND_LEAD_START_TICKS)
for _tick: int in 30:
clock.advance(DT)
assert_eq(clock.tick(), 130 + Tuning.NET_COMMAND_LEAD_START_TICKS)
clock.advance(DT * 0.25)
assert_near(clock.fraction(), 0.25, 0.001)
clock.stop()
clock.advance(1.0)
assert_eq(clock.tick(), 130 + Tuning.NET_COMMAND_LEAD_START_TICKS, "a stopped clock stays put")
func test_commands_arriving_late_twice_running_make_it_jump_ahead() -> void:
var start: int = clock.tick()
for _tick: int in 10:
clock.advance(DT)
# The server was about to run a tick and the newest command it had was for two
# ticks earlier: four short of having MARGIN waiting.
clock.observe(start + 9, start + 7)
assert_eq(clock.tick(), start + 10, "once could be a burst of lost packets")
assert_eq(clock.jumps, 0)
for _tick: int in 2:
clock.advance(DT)
clock.observe(start + 11, start + 9)
assert_eq(clock.jumps, 1)
assert_eq(clock.tick(), start + 12 + MARGIN + 1)
# Echoes of commands sent before the jump say nothing about the clock now.
var after: int = clock.tick()
clock.observe(start + 13, start + 11)
clock.observe(start + 15, start + 12)
assert_eq(clock.tick(), after)
assert_eq(clock.jumps, 1)
# And the first made after it shows the margin is right.
clock.observe(after - MARGIN + 1, after)
clock.observe(after - MARGIN + 3, after + 2)
assert_eq(clock.jumps, 1)
assert_near(clock.margin, MARGIN, 0.01)
func test_one_late_report_between_good_ones_changes_nothing() -> void:
var start: int = clock.tick()
for round: int in 20:
var sim_tick: int = start + 10 + round * 2
var waiting: int = -1 if round % 5 == 2 else MARGIN
clock.observe(sim_tick, sim_tick + waiting - 1)
assert_eq(clock.jumps, 0)
assert_eq(clock.tick(), start)
func test_far_too_early_and_it_waits_for_the_server() -> void:
var start: int = clock.tick()
clock.observe(110, 110 + MARGIN + 20)
assert_eq(clock.jumps, 1)
assert_true(clock.tick() < start - 10, "went back from %d to %d" % [start, clock.tick()])
func test_a_small_error_is_worked_off_by_running_fast_or_slow() -> void:
# One command too many waiting, every snapshot: the clock should lose a tick, slowly.
var sim_tick: int = 110
var truth: float = float(clock.tick())
for _round: int in 600:
clock.observe(sim_tick, sim_tick + MARGIN)
for _tick: int in 2:
clock.advance(DT)
truth += 1.0
sim_tick += 2
assert_eq(clock.jumps, 0)
var lost: float = truth - (float(clock.tick()) + clock.fraction())
assert_true(lost > 0.5 and lost < 30.0, "ran %.2f ticks slow over 40 s" % lost)
assert_true(clock.margin > MARGIN + 0.5, "smoothed margin %.2f" % clock.margin)
func test_no_command_received_yet_says_nothing() -> void:
var start: int = clock.tick()
for round: int in 10:
clock.observe(110 + round * 2, -1)
assert_eq(clock.tick(), start)
assert_eq(clock.jumps, 0)
+1
View File
@@ -0,0 +1 @@
uid://bshvxsxdk0wh1
+187
View File
@@ -0,0 +1,187 @@
extends TestCase
## Issue N3: predicting the client's own player and reconciling with the server, on a
## flat test ground with the server's simulation stepped by hand. Snapshots here
## arrive `DELAY` ticks after the state they describe.
const DELAY: int = 6
const DT: float = 1.0 / Tuning.TICK_RATE_HZ
var sim: Simulation
var server: SimEntity
var prediction: ClientPrediction
## What the client is sent, oldest first: [simulation tick, own block, record].
var snapshots: Array = []
func before_each() -> void:
sim = Simulation.new(9, SimGround.flat())
server = sim.entities.find(sim.add_player())
server.position = Vector3(500.0, 0.0, 500.0)
prediction = ClientPrediction.new()
prediction.begin(sim.ground, null)
snapshots.clear()
_snapshot()
_deliver()
func _snapshot() -> void:
snapshots.append([sim.tick, SnapshotSender.own_block(sim, server), NetSnapshot.record_of(server)])
func _deliver() -> float:
var snapshot: Array = snapshots.pop_front()
return prediction.reconcile(server.id, snapshot[1], snapshot[2], snapshot[0])
func _command(tick: int) -> PlayerCommand:
var buttons: int = PlayerCommand.BUTTON_SPRINT if tick % 90 < 45 else 0
if tick % 40 == 7:
buttons |= PlayerCommand.BUTTON_JUMP
return PlayerCommand.from_input(tick, Vector2(sin(tick * 0.03), 1.0), 0.5 + sin(tick * 0.01) * 0.5, 0.0, buttons)
## One tick of both ends: the client predicts `tick`, the server runs it with the
## command unless it is `lost`, and the snapshot from DELAY ticks ago arrives.
func _tick(lost: bool = false) -> float:
var command: PlayerCommand = _command(prediction.next_tick)
prediction.predict(command)
if not lost:
assert_true(sim.submit_command(server.id, command))
sim.step()
_snapshot()
return _deliver() if snapshots.size() > DELAY else 0.0
func test_the_first_snapshot_starts_prediction_where_the_server_is() -> void:
assert_true(prediction.active)
assert_eq(prediction.next_tick, 0)
assert_eq(prediction.player.position, server.position)
assert_eq(prediction.player.id, server.id)
func test_prediction_runs_ahead_and_matches_the_server_exactly() -> void:
for _round: int in 600:
assert_eq(_tick(), 0.0)
assert_eq(prediction.player.position, server.position, "the client is where the server is, without waiting to be told")
assert_eq(prediction.player.velocity, server.velocity)
assert_eq(prediction.mispredictions, 0)
assert_true(prediction.reconciles > 500)
assert_true(server.position.distance_to(Vector3(500.0, 0.0, 500.0)) > 20.0, "and they went somewhere")
assert_eq(prediction.hidden_correction(), 0.0)
func test_swimming_and_the_water_around_the_player_are_predicted() -> void:
sim.set_sea_level(3.0)
_snapshot()
_deliver()
var swum: int = 0
for _round: int in 300:
_tick()
swum += 1 if server.swimming else 0
assert_true(swum > 150, "deep water over a flat floor: swam for %d ticks" % swum)
assert_eq(prediction.player.position, server.position)
assert_eq(prediction.player.stamina_ticks, server.stamina_ticks)
assert_true(prediction.mispredictions <= 1, "only the sea arriving unannounced: %d" % prediction.mispredictions)
func test_a_command_the_server_never_got_is_corrected_and_the_fix_is_eased_in() -> void:
for _round: int in 75:
_tick()
assert_true(server.on_ground)
var lost_at: int = prediction.next_tick
_tick(true)
# The server stood still that tick; the client walked. Nobody knows yet.
var apart: float = prediction.player.position.distance_to(server.position)
assert_true(apart > 0.1 and apart < 0.3, "one tick of running: %.3f m" % apart)
var corrected: float = 0.0
var drawn_before: Vector3 = prediction.view_position()
for _round: int in DELAY + 1:
var drawn: Vector3 = prediction.view_position()
var moved: float = _tick()
if moved > 0.0:
corrected = moved
# The frame the news arrives, the drawn position doesn't jump: it moves by
# the tick just predicted and no more.
assert_true(prediction.view_position().distance_to(drawn) < 0.3, "drawn position moved %.3f m" % prediction.view_position().distance_to(drawn))
assert_near(prediction.hidden_correction(), moved, 0.001)
assert_near(corrected, apart, 0.05, "corrected by about what the lost tick was worth")
assert_eq(prediction.mispredictions, 1)
assert_eq(prediction.player.position, server.position, "back in step, tick %d on" % lost_at)
assert_true(drawn_before != prediction.view_position())
for _frame: int in 60:
prediction.smooth(1.0 / 60.0)
assert_eq(prediction.hidden_correction(), 0.0, "the offset fades out within a second")
for _round: int in 60:
assert_eq(_tick(), 0.0)
assert_eq(prediction.mispredictions, 1)
func test_being_moved_by_the_server_far_away_is_shown_at_once() -> void:
for _round: int in 30:
_tick()
server.position += Vector3(40.0, 0.0, 0.0)
for _round: int in DELAY + 2:
_tick()
assert_eq(prediction.snaps, 1)
assert_eq(prediction.hidden_correction(), 0.0)
assert_eq(prediction.player.position, server.position)
func test_drawing_between_ticks_goes_from_the_last_tick_to_this_one() -> void:
for _round: int in 20:
_tick()
var before: Vector3 = prediction.player.position
_tick()
var after: Vector3 = prediction.player.position
assert_eq(prediction.view_position(0.0), before)
assert_eq(prediction.view_position(1.0), after)
assert_eq(prediction.view_position(0.5), before.lerp(after, 0.5))
func test_the_barge_ride_and_the_leap_are_predicted_from_the_same_route() -> void:
sim = Simulation.new(21)
sim.start_drop()
server = sim.entities.find(sim.add_player())
prediction = ClientPrediction.new()
prediction.begin(sim.ground, Drop.plan(sim.ground, SimRng.new(21), 0))
snapshots.clear()
_snapshot()
_deliver()
assert_eq(prediction.player.drop_state, Drop.ABOARD)
var leap_at: int = sim.drop.duration_ticks / 2
for round: int in leap_at + 200:
var command: PlayerCommand = PlayerCommand.from_input(prediction.next_tick, Vector2(0.3, 1.0), 1.0, 0.0, PlayerCommand.BUTTON_JUMP if round == leap_at else 0)
prediction.predict(command)
sim.submit_command(server.id, command)
sim.step()
_snapshot()
if snapshots.size() > DELAY:
_deliver()
if prediction.player.position != server.position:
fail("apart at tick %d: %s and %s" % [sim.tick, prediction.player.position, server.position])
break
assert_true(server.drop_state == Drop.FREEFALL or server.drop_state == Drop.GLIDING, "leapt and falling")
assert_eq(prediction.mispredictions, 0)
func test_being_thrown_off_at_the_end_of_the_route_is_predicted_too() -> void:
sim = Simulation.new(21)
sim.start_drop()
server = sim.entities.find(sim.add_player())
prediction = ClientPrediction.new()
prediction.begin(sim.ground, Drop.plan(sim.ground, SimRng.new(21), 0))
snapshots.clear()
_snapshot()
_deliver()
for _round: int in sim.drop.duration_ticks + 30:
var command: PlayerCommand = PlayerCommand.from_input(prediction.next_tick, Vector2.ZERO, 0.0, 0.0)
prediction.predict(command)
sim.submit_command(server.id, command)
sim.step()
_snapshot()
if snapshots.size() > DELAY:
_deliver()
assert_ne(server.drop_state, Drop.ABOARD)
assert_eq(prediction.player.position, server.position)
assert_eq(prediction.mispredictions, 0)
+1
View File
@@ -0,0 +1 @@
uid://uf5mg4h3ht66
+41 -1
View File
@@ -58,7 +58,8 @@ func test_a_snapshot_round_trips_every_archetype_and_partial_masks() -> void:
[shot.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PROJECTILE), NetSnapshot.record_of(shot)],
]
var bytes: PackedByteArray = NetSnapshot.encode_snapshot(header, PackedInt32Array([70000, 5]), records)
var expected: int = NetSnapshot.HEADER_BYTES + 1 + 4 + 1 + 4 + 2
# The header, the watched entity, phases and sea, the own-block flag, two removals, the count.
var expected: int = NetSnapshot.HEADER_BYTES + 1 + 4 + 1 + 1 + 4 + 2
for entry: Array in records:
expected += NetSnapshot.record_bytes(entry[0], entry[2][0], entry[1])
assert_eq(bytes.size(), expected, "record_bytes() predicts the encoded size")
@@ -136,3 +137,42 @@ func test_match_notice_round_trips_a_63_bit_seed() -> void:
var back: Dictionary = NetSnapshot.decode_match(NetSnapshot.encode_match(Match.DROP, 7, seed_value))
assert_eq(back, {"phase": Match.DROP, "index": 7, "seed": seed_value})
assert_true(NetSnapshot.decode_match(NetSnapshot.encode_match(99, 7, 1)).is_empty(), "an unknown phase")
func test_the_own_block_round_trips_exactly() -> void:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var player: SimEntity = _player(sim, Vector3(100.123456, 7.654321, 900.000123))
player.velocity = Vector3(-3.3333333, 0.1, 6.5)
player.stamina_ticks = 1234
player.swimming = true
player.on_ground = false
player.drop_state = Drop.GLIDING
var own: Dictionary = NetSnapshot.self_of(player, 2.71828, 0b101010101)
var record: PackedInt32Array = NetSnapshot.record_of(player)
var header: Dictionary = {"tick": 9, "sim_tick": 8, "command_tick": 11, "own_id": player.id, "self": own}
var bytes: PackedByteArray = NetSnapshot.encode_snapshot(header, PackedInt32Array(), [[player.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PLAYER), record]])
var plain: PackedByteArray = NetSnapshot.encode_snapshot({"tick": 9, "sim_tick": 8, "own_id": player.id}, PackedInt32Array(), [[player.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PLAYER), record]])
assert_eq(bytes.size() - plain.size(), NetSnapshot.SELF_BYTES)
var back: Dictionary = NetSnapshot.decode_snapshot(bytes)
assert_eq(back["command_tick"], 11)
assert_eq(NetSnapshot.decode_snapshot(plain)["command_tick"], -1, "no command received yet")
assert_true((NetSnapshot.decode_snapshot(plain)["self"] as Dictionary).is_empty())
# Not near: the same, to the bit, which is what lets a prediction match the server.
var copy: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER)
NetSnapshot.apply_self(copy, back["self"])
assert_eq(copy.position, player.position)
assert_eq(copy.velocity, player.velocity)
assert_eq(copy.stamina_ticks, 1234)
assert_true(copy.swimming and not copy.on_ground)
assert_eq(copy.drop_state, Drop.GLIDING)
assert_eq(back["self"]["water"], own["water"])
assert_eq(back["self"]["water_mask"], 0b101010101)
for length: int in bytes.size():
assert_true(NetSnapshot.decode_snapshot(bytes.slice(0, length)).is_empty(), "cut to %d bytes" % length)
# A position that isn't a number is refused rather than handed to the movement code.
var poisoned: PackedByteArray = bytes.duplicate()
var at: int = NetSnapshot.HEADER_BYTES + NetSnapshot.varint_bytes(player.id) + 5
poisoned.encode_float(at, NAN)
assert_true(NetSnapshot.decode_snapshot(poisoned).is_empty(), "a NaN position")
poisoned.encode_float(at, INF)
assert_true(NetSnapshot.decode_snapshot(poisoned).is_empty(), "an infinite position")
+318
View File
@@ -0,0 +1,318 @@
extends TestCase
## Issue N3's numbers: two people play the start of a real match on a real island,
## each through a link with 100 ms of latency each way, 20 ms of jitter and 2% loss.
## They ride the barge, leap, glide down and then walk, sprint, strafe, jump and crouch
## about the middle of the island. Measures how far the server ever had to correct
## each one's own predicted movement, and how evenly each is drawn on the other's
## screen, against where the server really had them.
const TICK_MS: float = 1000.0 / Tuning.TICK_RATE_HZ
const FRAME_MS: float = 1000.0 / 60.0
## Play measured once both are on the ground, in ticks.
const GROUND_TICKS: int = 75 * Tuning.TICK_RATE_HZ
const LIMIT_TICKS: int = 200 * Tuning.TICK_RATE_HZ
var loop: ServerLoop
var game: NetGame
var clients: Array[ClientGame] = []
var leap_tick: int = 0
## Per client: the tick it first stood (or swam) after the drop, or -1.
var landed: Array[int] = []
func _input(tick: int, index: int) -> PlayerCommand:
var me: SimEntity = clients[index].prediction.player
var centre: Vector3 = Vector3(Tuning.WORLD_SIZE_METRES * 0.5, 0.0, Tuning.WORLD_SIZE_METRES * 0.5)
var move: Vector2 = Vector2.ZERO
var buttons: int = 0
var goal: Vector3 = centre
var wander: float = 0.0
if me.drop_state == Drop.ABOARD:
if tick >= leap_tick:
buttons |= PlayerCommand.BUTTON_JUMP
elif me.drop_state != Drop.NONE:
move = Vector2(0.0, 1.0)
else:
if landed[index] < 0:
landed[index] = tick
var since: int = tick - landed[index] + index * 7 * Tuning.TICK_RATE_HZ
var seconds: float = fmod(float(since) / Tuning.TICK_RATE_HZ, 24.0)
var lap: float = floorf(float(since) / Tuning.TICK_RATE_HZ / 24.0)
var angle: float = lap * 1.3 + index * PI
goal = centre + Vector3(cos(angle), 0.0, sin(angle)) * 40.0
wander = sin(float(since) * 0.05) * 0.8
if seconds < 4.0:
move = Vector2(0.0, 1.0)
elif seconds < 9.0:
move = Vector2(0.0, 1.0)
buttons |= PlayerCommand.BUTTON_SPRINT
elif seconds < 11.0:
move = Vector2(1.0, 0.3)
elif seconds < 12.0:
pass
elif seconds < 16.0:
move = Vector2(0.0, 1.0)
buttons |= PlayerCommand.BUTTON_SPRINT
if since % 45 < 2:
buttons |= PlayerCommand.BUTTON_JUMP
elif seconds < 19.0:
move = Vector2(0.2, 1.0)
buttons |= PlayerCommand.BUTTON_CROUCH
elif seconds < 22.0:
move = Vector2(-0.7, -0.7)
else:
move = Vector2(0.0, 1.0)
buttons |= PlayerCommand.BUTTON_SPRINT
var yaw: float = atan2(goal.x - me.position.x, goal.z - me.position.z) + wander
return PlayerCommand.from_input(tick, move, yaw, sin(float(tick) * 0.02) * 0.4, buttons)
## What a link with no jitter and no loss would draw at that moment: a straight line
## between the two snapshots around it, which are of every second tick, with positions
## as coarse as the wire makes them.
func _ideal(history: Array, time: float) -> Vector3:
var step: int = Tuning.NET_SNAPSHOT_INTERVAL_TICKS
var from: int = clampi(floori(time / step) * step, 0, history.size() - 1 - step)
var steps: float = NetSnapshot.POSITION_STEPS_PER_METRE
var a: Vector3 = (history[from] as Vector3 * steps).round() / steps
var b: Vector3 = (history[from + step] as Vector3 * steps).round() / steps
return a.lerp(b, clampf((time - from) / step, 0.0, 1.0))
## Where the server had an entity at a moment between ticks.
func _truth(history: Array, time: float) -> Vector3:
var index: int = clampi(floori(time), 0, history.size() - 2)
return (history[index] as Vector3).lerp(history[index + 1], clampf(time - index, 0.0, 1.0))
## Plays the match through links with `latency_ms` each way, plus or minus
## `jitter_ms`, losing `loss` of all packets. Returns what each client measured once
## both were on the ground, or nothing if they never got there.
func _play(latency_ms: float, jitter_ms: float, loss: float) -> Array[Dictionary]:
var results: Array[Dictionary] = []
loop = ServerLoop.new(7, 2, 0)
game = NetGame.new(loop, NetServer.new())
var flow: Match = loop.match_flow
assert_eq(flow.phase, Match.DROP)
var sim: Simulation = loop.sim
# Leap once the barge is over land.
leap_tick = sim.drop.duration_ticks / 2
for tick: int in range(30, sim.drop.duration_ticks):
var under: Vector3 = sim.drop.barge_position(tick)
if sim.ground.terrain_height(under.x, under.z) > Tuning.ISLAND_BEACH_TOP + 2.0:
leap_tick = tick
break
# Both clients generate the island once between them: it's the same island.
var mirror: Simulation = Simulation.new(flow.current_seed())
clients.clear()
landed.clear()
var down: Array[LinkSim] = []
var up: Array[LinkSim] = []
var entity: Array[int] = []
# Per entity: where the server had it before each simulation tick.
var history: Dictionary = {}
# Per client, in ground play: metres the server moved its player, and ticks it
# spent in the air, crouched and standing still.
var travelled: Array[float] = [0.0, 0.0]
var airborne: Array[int] = [0, 0]
var crouched: Array[int] = [0, 0]
for index: int in 2:
var handle: int = index + 1
game.adopt(handle)
var client: ClientGame = ClientGame.new()
client.make_world = func(_seed: int) -> Simulation: return mirror
client.sample_input = _input.bind(index)
client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice())
clients.append(client)
landed.append(-1)
down.append(LinkSim.new(latency_ms, jitter_ms, loss, 100 + index))
up.append(LinkSim.new(latency_ms, jitter_ms, loss, 200 + index))
entity.append(int(flow.entity_of[handle]))
history[entity[index]] = [sim.entities.find(entity[index]).position]
var planned: Drop = Drop.plan(mirror.ground, SimRng.new(flow.current_seed()), 0)
assert_eq(planned.start, sim.drop.start, "the client plans the server's barge route")
assert_eq(planned.finish, sim.drop.finish)
assert_eq(planned.duration_ticks, sim.drop.duration_ticks)
var next_tick_ms: float = 0.0
var next_frame_ms: Array[float] = [3.0, 11.0]
var ground_from: int = -1
# Own movement: every correction, as [metres, during ground play].
var corrections: Array = [[], []]
var own_step_max: Array[float] = [0.0, 0.0]
var own_hidden_max: Array[float] = [0.0, 0.0]
var own_last: Array = [null, null]
# The other player as drawn: [error sum, error max, frames, sum and max of how far
# off a perfect link's drawing, sum and max of how far each frame's step was off a
# perfect link's, stalls, slowest and fastest the drawing clock ran in a frame].
var seen: Array = [[0.0, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0, INF, 0.0], [0.0, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0, INF, 0.0]]
var shown_last: Array = [null, null]
var time_last: Array[float] = [0.0, 0.0]
var now: float = 0.0
while sim.tick < LIMIT_TICKS and (ground_from < 0 or sim.tick < ground_from + GROUND_TICKS):
if flow.phase == Match.RESULTS:
fail("the match ended at tick %d" % sim.tick)
break
if now >= next_tick_ms:
next_tick_ms += TICK_MS
for index: int in 2:
for bytes: PackedByteArray in up[index].receive(now):
game.take_input(index + 1, bytes)
loop.run_tick()
game.after_tick()
for index: int in 2:
var player: SimEntity = sim.entities.find(entity[index])
var track: Array = history[entity[index]]
if ground_from >= 0 and sim.tick >= ground_from:
travelled[index] += player.position.distance_to(track[track.size() - 1])
airborne[index] += 0 if player.on_ground or player.swimming else 1
crouched[index] += 1 if player.crouching else 0
track.append(player.position)
if game.snapshot_due():
for index: int in 2:
down[index].send(game.snapshot_for(index + 1), now)
if ground_from < 0 and landed[0] >= 0 and landed[1] >= 0:
ground_from = sim.tick + 2 * Tuning.TICK_RATE_HZ
for index: int in 2:
if now < next_frame_ms[index]:
continue
next_frame_ms[index] += FRAME_MS
var client: ClientGame = clients[index]
var measuring: bool = ground_from >= 0 and sim.tick >= ground_from
for bytes: PackedByteArray in down[index].receive(now):
client.receive(NetProtocol.CHANNEL_STATE, bytes)
if client.prediction.last_correction > 0.0:
(corrections[index] as Array).append([client.prediction.last_correction, measuring])
client.prediction.last_correction = 0.0
client.advance(FRAME_MS / 1000.0)
for bytes: PackedByteArray in client.outbox:
up[index].send(bytes, now)
client.outbox.clear()
if not measuring:
own_last[index] = null
shown_last[index] = null
continue
# This client's own player, as drawn.
var own: Vector3 = client.own_position()
if own_last[index] != null:
own_step_max[index] = maxf(own_step_max[index], own.distance_to(own_last[index]))
own_last[index] = own
own_hidden_max[index] = maxf(own_hidden_max[index], client.prediction.hidden_correction())
# The other player, as drawn here, against where the server had them then.
var other: int = entity[1 - index]
var shown: Dictionary = client.remote.sample(other)
if shown.is_empty():
fail("client %d can't see the other player at tick %d" % [index, sim.tick])
continue
var stats: Array = seen[index]
var track: Array = history[other]
var truth: Vector3 = _truth(track, client.remote.time)
var error: float = (shown["position"] as Vector3).distance_to(truth)
stats[0] += error
stats[1] = maxf(stats[1], error)
stats[2] += 1
var ideal: Vector3 = _ideal(track, client.remote.time)
var off: float = (shown["position"] as Vector3).distance_to(ideal)
stats[3] += off
stats[4] = maxf(stats[4], off)
if shown_last[index] != null:
var step: float = (shown["position"] as Vector3).distance_to(shown_last[index])
var ideal_step: float = ideal.distance_to(_ideal(track, time_last[index]))
var roughness: float = absf(step - ideal_step)
stats[5] += roughness
stats[6] = maxf(stats[6], roughness)
if ideal_step > 0.04 and step < ideal_step * 0.25:
stats[7] += 1
var ran: float = client.remote.time - time_last[index]
stats[8] = minf(stats[8], ran)
stats[9] = maxf(stats[9], ran)
shown_last[index] = shown["position"]
time_last[index] = client.remote.time
now += 1.0
assert_true(ground_from >= 0, "both players landed (leapt at tick %d, landed %s)" % [leap_tick, landed])
if ground_from < 0:
return results
print(" link: %.0f ms each way, +-%.0f ms jitter, %.0f%% loss; %d ticks, leapt at %d, ground play from %d" % [latency_ms, jitter_ms, loss * 100.0, sim.tick, leap_tick, ground_from])
for index: int in 2:
var client: ClientGame = clients[index]
var prediction: ClientPrediction = client.prediction
var worst: float = 0.0
var worst_ground: float = 0.0
var count_ground: int = 0
for entry: Array in corrections[index]:
worst = maxf(worst, entry[0])
if entry[1]:
worst_ground = maxf(worst_ground, entry[0])
count_ground += 1
var stats: Array = seen[index]
print(" client %d's player on the server, in ground play: moved %.0f m, %d ticks in the air, %d crouched" % [index, travelled[index], airborne[index], crouched[index]])
print(" client %d own player: %d snapshots compared, %d corrected (%d in ground play), largest %.3f m (%.3f m in ground play), largest hidden offset %.3f m, largest drawn step %.3f m; clock jumps %d, margin %.2f ticks; packets lost %d of %d down, %d of %d up" % [
index, prediction.reconciles, (corrections[index] as Array).size(), count_ground, worst, worst_ground,
own_hidden_max[index], own_step_max[index], client.clock.jumps, client.clock.margin,
down[index].lost, down[index].sent, up[index].lost, up[index].sent,
])
var frames: int = maxi(stats[2], 1)
print(" client %d sees the other: %d frames; against the server, off by mean %.3f m, max %.3f m; against a perfect link, off by mean %.4f m, max %.3f m, and each frame's step off by mean %.4f m, max %.3f m; %d stalls; drawing clock ran %.3f to %.3f ticks a frame; %d frames extrapolated, %d held" % [
index, stats[2], stats[0] / frames, stats[1], stats[3] / frames, stats[4], stats[5] / frames, stats[6], stats[7], stats[8], stats[9],
client.remote.extrapolated, client.remote.held,
])
results.append({
"travelled": travelled[index], "airborne": airborne[index], "crouched": crouched[index],
"reconciles": prediction.reconciles, "corrections": (corrections[index] as Array).size(),
"corrections_ground": count_ground, "worst": worst, "worst_ground": worst_ground,
"hidden": own_hidden_max[index], "snaps": prediction.snaps, "own_step": own_step_max[index],
"jumps": client.clock.jumps, "frames": stats[2], "error_mean": stats[0] / frames, "error_max": stats[1],
"off_mean": stats[3] / frames, "off_max": stats[4], "step_off_mean": stats[5] / frames,
"step_off_max": stats[6], "stalls": stats[7], "clock_slowest": stats[8], "clock_fastest": stats[9],
"held": client.remote.held,
})
return results
func test_100_ms_20_ms_jitter_and_2_percent_loss() -> void:
var results: Array[Dictionary] = _play(100.0, 20.0, 0.02)
assert_eq(results.size(), 2)
for index: int in results.size():
var result: Dictionary = results[index]
var who: String = "client %d" % index
# The play measured was real: the server moved each player about, by their commands.
assert_true(result["travelled"] > 150.0, "%s moved %.0f m" % [who, result["travelled"]])
assert_true(result["airborne"] > 30, "%s jumped" % who)
assert_true(result["crouched"] > 30, "%s crouched" % who)
assert_true(result["reconciles"] > 1000, "%s compared %d snapshots" % [who, result["reconciles"]])
# Own movement: nothing the player could see was ever corrected on the ground,
# and nothing at all had to be shown at once.
assert_true(result["worst_ground"] <= 0.02, "%s's largest correction on the ground was %.3f m" % [who, result["worst_ground"]])
assert_true(result["hidden"] <= 0.02, "%s's drawn position was off by up to %.3f m" % [who, result["hidden"]])
assert_true(result["worst"] <= 0.5, "%s's largest correction in the drop was %.3f m" % [who, result["worst"]])
assert_eq(result["snaps"], 0, "%s: corrections shown at once" % who)
# Sprinting covers 0.11 m a frame, and a jump or a step up adds height.
assert_true(result["own_step"] <= 0.3, "%s's own player moved %.3f m in one frame" % [who, result["own_step"]])
assert_true(result["jumps"] <= 2, "%s's clock jumped %d times" % [who, result["jumps"]])
# The other player: drawn where a perfect link would draw them, evenly.
assert_true(result["frames"] > 4000)
assert_true(result["error_mean"] <= 0.03, "%s drew the other %.3f m off the server on average" % [who, result["error_mean"]])
assert_true(result["off_mean"] <= 0.003, "%s drew the other %.4f m off a perfect link on average" % [who, result["off_mean"]])
assert_true(result["off_max"] <= 0.3, "%s drew the other up to %.3f m off a perfect link" % [who, result["off_max"]])
assert_true(result["step_off_max"] <= 0.15, "%s: a frame's step was %.3f m off" % [who, result["step_off_max"]])
assert_true(result["stalls"] <= 3, "%s: %d stalls" % [who, result["stalls"]])
assert_true(result["clock_slowest"] >= 0.45 and result["clock_fastest"] <= 0.55, "%s's drawing clock ran %.3f to %.3f ticks a frame" % [who, result["clock_slowest"], result["clock_fastest"]])
assert_eq(result["held"], 0, "%s: frames with the other player held still" % who)
## Three times the latency, twice the jitter and five times the loss. Corrections
## happen here, and must stay small enough to blend away.
func test_a_much_worse_link_still_plays() -> void:
var results: Array[Dictionary] = _play(150.0, 40.0, 0.10)
assert_eq(results.size(), 2)
for index: int in results.size():
var result: Dictionary = results[index]
var who: String = "client %d" % index
assert_true(result["travelled"] > 150.0, "%s moved %.0f m" % [who, result["travelled"]])
assert_true(result["worst_ground"] <= 1.0, "%s's largest correction on the ground was %.3f m" % [who, result["worst_ground"]])
assert_eq(result["snaps"], 0, "%s: corrections shown at once" % who)
assert_true(result["own_step"] <= 0.4, "%s's own player moved %.3f m in one frame" % [who, result["own_step"]])
assert_true(result["jumps"] <= 3, "%s's clock jumped %d times" % [who, result["jumps"]])
assert_true(result["error_mean"] <= 0.1, "%s drew the other %.3f m off the server on average" % [who, result["error_mean"]])
+1
View File
@@ -0,0 +1 @@
uid://bskai44qu4ths
+4 -3
View File
@@ -34,7 +34,8 @@ func test_24_players_stay_under_40_kb_a_second_and_inside_their_interest() -> vo
var biggest: int = 0
var send_usec: int = 0
var rounds: int = 0
# Per client, the bytes of the busiest second (20 snapshots in a row).
# Per client, the bytes of the busiest second: that many snapshots in a row.
var per_second: int = Tuning.TICK_RATE_HZ / Tuning.NET_SNAPSHOT_INTERVAL_TICKS
var window: Dictionary = {}
var worst_second: int = 0
while loop.ticks < TICKS and flow.phase != Match.RESULTS:
@@ -45,7 +46,7 @@ func test_24_players_stay_under_40_kb_a_second_and_inside_their_interest() -> vo
var started: int = Time.get_ticks_usec()
var built: Dictionary = {}
for handle: int in handles:
built[handle] = sender.build(handle, loop.sim, game.viewer_of(handle), loop.ticks, flow.phase)
built[handle] = game.snapshot_for(handle)
send_usec += Time.get_ticks_usec() - started
for handle: int in handles:
var bytes: PackedByteArray = built[handle]
@@ -54,7 +55,7 @@ func test_24_players_stay_under_40_kb_a_second_and_inside_their_interest() -> vo
biggest = maxi(biggest, bytes.size())
var recent: Array = window.get_or_add(handle, [])
recent.append(bytes.size() + PACKET_OVERHEAD_BYTES)
if recent.size() > 20:
if recent.size() > per_second:
recent.pop_front()
var second: int = 0
for size: int in recent:
+131
View File
@@ -0,0 +1,131 @@
extends TestCase
## Issue N3: drawing other entities between snapshots, a little in the past.
const DELAY: float = Tuning.NET_INTERP_DELAY_TICKS
const STEP: int = Tuning.NET_SNAPSHOT_INTERVAL_TICKS
const DT: float = 1.0 / Tuning.TICK_RATE_HZ
var sim: Simulation
var walker: SimEntity
var remote: SnapshotInterpolator
func before_each() -> void:
sim = Simulation.new(4, SimGround.flat())
walker = sim.entities.find(sim.add_player())
walker.position = Vector3(100.0, 0.0, 100.0)
remote = SnapshotInterpolator.new()
func _push(tick: int) -> void:
remote.push(tick, {walker.id: NetSnapshot.record_of(walker)})
func test_an_entity_is_drawn_between_the_snapshots_around_the_moment() -> void:
assert_true(remote.sample(walker.id).is_empty(), "nothing known yet")
_push(10)
assert_near(remote.time, 10.0 - DELAY, 0.0001, "the clock starts a delay behind")
assert_eq(remote.sample(walker.id)["position"], Vector3(100.0, 0.0, 100.0), "before the first sample: the first sample")
walker.position.x = 104.0
walker.yaw = 16384
_push(10 + STEP)
remote.time = 10.0 + STEP * 0.25
var shown: Dictionary = remote.sample(walker.id)
assert_near(shown["position"].x, 101.0, 0.001)
assert_near(shown["yaw"], PI * 0.125, 0.001)
remote.time = 10.0 + STEP
assert_near(remote.sample(walker.id)["position"].x, 104.0, 0.001)
assert_eq(remote.extrapolated, 0)
func test_yaw_turns_the_short_way_round() -> void:
walker.yaw = 65536 - 1820
_push(10)
walker.yaw = 1820
_push(10 + STEP)
remote.time = 10.0 + STEP * 0.5
var yaw: float = wrapf(remote.sample(walker.id)["yaw"], -PI, PI)
assert_near(yaw, 0.0, 0.01, "through north, not all the way round")
func test_past_the_newest_snapshot_it_carries_on_briefly_then_waits() -> void:
_push(10)
walker.position.x = 102.0
_push(10 + STEP)
var per_tick: float = 2.0 / STEP
remote.time = 10.0 + STEP + 2.0
assert_near(remote.sample(walker.id)["position"].x, 102.0 + per_tick * 2.0, 0.001)
assert_eq(remote.extrapolated, 1)
assert_eq(remote.held, 0)
remote.time = 10.0 + STEP + 50.0
assert_near(remote.sample(walker.id)["position"].x, 102.0 + per_tick * Tuning.NET_INTERP_EXTRAPOLATE_TICKS, 0.001)
assert_eq(remote.held, 1)
func test_a_wrong_guess_is_blended_away_not_shown_at_once() -> void:
_push(10)
walker.position.x = 102.0
_push(10 + STEP)
# The next snapshot is lost and the walker stops dead. Two ticks past the newest
# snapshot the guess has it still walking.
remote.time = 10.0 + STEP + 2.0
var guessed: float = remote.sample(walker.id)["position"].x
assert_true(guessed > 102.5)
_push(10 + STEP * 3)
var after: float = remote.sample(walker.id)["position"].x
assert_near(after, guessed, 0.001, "no jump on the frame the news arrives")
var last: float = after
for _frame: int in 90:
remote.advance(1.0 / 60.0)
remote.time = 10.0 + STEP + 2.0
var now: float = remote.sample(walker.id)["position"].x
assert_true(now <= last and last - now <= (last - 102.0) * 0.2 + 0.001, "eased from %.3f to %.3f" % [last, now])
last = now
assert_near(last, 102.0, 0.01, "and ends where the server had it")
func test_something_put_somewhere_new_is_drawn_there_at_once() -> void:
_push(10)
walker.position = Vector3(400.0, 0.0, 400.0)
_push(10 + STEP)
remote.time = 10.0 + STEP * 0.5
assert_eq(remote.sample(walker.id)["position"], Vector3(400.0, 0.0, 400.0))
func test_entities_that_leave_the_picture_are_forgotten_and_old_news_ignored() -> void:
_push(10)
walker.position.x = 150.0
_push(8)
remote.time = 10.0
assert_eq(remote.sample(walker.id)["position"].x, 100.0, "a snapshot older than the newest changes nothing")
remote.push(12, {})
assert_false(remote.has(walker.id))
assert_true(remote.sample(walker.id).is_empty())
func test_the_clock_runs_evenly_through_jittery_arrivals() -> void:
# Snapshots every STEP ticks, each arriving up to 40 ms early or late, drawn at 60 Hz.
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
rng.seed = 12
var arrivals: Array[float] = []
for index: int in 300:
arrivals.append(index * STEP * DT + rng.randf_range(-0.04, 0.04))
var next: int = 0
var slowest: float = INF
var fastest: float = 0.0
var worst_lag: float = 0.0
for frame: int in 1100:
var now: float = frame / 60.0
while next < arrivals.size() and arrivals[next] <= now:
walker.position.x = 100.0 + next
_push(next * STEP)
next += 1
var before: float = remote.time
remote.advance(1.0 / 60.0)
if frame > 120 and next < arrivals.size():
slowest = minf(slowest, remote.time - before)
fastest = maxf(fastest, remote.time - before)
worst_lag = maxf(worst_lag, absf(now * Tuning.TICK_RATE_HZ - DELAY - remote.time))
assert_true(slowest > 0.45 and fastest < 0.55, "ran %.3f to %.3f ticks a frame" % [slowest, fastest])
assert_true(worst_lag < 2.0, "strayed %.2f ticks from where it should be" % worst_lag)
@@ -0,0 +1 @@
uid://t6hhn8osim7n
+51
View File
@@ -264,3 +264,54 @@ func test_no_viewer_means_an_empty_snapshot() -> void:
assert_eq(receiver.entities.size(), 0)
assert_eq(receiver.own_id, 0)
assert_eq(receiver.match_phase, Match.LOBBY)
func test_the_own_block_goes_only_to_a_living_player_watching_themself() -> void:
var other: SimEntity = _other(Vector3(520.0, 0.0, 500.0))
viewer.velocity = Vector3(1.5, 0.0, -2.25)
sim.sea_level = 1.5
tick += STEP
var mine: Dictionary = NetSnapshot.decode_snapshot(sender.build(HANDLE, sim, viewer.id, tick, Match.PLAY, viewer.id))
assert_eq(mine["self"]["position"], viewer.position)
assert_eq(mine["self"]["velocity"], viewer.velocity)
assert_eq(mine["self"]["water"], 1.5)
assert_eq(mine["self"]["water_mask"], NetSnapshot.WATER_EVERYWHERE, "no flood on a test ground: the sea is everywhere")
tick += STEP
var watching: Dictionary = NetSnapshot.decode_snapshot(sender.build(HANDLE, sim, other.id, tick, Match.PLAY, viewer.id))
assert_true((watching["self"] as Dictionary).is_empty(), "spectating someone else")
viewer.eliminated = true
tick += STEP
var out: Dictionary = NetSnapshot.decode_snapshot(sender.build(HANDLE, sim, viewer.id, tick, Match.PLAY, viewer.id))
assert_true((out["self"] as Dictionary).is_empty(), "eliminated")
tick += STEP
var lobby: Dictionary = NetSnapshot.decode_snapshot(sender.build(HANDLE, sim, 0, tick, Match.LOBBY, 0))
assert_true((lobby["self"] as Dictionary).is_empty(), "no player")
func test_the_own_block_says_which_cells_around_the_player_are_flooded() -> void:
# A real island: the sea reaches the shore cells and not the land beside them.
var island: Simulation = Simulation.new(11)
var flood: Flood = island.flood
var player: SimEntity = island.entities.find(island.add_player())
var found: bool = false
for cz: int in range(1, flood.side - 1):
for cx: int in range(1, flood.side - 1):
var here: bool = flood.flooded[cz * flood.side + cx] != 0
var east: bool = flood.flooded[cz * flood.side + cx + 1] != 0
if here and not east:
player.position = Vector3((cx + 0.5) * flood.cell, 0.0, (cz + 0.5) * flood.cell)
found = true
break
if found:
break
assert_true(found, "a shore cell")
var own: Dictionary = SnapshotSender.own_block(island, player)
assert_eq(own["water"], flood.sea_level)
var mask: int = own["water_mask"]
assert_true(mask & (1 << 4) != 0, "the player's own cell is flooded")
assert_true(mask & (1 << 5) == 0, "the cell to the east is dry")
for dz: int in range(-1, 2):
for dx: int in range(-1, 2):
var at: Vector3 = player.position + Vector3(dx * flood.cell, 0.0, dz * flood.cell)
var wet: bool = island.water_level_at(at) > Flood.NO_WATER
assert_eq(mask & (1 << ((dz + 1) * 3 + dx + 1)) != 0, wet, "cell %d, %d" % [dx, dz])