Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions docs/netcode-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,117 @@ RTT:
With the default the throttle engaged at 5% loss in this run: the server
dropped 27% of its snapshot bytes, snapshot jitter rose 2.6 times, and
throttled input packets starved the input buffer.

## After phase 3: snapshot interpolation

Network schema 25. Remote pilots and aliens are no longer lerped toward the
newest snapshot (25% of the remaining distance per tick). Each one has a
`SnapshotBuffer` of transforms keyed by server tick. Once per client physics
tick, `FlightSession.render_remote()` draws them at a render time on the
server's timeline, which `ServerClock` keeps:

- **Clock.** Each snapshot gives an offset sample: its server tick / 60 minus
its local arrival time. The clock uses the median of the last 2 s of
samples, so single late or early packets barely move it. The render time
trails that estimate by `ServerClock.INTERPOLATION_DELAY` (100 ms, two
snapshot intervals; a playtesting setting). It advances by each physics
tick, time-scaled by at most ±5% to close a low-pass-filtered error, and
snaps only past 250 ms (connecting, or a stall). The largest sample (the
fastest path) was tried first. Frame and tick timing outliers set it, and it
left typical packets about 30 ms less buffer (4.8% against 1.2% of entity
ticks extrapolated at 150 ± 30 ms).
- **Interpolation.** Positions follow a cubic Hermite curve between the two
bracketing samples, with tangents taken across neighbouring samples. Angles
take the shortest path. Linear interpolation changed the drawn velocity at
every snapshot, which showed as acceleration spikes on about 10% of ticks.
- **Dry buffers.** Past the newest sample, the entity extrapolates its last
motion for at most `SnapshotBuffer.MAX_EXTRAPOLATION_TICKS` (250 ms), then
holds. Out-of-order packets of the same life still fill gaps; stale and
duplicate ticks are ignored.
- **Discontinuities** clear the buffer and snap to the new state: spawn and
launch (a new buffer), despawn and dock, a new life or alive state
(respawn, death, jump), map changes and visits, alien encounter resets and
the end of a return home, and session start or end. The per-entity
sequence, visit and life checks are unchanged.
- **Immediate state.** Health, shields, alive, docked and energy apply on
arrival. Death and respawn are not delayed to the render time: the server
has already decided them, and targeting and the HUD must not show a
destroyed ship as attackable. A ship can therefore vanish up to the delay
plus jitter early, about 3 m at cruise speed. Its explosion is drawn at the
authoritative position, well within its diameter.
- **Effects.** Laser and explosion points within 8 m of an entity's newest
received position move by that entity's drawn offset
(`FlightSession.drawn_point`). Beams join the drawn ships: remote ships in
the past, the local ship ahead of the server.

Tradeoff: remote ships are drawn about 100 ms plus the one-way latency in the
past. The server still decides hits on its current positions with no lag
compensation, so a pilot aims at a target that is further along than it is
drawn. Lag compensation, rewinding targets to the shooter's render time, is
out of scope and a possible later step.

The F8 overlay adds one line: interpolation delay, buffer depth (how far the
newest snapshot is ahead of the render time, min / mean over 2 s), the share
of remote entity ticks extrapolated, and underruns ("dry"). The jitter line
now also shows clock drift.

### Remote smoothness, before and after

The benchmark now has the measured client, routed through the relay, watch
the first extra pilot, which flies the same pattern and turns. Once per
physics tick it compares the drawn ship with the server's path (definitions in
`tests/netcode_benchmark.gd`). *Before* is the phase 2 build
(`feat/netcode-ticks`, 8a63bb0) running the same benchmark file. The earlier
metrics keep their definitions.

These runs shared the desktop with an unrelated heavy workload. The benchmark
process ran at 13–38 frames per second with three extra clients, not the
92–118 of phase 2. ENet is serviced once per frame, so snapshots arrived in
bursts. That inflates underruns and the main table's RTT column, which is why
the earlier tables are not repeated here. Both builds ran under the same load.
The last pair used one extra client, at 52 and 78 fps.

