N2: Snapshot replication and interest management
NetSnapshot defines the game traffic after the handshake: delta snapshots of quantized entity records, the client's input packet and a reliable match notice. SnapshotSender builds each client's snapshot against the newest one it acknowledged, tells it only about entities near the player it is watching, and keeps every snapshot under 1,200 bytes, nearest first, with a staleness bonus so nothing starves. SnapshotReceiver rebuilds the picture, ignores old and repeated snapshots and asks for a fresh start if it is ever sent a delta on something it doesn't hold. NetGame joins the transport to the match: people who connect become participants, their inputs go through ServerLoop.submit() once per tick, and snapshots go out 20 times a second. `--server --listen` makes the headless server take network players and wait in the lobby for the first of them. Measured by test on a 24-player match start with every player a client, a tenth of packets lost and late acknowledgements: 2.4 KB/s mean and 2.5 KB/s for the worst client, packet headers included, against a 40 KB/s limit. Closes #33 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,8 @@ const FAULT_TICK: int = 10
|
||||
|
||||
var config: ServerConfig
|
||||
var loop: ServerLoop
|
||||
## The network side, when the server was started with --listen.
|
||||
var game: NetGame = null
|
||||
|
||||
var _errors: ErrorCounter = ErrorCounter.new()
|
||||
var _accumulator: float = 0.0
|
||||
@@ -39,20 +41,38 @@ func _ready() -> void:
|
||||
if not config.has_seed:
|
||||
config.match_seed = _fresh_seed()
|
||||
Engine.max_fps = 0 if config.unthrottled else REALTIME_MAX_FPS
|
||||
loop = ServerLoop.new(config.match_seed, config.players, config.bots, null, config.bot_difficulty)
|
||||
var rules: MatchRules = null
|
||||
if config.listen:
|
||||
rules = MatchRules.new()
|
||||
rules.fill_with_bots = config.bots > 0
|
||||
loop = ServerLoop.new(config.match_seed, config.players, config.bots, rules, config.bot_difficulty)
|
||||
if config.listen:
|
||||
var net: NetServer = NetServer.new()
|
||||
var error: Error = net.listen(config.port)
|
||||
if error != OK:
|
||||
_log("listen_failed", {"port": config.port, "message": "couldn't listen on UDP port %d: %s" % [config.port, error_string(error)]})
|
||||
_finish(2)
|
||||
return
|
||||
game = NetGame.new(loop, net)
|
||||
var started: Dictionary = config.to_dictionary()
|
||||
started["engine"] = Engine.get_version_info()["string"]
|
||||
started["tick_rate_hz"] = Tuning.TICK_RATE_HZ
|
||||
started["world_hash"] = loop.sim.island.heightmap_hash()
|
||||
started["match_phase"] = loop.match_flow.phase_name()
|
||||
started["listening"] = false
|
||||
started["note"] = "networking arrives in v0.5; players join as idle slots until then"
|
||||
started["listening"] = game != null
|
||||
_log("start", started)
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if _finished or loop == null:
|
||||
return
|
||||
if game != null:
|
||||
game.poll()
|
||||
for event: Dictionary in game.events:
|
||||
var fields: Dictionary = {"handle": event["handle"], "name": event["name"], "players": game.net.player_count()}
|
||||
if event["type"] == "left":
|
||||
fields["reason"] = event["reason"]
|
||||
_log("player_" + String(event["type"]), fields)
|
||||
var due: int = UNTHROTTLED_BATCH
|
||||
if not config.unthrottled:
|
||||
_accumulator += delta
|
||||
@@ -79,6 +99,8 @@ func _tick() -> void:
|
||||
if config.fault == "script-error" and loop.ticks == FAULT_TICK:
|
||||
_deliberate_script_error()
|
||||
loop.run_tick()
|
||||
if game != null:
|
||||
game.after_tick()
|
||||
for event: Dictionary in loop.match_flow.events:
|
||||
if event["type"] in ["phase", "match_started", "match_ended"]:
|
||||
_log("match", event)
|
||||
@@ -94,6 +116,8 @@ func _tick() -> void:
|
||||
func _finish(requested_code: int) -> void:
|
||||
_finished = true
|
||||
var code: int = requested_code
|
||||
if game != null:
|
||||
game.net.close()
|
||||
if loop != null:
|
||||
var stats: Dictionary = loop.timing_stats()
|
||||
stats["state_hash"] = loop.sim.state_hash()
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
## 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.
|
||||
##
|
||||
## Call poll() once a frame before running ticks, and after_tick() after each tick.
|
||||
class_name NetGame
|
||||
extends RefCounted
|
||||
|
||||
var loop: ServerLoop
|
||||
var net: NetServer
|
||||
var sender: SnapshotSender = SnapshotSender.new()
|
||||
## What happened during the last poll(): {"type": "joined" or "left", "handle", "name",
|
||||
## "reason"}, for the server's log.
|
||||
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.
|
||||
var _last_command: Dictionary = {}
|
||||
|
||||
|
||||
func _init(server_loop: ServerLoop, server_net: NetServer) -> void:
|
||||
loop = server_loop
|
||||
net = server_net
|
||||
net.max_players = loop.match_flow.rules.max_players
|
||||
net.match_seed = loop.match_flow.current_seed()
|
||||
|
||||
|
||||
## Services the network: joins and leaves, then every input packet that arrived.
|
||||
func poll() -> void:
|
||||
events.clear()
|
||||
net.poll()
|
||||
# kick() adds to net.events, so walk a copy.
|
||||
for event: Dictionary in net.events.duplicate():
|
||||
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
|
||||
_send_match(handle)
|
||||
events.append(event)
|
||||
else:
|
||||
net.kick(handle, NetProtocol.REASON_FULL)
|
||||
elif event["type"] == "left" and sender.has_client(handle):
|
||||
loop.match_flow.leave(handle)
|
||||
sender.remove_client(handle)
|
||||
_last_command.erase(handle)
|
||||
events.append(event)
|
||||
for packet: Dictionary in net.packets:
|
||||
var handle: int = packet["handle"]
|
||||
if not sender.has_client(handle):
|
||||
continue
|
||||
var input: Dictionary = NetSnapshot.decode_input(packet["bytes"])
|
||||
if input.is_empty():
|
||||
bad_inputs += 1
|
||||
continue
|
||||
sender.acknowledge(handle, int(input["ack"]))
|
||||
if not loop.match_flow.in_match():
|
||||
continue
|
||||
# Packets repeat recent commands; each tick's command is offered once, whether
|
||||
# or not the simulation takes it.
|
||||
for command: PlayerCommand in input["commands"]:
|
||||
if command.tick <= int(_last_command[handle]):
|
||||
continue
|
||||
_last_command[handle] = command.tick
|
||||
if loop.submit(handle, command):
|
||||
sender.note_command(handle, command.tick)
|
||||
|
||||
|
||||
## Tells everyone about a change of phase, and sends snapshots when one is due.
|
||||
func after_tick() -> void:
|
||||
var flow: Match = loop.match_flow
|
||||
var changed: bool = false
|
||||
for event: Dictionary in flow.events:
|
||||
if event["type"] == "phase":
|
||||
changed = true
|
||||
if event["to"] == "lobby":
|
||||
# A new simulation: entity IDs and ticks start again.
|
||||
sender.reset()
|
||||
for handle: int in _last_command:
|
||||
_last_command[handle] = -1
|
||||
net.match_seed = flow.current_seed()
|
||||
if changed:
|
||||
for handle: int in net.handles():
|
||||
_send_match(handle)
|
||||
if loop.ticks % Tuning.NET_SNAPSHOT_INTERVAL_TICKS != 0:
|
||||
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)
|
||||
|
||||
|
||||
## The entity a participant is watching: their own player, the player they spectate
|
||||
## once eliminated, or 0 when they aren't in a match.
|
||||
func viewer_of(handle: int) -> int:
|
||||
var flow: Match = loop.match_flow
|
||||
if flow.phase == Match.LOBBY or flow.phase == Match.COUNTDOWN or not flow.entity_of.has(handle):
|
||||
return 0
|
||||
var target: int = flow.spectate_target(handle)
|
||||
if target != 0 and flow.entity_of.has(target):
|
||||
return int(flow.entity_of[target])
|
||||
return int(flow.entity_of[handle])
|
||||
|
||||
|
||||
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)
|
||||
@@ -0,0 +1 @@
|
||||
uid://b3uihs71yhq6f
|
||||
@@ -1,9 +1,13 @@
|
||||
## Command-line configuration for a headless server.
|
||||
##
|
||||
## tools/godot.sh -- --server [--seed=N] [--port=N] [--players=N] [--bots=N]
|
||||
## tools/godot.sh -- --server [--listen] [--port=N] [--seed=N] [--players=N] [--bots=N]
|
||||
## [--bot-difficulty=mixed|easy|normal|hard] [--ticks=N]
|
||||
## [--unthrottled] [--log-every=N]
|
||||
##
|
||||
## With `--listen` the server takes network players on UDP `--port`, waits in the lobby
|
||||
## for the first of them, and with any `--bots` above 0 fills each match's empty places
|
||||
## with bots. Without it the match starts at once with `--players` idle slots.
|
||||
##
|
||||
## Unknown or malformed arguments are errors, so a typo can't silently run the wrong
|
||||
## match. See `parse()`.
|
||||
class_name ServerConfig
|
||||
@@ -19,9 +23,11 @@ var server: bool = false
|
||||
## The match seed. `has_seed` is false when none was given and the server must pick one.
|
||||
var match_seed: int = 0
|
||||
var has_seed: bool = false
|
||||
## UDP port the server will listen on once networking lands (v0.5).
|
||||
## True when `--listen` was given: take network players on `port`.
|
||||
var listen: bool = false
|
||||
## UDP port a listening server uses.
|
||||
var port: int = DEFAULT_PORT
|
||||
## Player slots for human clients. Until v0.5 they join as idle players.
|
||||
## Idle player slots, for a server that isn't listening.
|
||||
var players: int = 0
|
||||
var bots: int = 0
|
||||
## Every bot's difficulty, as an index into Tuning.BOT_DIFFICULTIES, or -1 to mix them.
|
||||
@@ -59,6 +65,7 @@ func is_valid() -> bool:
|
||||
func to_dictionary() -> Dictionary:
|
||||
return {
|
||||
"seed": match_seed,
|
||||
"listen": listen,
|
||||
"port": port,
|
||||
"players": players,
|
||||
"bots": bots,
|
||||
@@ -72,6 +79,9 @@ func _parse_one(arg: String) -> void:
|
||||
if arg == "--unthrottled":
|
||||
unthrottled = true
|
||||
return
|
||||
if arg == "--listen":
|
||||
listen = true
|
||||
return
|
||||
var parts: PackedStringArray = arg.split("=", true, 1)
|
||||
if parts.size() != 2 or not arg.begins_with("--"):
|
||||
errors.append("unknown argument '%s'" % arg)
|
||||
@@ -129,6 +139,8 @@ func _validate() -> void:
|
||||
"--players plus --bots is %d, more than the match size of %d"
|
||||
% [players + bots, Tuning.SOLO_PLAYERS]
|
||||
)
|
||||
if listen and players > 0:
|
||||
errors.append("--players is for a server that isn't listening; with --listen, people join over the network")
|
||||
if ticks < 0:
|
||||
errors.append("--ticks can't be negative")
|
||||
if log_every < 0:
|
||||
|
||||
Reference in New Issue
Block a user