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:
@@ -10,6 +10,8 @@ var clients: Array[NetClient] = []
|
||||
## Every server event since the test began.
|
||||
var seen: Array[Dictionary] = []
|
||||
var raw_hosts: Array[ENetConnection] = []
|
||||
## Game packets the server handed to its owner since the test began.
|
||||
var handed: int = 0
|
||||
|
||||
|
||||
func before_each() -> void:
|
||||
@@ -17,6 +19,7 @@ func before_each() -> void:
|
||||
server.match_seed = 4242
|
||||
clients.clear()
|
||||
seen.clear()
|
||||
handed = 0
|
||||
raw_hosts.clear()
|
||||
assert_eq(server.listen(0, HOST), OK)
|
||||
assert_true(server.port() > 0)
|
||||
@@ -43,6 +46,7 @@ func _pump(done: Callable, limit_msec: int = 4000) -> bool:
|
||||
while Time.get_ticks_msec() - started < limit_msec:
|
||||
server.poll()
|
||||
seen.append_array(server.events)
|
||||
handed += server.packets.size()
|
||||
for client: NetClient in clients:
|
||||
client.poll()
|
||||
for host: ENetConnection in raw_hosts:
|
||||
@@ -242,11 +246,13 @@ func test_random_packets_from_guests_and_players_never_crash_the_server() -> voi
|
||||
for index: int in bytes.size():
|
||||
bytes[index] = rng.randi_range(0, 255)
|
||||
peer.send(rng.randi_range(0, 1), bytes, ENetPacketPeer.FLAG_RELIABLE)
|
||||
# A player who keeps sending HELLOs and junk stays a player and changes nothing.
|
||||
# A player who keeps sending HELLOs and junk stays a player and changes nothing. The
|
||||
# HELLOs are dropped; junk on the game channel goes to the owner, who can't read it.
|
||||
for _packet: int in 20:
|
||||
member._peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_hello("Someone Else"), ENetPacketPeer.FLAG_RELIABLE)
|
||||
member._peer.send(NetProtocol.CHANNEL_STATE, PackedByteArray([1, 2, 3]), ENetPacketPeer.FLAG_RELIABLE)
|
||||
assert_true(_pump(func() -> bool: return _events("refused").size() >= 12 and server.bad_packets >= 52), "refused %d, dropped %d" % [_events("refused").size(), server.bad_packets])
|
||||
assert_true(_pump(func() -> bool: return _events("refused").size() >= 12 and server.bad_packets >= 32 and handed >= 20), "refused %d, dropped %d, handed on %d" % [_events("refused").size(), server.bad_packets, handed])
|
||||
assert_eq(handed, 20)
|
||||
assert_eq(server.player_count(), 1)
|
||||
assert_eq(server.name_of(1), "Mara")
|
||||
assert_eq(_events("joined").size(), 1)
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
extends TestCase
|
||||
|
||||
## Issue N2: the wire format of snapshots, input packets and the match notice.
|
||||
|
||||
|
||||
func _player(sim: Simulation, at: Vector3) -> SimEntity:
|
||||
var player: SimEntity = sim.entities.find(sim.add_player())
|
||||
player.position = at
|
||||
return player
|
||||
|
||||
|
||||
func test_a_record_keeps_position_to_a_sixty_fourth_of_a_metre() -> void:
|
||||
var sim: Simulation = Simulation.new(3, SimGround.flat())
|
||||
var player: SimEntity = _player(sim, Vector3(511.37, -20.21, 1003.99))
|
||||
player.yaw = 40000
|
||||
player.pitch = -PlayerCommand.PITCH_MAX
|
||||
player.health = 73
|
||||
player.crouching = true
|
||||
var record: PackedInt32Array = NetSnapshot.record_of(player)
|
||||
assert_true(NetSnapshot.position_of(record).distance_to(player.position) < 0.014)
|
||||
assert_near(NetSnapshot.yaw_radians_of(record), float(40000) / 65536.0 * TAU, 0.0001)
|
||||
assert_near(NetSnapshot.pitch_radians_of(record), -PI * 0.5, 0.0001)
|
||||
assert_eq(record[NetSnapshot.R_HEALTH], 73)
|
||||
assert_true(record[NetSnapshot.R_FLAGS] & NetSnapshot.FLAG_CROUCHING != 0)
|
||||
assert_eq(record[NetSnapshot.R_HELD], 0, "the boathook")
|
||||
|
||||
|
||||
func test_positions_outside_the_world_are_clamped_not_wrapped() -> void:
|
||||
var sim: Simulation = Simulation.new(3, SimGround.flat())
|
||||
var player: SimEntity = _player(sim, Vector3(-50.0, 5000.0, 2000.0))
|
||||
var where: Vector3 = NetSnapshot.position_of(NetSnapshot.record_of(player))
|
||||
assert_near(where.x, 0.0, 0.001)
|
||||
assert_near(where.z, 65535.0 / 64.0, 0.001)
|
||||
assert_near(where.y, 65535.0 / 64.0 - NetSnapshot.Y_OFFSET_METRES, 0.001)
|
||||
|
||||
|
||||
func test_a_snapshot_round_trips_every_archetype_and_partial_masks() -> void:
|
||||
var sim: Simulation = Simulation.new(3, SimGround.flat())
|
||||
var player: SimEntity = _player(sim, Vector3(100.0, 0.0, 100.0))
|
||||
var pickup: SimEntity = sim.entities.find(Inventory.spawn_pickup(sim, Vector3(101.0, 0.0, 100.0), 1, 7, -1, 2))
|
||||
var shot: SimEntity = sim.entities.create(SimEntity.ARCHETYPE_PROJECTILE)
|
||||
shot.position = Vector3(120.0, 9.0, 80.0)
|
||||
shot.item = 4
|
||||
shot.owner_id = player.id
|
||||
var before: PackedInt32Array = NetSnapshot.record_of(player)
|
||||
player.position.x += 3.0
|
||||
player.health = 12
|
||||
var after: PackedInt32Array = NetSnapshot.record_of(player)
|
||||
var mask: int = NetSnapshot.diff_mask(before, after)
|
||||
assert_eq(mask, 0b101, "position and vitals changed, nothing else")
|
||||
var header: Dictionary = {
|
||||
"tick": 900, "baseline": 897, "sim_tick": 300, "command_tick": 298, "own_id": player.id,
|
||||
"match_phase": Match.PLAY, "tide_phase": 2, "sea_cm": -150,
|
||||
}
|
||||
var records: Array = [
|
||||
[player.id, mask, after],
|
||||
[pickup.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PICKUP), NetSnapshot.record_of(pickup)],
|
||||
[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
|
||||
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")
|
||||
var back: Dictionary = NetSnapshot.decode_snapshot(bytes)
|
||||
for key: String in header:
|
||||
assert_eq(back[key], header[key], key)
|
||||
assert_eq(back["removed"], PackedInt32Array([70000, 5]))
|
||||
assert_eq((back["records"] as Array).size(), 3)
|
||||
var merged: PackedInt32Array = NetSnapshot.merge_record(before, SimEntity.ARCHETYPE_PLAYER, back["records"][0][2], back["records"][0][3])
|
||||
assert_eq(merged, after)
|
||||
assert_eq(NetSnapshot.merge_record(PackedInt32Array(), SimEntity.ARCHETYPE_PICKUP, back["records"][1][2], back["records"][1][3]), NetSnapshot.record_of(pickup))
|
||||
assert_eq(NetSnapshot.merge_record(PackedInt32Array(), SimEntity.ARCHETYPE_PROJECTILE, back["records"][2][2], back["records"][2][3]), NetSnapshot.record_of(shot))
|
||||
|
||||
|
||||
func test_a_partial_record_for_an_unknown_entity_is_refused() -> void:
|
||||
assert_eq(NetSnapshot.merge_record(PackedInt32Array(), SimEntity.ARCHETYPE_PLAYER, 0b1, PackedInt32Array([1, 2, 3])), PackedInt32Array())
|
||||
var pickup: PackedInt32Array = PackedInt32Array([SimEntity.ARCHETYPE_PICKUP, 1, 2, 3, 4, 5, 6])
|
||||
assert_eq(NetSnapshot.merge_record(pickup, SimEntity.ARCHETYPE_PLAYER, 0b1, PackedInt32Array([1, 2, 3])), PackedInt32Array(), "an ID can't change archetype")
|
||||
|
||||
|
||||
func test_truncated_and_corrupt_snapshots_decode_to_nothing_without_errors() -> void:
|
||||
var sim: Simulation = Simulation.new(3, SimGround.flat())
|
||||
var records: Array = []
|
||||
for index: int in 5:
|
||||
var player: SimEntity = _player(sim, Vector3(100.0 + index, 0.0, 100.0))
|
||||
records.append([player.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PLAYER), NetSnapshot.record_of(player)])
|
||||
var bytes: PackedByteArray = NetSnapshot.encode_snapshot({"tick": 5, "own_id": 1}, PackedInt32Array([9]), records)
|
||||
assert_false(NetSnapshot.decode_snapshot(bytes).is_empty())
|
||||
for length: int in bytes.size():
|
||||
assert_true(NetSnapshot.decode_snapshot(bytes.slice(0, length)).is_empty(), "cut to %d bytes" % length)
|
||||
var longer: PackedByteArray = bytes.duplicate()
|
||||
longer.append(0)
|
||||
assert_true(NetSnapshot.decode_snapshot(longer).is_empty(), "trailing bytes")
|
||||
# Every single-byte corruption either decodes to something or to nothing; none may
|
||||
# raise an engine error, which would fail this test.
|
||||
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
|
||||
rng.seed = 77
|
||||
for _round: int in 400:
|
||||
var broken: PackedByteArray = bytes.duplicate()
|
||||
broken[rng.randi_range(0, broken.size() - 1)] = rng.randi_range(0, 255)
|
||||
NetSnapshot.decode_snapshot(broken)
|
||||
for _round: int in 200:
|
||||
var noise: PackedByteArray = PackedByteArray()
|
||||
noise.resize(rng.randi_range(0, 80))
|
||||
for index: int in noise.size():
|
||||
noise[index] = rng.randi_range(0, 255)
|
||||
if noise.size() > 0:
|
||||
noise[0] = NetSnapshot.MSG_SNAPSHOT
|
||||
NetSnapshot.decode_snapshot(noise)
|
||||
NetSnapshot.decode_input(noise)
|
||||
NetSnapshot.decode_match(noise)
|
||||
|
||||
|
||||
func test_input_round_trips_and_keeps_the_newest_commands() -> void:
|
||||
var commands: Array[PlayerCommand] = []
|
||||
for tick: int in range(50, 62):
|
||||
commands.append(PlayerCommand.from_input(tick, Vector2(0.5, -1.0), 1.0, 0.2, PlayerCommand.BUTTON_JUMP, 2, 1))
|
||||
var bytes: PackedByteArray = NetSnapshot.encode_input(4321, commands)
|
||||
var back: Dictionary = NetSnapshot.decode_input(bytes)
|
||||
assert_eq(back["ack"], 4321)
|
||||
var got: Array[PlayerCommand] = back["commands"]
|
||||
assert_eq(got.size(), NetSnapshot.MAX_INPUT_COMMANDS)
|
||||
assert_eq(got[0].tick, 62 - NetSnapshot.MAX_INPUT_COMMANDS)
|
||||
assert_eq(got[got.size() - 1].tick, 61)
|
||||
assert_eq(got[0].encode(), commands[commands.size() - NetSnapshot.MAX_INPUT_COMMANDS].encode())
|
||||
assert_true(NetSnapshot.decode_input(bytes.slice(0, bytes.size() - 1)).is_empty())
|
||||
var lying: PackedByteArray = bytes.duplicate()
|
||||
lying[5] = 200
|
||||
assert_true(NetSnapshot.decode_input(lying).is_empty(), "a count the packet doesn't hold")
|
||||
assert_eq((NetSnapshot.decode_input(NetSnapshot.encode_input(0, []))["commands"] as Array).size(), 0)
|
||||
|
||||
|
||||
func test_match_notice_round_trips_a_63_bit_seed() -> void:
|
||||
var seed_value: int = 0x7FFFFFFFFFFFFFF1
|
||||
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")
|
||||
@@ -0,0 +1 @@
|
||||
uid://b21v680p10uly
|
||||
@@ -0,0 +1,129 @@
|
||||
extends TestCase
|
||||
|
||||
## Issue N2's numbers: a whole 24-player match start, every player a client, over a
|
||||
## link that loses a tenth of its packets and acknowledges late. Measures what each
|
||||
## client is sent, and checks that nothing outside its interest area is in it.
|
||||
|
||||
## Bytes around every snapshot on the wire: IPv4 and UDP headers, and ENet's protocol
|
||||
## and command headers for an unreliable, unsequenced send.
|
||||
const PACKET_OVERHEAD_BYTES: int = 28 + 4 + 8
|
||||
const TICKS: int = 2700
|
||||
## Snapshots between a snapshot leaving and its acknowledgement arriving.
|
||||
const ACK_DELAY: int = 2
|
||||
|
||||
|
||||
func test_24_players_stay_under_40_kb_a_second_and_inside_their_interest() -> void:
|
||||
var loop: ServerLoop = ServerLoop.new(4, 0, Tuning.SOLO_PLAYERS)
|
||||
var game: NetGame = NetGame.new(loop, NetServer.new())
|
||||
var flow: Match = loop.match_flow
|
||||
var sender: SnapshotSender = game.sender
|
||||
var receivers: Dictionary = {}
|
||||
var pending: Dictionary = {}
|
||||
var handles: Array[int] = flow.participants.duplicate()
|
||||
assert_eq(handles.size(), Tuning.SOLO_PLAYERS)
|
||||
for handle: int in handles:
|
||||
sender.add_client(handle)
|
||||
receivers[handle] = SnapshotReceiver.new()
|
||||
pending[handle] = []
|
||||
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
|
||||
rng.seed = 99
|
||||
var limit_players: float = Tuning.NET_INTEREST_PLAYERS_METRES + 0.05
|
||||
var limit_pickups: float = Tuning.NET_INTEREST_PICKUPS_METRES + 0.05
|
||||
var records_seen: int = 0
|
||||
var most_entities: int = 0
|
||||
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).
|
||||
var window: Dictionary = {}
|
||||
var worst_second: int = 0
|
||||
while loop.ticks < TICKS and flow.phase != Match.RESULTS:
|
||||
loop.run_tick()
|
||||
if loop.ticks % Tuning.NET_SNAPSHOT_INTERVAL_TICKS != 0:
|
||||
continue
|
||||
rounds += 1
|
||||
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)
|
||||
send_usec += Time.get_ticks_usec() - started
|
||||
for handle: int in handles:
|
||||
var bytes: PackedByteArray = built[handle]
|
||||
var viewer: SimEntity = loop.sim.entities.find(game.viewer_of(handle))
|
||||
assert_true(bytes.size() <= Tuning.NET_SNAPSHOT_MAX_BYTES)
|
||||
biggest = maxi(biggest, bytes.size())
|
||||
var recent: Array = window.get_or_add(handle, [])
|
||||
recent.append(bytes.size() + PACKET_OVERHEAD_BYTES)
|
||||
if recent.size() > 20:
|
||||
recent.pop_front()
|
||||
var second: int = 0
|
||||
for size: int in recent:
|
||||
second += size
|
||||
worst_second = maxi(worst_second, second)
|
||||
for entry: Array in NetSnapshot.decode_snapshot(bytes)["records"]:
|
||||
records_seen += 1
|
||||
var entity: SimEntity = loop.sim.entities.find(entry[0])
|
||||
if entity == null or viewer == null:
|
||||
fail("a record for entity %d, which isn't there" % entry[0])
|
||||
continue
|
||||
var away: float = Vector2(entity.position.x - viewer.position.x, entity.position.z - viewer.position.z).length()
|
||||
var limit: float = limit_pickups if entity.archetype == SimEntity.ARCHETYPE_PICKUP else limit_players
|
||||
if entity.id != viewer.id and away > limit:
|
||||
fail("client %d was sent entity %d, %.1f m away (limit %.1f)" % [handle, entity.id, away, limit])
|
||||
var receiver: SnapshotReceiver = receivers[handle]
|
||||
if rng.randf() >= 0.1:
|
||||
receiver.apply(bytes)
|
||||
most_entities = maxi(most_entities, receiver.entities.size())
|
||||
var queue: Array = pending[handle]
|
||||
queue.append(receiver.ack_tick())
|
||||
if queue.size() > ACK_DELAY:
|
||||
var ack: int = queue.pop_front()
|
||||
if rng.randf() >= 0.1:
|
||||
sender.acknowledge(handle, ack)
|
||||
assert_true(flow.phase == Match.PLAY or flow.phase == Match.RESULTS, "the run reached play: %s" % flow.phase_name())
|
||||
var seconds: float = float(rounds) * Tuning.NET_SNAPSHOT_INTERVAL_TICKS / Tuning.TICK_RATE_HZ
|
||||
var worst_rate: float = 0.0
|
||||
var total: float = 0.0
|
||||
var full: int = 0
|
||||
var deferred: int = 0
|
||||
for handle: int in handles:
|
||||
var stats: Dictionary = sender.stats(handle)
|
||||
var rate: float = (float(stats["bytes"]) + float(stats["snapshots"]) * PACKET_OVERHEAD_BYTES) / seconds
|
||||
worst_rate = maxf(worst_rate, rate)
|
||||
total += rate
|
||||
full += int(stats["full"])
|
||||
deferred += int(stats["deferred"])
|
||||
var receiver: SnapshotReceiver = receivers[handle]
|
||||
assert_eq(receiver.malformed, 0)
|
||||
assert_eq(receiver.missing_baseline, 0)
|
||||
print(" %d clients, %.0f s, 10%% loss: mean %.1f KB/s, worst client %.1f KB/s, worst single second %.1f KB, largest snapshot %d bytes" % [handles.size(), seconds, total / handles.size() / 1000.0, worst_rate / 1000.0, worst_second / 1000.0, biggest])
|
||||
print(" %d records sent, %d full snapshots, %d updates deferred, most entities one client held %d, building all 24 took %.2f ms a round" % [records_seen, full, deferred, most_entities, send_usec / 1000.0 / rounds])
|
||||
assert_true(worst_rate < 40_000.0, "worst client averaged %.0f bytes a second" % worst_rate)
|
||||
assert_true(worst_second < 40_000, "worst single second was %d bytes" % worst_second)
|
||||
assert_true(records_seen > 10_000, "the match really was replicated: %d records" % records_seen)
|
||||
# Snapshots build on nothing until the first acknowledgement arrives, and again if
|
||||
# that first one was lost. After that, loss never forces another.
|
||||
assert_true(full <= handles.size() * (ACK_DELAY + 3), "%d full snapshots" % full)
|
||||
# With the link quiet again, every client ends with exactly what it may see.
|
||||
for _round: int in 12:
|
||||
for _tick: int in Tuning.NET_SNAPSHOT_INTERVAL_TICKS:
|
||||
loop.run_tick()
|
||||
if flow.phase == Match.RESULTS:
|
||||
break
|
||||
for handle: int in handles:
|
||||
var receiver: SnapshotReceiver = receivers[handle]
|
||||
receiver.apply(sender.build(handle, loop.sim, game.viewer_of(handle), loop.ticks, flow.phase))
|
||||
sender.acknowledge(handle, receiver.ack_tick())
|
||||
var checked: int = 0
|
||||
for handle: int in handles:
|
||||
var receiver: SnapshotReceiver = receivers[handle]
|
||||
var viewer: SimEntity = loop.sim.entities.find(game.viewer_of(handle))
|
||||
var visible: Array[int] = SnapshotSender.interest(loop.sim, viewer)
|
||||
assert_eq(receiver.entities.size(), visible.size(), "client %d's entity count" % handle)
|
||||
for entity_id: int in visible:
|
||||
if receiver.entities.has(entity_id):
|
||||
checked += 1
|
||||
assert_eq(receiver.entities[entity_id], NetSnapshot.record_of(loop.sim.entities.find(entity_id)))
|
||||
else:
|
||||
fail("client %d is missing entity %d" % [handle, entity_id])
|
||||
assert_true(checked > handles.size())
|
||||
@@ -0,0 +1 @@
|
||||
uid://2npkbpeepyqn
|
||||
@@ -0,0 +1,266 @@
|
||||
extends TestCase
|
||||
|
||||
## Issue N2: SnapshotSender and SnapshotReceiver together, over a link that loses,
|
||||
## delays and repeats packets. Interest management and the size budget.
|
||||
|
||||
const HANDLE: int = 1
|
||||
const STEP: int = Tuning.NET_SNAPSHOT_INTERVAL_TICKS
|
||||
|
||||
var sim: Simulation
|
||||
var viewer: SimEntity
|
||||
var sender: SnapshotSender
|
||||
var receiver: SnapshotReceiver
|
||||
var tick: int = 0
|
||||
## Every packet built for the client, delivered or not.
|
||||
var packets: Array[PackedByteArray] = []
|
||||
|
||||
|
||||
func before_each() -> void:
|
||||
sim = Simulation.new(5, SimGround.flat())
|
||||
viewer = sim.entities.find(sim.add_player())
|
||||
viewer.position = Vector3(500.0, 0.0, 500.0)
|
||||
sender = SnapshotSender.new()
|
||||
sender.add_client(HANDLE)
|
||||
receiver = SnapshotReceiver.new()
|
||||
tick = 0
|
||||
packets.clear()
|
||||
|
||||
|
||||
func _other(at: Vector3) -> SimEntity:
|
||||
var player: SimEntity = sim.entities.find(sim.add_player())
|
||||
player.position = at
|
||||
return player
|
||||
|
||||
|
||||
## Builds the next snapshot. Delivers it and returns the acknowledgement unless told not to.
|
||||
func _send(deliver: bool = true, acknowledge: bool = true) -> PackedByteArray:
|
||||
tick += STEP
|
||||
var bytes: PackedByteArray = sender.build(HANDLE, sim, viewer.id, tick, Match.PLAY)
|
||||
packets.append(bytes)
|
||||
assert_true(bytes.size() <= Tuning.NET_SNAPSHOT_MAX_BYTES, "snapshot of %d bytes" % bytes.size())
|
||||
if deliver:
|
||||
receiver.apply(bytes)
|
||||
if acknowledge:
|
||||
sender.acknowledge(HANDLE, receiver.ack_tick())
|
||||
return bytes
|
||||
|
||||
|
||||
## Fails unless the client's picture is exactly what it may see, as it is now.
|
||||
func _assert_in_step(context: String) -> void:
|
||||
var visible: Array[int] = SnapshotSender.interest(sim, viewer)
|
||||
assert_eq(receiver.entities.size(), visible.size(), "%s: entity count" % context)
|
||||
for entity_id: int in visible:
|
||||
if not receiver.entities.has(entity_id):
|
||||
fail("%s: entity %d is missing" % [context, entity_id])
|
||||
continue
|
||||
assert_eq(receiver.entities[entity_id], NetSnapshot.record_of(sim.entities.find(entity_id)), "%s: entity %d" % [context, entity_id])
|
||||
|
||||
|
||||
func test_first_snapshot_is_full_and_later_ones_carry_only_changes() -> void:
|
||||
var other: SimEntity = _other(Vector3(520.0, 0.0, 500.0))
|
||||
var first: PackedByteArray = _send()
|
||||
assert_eq(NetSnapshot.decode_snapshot(first)["baseline"], 0)
|
||||
assert_eq(receiver.own_id, viewer.id)
|
||||
_assert_in_step("first")
|
||||
var quiet: Dictionary = NetSnapshot.decode_snapshot(_send())
|
||||
assert_eq(quiet["baseline"], tick - STEP)
|
||||
assert_eq((quiet["records"] as Array).size(), 0, "nothing moved")
|
||||
other.position.x += 1.0
|
||||
var moved: Dictionary = NetSnapshot.decode_snapshot(_send())
|
||||
assert_eq((moved["records"] as Array).size(), 1)
|
||||
assert_eq(moved["records"][0][2], 0b1, "only the position group")
|
||||
_assert_in_step("moved")
|
||||
assert_eq(sender.stats(HANDLE)["full"], 1)
|
||||
|
||||
|
||||
func test_header_carries_the_tide_the_clock_and_the_command_echo() -> void:
|
||||
sim.tide = Tide.new(0)
|
||||
sim.sea_level = 3.25
|
||||
sim.tick = 77
|
||||
sender.note_command(HANDLE, 75)
|
||||
sender.note_command(HANDLE, 60)
|
||||
_send()
|
||||
assert_near(receiver.sea_level, 3.25, 0.001)
|
||||
assert_eq(receiver.sim_tick, 77)
|
||||
assert_eq(receiver.command_tick, 75)
|
||||
assert_eq(receiver.match_phase, Match.PLAY)
|
||||
|
||||
|
||||
func test_the_client_recovers_from_lost_snapshots_and_lost_acknowledgements() -> void:
|
||||
var others: Array[SimEntity] = []
|
||||
for index: int in 12:
|
||||
others.append(_other(Vector3(480.0 + index * 4.0, 0.0, 510.0)))
|
||||
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
|
||||
rng.seed = 2026
|
||||
var delivered: int = 0
|
||||
for round: int in 400:
|
||||
for other: SimEntity in others:
|
||||
if rng.randf() < 0.6:
|
||||
other.position += Vector3(rng.randf_range(-1.0, 1.0), 0.0, rng.randf_range(-1.0, 1.0))
|
||||
other.yaw = rng.randi_range(0, 65535)
|
||||
if rng.randf() < 0.05:
|
||||
other.health = rng.randi_range(1, 100)
|
||||
if round == 150:
|
||||
sim.remove_player(others.pop_back().id)
|
||||
var arrives: bool = rng.randf() >= 0.4
|
||||
_send(arrives, rng.randf() >= 0.4)
|
||||
if arrives:
|
||||
delivered += 1
|
||||
_assert_in_step("round %d" % round)
|
||||
assert_true(delivered > 150 and delivered < 300, "the link lost a real share: %d of 400 arrived" % delivered)
|
||||
assert_eq(receiver.missing_baseline, 0, "a delta never builds on something the client didn't confirm")
|
||||
assert_eq(receiver.malformed, 0)
|
||||
assert_eq(sender.stats(HANDLE)["full"], 1, "loss alone never needs a second full snapshot")
|
||||
|
||||
|
||||
func test_duplicates_and_stale_snapshots_are_ignored() -> void:
|
||||
var other: SimEntity = _other(Vector3(520.0, 0.0, 500.0))
|
||||
var old: PackedByteArray = _send()
|
||||
other.position.x += 5.0
|
||||
var newer: PackedByteArray = _send()
|
||||
assert_false(receiver.apply(old), "an older snapshot arriving late")
|
||||
assert_false(receiver.apply(newer), "the same snapshot twice")
|
||||
assert_eq(receiver.ignored_old, 2)
|
||||
_assert_in_step("after repeats")
|
||||
|
||||
|
||||
func test_a_long_silence_falls_back_to_a_full_snapshot() -> void:
|
||||
var other: SimEntity = _other(Vector3(520.0, 0.0, 500.0))
|
||||
_send()
|
||||
# Longer than the server remembers: everything it could build on is forgotten.
|
||||
for _round: int in Tuning.NET_SNAPSHOT_HISTORY + 5:
|
||||
other.position.x += 0.1
|
||||
_send(false, false)
|
||||
var bytes: PackedByteArray = _send()
|
||||
assert_eq(NetSnapshot.decode_snapshot(bytes)["baseline"], 0)
|
||||
_assert_in_step("after the silence")
|
||||
assert_true(sender.stats(HANDLE)["full"] >= 2)
|
||||
|
||||
|
||||
func test_a_client_that_lost_its_baseline_asks_again_and_recovers() -> void:
|
||||
_other(Vector3(520.0, 0.0, 500.0))
|
||||
_send()
|
||||
_send()
|
||||
# A client that restarted its picture: it holds nothing the server builds on.
|
||||
receiver = SnapshotReceiver.new()
|
||||
_send()
|
||||
assert_eq(receiver.missing_baseline, 1)
|
||||
assert_eq(receiver.ack_tick(), 0)
|
||||
assert_eq(receiver.entities.size(), 0)
|
||||
_send()
|
||||
_assert_in_step("after asking again")
|
||||
|
||||
|
||||
func test_no_data_about_entities_outside_the_interest_area() -> void:
|
||||
var range: float = Tuning.NET_INTEREST_PLAYERS_METRES
|
||||
var near: SimEntity = _other(viewer.position + Vector3(range - 5.0, 0.0, 0.0))
|
||||
var far: SimEntity = _other(viewer.position + Vector3(range + 5.0, 0.0, 0.0))
|
||||
var far_item: int = Inventory.spawn_pickup(sim, viewer.position + Vector3(0.0, 0.0, Tuning.NET_INTEREST_PICKUPS_METRES + 3.0), 1, 1)
|
||||
var near_item: int = Inventory.spawn_pickup(sim, viewer.position + Vector3(0.0, 0.0, Tuning.NET_INTEREST_PICKUPS_METRES - 3.0), 1, 1)
|
||||
for _round: int in 10:
|
||||
far.position.z += 1.0
|
||||
far.health -= 1
|
||||
_send()
|
||||
assert_true(receiver.entities.has(near.id) and receiver.entities.has(near_item))
|
||||
for bytes: PackedByteArray in packets:
|
||||
var snapshot: Dictionary = NetSnapshot.decode_snapshot(bytes)
|
||||
for entry: Array in snapshot["records"]:
|
||||
assert_true(entry[0] != far.id and entry[0] != far_item, "a record for an entity out of range")
|
||||
assert_false((snapshot["removed"] as PackedInt32Array).has(far.id), "even its ID stays unsaid")
|
||||
# It walks into range: now the client hears of it, in full.
|
||||
far.position = viewer.position + Vector3(range - 1.0, 0.0, 0.0)
|
||||
_send()
|
||||
assert_true(receiver.entities.has(far.id))
|
||||
assert_eq(Array(receiver.added), [far.id])
|
||||
# And out again: it is removed, and nothing more is said about it.
|
||||
far.position = viewer.position + Vector3(range + 1.0, 0.0, 0.0)
|
||||
_send()
|
||||
assert_false(receiver.entities.has(far.id))
|
||||
assert_eq(Array(receiver.removed), [far.id])
|
||||
var before: int = packets.size()
|
||||
for _round: int in 5:
|
||||
far.position.z -= 1.0
|
||||
_send()
|
||||
for index: int in range(before, packets.size()):
|
||||
assert_eq((NetSnapshot.decode_snapshot(packets[index])["records"] as Array).size(), 0)
|
||||
_assert_in_step("at the end")
|
||||
|
||||
|
||||
func test_height_does_not_hide_a_player_overhead() -> void:
|
||||
var above: SimEntity = _other(viewer.position + Vector3(10.0, Tuning.BARGE_ALTITUDE, 0.0))
|
||||
_send()
|
||||
assert_true(receiver.entities.has(above.id))
|
||||
|
||||
|
||||
func test_a_crowd_is_spread_over_several_snapshots_nearest_first() -> void:
|
||||
var ids: Array[int] = []
|
||||
for index: int in 600:
|
||||
var angle: float = index * 0.37
|
||||
var reach: float = 2.0 + float(index) / 600.0 * (Tuning.NET_INTEREST_PICKUPS_METRES - 4.0)
|
||||
ids.append(Inventory.spawn_pickup(sim, viewer.position + Vector3(cos(angle) * reach, 0.0, sin(angle) * reach), 1, 1))
|
||||
var first: PackedByteArray = _send()
|
||||
assert_true(first.size() > Tuning.NET_SNAPSHOT_MAX_BYTES - 16, "the first snapshot is full to the brim")
|
||||
assert_true(receiver.entities.has(viewer.id), "the client's own player always travels")
|
||||
var got: int = receiver.entities.size() - 1
|
||||
assert_true(got > 50 and got < 600, "%d of 600 fitted" % got)
|
||||
var furthest_got: float = 0.0
|
||||
var nearest_missing: float = 1.0e9
|
||||
for entity_id: int in ids:
|
||||
var distance: float = sim.entities.find(entity_id).position.distance_to(viewer.position)
|
||||
if receiver.entities.has(entity_id):
|
||||
furthest_got = maxf(furthest_got, distance)
|
||||
else:
|
||||
nearest_missing = minf(nearest_missing, distance)
|
||||
assert_true(furthest_got <= nearest_missing + 0.1, "nearest first: got out to %.1f m, missing from %.1f m" % [furthest_got, nearest_missing])
|
||||
for _round: int in 12:
|
||||
_send()
|
||||
_assert_in_step("after a dozen snapshots")
|
||||
assert_true(sender.stats(HANDLE)["deferred"] > 0)
|
||||
|
||||
|
||||
func test_a_distant_entity_is_not_starved_by_a_busy_foreground() -> void:
|
||||
# More near entities changing every snapshot than one snapshot can hold.
|
||||
var busy: Array[SimEntity] = []
|
||||
for index: int in 200:
|
||||
busy.append(_other(viewer.position + Vector3(5.0 + index * 0.5, 0.0, 3.0)))
|
||||
var distant: SimEntity = _other(viewer.position + Vector3(0.0, 0.0, Tuning.NET_INTEREST_PLAYERS_METRES - 10.0))
|
||||
for _round: int in 30:
|
||||
_send()
|
||||
var seen: int = 0
|
||||
for round: int in 60:
|
||||
for other: SimEntity in busy:
|
||||
other.position.z += 0.25
|
||||
other.yaw = (other.yaw + 500) % 65536
|
||||
distant.position.x += 0.5
|
||||
var before: PackedInt32Array = receiver.entities.get(distant.id, PackedInt32Array())
|
||||
_send()
|
||||
if receiver.entities.get(distant.id, PackedInt32Array()) != before:
|
||||
seen += 1
|
||||
assert_true(sender.stats(HANDLE)["deferred"] > 0, "the snapshots really were over full")
|
||||
assert_true(seen >= 3, "the distant player was updated %d times in 60 snapshots" % seen)
|
||||
|
||||
|
||||
func test_a_new_match_starts_from_nothing() -> void:
|
||||
_other(Vector3(520.0, 0.0, 500.0))
|
||||
_send()
|
||||
_send()
|
||||
# A new simulation reuses entity IDs for different things.
|
||||
sender.reset()
|
||||
sim = Simulation.new(6, SimGround.flat())
|
||||
viewer = sim.entities.find(sim.add_player())
|
||||
viewer.position = Vector3(100.0, 0.0, 100.0)
|
||||
Inventory.spawn_pickup(sim, Vector3(101.0, 0.0, 100.0), 1, 1)
|
||||
var bytes: PackedByteArray = _send()
|
||||
assert_eq(NetSnapshot.decode_snapshot(bytes)["baseline"], 0)
|
||||
_assert_in_step("new match")
|
||||
assert_eq(receiver.malformed, 0)
|
||||
|
||||
|
||||
func test_no_viewer_means_an_empty_snapshot() -> void:
|
||||
_other(Vector3(520.0, 0.0, 500.0))
|
||||
tick += STEP
|
||||
var bytes: PackedByteArray = sender.build(HANDLE, sim, 0, tick, Match.LOBBY)
|
||||
assert_true(receiver.apply(bytes))
|
||||
assert_eq(receiver.entities.size(), 0)
|
||||
assert_eq(receiver.own_id, 0)
|
||||
assert_eq(receiver.match_phase, Match.LOBBY)
|
||||
@@ -0,0 +1 @@
|
||||
uid://cfvw1mabf2tdh
|
||||
Reference in New Issue
Block a user