| Added RTT | Loss | Build | Path error mean / p95 / max | Lag behind server | Drawn accel p95 / max | Spikes | Render-time error mean / p95 / max | Extrapolated | Buffer depth min / mean |
| ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 0 ms | 0% | before | 0.03 / 0.10 / 0.33 m | 113 ms | 1994 / 6707 m/s² | 86.1% | - | - | - |
| 0 ms | 0% | after | 0.00 / 0.01 / 0.18 m | 104 ms | 83 / 1136 m/s² | 1.8% | 0.00 / 0.01 / 0.21 m | 3.2% | -62 / 57 ms |
| 100 ms | 0% | before | 0.03 / 0.09 / 1.23 m | 158 ms | 1592 / 4618 m/s² | 86.5% | - | - | - |
| 100 ms | 0% | after | 0.00 / 0.01 / 0.66 m | 164 ms | 111 / 1015 m/s² | 2.6% | 0.00 / 0.01 / 0.19 m | 4.9% | -57 / 54 ms |
| 200 ms | 0% | before | 0.03 / 0.09 / 1.46 m | 211 ms | 1568 / 4514 m/s² | 85.9% | - | - | - |
| 200 ms | 0% | after | 0.01 / 0.01 / 1.14 m | 235 ms | 99 / 889 m/s² | 2.6% | 0.00 / 0.01 / 0.19 m | 6.9% | -72 / 56 ms |
| 0 ms | 5% | before | 0.03 / 0.10 / 0.50 m | 124 ms | 1990 / 4843 m/s² | 85.6% | - | - | - |
| 0 ms | 5% | after | 0.00 / 0.01 / 0.70 m | 120 ms | 115 / 882 m/s² | 3.4% | 0.01 / 0.03 / 0.15 m | 5.7% | -65 / 59 ms |
| 100 ms | 5% | before | 0.03 / 0.09 / 0.46 m | 165 ms | 1800 / 4868 m/s² | 84.8% | - | - | - |
| 100 ms | 5% | after | 0.00 / 0.01 / 0.41 m | 163 ms | 111 / 2328 m/s² | 3.0% | 0.01 / 0.03 / 0.52 m | 6.4% | -123 / 55 ms |
| 200 ms | 5% | before | 0.03 / 0.10 / 0.92 m | 213 ms | 1649 / 6602 m/s² | 85.0% | - | - | - |
| 200 ms | 5% | after | 0.01 / 0.01 / 1.14 m | 235 ms | 131 / 927 m/s² | 3.6% | 0.01 / 0.03 / 0.18 m | 6.4% | -73 / 54 ms |
| 150 ± 30 ms | 5% | before | 0.04 / 0.12 / 2.44 m | 215 ms | 2999 / 11859 m/s² | 83.9% | - | - | - |
| 150 ± 30 ms | 5% | after | 0.01 / 0.03 / 1.95 m | 203 ms | 118 / 2522 m/s² | 3.6% | 0.01 / 0.04 / 0.54 m | 8.5% | -127 / 60 ms |
| 150 ± 30 ms, 1 extra client | 5% | before | 0.03 / 0.10 / 0.81 m | 166 ms | 1610 / 4454 m/s² | 86.7% | - | - | - |
| 150 ± 30 ms, 1 extra client | 5% | after | 0.00 / 0.01 / 0.75 m | 185 ms | 81 / 2139 m/s² | 0.4% | 0.00 / 0.02 / 0.41 m | 1.0% | -96 / 64 ms |

The server's own path measures 60 / 80 m/s² (p95 / max) in nearly every run.
A brush with the station's collision envelope can push its maximum toward
1000 m/s². Spikes are ticks whose drawn acceleration exceeds three times the
server's p95.

### Observations

