Files
tidewall/src/net/client_game.gd
T
claudeandClaude Opus 5.5 5e1704e224 N4: Lag-compensated hit validation
A network client draws other players in the past and its commands take time
to arrive, so by the time the server fires a shot the target has moved on:
8 ticks at a 50 ms round trip, 12 at 200 ms.

Each PlayerCommand now carries view_lag: how far back its player was seeing
everyone else, in quarter ticks. The simulation keeps where every player's
body has been for the last 15 ticks (HitHistory), and a hitscan shot is
traced against other players where they were at the moment the shooter saw,
and against the world as it is now. Projectiles aren't rewound.

The client claims only when it was looking and where it aimed; the server
works out the hit from its own record. The moment is never more than
Tuning.LAG_COMPENSATION_MAX_TICKS back, never in the future, and never
earlier than a moment the same player has already claimed.

Commands are 15 bytes, so the command log's version is 2. The lag is in the
log, and replays judge every shot as the match did.

Measured in test/net/test_lag_compensation_link.gd over a simulated link:
a client firing at a walking target as drawn on its own screen hits 41 of
41 shots at 50, 100 and 200 ms round trips, 0 of 41 with the lag ignored,
and 0 of 41 at 500 ms, past the cap.

Closes #35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:45:23 -05:00

175 lines
6.0 KiB
GDScript

## 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
if remote.started:
# How far back everyone else is being drawn right now, for the server to judge
# shots by.
command.view_lag = clampi(roundi((float(tick) - remote.time) * PlayerCommand.VIEW_LAG_STEPS_PER_TICK), 0, 255)
_last_yaw = command.yaw
_last_pitch = command.pitch
return command