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
+60 -7
View File
@@ -33,8 +33,8 @@ Net ──┘ └─ UI / HUD
The simulation runs at `Tuning.TICK_RATE_HZ` (30 Hz, 33.33 ms). The server runs a fixed
accumulator and may run several ticks to catch up, with no more than 5 per frame.
Snapshots go out at 20 Hz. The client renders at any frame rate and interpolates
remote entities roughly 100 ms in the past.
Snapshots go out every second tick, 15 a second. The client renders at any frame rate,
predicts its own player and draws everyone else about 130 ms in the past.
## Player command stream
@@ -154,8 +154,9 @@ A snapshot is a binary, little-endian packet on channel 1, unreliable:
| Part | Contents |
|---|---|
| Header | Message type (u8), server tick (u32), baseline tick (u32, 0 = builds on nothing), simulation tick (u32), last command tick taken from this client (u32), the entity the client is watching (varint) |
| Header | Message type (u8), server tick (u32), baseline tick (u32, 0 = builds on nothing), simulation tick (u32), the newest command tick received from this client plus one (u32, 0 = none yet), the entity the client is watching (varint) |
| Match and tide | Match phase (u8), tide phase (u8), sea level in centimetres (s16) |
| Own block | A flag (u8), then, while the client's own player is alive and is who it watches, 37 bytes nobody else is sent: position and velocity as f32, the water level around the player as f64, which of the nine flood cells around the player that water reaches (u16), swimming stamina (u16) and state flags (u8) |
| Removed | Count (u8), then IDs (varint) |
| Entities | Count (u16), then records of ID (varint), archetype and changed-group mask (u8), then only the groups that changed |
@@ -180,15 +181,16 @@ items on the ground within `NET_INTEREST_PICKUPS_METRES` (90 m), measured on the
An entity that leaves range is removed from the client's picture and nothing more is
said about it. Outside a match there is no viewer and a snapshot is only its header.
**Budget.** A snapshot is at most `Tuning.NET_SNAPSHOT_MAX_BYTES` (1,200), so 20 a
second is at most 24 KB/s before packet headers and never fragments. When more has
**Budget.** A snapshot is at most `Tuning.NET_SNAPSHOT_MAX_BYTES` (1,200), so 15 a
second is at most 18 KB/s before packet headers and never fragments. When more has
changed than fits, the client's own player goes first, then the nearest, and each
snapshot an update has waited counts as 6 m closer, so nothing waits for ever. What
didn't fit is still owed and goes in a later snapshot.
**Input.** The client answers on channel 1 with the snapshot tick it holds and its
last few commands (`Tuning.NET_INPUT_REDUNDANCY`), oldest first. `NetGame`
(`src/server/`) offers each tick's command to `ServerLoop.submit()` once.
(`src/server/`) offers each tick's command to `ServerLoop.submit()` once, and echoes
the newest tick it has received in every snapshot, taken or not.
**Match notice.** On joining and at every change of phase the server sends, reliably
on channel 0, the match phase, index and seed, so the client can generate the island.
@@ -196,13 +198,64 @@ on channel 0, the match phase, index and seed, so the client can generate the is
Building changes will also travel on a reliable ordered event stream (N5), since a
dropped wall is a gameplay lie.
## The client: prediction, reconciliation and interpolation
`ClientGame` (`src/net/`) is a client's side of a match. It works on packets, so it
runs the same over a `NetClient` or a test's simulated link. From the seed in the
MATCH notice it generates the island itself (a `Simulation` it never steps) and plans
the same barge route, so it can run the server's movement code on the server's ground.
**The command clock.** A command must reach the server before the tick it names, so
the client's tick runs ahead of the server's by the trip there plus a margin. Nobody
measures the trip. Each snapshot says which tick the server was about to run and the
newest command tick it had received; the difference is how many commands were
waiting. `ClientClock` holds that at `Tuning.NET_COMMAND_MARGIN_TICKS` (3): it jumps
ahead if commands arrive late two snapshots running, waits if they are far too early,
and otherwise runs up to 2% fast or slow. With three commands waiting and each packet
repeating the last three, jitter and a lost packet or two cost nothing.
**Prediction.** `ClientPrediction` keeps a copy of the client's own player and runs
every command on it as it is made, through `Movement.step`, `Water.update` and
`Drop.ride`, the same code the server runs. The player moves at once, not a round trip
later.
**Reconciliation.** The own block in each snapshot is the player's exact state before
the snapshot's simulation tick: 32-bit floats, as the server holds them, not the
quantized record. If that equals what was predicted before that tick, nothing happens,
which is the normal case. If not, the copy is put where the server says, every command
since is run again, and the distance the player's present position moved is the
correction. A correction is never shown at once: the drawn position keeps an offset
that fades at `NET_CORRECTION_SMOOTH_RATE`, unless it is over 3 m, which is shown as
the teleport it is. What the client can't predict yet: built pieces and broken props
(not replicated until N5), a basin still filling after a breach, and anything another
player does to it.
**Interpolation.** `SnapshotInterpolator` draws every other entity
`Tuning.NET_INTERP_DELAY_TICKS` (4 ticks, two snapshots) in the past, on a straight
line between the snapshots either side of that moment, with yaw turning the short way.
The moment drawn is a clock of its own, steered gently towards where arrivals say it
should be, so jitter in the network never becomes jitter on screen. When a snapshot is
lost the entity carries on along its last heading for up to 3 ticks; if that guess was
wrong, the difference is blended away when the news arrives.
**Measured** (`test/net/test_prediction_link.gd`, simulated link, headless): two
players through the drop and 75 s of walking, sprinting, strafing, jumping and
crouching on a real island, each with 100 ms of latency each way, 20 ms of jitter and
2% loss. Own movement: about 1,400 snapshots compared per client and none needed a
correction. The other player was drawn on average 0.4 mm from where a perfect link
would draw them, and 9 mm from where the server had them at that moment; a lost
snapshot during a sudden stop or start showed as at most 13 cm of drift, eased out. At
150 ms, 40 ms and 10% loss a client took 3 to 7 corrections of at most 22 cm, all
blended. These are measurements of the netcode's arithmetic, not of how it feels in
the hand, which needs a real playtest.
## Module map
| Path | Holds | May depend on |
|---|---|---|
| `src/sim/` | Tick loop, entities, RNG, commands, tide, combat, building | `src/sim/` only |
| `src/bots/` | Bot brains that produce `PlayerCommand`s | `src/sim/` |
| `src/net/` | Transport, snapshot encoding, prediction, lag compensation | `src/sim/` |
| `src/net/` | Transport, snapshot encoding, the client's side of a match (prediction, interpolation), lag compensation | `src/sim/` |
| `src/server/` | Headless and listening servers, joining the network to the match | `src/sim/`, `src/bots/`, `src/net/` |
| `src/client/` | World rendering, camera, input, effects | `src/sim/`, `src/net/` |
| `src/ui/` | HUD, menus, map | `src/sim/` (read only), `src/client/` |
+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.
+92 -23
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,6 +126,23 @@ 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)
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]
record[R_HELD] = clampi(held + 1, 0, 255)
SimEntity.ARCHETYPE_PICKUP:
record[R_ITEM] = clampi(entity.item + 1, 0, 255)
record[R_COUNT] = clampi(entity.item_count, 0, 65535)
record[R_TIER] = clampi(entity.item_tier, 0, 255)
SimEntity.ARCHETYPE_PROJECTILE:
record[R_ITEM] = clampi(entity.item + 1, 0, 255)
record[R_OWNER] = entity.owner_id & 0xFFFFFFFF
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
@@ -130,19 +156,30 @@ static func record_of(entity: SimEntity) -> PackedInt32Array:
flags |= FLAG_RELOADING
if entity.use_ticks > 0:
flags |= FLAG_USING
record[R_FLAGS] = flags
var held: int = -1
if entity.selected >= 1 and entity.selected <= entity.slot_items.size():
held = entity.slot_items[entity.selected - 1]
record[R_HELD] = clampi(held + 1, 0, 255)
SimEntity.ARCHETYPE_PICKUP:
record[R_ITEM] = clampi(entity.item + 1, 0, 255)
record[R_COUNT] = clampi(entity.item_count, 0, 65535)
record[R_TIER] = clampi(entity.item_tier, 0, 255)
SimEntity.ARCHETYPE_PROJECTILE:
record[R_ITEM] = clampi(entity.item + 1, 0, 255)
record[R_OWNER] = entity.owner_id & 0xFFFFFFFF
return record
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.
@@ -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))
+47 -20
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"]
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):
continue
var input: Dictionary = NetSnapshot.decode_input(packet["bytes"])
return
var input: Dictionary = NetSnapshot.decode_input(bytes)
if input.is_empty():
bad_inputs += 1
continue
return
sender.acknowledge(handle, int(input["ack"]))
if not loop.match_flow.in_match():
continue
return
# Packets repeat recent commands; each tick's command is offered once, whether
# or not the simulation takes it.
# 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
_last_command[handle] = command.tick
if loop.submit(handle, command):
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
+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])
+142
View File
@@ -0,0 +1,142 @@
extends TestCase
## Issue N3: ClientGame against a real server. Over loopback UDP with a NetClient, and
## by hand, packet by packet.
const HOST: String = "127.0.0.1"
const DT: float = 1.0 / Tuning.TICK_RATE_HZ
var loop: ServerLoop
var net: NetServer
var game: NetGame
func _rules() -> MatchRules:
var rules: MatchRules = MatchRules.new()
rules.max_players = 3
rules.min_players = 1
rules.lobby_ticks = 6
rules.countdown_ticks = 6
rules.results_ticks = 6
return rules
func before_each() -> void:
loop = ServerLoop.new(31, 0, 2, _rules())
net = NetServer.new()
game = NetGame.new(loop, net)
func after_each() -> void:
net.close()
func test_a_client_joins_over_udp_generates_the_island_and_plays() -> void:
assert_eq(net.listen(0, HOST), OK)
var link: NetClient = NetClient.new()
var client: ClientGame = ClientGame.new()
client.attach(link)
client.sample_input = func(tick: int) -> PlayerCommand:
return PlayerCommand.from_input(tick, Vector2(0.0, 1.0), 2.0, 0.1)
assert_eq(link.connect_to(HOST, net.port(), "Mara"), OK)
var started: int = Time.get_ticks_msec()
var played: int = 0
# A server tick and a client frame of the same length each round, so both clocks
# agree however fast the test machine is.
while Time.get_ticks_msec() - started < 20000 and played < 150:
game.poll()
loop.run_tick()
game.after_tick()
client.poll()
client.advance(DT)
if client.playing():
played += 1
OS.delay_msec(1)
link.leave()
assert_eq(played, 150, "the client got into the match and played")
var flow: Match = loop.match_flow
assert_true(flow.in_match())
assert_eq(client.world_seed, flow.current_seed())
assert_eq(client.world.island.heightmap_hash(), loop.sim.island.heightmap_hash(), "the same island on both ends")
assert_eq(client.match_phase, flow.phase)
var mine: SimEntity = loop.sim.entities.find(flow.entity_of[link.handle])
assert_eq(client.prediction.player.id, mine.id)
assert_eq(mine.yaw, PlayerCommand.from_input(0, Vector2.ZERO, 2.0, 0.0).yaw, "the server is applying this client's commands")
assert_eq(client.prediction.player.drop_state, mine.drop_state)
assert_true(client.prediction.reconciles > 50, "%d snapshots compared" % client.prediction.reconciles)
assert_true(client.prediction.max_correction < 2.0, "largest correction %.3f m" % client.prediction.max_correction)
assert_true(client.own_position().distance_to(mine.position) < 10.0, "drawn %.1f m from where the server has it" % client.own_position().distance_to(mine.position))
# The two bots ride the same barge.
assert_eq(flow.entity_of.size(), 3)
for handle: int in flow.entity_of:
assert_true(client.remote.has(flow.entity_of[handle]), "player %d is drawn" % handle)
assert_eq(client.bad_packets, 0)
assert_eq(game.bad_inputs, 0)
func test_in_the_lobby_it_only_says_which_snapshot_it_holds() -> void:
var worlds: Array[int] = []
var client: ClientGame = ClientGame.new()
client.make_world = func(match_seed: int) -> Simulation:
worlds.append(match_seed)
return Simulation.new(match_seed, SimGround.flat())
loop.match_flow.rules.min_players = 5
assert_true(loop.match_flow.join(7))
game.adopt(7)
client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice())
assert_eq(worlds, [loop.match_flow.current_seed()], "the island is made as soon as the seed is known")
for _round: int in 4:
loop.run_tick()
game.after_tick()
if game.snapshot_due():
client.receive(NetProtocol.CHANNEL_STATE, game.snapshot_for(7))
client.advance(DT)
assert_false(client.playing())
assert_eq(client.match_phase, Match.LOBBY)
assert_eq(client.outbox.size(), 2, "one answer per snapshot")
var answer: Dictionary = NetSnapshot.decode_input(client.outbox[1])
assert_eq(answer["ack"], client.receiver.tick)
assert_eq((answer["commands"] as Array).size(), 0)
# Junk is counted and changes nothing.
client.receive(NetProtocol.CHANNEL_CONTROL, PackedByteArray([NetSnapshot.MSG_MATCH, 1, 2]))
client.receive(NetProtocol.CHANNEL_STATE, PackedByteArray([NetSnapshot.MSG_SNAPSHOT, 9, 9]))
assert_eq(client.bad_packets, 1)
assert_eq(client.receiver.malformed, 1)
assert_eq(worlds.size(), 1)
func test_a_new_match_starts_everything_again() -> void:
var worlds: Array[int] = []
var client: ClientGame = ClientGame.new()
client.make_world = func(match_seed: int) -> Simulation:
worlds.append(match_seed)
return Simulation.new(match_seed, SimGround.flat())
assert_true(loop.match_flow.join(7))
game.adopt(7)
client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice())
var first_seed: int = loop.match_flow.current_seed()
var sent: int = 0
for _round: int in 60:
for bytes: PackedByteArray in client.outbox:
game.take_input(7, bytes)
sent += 1
client.outbox.clear()
loop.run_tick()
game.after_tick()
for event: Dictionary in loop.match_flow.events:
if event["type"] == "phase":
client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice())
if game.snapshot_due():
client.receive(NetProtocol.CHANNEL_STATE, game.snapshot_for(7))
client.advance(DT)
assert_true(client.playing(), "phase %s" % loop.match_flow.phase_name())
assert_true(sent > 30)
assert_true(client.receiver.command_tick >= 0, "the server echoes the commands it gets")
assert_eq(worlds, [first_seed], "one world for the whole match")
# The server moves on to another match: a notice with the next index and seed.
client.receive(NetProtocol.CHANNEL_CONTROL, NetSnapshot.encode_match(Match.LOBBY, 1, first_seed + 1))
assert_false(client.playing())
assert_false(client.clock.running)
assert_false(client.remote.started)
assert_eq(worlds, [first_seed, first_seed + 1])
assert_eq(client.match_index, 1)
+1
View File
@@ -0,0 +1 @@
uid://bx6t6juefcn17