- **The stutter is gone.** The old lerp chased a target that stepped at every
snapshot, so its drawn velocity jumped on most ticks. Its p95 acceleration
was 1.6–3.0 km/s², 25–50 times the real motion, even on a clean link.
Buffered Hermite interpolation draws within 1.3–2.2 times the server's own
p95, and the drawn path stays within centimetres of a path the ship really
flew.
- **The delay is similar.** The drawn ship trails the server by about 100 ms
plus the one-way latency (104–235 ms here). The old lerp trailed by a
similar amount through its smoothing lag, but its drawn path cut corners
and never sat on the real one.
- **Extrapolation is rare but sensitive to load.** At about 50 fps, 1% of
entity ticks are drawn past the newest sample. At 13–38 fps, arrivals
bunched into frames raise that to 3–9%. The peaks in the maximum columns
are the corrections when fresh samples replace an extrapolation. If
playtests on real links show underruns, raise the interpolation delay.
- `tests/interpolation_network_test.gd` checks the same measures through the
relay at 150 ± 30 ms with 5% loss. It also replays the old lerp from the same
packets and asserts that it stutters (80–86% spike ticks against 0–5%).
9 changes: 9 additions & 0 deletions scripts/alien.gd
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ var contributors: Array[int] = []
# Weapons outrange detection; whoever damaged this life stays a target while eligible.
var last_attacker: Pilot = null
var snapshot_goal: Dictionary = {}
## Client: buffered snapshot transforms drawn by SessionCombat.interpolate().
var snapshot_buffer := SnapshotBuffer.new()


## Client: forgets replicated state at a discontinuity (session start or end,
## or a map change); the next snapshot snaps to the server's state.
func clear_snapshots() -> void:
snapshot_goal.clear()
snapshot_buffer.clear()


func tuning() -> Dictionary:
Expand Down
137 changes: 118 additions & 19 deletions scripts/flight_session.gd
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const MAX_PLAYERS: int = 10
const INPUT_TIMEOUT_TICKS: int = InputBuffer.TIMEOUT_TICKS
const CONNECT_TIMEOUT: float = 10.0
# Bump when packet contents or shared physics change without an RPC signature change.
const NETWORK_SCHEMA: int = 24
const NETWORK_SCHEMA: int = 25
## ENet packet throttle for every server/client peer: [interval ms,
## acceleration, deceleration]. ENet's default deceleration (2) discards
## unreliable packets at the sender whenever one round trip exceeds the
Expand All @@ -17,6 +17,9 @@ const NETWORK_SCHEMA: int = 24
## are redundant, so deceleration 0 keeps the throttle open. Reliable traffic
## keeps ENet's own windowing and resends.
const ENET_THROTTLE := [5000, 2, 0]
## Laser and explosion points within this distance (m) of an entity's newest
## received position are moved onto where that entity is drawn.
const ANCHOR_RADIUS := 8.0
const BUILD_MISMATCH := "Client and server builds are incompatible. Use the matching client and server from the same release or PR preview."

var sector: Sector
Expand All @@ -34,7 +37,13 @@ var input_buffers: Dictionary[int, InputBuffer] = {}
var server_tick: int = 0
## Client: local pilot inputs, prediction and reconciliation.
var prediction := FlightPrediction.new()
## Client: newest applied state of each pilot, keyed by peer.
var goals: Dictionary[int, Dictionary] = {}
## Client: estimated server time and the render time remote entities use.
var clock := ServerClock.new()
## Client: interpolation buffers of remote pilots, keyed by peer. Cleared
## with `goals` at every discontinuity.
var remote_buffers: Dictionary[int, SnapshotBuffer] = {}
var send_clock: float = 0.0
var connect_clock: float = 0.0
var received_snapshot: bool = false
Expand Down Expand Up @@ -569,6 +578,7 @@ func spawn(id: int, location: Vector3, docked: bool = false, map: int = 0) -> vo
ship.position = location
ship.map_id = map
ships[id] = ship
remote_buffers.erase(id)
combat.add_player(id, location)
ship.set_meta("docked", docked)
if docked:
Expand Down Expand Up @@ -752,6 +762,7 @@ func despawn(id: int) -> void:
commands.erase(id)
input_buffers.erase(id)
goals.erase(id)
remote_buffers.erase(id)
player_sequences.erase(id)
combat.remove_player(id)

Expand Down Expand Up @@ -812,18 +823,81 @@ func tick(delta: float) -> void:
disconnect_session("Connected, but no sector arrived. Check that client and server builds match, then try again.")
return
predict_local(delta, movement, boost)
combat.interpolate(delta)
for id: int in goals:
if not ships.has(id) or ships[id].map_id != sector.map_id:
continue
var ship := ships[id]
var goal: Dictionary = goals[id]
if ship == sector.player:
continue
ship.position = ship.position.lerp(goal["position"], minf(1.0, delta * 15.0))
var angles: Vector3 = goal["rotation"]
ship.rotation.x = lerp_angle(ship.rotation.x, angles.x, minf(1.0, delta * 15.0))
ship.rotation.y = lerp_angle(ship.rotation.y, angles.y, minf(1.0, delta * 15.0))
render_remote(delta)


## Client: draws remote pilots and aliens at the render time, between buffered
## snapshots (see ServerClock and SnapshotBuffer). Runs once per physics tick,
## so they step in time with the local ship and camera.
func render_remote(delta: float) -> void:
clock.advance(delta)
if not clock.synced:
return
var render_tick := clock.render_tick()
var counts := PackedInt32Array([0, 0, 0, 0])
for id: int in remote_buffers:
var ship: Pilot = ships.get(id)
if ship == null or ship == sector.player or ship.map_id != sector.map_id:
continue
draw_sample(ship, remote_buffers[id], render_tick, counts, false)
combat.interpolate(render_tick, counts)
net_stats.record_interpolation(clock, counts[0], counts[1], counts[2], counts[3])


## Moves one entity to its buffered transform at `render_tick` and counts the
## SnapshotBuffer mode used in `counts`: [interpolated, extrapolated, held,
## underruns].
static func draw_sample(node: Node3D, buffer: SnapshotBuffer, render_tick: float, counts: PackedInt32Array, all_axes: bool) -> void:
var underruns := buffer.underruns
var result := buffer.sample(render_tick)
if result.is_empty():
return
node.position = result["position"]
var angles: Vector3 = result["rotation"]
if all_axes:
node.rotation = angles
else:
# Pilots replicate pitch and yaw; roll is cosmetic banking on the model.
node.rotation.x = angles.x
node.rotation.y = angles.y
match int(result["mode"]):
SnapshotBuffer.Mode.INTERPOLATED: counts[0] += 1
SnapshotBuffer.Mode.EXTRAPOLATED: counts[1] += 1
SnapshotBuffer.Mode.HELD: counts[2] += 1
counts[3] += buffer.underruns - underruns


## Client: moves a world-space effect point the server placed at an entity's
## position onto where that entity is drawn. Remote entities are drawn about
## ServerClock.INTERPOLATION_DELAY in the past and the local ship ahead of the
## server, so lasers would otherwise start and end beside their ships.
func drawn_point(point: Vector3) -> Vector3:
if not active or multiplayer.is_server():
return point
var best := ANCHOR_RADIUS
var shift := Vector3.ZERO
if net_stats.has_server_state and sector.player.alive:
var distance := point.distance_to(net_stats.server_position)
if distance < best:
best = distance
shift = sector.player.position + sector.player.visual_offset - net_stats.server_position
for id: int in remote_buffers:
var ship: Pilot = ships.get(id)
var buffer := remote_buffers[id]
if ship == null or ship == sector.player or not ship.visible or buffer.is_empty():
continue
var distance := point.distance_to(buffer.newest_position())
if distance < best:
best = distance
shift = ship.position - buffer.newest_position()
for alien: Alien in sector.aliens.values():
if not alien.visible or alien.snapshot_buffer.is_empty():
continue
var distance := point.distance_to(alien.snapshot_buffer.newest_position())
if distance < best:
best = distance
shift = alien.position - alien.snapshot_buffer.newest_position()
return point + shift


## Server: consumes this tick's input for a remote pilot and simulates it with
Expand Down Expand Up @@ -1026,6 +1100,7 @@ func world_snapshot(packet: PackedByteArray) -> void:
var sequence: int = world["sequence"]
var visit: int = world["visit"]
net_stats.server_tick = maxi(net_stats.server_tick, world["tick"])
clock.observe(world["tick"])
var owner: Dictionary = world["owner"]
if not owner.is_empty():
combat.ammo_snapshot(owner["rounds"], sequence, owner["rockets"], visit)
Expand All @@ -1039,28 +1114,41 @@ func world_snapshot(packet: PackedByteArray) -> void:
var profile: Array = player_profiles.get(id, [-1])
if profile[0] == state["profile"]:
players[id] = SnapshotCodec.player_state(state, profile[1])
snapshot(players, {}, sequence, visit)
snapshot(players, {}, sequence, visit, world["tick"])
for id: int in world["aliens"]:
var state: Dictionary = world["aliens"][id]
var profile: Array = alien_profiles.get(id, [-1])
if profile[0] == state["profile"]:
snapshot({}, SnapshotCodec.alien_state(state, profile[1]), sequence, visit)
snapshot({}, SnapshotCodec.alien_state(state, profile[1]), sequence, visit, world["tick"])


## Applies decoded world state. Each entity rejects state older than its last update.
func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit: int = -1) -> void:
## Applies decoded world state sent on server `tick`. Each entity rejects state
## older than its last update, though an older packet's transform can still
## fill a remote entity's interpolation buffer. Direct calls without a tick
## (tests) reuse the newest received tick.
func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit: int = -1, tick: int = -1) -> void:
if not active or not receives_map(visit):
return
if tick < 0:
tick = maxi(clock.latest_tick, 0)
# Packets may arrive out of order. Reject stale state per entity, not per whole packet.
if not alien_state.is_empty():
var alien_id: int = alien_state["id"]
if sequence > alien_sequences.get(alien_id, -1):
combat.apply_alien(alien_state)
combat.apply_alien(alien_state, tick)
alien_sequences[alien_id] = sequence
else:
combat.buffer_late_alien(alien_state, tick)
for id: int in state:
if not ships.has(id) or sequence <= player_sequences.get(id, -1):
if not ships.has(id):
continue
var data: Dictionary = state[id]
if sequence <= player_sequences.get(id, -1):
# Same life and state: the transform still belongs to the current motion.
var late := ships[id]
if late != sector.player and remote_buffers.has(id) and int(data["life"]) == int(late.get_meta("life", 0)) and bool(data["alive"]) == late.alive:
remote_buffers[id].push(tick, data["position"], data["rotation"])
continue
if int(data["life"]) < int(ships[id].get_meta("life", 0)):
continue
# Reliable dock/launch acknowledgements and snapshots travel on different channels.
Expand All @@ -1075,6 +1163,14 @@ func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit:
ship.rotation = data["rotation"]
if ship != sector.player:
ship.energy = data["energy"]
# A new life, or the first state after a spawn or launch, starts a new motion.
var buffer: SnapshotBuffer = remote_buffers.get_or_add(id, SnapshotBuffer.new())
if reset or buffer.is_empty():
buffer.clear()
ship.position = data["position"]
ship.rotation.x = data["rotation"].x
ship.rotation.y = data["rotation"].y
buffer.push(tick, data["position"], data["rotation"], true)
else:
var authoritative := {"position": data["position"], "rotation": data["rotation"], "energy": data["energy"],
"velocity": data["velocity"] if ship.alive else Vector3.ZERO}
Expand Down Expand Up @@ -1132,6 +1228,8 @@ func disconnect_session(message: String) -> void:
input_buffers.clear()
server_tick = 0
goals.clear()
remote_buffers.clear()
clock.reset()
received_snapshot = false
snapshot_sequence = 0
player_sequences.clear()
Expand Down Expand Up @@ -1347,6 +1445,7 @@ func map_changed(id: int, data: Dictionary, sequence: int) -> void:
prediction.reset(ship)
ship.sim_rotation = data["rotation"]
goals.erase(id)
remote_buffers.erase(id)
player_sequences[id] = maxi(player_sequences.get(id, -1), sequence)
if ship == sector.player:
sector.activate_map(ship.map_id)
Expand Down
Loading
Loading