diff --git a/README.md b/README.md index 54f7b75..dd4100b 100644 --- a/README.md +++ b/README.md @@ -318,7 +318,7 @@ The Audio tab has master/effects volume, mute and a test sound. The Graphics tab Changes apply immediately except anisotropic strength changes, which require restarting the game. Controls and graphics persist in `user://settings.cfg`, and existing audio preferences remain in `user://audio.cfg`. Esc returns to the previous menu. Fixed shortcuts remain available outside settings: F11 toggles fullscreen, F3 shows performance, F8 shows the netcode overlay, F4 toggles antialiasing, and F5/F6 cycle resolutions while paused. F10 quits from a menu. The server keeps running while menus are open; losing focus releases your controls, but incoming damage can continue. -For netcode debugging, the Graphics tab's **Route connections through the network simulator (debug)** option, or launching with `--netsim`, sends the next connection through a local relay that adds latency, jitter, loss and duplication in both directions. `--netsim-rtt=MS`, `--netsim-jitter=MS` (± round trip), `--netsim-loss=PERCENT` and `--netsim-duplicate=PERCENT` set starting conditions. The F8 overlay shows round-trip time, traffic, snapshot jitter and reconciliation corrections, has sliders that change the simulator's conditions live, and can draw a translucent ghost at the server's position for your ship. Normal connections never use the relay, and the option is not saved. +For netcode debugging, the Graphics tab's **Route connections through the network simulator (debug)** option, or launching with `--netsim`, sends the next connection through a local relay that adds latency, jitter, loss and duplication in both directions. `--netsim-rtt=MS`, `--netsim-jitter=MS` (± round trip), `--netsim-loss=PERCENT` and `--netsim-duplicate=PERCENT` set starting conditions. The F8 overlay shows round-trip time, traffic, snapshot jitter, unacknowledged and replayed inputs, the server's input buffer and lost, late and duplicate input counts, the simulation error at each reconciliation and the smoothed visual offset that hides it, has sliders that change the simulator's conditions live, and can draw a translucent ghost at the server's position for your ship. Normal connections never use the relay, and the option is not saved. The flight quickslot bar has ten mixed, rebindable slots (`1–0` by default). Its `+` button opens item categories and allows assigning, swapping or clearing items diff --git a/docs/netcode-baseline.md b/docs/netcode-baseline.md index 54e4c78..68821ba 100644 --- a/docs/netcode-baseline.md +++ b/docs/netcode-baseline.md @@ -3,8 +3,9 @@ Movement networking measured before the netcode rework (network schema 23), with the network simulator from phase 1 of the [real-time netcode rework](../GAME_PLAN.md#real-time-netcode-rework). Later -phases rerun the same benchmark unchanged; phase 6 folds these tables into -`docs/NETCODE.md`. +phases rerun the same benchmark and append their results below; phase 2 +redefined three metrics, as its section explains. Phase 6 folds these tables +into `docs/NETCODE.md`. ``` godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=baseline @@ -52,3 +53,91 @@ the header of `tests/netcode_benchmark.gd`. several seconds; the benchmark's warm-up covers that. - At 0 ms the 28 ms RTT and 16 ms jitter p95 mostly reflect frame timing in a single process hosting five sectors: ENet is serviced once per frame. + +## After phase 2: ticks, input sequencing and reconciliation + +Network schema 24. The same benchmark, scripted input and conditions, plus the +150 ± 30 ms, 5% loss condition used by phase 5 (`--scenario=degraded`). +Measured on the same Windows 11 desktop (92–118 frames per second). + +``` +godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=baseline +godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=degraded +``` + +Three metrics changed meaning, because the thing they measured changed (the +benchmark header has the full definitions): + +- **Sim error** replaces *prediction error*. It is how far rewinding to the + authoritative state and replaying the unacknowledged inputs moved the + predicted ship at each reconciliation. Zero means the server simulated + exactly what the client predicted. The old metric compared the predicted + ship with a round-trip-old position, which mostly measured latency. +- **Visual offset** replaces *correction*. Corrections no longer move the drawn + ship within a frame: the model and camera are drawn at a decaying offset + from the simulated ship. This is that offset, sampled every client tick. +- **Inputs** replace *commands*. Clients now send one input per 60 Hz tick + (30 packets per second, each repeating up to ten unacknowledged inputs). + *Lost* counts inputs the server skipped because they never arrived; late, + catch-up drops and starved ticks are the server's input buffer counters. + +| Added RTT | Loss | ENet RTT | Client up | Client down | Server to client | Snapshot jitter mean / p95 / max | Sim error mean / p95 / max | Visual offset mean / p95 / max | Gap to server now mean / p95 | Replay mean / max | Server buffer | Inputs sent / applied / lost | Late / dropped / starved | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 0 ms | 0% | 32 ms | 2.7 KB/s | 14.4 KB/s | 14.4 KB/s | 5.8 / 16.3 / 24.9 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 2.00 / 3.44 m | 4.5 / 6 | 2.8 | 1201 / 1201 / 0 | 0 / 0 / 0 | +| 100 ms | 0% | 107 ms | 3.5 KB/s | 14.9 KB/s | 14.9 KB/s | 4.5 / 10.1 / 23.6 ms | 0.00 / 0.00 / 0.01 m | 0.00 / 0.00 / 0.01 m | 2.99 / 5.14 m | 9.0 / 10 | 2.3 | 1200 / 1200 / 0 | 0 / 0 / 0 | +| 200 ms | 0% | 205 ms | 3.5 KB/s | 14.4 KB/s | 14.4 KB/s | 5.0 / 12.1 / 19.5 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 4.59 / 7.92 m | 15.3 / 18 | 2.5 | 1200 / 1199 / 0 | 0 / 0 / 1 | +| 0 ms | 5% | 32 ms | 3.1 KB/s | 14.5 KB/s | 15.0 KB/s | 8.0 / 22.9 / 70.3 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 2.90 / 5.08 m | 6.6 / 8 | 4.6 | 1200 / 1200 / 0 | 0 / 0 / 0 | +| 100 ms | 5% | 109 ms | 3.5 KB/s | 13.9 KB/s | 14.4 KB/s | 7.5 / 18.8 / 61.8 ms | 0.00 / 0.00 / 1.21 m | 0.01 / 0.00 / 1.05 m | 4.45 / 7.65 m | 12.3 / 15 | 5.2 | 1200 / 1200 / 0 | 0 / 2 / 0 | +| 200 ms | 5% | 208 ms | 3.5 KB/s | 13.2 KB/s | 14.4 KB/s | 9.8 / 48.8 / 116.0 ms | 0.00 / 0.00 / 0.62 m | 0.01 / 0.01 / 0.54 m | 5.75 / 9.93 m | 17.8 / 20 | 4.8 | 1200 / 1199 / 0 | 0 / 1 / 1 | +| 150 ± 30 ms | 5% | 158 ms | 3.5 KB/s | 13.7 KB/s | 14.4 KB/s | 12.9 / 33.1 / 71.8 ms | 0.00 / 0.00 / 0.00 m | 0.00 / 0.00 / 0.00 m | 4.96 / 8.51 m | 14.5 / 16 | 4.7 | 1200 / 1200 / 0 | 0 / 0 / 0 | + +### Observations + +- **Replays match the server.** Straight flight replays bit for bit. Turning + leaves float-rounding differences of a few millimetres, too small to show + in the table's two decimals. Larger corrections come only from the server's + input buffer policy: a catch-up drop or a starved tick shifts the server by + one tick of motion (0.5–1.4 m), and the visual offset hides it over about + 0.3 s. +- **No input is lost**, at any condition: each input travels in up to five + packets, so 5% loss and short bursts never leave a gap. +- **ENet's throttle no longer discards traffic at 200 ms.** The server now + sends its full snapshot rate at every condition (14.4 KB/s, against 6.3 and + 10.6 KB/s before). The fix is the throttle configuration below, not the + redundancy. +- **The gap to the server grew,** from 1.6/3.3 m to 3.0/4.6 m at 100/200 ms. + That is the intended effect of prediction: the local ship now runs ahead of + the server by the upstream delay plus the server's input buffer (2–5 ticks, + 33–83 ms) instead of being dragged back toward old snapshots. Controls + respond in the same frame at every latency. +- **Upload doubled** (1.1 to 3.5 KB/s) for 30 redundant input packets per + second; downstream is unchanged. + +### ENet packet throttle + +ENet throttles unreliable packets at the sender. Each peer keeps a packet +throttle (0–32) and drops that share of unreliable packets. Every throttle +interval (5 s) it compares the latest round trip with the previous interval's +mean: lower round trips accelerate the throttle, and a round trip above the +mean plus twice its variance decelerates it. With steady added delay the +variance is tiny, so ordinary frame-timing noise decelerates it repeatedly. +That produced the baseline's 25–35% loss of commands and snapshots at 200 ms. + +Clients and the server now call `ENetPacketPeer.throttle_configure(5000, 2, 0)` +on every server/client peer (`FlightSession.ENET_THROTTLE`). Deceleration 0 +keeps the throttle fully open. Dorbit's unreliable traffic is small and paced, +so it needs no congestion back-off. Reliable traffic keeps ENet's own +windowing, acknowledgements and resends, and the full suite of reliable +gameplay tests passes. Measured with the same phase 2 build, at 200 ms added +RTT: + +| ENet deceleration | Loss | Server to client | Snapshot jitter p95 | Sim error max | Starved / dropped | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 2 (ENet default) | 0% | 14.9 KB/s | 19.7 ms | 0.71 m | 1 / 2 | +| 2 (ENet default) | 5% | 10.5 KB/s | 126.6 ms | 2.16 m | 11 / 11 | +| 0 (phase 2) | 0% | 14.4 KB/s | 12.1 ms | 0.00 m | 1 / 0 | +| 0 (phase 2) | 5% | 14.4 KB/s | 48.8 ms | 0.62 m | 1 / 1 | + +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. diff --git a/scripts/flight_input.gd b/scripts/flight_input.gd new file mode 100644 index 0000000..f581aa2 --- /dev/null +++ b/scripts/flight_input.gd @@ -0,0 +1,90 @@ +class_name FlightInput +extends RefCounted +## Compact flight input packets from a client to the server. +## +## A client samples one input per physics tick (60 Hz): a per-connection +## sequence number, its local tick, movement, boost and the facing it requests. +## Every packet repeats the most recent unacknowledged inputs, so a lost packet +## costs nothing while a later one arrives. Sequence numbers in a packet are +## consecutive, so only the first is sent. +## +## Layout (little endian): +## u8 flags (FIRE), u32 life, i32 encounter, i32 target, u32 client tick of +## the newest input, u32 first sequence, u8 count, then per input: +## 3 x i8 movement (axis * 127), u16 yaw, i16 pitch, u8 flags (BOOST). +## Movement and facing are quantized here, and clients predict with the +## quantized values, so the server and the client simulate the same numbers. + +const FIRE := 1 +const BOOST := 1 +## Inputs per packet: at 30 packets per second (two inputs each) ten inputs +## cover a burst of four lost packets. A playtesting setting. +const REDUNDANCY := 10 +const MAX_INPUTS := 16 +const HEADER_SIZE := 22 +const INPUT_SIZE := 8 +const MOVEMENT_SCALE := 127.0 +const YAW_SCALE := 65536.0 / TAU +const PITCH_SCALE := 20000.0 +const PITCH_LIMIT := 1.48 + + +static func quantize_movement(movement: Vector3) -> Vector3: + var result := Vector3.ZERO + for axis in 3: + result[axis] = roundf(clampf(movement[axis], -1.0, 1.0) * MOVEMENT_SCALE) / MOVEMENT_SCALE + return result + + +## Facing as the server decodes it: yaw wrapped to [-PI, PI), pitch clamped. +static func quantize_facing(angles: Vector3) -> Vector3: + var yaw := posmod(roundi((wrapf(angles.y, -PI, PI) + PI) * YAW_SCALE), 65536) + var pitch := roundi(clampf(angles.x, -PITCH_LIMIT, PITCH_LIMIT) * PITCH_SCALE) + return Vector3(pitch / PITCH_SCALE, yaw / YAW_SCALE - PI, 0.0) + + +## `inputs` hold {seq, movement, boost, facing} with consecutive sequences. +static func encode(life: int, fire: bool, encounter: int, target: int, client_tick: int, inputs: Array) -> PackedByteArray: + var buffer := StreamPeerBuffer.new() + buffer.put_u8(FIRE if fire else 0) + buffer.put_u32(life) + buffer.put_32(encounter) + buffer.put_32(target) + buffer.put_u32(client_tick) + buffer.put_u32(inputs[0]["seq"] if not inputs.is_empty() else 0) + buffer.put_u8(inputs.size()) + for input: Dictionary in inputs: + var movement: Vector3 = input["movement"] + for axis in 3: + buffer.put_8(roundi(clampf(movement[axis], -1.0, 1.0) * MOVEMENT_SCALE)) + var facing: Vector3 = input["facing"] + buffer.put_u16(posmod(roundi((wrapf(facing.y, -PI, PI) + PI) * YAW_SCALE), 65536)) + buffer.put_16(roundi(clampf(facing.x, -PITCH_LIMIT, PITCH_LIMIT) * PITCH_SCALE)) + buffer.put_u8(BOOST if input["boost"] else 0) + return buffer.data_array + + +## Returns {fire, life, encounter, target, tick, inputs: [{seq, movement, +## boost, facing}]}, or {} for a malformed packet. Values are always finite +## and in range, whatever the sender wrote. +static func decode(packet: PackedByteArray) -> Dictionary: + if packet.size() < HEADER_SIZE: + return {} + var buffer := StreamPeerBuffer.new() + buffer.data_array = packet + var result := {"fire": buffer.get_u8() & FIRE != 0, "life": buffer.get_u32(), "encounter": buffer.get_32(), + "target": buffer.get_32(), "tick": buffer.get_u32(), "inputs": []} + var first := buffer.get_u32() + var count := buffer.get_u8() + if count < 1 or count > MAX_INPUTS or packet.size() != HEADER_SIZE + count * INPUT_SIZE: + return {} + for index in count: + var movement := Vector3.ZERO + for axis in 3: + movement[axis] = clampi(buffer.get_8(), -127, 127) / MOVEMENT_SCALE + var yaw := buffer.get_u16() + var pitch := clampi(buffer.get_16(), -roundi(PITCH_LIMIT * PITCH_SCALE), roundi(PITCH_LIMIT * PITCH_SCALE)) + result["inputs"].append({"seq": first + index, "movement": movement, + "facing": Vector3(pitch / PITCH_SCALE, yaw / YAW_SCALE - PI, 0.0), + "boost": buffer.get_u8() & BOOST != 0}) + return result diff --git a/scripts/flight_input.gd.uid b/scripts/flight_input.gd.uid new file mode 100644 index 0000000..9da92b9 --- /dev/null +++ b/scripts/flight_input.gd.uid @@ -0,0 +1 @@ +uid://qwlgiboqby6m diff --git a/scripts/flight_prediction.gd b/scripts/flight_prediction.gd new file mode 100644 index 0000000..c2be169 --- /dev/null +++ b/scripts/flight_prediction.gd @@ -0,0 +1,102 @@ +class_name FlightPrediction +extends RefCounted +## Client-side prediction and reconciliation of the local pilot. +## +## Each client physics tick samples one input, keeps it until the server +## acknowledges it, and simulates it at once with Pilot.simulate_input(), the +## same step the server runs per consumed input. Each new owner snapshot names +## the last input the server processed: the client drops acknowledged inputs, +## resets the ship's simulation state (position, velocity, energy, facing and +## turn budget) to the authoritative state and replays the rest in the same +## physics tick. The replay never touches the view facing, so mouse steering +## stays immediate. +## +## Corrections are hidden by drawing the model and camera at a world-space +## offset from the simulated ship, which decays exponentially. The simulation +## itself is never smoothed. + +## Physics ticks between input packets (30 packets per second). +const SEND_INTERVAL_TICKS := 2 +## Unacknowledged inputs kept for replay (two seconds); older ones are dropped. +const MAX_PENDING := 120 +## Time constant of the decaying correction offset, in seconds: about 63% of +## a correction is hidden after this long and 95% after three times as long. +## A playtesting setting. +const SMOOTHING_TIME := 0.12 +## Corrections larger than this, in metres, snap instead of smoothing. +const SNAP_DISTANCE := 10.0 + +## Sequence of the next sampled input. Sequences rise for the whole connection. +var next_seq: int = 1 +var client_tick: int = 0 +## Unacknowledged inputs, oldest first: {seq, tick, movement, boost, facing}. +var pending: Array[Dictionary] = [] +## Newest owner state awaiting reconciliation, or {}. +var authoritative: Dictionary = {} +var last_ack: int = 0 + + +## Forgets inputs and the correction offset at a discontinuity (connect, +## spawn, respawn, jump, dock or launch). The next snapshot re-anchors the +## simulation. +func reset(ship: Pilot) -> void: + pending.clear() + authoritative = {} + ship.sim_rotation = ship.rotation + ship.turn_budget = Pilot.MAX_TURN_RATE * (1.0 / Engine.physics_ticks_per_second + Pilot.TURN_LATENCY_ALLOWANCE) + ship.set_visual_offset(Vector3.ZERO) + + +## Samples this tick's input and predicts it. +func predict(ship: Pilot, delta: float, movement: Vector3, boost: bool) -> void: + ship.apply_look(delta) + # Predict with exactly the facing the server will decode. + var facing := FlightInput.quantize_facing(ship.rotation) + ship.rotation = facing + var input := {"seq": next_seq, "tick": client_tick, "movement": FlightInput.quantize_movement(movement), "boost": boost, "facing": facing} + next_seq += 1 + pending.append(input) + if pending.size() > MAX_PENDING: + pending.pop_front() + ship.simulate_input(delta, input["movement"], boost, facing) + ship.present_motion(delta, input["movement"]) + + +## The newest unacknowledged inputs, ready to send. +func packet(life: int, fire: bool, encounter: int, target: int) -> PackedByteArray: + var inputs := pending.slice(maxi(0, pending.size() - FlightInput.REDUNDANCY)) + return FlightInput.encode(life, fire, encounter, target, client_tick, inputs) + + +## Rewinds to the newest authoritative state and replays unacknowledged +## inputs. Call from a physics tick: move_and_slide() uses the physics delta. +func reconcile(ship: Pilot, delta: float, stats: NetStats) -> void: + if authoritative.is_empty(): + return + var state := authoritative + authoritative = {} + var ack: int = state.get("ack", last_ack) + var ack_lag := -1 + while not pending.is_empty() and pending[0]["seq"] <= ack: + ack_lag = client_tick - int(pending[0]["tick"]) + pending.pop_front() + last_ack = maxi(last_ack, ack) + var predicted := ship.position + ship.position = state["position"] + ship.velocity = state["velocity"] + ship.energy = state["energy"] + ship.sim_rotation = state["rotation"] + ship.turn_budget = state.get("turn_budget", ship.turn_budget) + for input: Dictionary in pending: + ship.simulate_input(delta, input["movement"], input["boost"], input["facing"]) + var error := predicted.distance_to(ship.position) + var offset := ship.visual_offset + predicted - ship.position + ship.set_visual_offset(Vector3.ZERO if offset.length() > SNAP_DISTANCE else offset) + stats.record_reconciliation(error, pending.size(), ack_lag, int(state.get("input_depth", -1))) + + +## Decays the correction offset by one tick and re-applies it under the +## current view rotation. +func smooth(ship: Pilot, delta: float) -> void: + var offset := ship.visual_offset * exp(-delta / SMOOTHING_TIME) + ship.set_visual_offset(Vector3.ZERO if offset.length_squared() < 1e-8 else offset) diff --git a/scripts/flight_prediction.gd.uid b/scripts/flight_prediction.gd.uid new file mode 100644 index 0000000..5e264a8 --- /dev/null +++ b/scripts/flight_prediction.gd.uid @@ -0,0 +1 @@ +uid://lt2u101iq6mj diff --git a/scripts/flight_session.gd b/scripts/flight_session.gd index e5b257a..299b48a 100644 --- a/scripts/flight_session.gd +++ b/scripts/flight_session.gd @@ -4,10 +4,19 @@ extends Node const PORT: int = 24567 const MAX_PLAYERS: int = 10 -const COMMAND_TIMEOUT: float = 0.5 +## Server ticks a pilot's latest fire intent stays valid without new input packets. +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 = 23 +const NETWORK_SCHEMA: int = 24 +## 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 +## previous interval's by twice its variance, which a steady high-latency link +## does constantly. Dorbit's unreliable traffic is small and paced, and inputs +## are redundant, so deceleration 0 keeps the throttle open. Reliable traffic +## keeps ENet's own windowing and resends. +const ENET_THROTTLE := [5000, 2, 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 @@ -15,7 +24,16 @@ var active: bool = false var connecting: bool = false var status: String = "Choose a server and connect." var ships: Dictionary[int, Pilot] = {} +## Server: each pilot's latest intent from its newest input packet: +## {movement, rotation, boost, fire, encounter, target, seq, tick}. Movement +## comes from input_buffers; this keeps fire and targeting. var commands: Dictionary[int, Dictionary] = {} +## Server: buffered flight inputs per pilot, consumed one per tick. +var input_buffers: Dictionary[int, InputBuffer] = {} +## Server simulation tick, advanced once per server physics tick. +var server_tick: int = 0 +## Client: local pilot inputs, prediction and reconciliation. +var prediction := FlightPrediction.new() var goals: Dictionary[int, Dictionary] = {} var send_clock: float = 0.0 var connect_clock: float = 0.0 @@ -345,6 +363,7 @@ func protocol_fingerprint(schema: int = NETWORK_SCHEMA) -> String: func begin_authentication(id: int) -> void: if not multiplayer.is_server(): return + configure_throttle(id) var nonce := Crypto.new().generate_random_bytes(32) if sector.dedicated_server else PackedByteArray([0]) challenges[id] = nonce multiplayer.send_auth(id, JSON.stringify({"nonce": nonce.hex_encode(), "protocol": protocol_fingerprint()}).to_utf8_buffer()) @@ -461,6 +480,8 @@ func start_flight() -> void: sector.player.rotation = Vector3.ZERO sector.player.map_id = 0 sector.player.map_visit = 0 + prediction = FlightPrediction.new() + prediction.reset(sector.player) sector.activate_map(0) # Players cannot push each other, but can block weapon line of sight. sector.player.collision_mask = 1 @@ -471,7 +492,18 @@ func start_flight() -> void: menu.hide() +## Applies ENET_THROTTLE to one ENet peer (ENet tells the other end too). +func configure_throttle(id: int) -> void: + var enet := multiplayer.multiplayer_peer as ENetMultiplayerPeer + if enet == null: + return + var peer := enet.get_peer(id) + if peer != null: + peer.throttle_configure(ENET_THROTTLE[0], ENET_THROTTLE[1], ENET_THROTTLE[2]) + + func connected() -> void: + configure_throttle(1) if sector.client_only: preferences.remember(attempted_address, attempted_port) sector.preflight = sector.client_only @@ -616,7 +648,7 @@ func dock_request() -> void: ship.velocity = Vector3.ZERO combat.records[id]["life"] += 1 ship.set_meta("life", combat.records[id]["life"]) - commands.erase(id) + clear_commands(id) for enemy: Alien in sector.world_aliens.values(): enemy.contributors.erase(id) for peer_id in multiplayer.get_peers(): @@ -640,6 +672,7 @@ func flight_docked(id: int, data: Dictionary, sequence: int) -> void: sector.player.rotation = data["rotation"] sector.player.velocity = Vector3.ZERO sector.player.energy = data["energy"] + prediction.reset(sector.player) sector.set_paused(true) sector.main_menu.show_home() # Keep a sequence barrier when an observer later receives the same peer's relaunch. @@ -656,7 +689,7 @@ func launch_request() -> void: ships[id].set_meta("docked", false) ships[id].show() ships[id].collision_layer = 2 - commands.erase(id) + clear_commands(id) for peer_id in multiplayer.get_peers(): if peer_id != id: spawn.rpc_id(peer_id, id, ships[id].position) @@ -671,6 +704,7 @@ func flight_launched(id: int) -> void: ships[id].show() ships[id].collision_layer = 2 if id == multiplayer.get_unique_id(): + prediction.reset(sector.player) sector.preflight = false sector.main_menu.hide() sector.main_menu.hide_pages() @@ -716,6 +750,7 @@ func despawn(id: int) -> void: profile_revisions.erase(Vector2i(1, id)) ships.erase(id) commands.erase(id) + input_buffers.erase(id) goals.erase(id) player_sequences.erase(id) combat.remove_player(id) @@ -737,6 +772,7 @@ func tick(delta: float) -> void: var boost := not sector.dedicated_server and not sector.paused and not sector.autopilot.enabled and Input.is_action_pressed("boost") send_clock += delta if multiplayer.is_server(): + server_tick += 1 var phase_started := Time.get_ticks_usec() if benchmark_timing else 0 if benchmark_timing: benchmark_phases.clear() if sector.dedicated_server: @@ -756,11 +792,7 @@ func tick(delta: float) -> void: if not ship.alive: continue if id != 1: - var command: Dictionary = commands.get(id, {}) - var fresh: bool = not command.is_empty() and Time.get_ticks_msec() - command["time"] < COMMAND_TIMEOUT * 1000 - if fresh: - ship.turn_toward(command["rotation"], delta) - ship.fly_command(delta, command["movement"] if fresh else Vector3.ZERO, command["boost"] if fresh else false) + simulate_pilot(id, delta) sector.tick_radiation(ship, delta) if benchmark_timing: benchmark_phases["flight_us"] = Time.get_ticks_usec() - phase_started @@ -779,15 +811,7 @@ func tick(delta: float) -> void: if connect_clock >= CONNECT_TIMEOUT: disconnect_session("Connected, but no sector arrived. Check that client and server builds match, then try again.") return - if sector.player.alive: - if not sector.preflight: - sector.player.fly_command(delta, movement, boost) - if send_clock >= 0.05: - send_clock = 0.0 - var enemy := sector.target as Alien - if not sector.preflight: - net_stats.commands_sent += 1 - command_flight.rpc_id(1, movement, sector.player.rotation, boost, sector.auto_fire and enemy != null and not sector.paused, int(sector.player.get_meta("life", 0)), enemy.life if enemy != null else -1, enemy.alien_id if enemy != null else -1) + 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: @@ -802,11 +826,69 @@ func tick(delta: float) -> void: ship.rotation.y = lerp_angle(ship.rotation.y, angles.y, minf(1.0, delta * 15.0)) +## Server: consumes this tick's input for a remote pilot and simulates it with +## the same step the owner predicts with. Only movement, boost and requested +## facing come from the client; position and velocity never do. +func simulate_pilot(id: int, delta: float) -> void: + var ship := ships[id] + var buffer: InputBuffer = input_buffers.get_or_add(id, InputBuffer.new()) + var input := buffer.consume() + var movement: Vector3 = input.get("movement", Vector3.ZERO) + # Keep the exact simulation facing between ticks. Reading `rotation` back + # after move_and_slide() decomposes the basis, so it is adopted only when + # something else (spawn, jump, dock or respawn) set a new facing. + if not ship.rotation.is_equal_approx(ship.sim_rotation): + ship.sim_rotation = ship.rotation + # Idle pilots hold their facing and brake. + ship.simulate_input(delta, movement, input.get("boost", false), input.get("facing", ship.rotation)) + ship.rotation = ship.sim_rotation + ship.present_motion(delta, movement) + + +## Client: reconciles the local ship against the newest snapshot, then samples, +## predicts and periodically sends this tick's input. +func predict_local(delta: float, movement: Vector3, boost: bool) -> void: + prediction.client_tick += 1 + var ship := sector.player + if not ship.alive or sector.preflight: + ship.set_visual_offset(Vector3.ZERO) + return + prediction.reconcile(ship, delta, net_stats) + prediction.predict(ship, delta, movement, boost) + net_stats.inputs_sent += 1 + if prediction.client_tick % FlightPrediction.SEND_INTERVAL_TICKS == 0: + var enemy := sector.target as Alien + net_stats.input_packets_sent += 1 + flight_inputs.rpc_id(1, prediction.packet(int(ship.get_meta("life", 0)), sector.auto_fire and enemy != null and not sector.paused, + enemy.life if enemy != null else -1, enemy.alien_id if enemy != null else -1)) + prediction.smooth(ship, delta) + net_stats.unacked_inputs = prediction.pending.size() + net_stats.record_visual_offset(ship.visual_offset.length()) + + +## Sends one input outside local prediction, for scripted clients and tests. +## The server validates it exactly like predicted inputs. +func send_command(movement: Vector3, angles: Vector3, boost: bool, fire: bool = false, life: int = 0, encounter: int = 0, target_id: int = -1) -> void: + var input := {"seq": prediction.next_seq, "movement": movement, "boost": boost, "facing": angles} + prediction.next_seq += 1 + flight_inputs.rpc_id(1, FlightInput.encode(life, fire, encounter, target_id, prediction.client_tick, [input])) + + +## Server: forgets a pilot's intent and buffered inputs when its flight or life +## ends, so nothing from the previous flight can steer or fire. +func clear_commands(id: int) -> void: + commands.erase(id) + if input_buffers.has(id): + input_buffers[id].reset() + + ## Player snapshot including transform. `owner_view` adds private progress and is ## sent only to the owning peer. func player_state(id: int, owner_view: bool) -> Dictionary: var ship := ships[id] - var data := {"position": ship.position, "rotation": ship.rotation, "velocity": ship.velocity, "energy": ship.energy} + # Remote pilots send their exact simulation facing, which owners replay from. + var facing := ship.sim_rotation if id != 1 and ship.rotation.is_equal_approx(ship.sim_rotation) else ship.rotation + var data := {"position": ship.position, "rotation": facing, "velocity": ship.velocity, "energy": ship.energy} data.merge(combat.pack_player(id, owner_view)) return data @@ -850,13 +932,18 @@ func send_snapshot() -> void: visible[id] = profiles[id] var map := ships[viewer].map_id send_profiles(viewer, visible, alien_profiles_by_map[map]) - world_snapshot.rpc_id(viewer, SnapshotCodec.world(snapshot_sequence, ships[viewer].map_visit, players, map_aliens[map])) + world_snapshot.rpc_id(viewer, SnapshotCodec.world(snapshot_sequence, ships[viewer].map_visit, server_tick, players, map_aliens[map])) ## Private ammunition, rocket and boost state carried in the owner's entry. func owner_extras(id: int) -> Dictionary: var ship := ships[id] - var extras := {"rounds": combat.ammo_rounds(id), "rockets": ship.rockets.state()} + var extras := {"rounds": combat.ammo_rounds(id), "rockets": ship.rockets.state(), "turn_budget": ship.turn_budget} + if input_buffers.has(id): + var buffer := input_buffers[id] + extras["ack"] = maxi(buffer.last_seq, 0) + extras["depth"] = buffer.depth() + extras["inputs"] = buffer.counters() if sector.dedicated_server: extras["boosts"] = ship.resource_boosts extras["revision"] = store.pilots[pilot_ids[id]]["equipment"]["revision"] @@ -892,24 +979,30 @@ func send_profiles(viewer: int, players: Dictionary, aliens: Dictionary) -> void entity_profiles.rpc_id(viewer, changed_players, changed_aliens) -@rpc("any_peer", "call_remote", "unreliable_ordered", 1) -func command_flight(movement: Vector3, angles: Vector3, boost: bool, fire: bool = false, life: int = 0, encounter: int = 0, target_id: int = -1) -> void: +## A client's recent flight inputs; see FlightInput. Unsequenced: the input +## buffer orders and deduplicates them, and stale fire intent is ignored. +@rpc("any_peer", "call_remote", "unreliable", 1) +func flight_inputs(packet: PackedByteArray) -> void: if not active or not multiplayer.is_server(): return var id := multiplayer.get_remote_sender_id() - if not ships.has(id) or not movement.is_finite() or not angles.is_finite(): + var decoded := FlightInput.decode(packet) + if not ships.has(id) or decoded.is_empty(): return if ships[id].get_meta("docked", false): return - if not ships[id].alive or combat.records[id]["life"] != life: + if not ships[id].alive or combat.records[id]["life"] != decoded["life"]: return - net_stats.record_command_received(id) - commands[id] = { - "movement": movement.limit_length(), - "rotation": Vector3(clampf(angles.x, -1.48, 1.48), wrapf(angles.y, -PI, PI), 0), - "boost": boost, "time": Time.get_ticks_msec(), - "fire": fire, "encounter": encounter, "target": target_id, - } + var buffer: InputBuffer = input_buffers.get_or_add(id, InputBuffer.new()) + for input: Dictionary in decoded["inputs"]: + buffer.receive(input["seq"], {"movement": input["movement"].limit_length(), "boost": input["boost"], "facing": input["facing"]}) + var newest: Dictionary = decoded["inputs"][-1] + if newest["seq"] >= int(commands.get(id, {}).get("seq", -1)): + commands[id] = { + "movement": newest["movement"].limit_length(), "rotation": newest["facing"], "boost": newest["boost"], + "fire": decoded["fire"], "encounter": decoded["encounter"], "target": decoded["target"], + "seq": newest["seq"], "tick": server_tick, + } @rpc("authority", "call_remote", "reliable") @@ -932,6 +1025,7 @@ func world_snapshot(packet: PackedByteArray) -> void: return var sequence: int = world["sequence"] var visit: int = world["visit"] + net_stats.server_tick = maxi(net_stats.server_tick, world["tick"]) var owner: Dictionary = world["owner"] if not owner.is_empty(): combat.ammo_snapshot(owner["rounds"], sequence, owner["rockets"], visit) @@ -979,19 +1073,33 @@ func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit: if reset: ship.position = data["position"] ship.rotation = data["rotation"] - ship.energy = data["energy"] - if ship == sector.player: - # Predict locally for immediate controls; reconcile against host position. - var location: Vector3 = data["position"] - var predicted := ship.position - if not received_snapshot or ship.position.distance_to(location) > 10.0: - ship.position = location + if ship != sector.player: + ship.energy = data["energy"] + else: + var authoritative := {"position": data["position"], "rotation": data["rotation"], "energy": data["energy"], + "velocity": data["velocity"] if ship.alive else Vector3.ZERO} + for key: String in ["ack", "input_depth", "turn_budget"]: + if data.has(key): + authoritative[key] = data[key] + if reset or not received_snapshot: + # A new life or connection starts from the server's state. + prediction.reset(ship) + ship.position = data["position"] + ship.velocity = authoritative["velocity"] + ship.energy = data["energy"] + ship.sim_rotation = data["rotation"] + ship.turn_budget = authoritative.get("turn_budget", ship.turn_budget) + prediction.last_ack = maxi(prediction.last_ack, int(authoritative.get("ack", 0))) else: - ship.position = ship.position.lerp(location, 0.2) - if received_snapshot and not reset: - net_stats.record_correction(predicted.distance_to(location), predicted.distance_to(ship.position)) - net_stats.record_server_state(location, data["rotation"]) - ship.velocity = data["velocity"] if ship.alive else Vector3.ZERO + # Rewind and replay in the next physics tick (FlightPrediction.reconcile). + prediction.authoritative = authoritative + if prediction.pending.is_empty(): + # Nothing to replay while not predicting (docked, destroyed or + # scripted): adopt the state now, without move_and_slide(). + prediction.reconcile(ship, 1.0 / Engine.physics_ticks_per_second, net_stats) + net_stats.record_server_state(data["position"], data["rotation"]) + if data.has("inputs"): + net_stats.server_inputs = data["inputs"] received_snapshot = true status = "Connected. Players: %d/%d" % [ships.size(), MAX_PLAYERS] @@ -1021,6 +1129,8 @@ func disconnect_session(message: String) -> void: ship.queue_free() ships.clear() commands.clear() + input_buffers.clear() + server_tick = 0 goals.clear() received_snapshot = false snapshot_sequence = 0 @@ -1210,7 +1320,7 @@ func transfer(id: int, destination: int) -> void: ship.rockets.unload() combat.records[id]["life"] += 1 ship.set_meta("life", combat.records[id]["life"]) - commands.erase(id) + clear_commands(id) for enemy: Alien in sector.world_aliens.values(): enemy.contributors.erase(id) announce_map_change(id) @@ -1233,6 +1343,9 @@ func map_changed(id: int, data: Dictionary, sequence: int) -> void: ship.rotation = data["rotation"] ship.energy = data["energy"] ship.velocity = data["velocity"] + if ship == sector.player: + prediction.reset(ship) + ship.sim_rotation = data["rotation"] goals.erase(id) player_sequences[id] = maxi(player_sequences.get(id, -1), sequence) if ship == sector.player: diff --git a/scripts/input_buffer.gd b/scripts/input_buffer.gd new file mode 100644 index 0000000..b40ddd0 --- /dev/null +++ b/scripts/input_buffer.gd @@ -0,0 +1,144 @@ +class_name InputBuffer +extends RefCounted +## Server-side flight inputs of one pilot, consumed one per server tick. +## +## Inputs arrive redundantly and possibly out of order. `receive()` keeps each +## sequence number once; `consume()`, called exactly once per server tick, +## applies the oldest buffered input in sequence order. +## +## Starvation: when no input is buffered, the tick reuses the last applied +## input without advancing the sequence, so a ship keeps its course through a +## late packet. Each starved tick delays the inputs behind it by one tick, so +## the buffer grows by itself to cover the jitter it sees. After +## TIMEOUT_TICKS starved ticks the pilot is treated as idle (no thrust, no +## boost, facing held), and its ship brakes. +## +## Catch-up: latency stays bounded. If the smallest depth seen after consuming +## over CATCH_UP_WINDOW ticks exceeds SPARE_DEPTH, the oldest surplus inputs +## are dropped. Depth beyond MAX_DEPTH is dropped at once. Dropped inputs are +## counted separately from inputs that never arrived. +## +## Counters (cumulative for the connection): applied, duplicates (already +## buffered or applied), late (arrived after their tick was skipped), lost +## (sequence gaps skipped: never applied), dropped (discarded by catch-up or +## overflow) and starved (ticks without a new input, until the timeout). + +## Ticks without new input before the ship is treated as idle (0.5 s). +const TIMEOUT_TICKS := 30 +## Ticks over which the minimum depth is observed before catching up (2 s). +const CATCH_UP_WINDOW := 120 +## Spare buffered inputs kept for jitter; more for a whole window is surplus. +const SPARE_DEPTH := 2 +## Hard bound on buffered inputs (200 ms of extra input latency). +const MAX_DEPTH := 12 +## Remembered skipped sequences, for classifying late arrivals. +const MISSED_MEMORY := 256 + +var pending: Dictionary[int, Dictionary] = {} +## Last applied or skipped sequence, or -1 before the first input. +var last_seq: int = -1 +## Last applied input, reused while starved. +var last_input: Dictionary = {} +## Consecutive ticks without a new input. +var starved_ticks: int = 0 +var applied: int = 0 +var duplicates: int = 0 +var late: int = 0 +var lost: int = 0 +var dropped: int = 0 +var starved: int = 0 +var received: int = 0 +var _resync: bool = true +var _missed: Dictionary[int, bool] = {} +var _window_min: int = 1 << 30 +var _window_ticks: int = 0 + + +func depth() -> int: + return pending.size() + + +func receive(seq: int, input: Dictionary) -> void: + received += 1 + if seq <= last_seq: + if _missed.erase(seq): + late += 1 + else: + duplicates += 1 + return + if pending.has(seq): + duplicates += 1 + return + pending[seq] = input + if pending.size() > MAX_DEPTH * 2: + # A flood cannot grow the buffer; the oldest inputs give way. + drop_oldest(pending.size() - MAX_DEPTH * 2) + + +## Returns the input for this tick: the next buffered input, the last one +## while starved, or {} once idle (no input yet, or past the timeout). +func consume() -> Dictionary: + if pending.is_empty(): + _window_min = 0 + _window_ticks += 1 + if last_input.is_empty() or starved_ticks >= TIMEOUT_TICKS: + return {} + starved_ticks += 1 + starved += 1 + return last_input + var seq: int = pending.keys().min() + advance_to(seq) + last_input = pending[seq] + pending.erase(seq) + applied += 1 + starved_ticks = 0 + if pending.size() > MAX_DEPTH: + drop_oldest(pending.size() - MAX_DEPTH) + _window_min = mini(_window_min, pending.size()) + _window_ticks += 1 + if _window_ticks >= CATCH_UP_WINDOW: + if _window_min > SPARE_DEPTH: + drop_oldest(_window_min - SPARE_DEPTH) + _window_ticks = 0 + _window_min = 1 << 30 + if _missed.size() > MISSED_MEMORY: + for old: int in _missed.keys(): + if old < last_seq - MISSED_MEMORY: + _missed.erase(old) + return last_input + + +func drop_oldest(count: int) -> void: + var order := pending.keys() + order.sort() + for index in mini(count, order.size()): + advance_to(order[index]) + pending.erase(order[index]) + dropped += 1 + + +## Moves past `seq`, counting any sequences skipped on the way as lost. +func advance_to(seq: int) -> void: + if not _resync and seq > last_seq + 1: + lost += seq - last_seq - 1 + for skipped in range(maxi(last_seq + 1, seq - MISSED_MEMORY), seq): + _missed[skipped] = true + _resync = false + last_seq = maxi(last_seq, seq) + + +## Discards buffered inputs when a life ends (dock, jump, death or relaunch). +## Counters persist; the next accepted input starts a new run without +## counting the gap before it as lost. +func reset() -> void: + pending.clear() + last_input = {} + starved_ticks = 0 + _resync = true + _window_min = 1 << 30 + _window_ticks = 0 + + +func counters() -> Dictionary: + return {"applied": applied, "duplicates": duplicates, "late": late, "lost": lost, + "dropped": dropped, "starved": starved, "received": received} diff --git a/scripts/input_buffer.gd.uid b/scripts/input_buffer.gd.uid new file mode 100644 index 0000000..adb8126 --- /dev/null +++ b/scripts/input_buffer.gd.uid @@ -0,0 +1 @@ +uid://cw5tnffey85kj diff --git a/scripts/net_stats.gd b/scripts/net_stats.gd index c41b705..2cac64f 100644 --- a/scripts/net_stats.gd +++ b/scripts/net_stats.gd @@ -12,11 +12,19 @@ extends RefCounted ## - snapshot jitter: for each world snapshot, |time since the previous one - ## 50 ms|, as handled by the client (so it includes frame quantization). The ## mean and maximum cover the last JITTER_WINDOW intervals. -## - error_m: distance between the predicted local ship and the authoritative -## position in a snapshot, before reconciliation. -## - correction_m: how far reconciliation then moved the local ship. -## - commands_sent: flight commands the client sent. The server counts the -## commands it accepted per pilot in commands_received. +## - error_m: simulation error at reconciliation: how far rewinding to the +## authoritative state and replaying unacknowledged inputs moved the +## predicted ship. Zero when the server simulated exactly what was predicted. +## - offset_m: the decaying visual offset that hides those corrections, sampled +## once per physics tick: how far the drawn ship is from the simulated one. +## - replayed_ticks: unacknowledged inputs replayed at a reconciliation. +## - ack_lag_ticks: client ticks between sampling the newest acknowledged +## input and its acknowledgement arriving (round trip plus server buffering). +## - server_input_depth: inputs the server had buffered for this pilot. +## - inputs_sent / input_packets_sent: inputs sampled and packets sent; each +## packet repeats recent unacknowledged inputs. +## - server_inputs: the server's counters for this pilot's inputs (see +## InputBuffer): applied, duplicates, late, lost, dropped and starved. const SNAPSHOT_INTERVAL_MS := 50.0 const JITTER_WINDOW := 100 @@ -34,20 +42,27 @@ var snapshots_received: int = 0 var snapshot_intervals: PackedFloat32Array = [] var latest_error_m: float = 0.0 var max_error_m: float = 0.0 -var latest_correction_m: float = 0.0 -var max_correction_m: float = 0.0 +var latest_offset_m: float = 0.0 +var max_offset_m: float = 0.0 var corrections: int = 0 +var replayed_ticks: int = 0 +var max_replayed_ticks: int = 0 +var ack_lag_ticks: int = 0 +var server_input_depth: int = -1 +var unacked_inputs: int = 0 +var server_tick: int = 0 +var server_inputs: Dictionary = {} ## Last authoritative state of the local ship, for the server ghost. var has_server_state: bool = false var server_position: Vector3 = Vector3.ZERO var server_rotation: Vector3 = Vector3.ZERO -var commands_sent: int = 0 -## Server only: accepted flight commands per peer. -var commands_received: Dictionary[int, int] = {} +var inputs_sent: int = 0 +var input_packets_sent: int = 0 ## When true, every error, correction and jitter sample is kept for percentiles. var keep_samples: bool = false var error_samples: PackedFloat32Array = [] -var correction_samples: PackedFloat32Array = [] +var offset_samples: PackedFloat32Array = [] +var replay_samples: PackedFloat32Array = [] var jitter_samples: PackedFloat32Array = [] var _last_arrival_usec: int = -1 @@ -69,8 +84,13 @@ func reset() -> void: snapshots_received = 0 snapshot_intervals = PackedFloat32Array() has_server_state = false - commands_sent = 0 - commands_received.clear() + inputs_sent = 0 + input_packets_sent = 0 + unacked_inputs = 0 + server_tick = 0 + server_inputs = {} + server_input_depth = -1 + ack_lag_ticks = 0 _last_arrival_usec = -1 _sample_started_usec = -1 _window_up_bytes = 0 @@ -84,11 +104,14 @@ func reset() -> void: func reset_extremes() -> void: latest_error_m = 0.0 max_error_m = 0.0 - latest_correction_m = 0.0 - max_correction_m = 0.0 + latest_offset_m = 0.0 + max_offset_m = 0.0 corrections = 0 + replayed_ticks = 0 + max_replayed_ticks = 0 error_samples = PackedFloat32Array() - correction_samples = PackedFloat32Array() + offset_samples = PackedFloat32Array() + replay_samples = PackedFloat32Array() jitter_samples = PackedFloat32Array() @@ -118,15 +141,28 @@ func snapshot_jitter() -> Vector2: ## Records one reconciliation of the local ship against authoritative state. -func record_correction(error_m: float, correction_m: float) -> void: +## `ack_lag` and `depth` are negative when unknown. +func record_reconciliation(error_m: float, replayed: int, ack_lag: int = -1, depth: int = -1) -> void: latest_error_m = error_m - latest_correction_m = correction_m max_error_m = maxf(max_error_m, error_m) - max_correction_m = maxf(max_correction_m, correction_m) + replayed_ticks = replayed + max_replayed_ticks = maxi(max_replayed_ticks, replayed) + unacked_inputs = replayed + if ack_lag >= 0: + ack_lag_ticks = ack_lag + if depth >= 0: + server_input_depth = depth corrections += 1 if keep_samples: error_samples.append(error_m) - correction_samples.append(correction_m) + replay_samples.append(replayed) + + +func record_visual_offset(offset_m: float) -> void: + latest_offset_m = offset_m + max_offset_m = maxf(max_offset_m, offset_m) + if keep_samples: + offset_samples.append(offset_m) func record_server_state(position: Vector3, rotation: Vector3) -> void: @@ -135,10 +171,6 @@ func record_server_state(position: Vector3, rotation: Vector3) -> void: server_rotation = rotation -func record_command_received(id: int) -> void: - commands_received[id] = commands_received.get(id, 0) + 1 - - ## Reads RTT and host traffic from a client's ENet peer, at most once per ## second. Takes ENet's host counters (pop_statistic), so call it from one ## place per host. Returns whether the rates were refreshed. diff --git a/scripts/netcode_overlay.gd b/scripts/netcode_overlay.gd index e2e7fbe..7d7bda0 100644 --- a/scripts/netcode_overlay.gd +++ b/scripts/netcode_overlay.gd @@ -5,6 +5,9 @@ extends Control ## Client-side diagnostics only; nothing here is sent to the server. const SIZE := Vector2(340, 356) +# Readings start here; the controls sit below them. +const LINE_HEIGHT := 16 +const CONTROLS_TOP := 146 const REFRESH := 0.25 const DIRECTION_LABELS := ["Both ways (round trip)", "Upstream only", "Downstream only"] # Slider limits per mode: [round trip, one way]. @@ -29,8 +32,8 @@ func _ready() -> void: mouse_filter = Control.MOUSE_FILTER_IGNORE size = SIZE var rows := VBoxContainer.new() - rows.position = Vector2(12, 138) - rows.size = Vector2(SIZE.x - 24, SIZE.y - 146) + rows.position = Vector2(12, CONTROLS_TOP) + rows.size = Vector2(SIZE.x - 24, SIZE.y - CONTROLS_TOP - 8) rows.add_theme_constant_override("separation", 2) add_child(rows) direction = OptionButton.new() @@ -194,16 +197,18 @@ func _draw() -> void: lines.append("Not connected to a server.") else: var jitter := stats.snapshot_jitter() - lines.append("RTT %d ms" % roundi(stats.rtt_ms)) - lines.append("Up %s/s Down %s/s" % [String.humanize_size(int(stats.up_bytes_per_second)), String.humanize_size(int(stats.down_bytes_per_second))]) + lines.append("RTT %d ms Up %s/s Down %s/s" % [roundi(stats.rtt_ms), String.humanize_size(int(stats.up_bytes_per_second)), String.humanize_size(int(stats.down_bytes_per_second))]) lines.append("Snapshot jitter %.1f ms mean / %.1f ms max" % [jitter.x, jitter.y]) - lines.append("Correction %.2f m last / %.2f m max" % [stats.latest_correction_m, stats.max_correction_m]) - lines.append("Prediction error %.2f m last / %.2f m max" % [stats.latest_error_m, stats.max_error_m]) + lines.append("Inputs %d unacked, replayed %d (max %d)" % [stats.unacked_inputs, stats.replayed_ticks, stats.max_replayed_ticks]) + lines.append("Ack lag %d ticks, server buffer %s" % [stats.ack_lag_ticks, str(stats.server_input_depth) if stats.server_input_depth >= 0 else "-"]) + lines.append("Sim error %.2f / %.2f m max, offset %.2f m" % [stats.latest_error_m, stats.max_error_m, stats.latest_offset_m]) + var inputs := stats.server_inputs + lines.append("Server lost %d late %d dup %d starved %d" % [inputs.get("lost", 0), inputs.get("late", 0), inputs.get("duplicates", 0), inputs.get("starved", 0)]) if simulator.is_running(): var relay := simulator.stats() lines.append("Relay lost %d up / %d down, dup %d / %d" % [relay["up"]["dropped_packets"], relay["down"]["dropped_packets"], relay["up"]["duplicated_packets"], relay["down"]["duplicated_packets"]]) for index in lines.size(): - draw_string(font, Vector2(12, 44 + index * 18), lines[index], HORIZONTAL_ALIGNMENT_LEFT, SIZE.x - 24, 14, FlightHud.INK if index == 0 else FlightHud.MUTED) + draw_string(font, Vector2(12, 44 + index * LINE_HEIGHT), lines[index], HORIZONTAL_ALIGNMENT_LEFT, SIZE.x - 24, 14, FlightHud.INK if index == 0 else FlightHud.MUTED) func update_ghost(shown: bool) -> void: diff --git a/scripts/pilot.gd b/scripts/pilot.gd index 1f2385d..8f0ecaf 100644 --- a/scripts/pilot.gd +++ b/scripts/pilot.gd @@ -9,6 +9,7 @@ const MIN_INERTIA_RATIO: float = 0.3 # 180° flick in that time, so honest steering is not visibly delayed. const MAX_TURN_RATE: float = TAU * 2.0 const TURN_LATENCY_ALLOWANCE: float = 0.05 # One command interval absorbs jittered packets. +const ARM_POSITION := Vector3(0.0, 2.5, 0.0) @export var cruise_speed: float = 41.0 @export var boost_speed: float = 83.0 @@ -43,6 +44,11 @@ var extras_clock: float = 0.0 var repair_visual: RepairBotVisual var exhaust: ShipExhaust var turn_budget: float = 0.0 +## Facing used by simulate_input(). The server copies it to `rotation`; the +## owning client keeps its view in `rotation` instead. +var sim_rotation: Vector3 = Vector3.ZERO +## World-space render offset of the model and camera; see set_visual_offset(). +var visual_offset: Vector3 = Vector3.ZERO func firing_blocker(target: SpaceShip) -> String: @@ -97,7 +103,7 @@ func _ready() -> void: model.queue_free() attach_model() arm = SpringArm3D.new() - arm.position = Vector3(0.0, 2.5, 0.0) + arm.position = ARM_POSITION arm.rotation.x = -0.12 arm.spring_length = 16.0 arm.margin = 0.5 @@ -171,18 +177,46 @@ func thrust_multiplier() -> float: func turn_toward(angles: Vector3, delta: float) -> void: # Clients predict their own facing; the server only follows it at a bounded rate. + rotation = bounded_turn(rotation, angles, delta) + + +## Steps `from` toward `angles` within the turn budget, spending it. +func bounded_turn(from: Vector3, angles: Vector3, delta: float) -> Vector3: turn_budget = minf(turn_budget + MAX_TURN_RATE * delta, MAX_TURN_RATE * (delta + TURN_LATENCY_ALLOWANCE)) - var step := Vector2(angle_difference(rotation.y, angles.y), angles.x - rotation.x).limit_length(turn_budget) + var step := Vector2(angle_difference(from.y, angles.y), angles.x - from.x).limit_length(turn_budget) turn_budget -= step.length() - rotation = Vector3(clampf(rotation.x + step.y, -1.48, 1.48), wrapf(rotation.y + step.x, -PI, PI), 0.0) + return Vector3(clampf(from.x + step.y, -1.48, 1.48), wrapf(from.y + step.x, -PI, PI), 0.0) func fly_command(delta: float, movement: Vector3, boost: bool) -> void: - # Ease mouse motion over a few frames; remote ships receive the resulting angles. + apply_look(delta) + thrust(delta, movement, boost, global_basis) + present_motion(delta, movement) + + +## Eases mouse motion over a few frames; remote ships receive the resulting angles. +func apply_look(delta: float) -> void: var look_step := pending_look * (1.0 - exp(-delta / steering_response)) pending_look -= look_step rotation.y += look_step.x rotation.x = clampf(rotation.x + look_step.y, -1.48, 1.48) + + +## One networked input tick, run identically by the server and, when +## predicting and replaying, by the owning client: turn `sim_rotation` toward +## the requested facing within the turn limit, then thrust along it. The body +## moves with the simulation facing, so collision contacts match on both +## sides; the node's previous `rotation` is restored afterwards, so the +## owner's view can lead the turn-limited simulation facing during flicks. +func simulate_input(delta: float, movement: Vector3, boost: bool, facing: Vector3) -> void: + sim_rotation = bounded_turn(sim_rotation, facing, delta) + var view := rotation + rotation = sim_rotation + thrust(delta, movement, boost, Basis.from_euler(sim_rotation)) + rotation = view + + +func thrust(delta: float, movement: Vector3, boost: bool, facing: Basis) -> void: movement = movement.limit_length() boosting = boost and movement.length() > 0.1 and energy > 1.0 if boosting: @@ -190,18 +224,34 @@ func fly_command(delta: float, movement: Vector3, boost: bool) -> void: else: energy = minf(100.0, energy + 18.0 * delta) var speed := boost_speed if boosting else cruise_speed - var desired_velocity := global_basis * movement * speed - var thrust := acceleration + var desired_velocity := facing * movement * speed + var thrust_rate := acceleration # Keep world-space momentum through turns, with stronger assistance when stopping or reversing. if velocity.dot(desired_velocity) < 0.0: - thrust = counter_thrust + thrust_rate = counter_thrust elif desired_velocity.length_squared() < velocity.length_squared(): - thrust = braking - var next_velocity := velocity.move_toward(desired_velocity, thrust * thrust_multiplier() * delta) + thrust_rate = braking + var next_velocity := velocity.move_toward(desired_velocity, thrust_rate * thrust_multiplier() * delta) # Assistance can shed or redirect momentum, but gaining speed retains the # original acceleration, including launch, boost and recovery after a turn. velocity = next_velocity.limit_length(velocity.length() + acceleration * delta) move_and_slide() + + +## Cosmetic banking and boost field of view; never part of the simulation. +func present_motion(delta: float, movement: Vector3) -> void: if render_enabled: - model.rotation.z = lerp_angle(model.rotation.z, -movement.x * 0.23, delta * 5.0) + model.rotation.z = lerp_angle(model.rotation.z, -movement.limit_length().x * 0.23, delta * 5.0) camera.fov = lerpf(camera.fov, 83.0 if boosting else 75.0, delta * 3.0) + + +## Draws the model and camera `offset` (world space) away from the simulated +## position. Owner prediction uses it to hide reconciliation corrections. +func set_visual_offset(offset: Vector3) -> void: + visual_offset = offset + if not render_enabled or not is_instance_valid(model): + return + var local := global_basis.inverse() * offset + model.position = local + if is_instance_valid(arm): + arm.position = ARM_POSITION + local diff --git a/scripts/session_combat.gd b/scripts/session_combat.gd index bd4df0a..0361caf 100644 --- a/scripts/session_combat.gd +++ b/scripts/session_combat.gd @@ -394,7 +394,7 @@ func tick(delta: float) -> void: ship.rotation = Vector3.ZERO records[id]["life"] += 1 ship.set_meta("life", records[id]["life"]) - session.commands.erase(id) + session.clear_commands(id) if change_map: session.announce_map_change(id) continue @@ -465,7 +465,7 @@ func remote_target(id: int) -> Alien: func remote_firing(id: int) -> bool: var command: Dictionary = session.commands.get(id, {}) var alien := remote_target(id) - return is_instance_valid(alien) and alien.available() and command.get("fire", false) and command.get("encounter", -1) == alien.life and Time.get_ticks_msec() - command["time"] < FlightSession.COMMAND_TIMEOUT * 1000 + return is_instance_valid(alien) and alien.available() and command.get("fire", false) and command.get("encounter", -1) == alien.life and session.server_tick - int(command.get("tick", -FlightSession.INPUT_TIMEOUT_TICKS)) < FlightSession.INPUT_TIMEOUT_TICKS func choose_target(alien: Alien) -> Pilot: @@ -552,7 +552,7 @@ func destroyed(ship: SpaceShip) -> void: return records[id]["credits"] -= fee records[id]["respawn"] = 3.0 - session.commands.erase(id) + session.clear_commands(id) if ship == session.sector.player: session.sector.select_target(null) session.sector.autopilot.cancel() @@ -684,7 +684,7 @@ func contract_action(id: int, life: int, action: String, offer: String, run: Str return false records[id]["credits"] = balance records[id]["contracts"] = next - session.commands.erase(id) + session.clear_commands(id) message(id, notice) if id == 1: update_local(records[id]) @@ -722,7 +722,7 @@ func repair(id: int, life: int) -> bool: records[id]["credits"] -= cost ship.reset_health() ship.energy = 100.0 - session.commands.erase(id) + session.clear_commands(id) if records[id]["stage"] >= 3: records[id]["stage"] = 4 message(id, "Repairs complete. Cost: %d credits." % cost, "purchase") diff --git a/scripts/ship_exhaust.gd b/scripts/ship_exhaust.gd index d0c6366..69a83ec 100644 --- a/scripts/ship_exhaust.gd +++ b/scripts/ship_exhaust.gd @@ -80,7 +80,8 @@ func _process(delta: float) -> void: func track(delta: float) -> void: - var location := ship.global_position + # The drawn position, so hidden reconciliation corrections never pulse the plume. + var location := ship.global_position + ship.visual_offset if not tracking or location.distance_to(last_position) > TELEPORT_SPEED * delta: tracking = true last_position = location diff --git a/scripts/snapshot_codec.gd b/scripts/snapshot_codec.gd index 23e7a4e..7e9f91e 100644 --- a/scripts/snapshot_codec.gd +++ b/scripts/snapshot_codec.gd @@ -14,10 +14,14 @@ const REPAIRING := 8 const BOOSTS := 16 const RETURNING := 4 const ENGAGED := 8 +## Server input counters carried in the owner entry; see InputBuffer. +const INPUT_COUNTERS := ["applied", "duplicates", "late", "lost", "dropped", "starved"] ## Public movement and health for one pilot. `extras` (owner entries only) adds -## velocity, private progress, ammunition, rocket and boost state. +## velocity, the input acknowledgement (last processed input `ack`, buffered +## `depth`, `turn_budget` and the server's `inputs` counters), private +## progress, ammunition, rocket and boost state. static func player_entry(id: int, data: Dictionary, revision: int, extras: Dictionary = {}) -> PackedByteArray: var owner := data.has("credits") var systems: PackedFloat32Array = data["systems"] @@ -41,6 +45,12 @@ static func player_entry(id: int, data: Dictionary, revision: int, extras: Dicti if not owner: return buffer.data_array put_vector(buffer, data["velocity"]) + buffer.put_u32(extras.get("ack", 0)) + buffer.put_u8(clampi(extras.get("depth", 0), 0, 255)) + buffer.put_float(extras.get("turn_budget", 0.0)) + var inputs: Dictionary = extras.get("inputs", {}) + for key: String in INPUT_COUNTERS: + buffer.put_u32(inputs.get(key, 0)) buffer.put_u32(data["credits"]) buffer.put_u32(data["kills"]) buffer.put_u8(data["stage"]) @@ -99,10 +109,12 @@ static func alien_profile(data: Dictionary) -> Array: return [data["kind"], data["home"]] -static func world(sequence: int, visit: int, players: Array[PackedByteArray], aliens: Array[PackedByteArray]) -> PackedByteArray: +## `tick` is the server simulation tick the snapshot was taken after. +static func world(sequence: int, visit: int, tick: int, players: Array[PackedByteArray], aliens: Array[PackedByteArray]) -> PackedByteArray: var buffer := StreamPeerBuffer.new() buffer.put_u32(sequence) buffer.put_u32(visit) + buffer.put_u32(tick) buffer.put_u8(players.size()) buffer.put_u8(aliens.size()) var packet := buffer.data_array @@ -113,15 +125,15 @@ static func world(sequence: int, visit: int, players: Array[PackedByteArray], al return packet -## Returns {sequence, visit, players: {id: state}, aliens: {id: state}, owner}. +## Returns {sequence, visit, tick, players: {id: state}, aliens: {id: state}, owner}. ## Each state's `profile` names its profile revision. States lack profile fields ## until merged with `player_state` or `alien_state`. `owner` holds ammunition, rockets and boosts, or is empty. static func decode_world(packet: PackedByteArray) -> Dictionary: - if packet.size() < 10: + if packet.size() < 14: return {} var buffer := StreamPeerBuffer.new() buffer.data_array = packet - var result := {"sequence": buffer.get_u32(), "visit": buffer.get_u32(), "players": {}, "aliens": {}, "owner": {}} + var result := {"sequence": buffer.get_u32(), "visit": buffer.get_u32(), "tick": buffer.get_u32(), "players": {}, "aliens": {}, "owner": {}} var player_count := buffer.get_u8() var alien_count := buffer.get_u8() for index in range(player_count): @@ -136,6 +148,13 @@ static func decode_world(packet: PackedByteArray) -> Dictionary: data["repairing"] = flags & REPAIRING != 0 if flags & OWNER: data["velocity"] = get_vector(buffer) + data["ack"] = buffer.get_u32() + data["input_depth"] = buffer.get_u8() + data["turn_budget"] = buffer.get_float() + var inputs := {} + for key: String in INPUT_COUNTERS: + inputs[key] = buffer.get_u32() + data["inputs"] = inputs data["credits"] = buffer.get_u32() data["kills"] = buffer.get_u32() data["stage"] = buffer.get_u8() diff --git a/scripts/station_desk.gd b/scripts/station_desk.gd index f1bf238..b72829c 100644 --- a/scripts/station_desk.gd +++ b/scripts/station_desk.gd @@ -67,7 +67,7 @@ func station_request(id: int, sequence: int, action: String, subject: String, sh # the new fitting), boost energy, cooldowns and damage timer. records[id]["life"] += 1 session.ships[id].set_meta("life", records[id]["life"]) - session.commands.erase(id) + session.clear_commands(id) session.ships[id].velocity = Vector3.ZERO publish_inventory(id, result) if action == "gate_assemble" and pilot["equipment"]["revision"] > previous_revision: diff --git a/tests/alien_sector_test.gd b/tests/alien_sector_test.gd index 352ffe2..c38f401 100644 --- a/tests/alien_sector_test.gd +++ b/tests/alien_sector_test.gd @@ -4,7 +4,7 @@ extends "res://tests/dedicated_server_test.gd" func fire_at(server: Sector, clients: Array[Sector], enemies: Array[Alien], life: int = -1, phase: String = "fire") -> void: # All simultaneous intents must reach the server in the same turn, so combat - # can consume them together even when each frame exceeds COMMAND_TIMEOUT. + # can consume them together however long each frame takes. var intents: Array[Dictionary] = [] for index in range(clients.size()): var enemy := enemies[index] @@ -45,26 +45,27 @@ func run() -> void: for enemy: Alien in server.aliens.values(): check(SnapshotCodec.alien_entry(combat.pack_alien(enemy), 1).size() <= 58, "Alien snapshot entry stays compact") check(not first.aliens[enemy.alien_id].simulation_authority, "Clients cannot simulate any alien") - first.session.command_flight.rpc_id(1, Vector3.ZERO, Vector3.ZERO, false, true, 0, 0, 999) + first.session.send_command(Vector3.ZERO, Vector3.ZERO, false, true, 0, 0, 999) await settle(0.06) check(not combat.remote_firing(first_id), "Unknown alien IDs cannot fire or claim a reward") - # Regress CI stalls longer than COMMAND_TIMEOUT after settings have loaded. + # Regress CI stalls after settings have loaded: fire intents age in server + # ticks, so slow frames alone never expire them. var previous_max_fps := Engine.max_fps Engine.max_fps = 1 await fire_at(server, [first, second], [scout, heavy], -1, "slow-frame simultaneous encounters") combat.tick(0.01) - # Reproduce the scheduler condition explicitly: a received command goes stale - # across capped frames without client heartbeats, then actual ENet retries must - # converge again. The production timeout remains authoritative. # Own polling during this regression so a convenient automatic poll cannot # hide a missing receipt barrier in fire_at. Restore it before other fixtures. var previous_multiplayer_poll := multiplayer_poll multiplayer_poll = false await process_frame await process_frame - check(not combat.remote_firing(first_id) and not combat.remote_firing(second_id), "Slow frames expire both received fire intents at the production timeout") + check(combat.remote_firing(first_id) and combat.remote_firing(second_id), "Slow frames without server ticks keep both fire intents") + # Server ticks without input packets expire the intents at the production timeout. + server.session.server_tick += FlightSession.INPUT_TIMEOUT_TICKS + check(not combat.remote_firing(first_id) and not combat.remote_firing(second_id), "Input timeout ticks expire both received fire intents") await fire_at(server, [first, second], [scout, heavy], -1, "slow-frame retry after expiry") - check(combat.remote_firing(first_id) and combat.remote_firing(second_id), "ENet retries restore both fresh intents together after slow-frame expiry") + check(combat.remote_firing(first_id) and combat.remote_firing(second_id), "ENet retries restore both fresh intents together after expiry") multiplayer_poll = previous_multiplayer_poll Engine.max_fps = previous_max_fps check(scout.shield < scout.max_shield and heavy.shield < heavy.max_shield, "Two simultaneous fire intents damage independent aliens") @@ -92,7 +93,7 @@ func run() -> void: check(combat.records[first_id]["credits"] == 300 and combat.records[second_id]["credits"] == 0, "Scout pays only its contributor") check(heavy.hull + heavy.shield == heavy_health and heavy.life == heavy_life and heavy.contributors == [second_id], "Scout death preserves Heavy health, life and contributions") # These clients disable physics/input heartbeats. Snapshot convergence may take - # longer than COMMAND_TIMEOUT; check retained intent independently of its age. + # longer than the input timeout; check retained intent independently of its age. var heavy_command: Dictionary = server.session.commands.get(second_id, {}) check(second.target == second.aliens[4] and second.auto_fire and combat.remote_target(second_id) == heavy and heavy_command.get("fire", false) and heavy_command.get("encounter", -1) == heavy.life, "Another alien's death preserves Heavy targeting and fire intent") var timer := scout.respawn diff --git a/tests/connected_maps_test.gd b/tests/connected_maps_test.gd index 01afe09..1601f8a 100644 --- a/tests/connected_maps_test.gd +++ b/tests/connected_maps_test.gd @@ -142,7 +142,7 @@ func run() -> void: first.session.combat.ammo_snapshot(PackedInt32Array(), 999999, {}, old_visit) check(first.get_child_count() == effect_count and first.player.ammo == ammo, "Delayed effects and owner ammunition cannot enter the new visit") check(first.world_aliens[0].snapshot_goal.is_empty() and not first.loot.drops.has(999), "Delayed world snapshots and loot from a prior visit are discarded") - first.session.command_flight.rpc_id(1, Vector3.ONE, Vector3.ZERO, false, true, 0, 0, 0) + first.session.send_command(Vector3.ONE, Vector3.ZERO, false, true, 0, 0, 0) await settle(0.06) check(not server.session.commands.has(id), "Prior-flight movement and fire cannot cross the gate") var enemy: Alien = server.map_rosters[1][100] @@ -229,5 +229,5 @@ func run() -> void: func fire_at(client: Sector, enemy: Alien) -> void: - client.session.command_flight.rpc_id(1, Vector3.ZERO, Vector3.ZERO, false, true, int(client.player.get_meta("life", 0)), enemy.life, enemy.alien_id) + client.session.send_command(Vector3.ZERO, Vector3.ZERO, false, true, int(client.player.get_meta("life", 0)), enemy.life, enemy.alien_id) await settle(0.06) diff --git a/tests/extras_batch_test.gd b/tests/extras_batch_test.gd index 8b6a590..51453bc 100644 --- a/tests/extras_batch_test.gd +++ b/tests/extras_batch_test.gd @@ -87,7 +87,7 @@ func run() -> void: boundary[1] = saved["pilots"]["pilot2"]["ammo"]["x1"] == 10000 store.measuring = true for id: int in server.session.ships: - server.session.commands[id] = {"target": server.alien.alien_id, "fire": true, "encounter": server.alien.life, "time": Time.get_ticks_msec()} + server.session.commands[id] = {"target": server.alien.alien_id, "fire": true, "encounter": server.alien.life, "tick": server.session.server_tick} var damage_after_commit := [false] server.alien.damaged.connect(func(_target: SpaceShip, _attacker: SpaceShip): var saved: Dictionary = JSON.parse_string(FileAccess.get_file_as_string(store.path)) diff --git a/tests/input_buffer_test.gd b/tests/input_buffer_test.gd new file mode 100644 index 0000000..89b38b1 --- /dev/null +++ b/tests/input_buffer_test.gd @@ -0,0 +1,162 @@ +extends SceneTree +## InputBuffer ordering, deduplication, redundancy, starvation, catch-up and +## timeout, plus FlightInput packet round trips. + +var failures: int = 0 +var checks: int = 0 + + +func _initialize() -> void: + run() + + +func check(condition: bool, description: String) -> void: + checks += 1 + if not condition: + failures += 1 + push_error(description) + + +func input(seq: int, x: float = 0.0) -> Dictionary: + return {"seq": seq, "movement": Vector3(x, 0, 0), "boost": false, "facing": Vector3.ZERO} + + +## Delivers what a client would send after sampling `newest`: the last +## FlightInput.REDUNDANCY inputs, oldest first. +func deliver(buffer: InputBuffer, newest: int) -> void: + for seq in range(maxi(1, newest - FlightInput.REDUNDANCY + 1), newest + 1): + buffer.receive(seq, input(seq, seq)) + + +func applied_seq(result: Dictionary) -> int: + return int(result["movement"].x) if not result.is_empty() else -1 + + +func run() -> void: + # Duplicates and reordering: each sequence is applied once, in order. + var buffer := InputBuffer.new() + for seq in [3, 1, 2, 2, 1, 3]: + buffer.receive(seq, input(seq, seq)) + check(buffer.depth() == 3 and buffer.duplicates == 3, "Duplicates are discarded while buffered") + var order: Array[int] = [] + for tick in 3: + order.append(applied_seq(buffer.consume())) + check(order == [1, 2, 3] and buffer.applied == 3, "Out-of-order inputs are applied once each, in sequence order") + buffer.receive(2, input(2, 2)) + check(buffer.duplicates == 4 and buffer.late == 0 and buffer.depth() == 0, "An already applied input is a duplicate") + + # Redundancy: losing whole packets loses no inputs while a later packet arrives. + buffer = InputBuffer.new() + var sent := 0 + var packets := 0 + var lost_packets := 0 + var rng := RandomNumberGenerator.new() + rng.seed = 5 + var applied: Array[int] = [] + var burst := 0 + for tick in range(1, 6001): + sent = tick + if tick % FlightPrediction.SEND_INTERVAL_TICKS == 0: + packets += 1 + # 5% random loss plus a three-packet burst every 500 packets. + var drop := rng.randf() < 0.05 or burst > 0 + if packets % 500 == 0: + burst = 3 + if burst > 0: + burst -= 1 + if drop: + lost_packets += 1 + else: + deliver(buffer, sent) + # The server runs two ticks behind the client here. + if tick > 2: + var result := buffer.consume() + if buffer.starved_ticks == 0 and not result.is_empty(): + applied.append(applied_seq(result)) + check(lost_packets > 150, "The redundancy scenario drops many packets (%d)" % lost_packets) + check(buffer.lost == 0 and buffer.late == 0, "5%% loss and three-packet bursts lose no inputs (lost %d, late %d)" % [buffer.lost, buffer.late]) + var in_order := true + for index in range(1, applied.size()): + in_order = in_order and applied[index] == applied[index - 1] + 1 + check(in_order and applied.size() + buffer.dropped + buffer.depth() >= sent - 4, "Every input is applied once in order, apart from catch-up drops") + + # Gaps beyond the redundancy window are skipped and counted as lost; their + # late arrival is recognized. + buffer = InputBuffer.new() + buffer.receive(1, input(1, 1)) + buffer.consume() + buffer.receive(5, input(5, 5)) + check(applied_seq(buffer.consume()) == 5 and buffer.lost == 3, "A sequence gap is skipped and counted as lost") + buffer.receive(3, input(3, 3)) + check(buffer.late == 1 and buffer.depth() == 0, "An input arriving after its slot was skipped is late, not applied") + + # Starvation reuses the last input without advancing; then the timeout idles. + buffer = InputBuffer.new() + check(buffer.consume().is_empty() and buffer.starved == 0, "A pilot without any input is idle, not starved") + buffer.receive(1, input(1, 1)) + buffer.consume() + var reused := 0 + for tick in InputBuffer.TIMEOUT_TICKS: + if applied_seq(buffer.consume()) == 1: + reused += 1 + check(reused == InputBuffer.TIMEOUT_TICKS and buffer.starved == InputBuffer.TIMEOUT_TICKS and buffer.last_seq == 1, "Starved ticks reuse the last input without advancing the sequence") + check(buffer.consume().is_empty(), "After the tick timeout the pilot is idle") + buffer.receive(2, input(2, 2)) + check(applied_seq(buffer.consume()) == 2 and buffer.starved_ticks == 0 and buffer.lost == 0, "A new input ends starvation without loss") + + # Catch-up: surplus depth held for a whole window is dropped down to the spare depth. + buffer = InputBuffer.new() + var next := 1 + for seq in range(1, 9): + buffer.receive(seq, input(seq, seq)) + next = seq + 1 + for tick in InputBuffer.CATCH_UP_WINDOW: + buffer.receive(next, input(next, next)) + next += 1 + buffer.consume() + check(buffer.depth() == InputBuffer.SPARE_DEPTH and buffer.dropped == 8 - 1 - InputBuffer.SPARE_DEPTH + 1, "Persistent surplus is dropped to the spare depth (depth %d, dropped %d)" % [buffer.depth(), buffer.dropped]) + check(buffer.lost == 0, "Catch-up drops are not counted as lost inputs") + # A burst beyond the hard bound is trimmed at once. + for seq in range(next, next + InputBuffer.MAX_DEPTH + 6): + buffer.receive(seq, input(seq, seq)) + buffer.consume() + check(buffer.depth() == InputBuffer.MAX_DEPTH, "Buffered latency never exceeds MAX_DEPTH ticks") + # Floods cannot grow the buffer without bound between ticks. + for seq in range(next + 100, next + 200): + buffer.receive(seq, input(seq, seq)) + check(buffer.depth() <= InputBuffer.MAX_DEPTH * 2, "A flood of inputs stays bounded") + + # A new life resynchronizes without counting the skipped sequences as lost. + buffer = InputBuffer.new() + buffer.receive(1, input(1, 1)) + buffer.consume() + buffer.receive(2, input(2, 2)) + buffer.reset() + check(buffer.depth() == 0 and buffer.consume().is_empty(), "Reset discards buffered inputs and the reused input") + buffer.receive(40, input(40, 40)) + check(applied_seq(buffer.consume()) == 40 and buffer.lost == 0, "The first input after a reset starts a new run") + buffer.receive(30, input(30, 30)) + check(buffer.depth() == 0, "Inputs from before the reset are never applied") + + # FlightInput packets round trip with quantized values. + var inputs: Array = [] + for seq in range(100, 100 + FlightInput.REDUNDANCY): + inputs.append({"seq": seq, "movement": Vector3(0.5, -1.0, 0.25), "boost": seq % 2 == 0, "facing": Vector3(1.2, -2.5, 0)}) + var packet := FlightInput.encode(7, true, 12, 3, 999, inputs) + check(packet.size() == FlightInput.HEADER_SIZE + inputs.size() * FlightInput.INPUT_SIZE and packet.size() <= 102, "Input packets stay compact (%d bytes)" % packet.size()) + var decoded := FlightInput.decode(packet) + check(decoded["life"] == 7 and decoded["fire"] and decoded["encounter"] == 12 and decoded["target"] == 3 and decoded["tick"] == 999, "Packet header fields round trip") + var exact := true + for index in inputs.size(): + var original: Dictionary = inputs[index] + var copy: Dictionary = decoded["inputs"][index] + exact = exact and copy["seq"] == original["seq"] and copy["boost"] == original["boost"] + exact = exact and copy["movement"] == FlightInput.quantize_movement(original["movement"]) and copy["facing"] == FlightInput.quantize_facing(original["facing"]) + exact = exact and copy["movement"].distance_to(original["movement"]) < 0.01 and copy["facing"].distance_to(original["facing"]) < 0.0002 + check(exact, "Decoded inputs equal the client's quantized prediction values exactly") + check(is_equal_approx(FlightInput.quantize_facing(Vector3(9.0, 4.0, 0)).x, 1.48) and absf(FlightInput.quantize_facing(Vector3(0, 4.0, 0)).y - wrapf(4.0, -PI, PI)) < 0.0001, "Facing is clamped and wrapped like server validation") + check(FlightInput.decode(packet.slice(0, packet.size() - 1)).is_empty() and FlightInput.decode(packet + PackedByteArray([0])).is_empty() and FlightInput.decode(PackedByteArray()).is_empty(), "Truncated or oversized packets are rejected") + var empty := FlightInput.encode(1, false, 0, 0, 0, []) + check(FlightInput.decode(empty).is_empty(), "Packets without inputs are rejected") + print("Input buffer checks: %d passed, %d failed" % [checks - failures, failures]) + quit(0 if failures == 0 else 1) diff --git a/tests/input_buffer_test.gd.uid b/tests/input_buffer_test.gd.uid new file mode 100644 index 0000000..f0e3930 --- /dev/null +++ b/tests/input_buffer_test.gd.uid @@ -0,0 +1 @@ +uid://cix10eb3yhw6o diff --git a/tests/main_menu_test.gd b/tests/main_menu_test.gd index f8850c0..478a3cd 100644 --- a/tests/main_menu_test.gd +++ b/tests/main_menu_test.gd @@ -88,7 +88,7 @@ func run() -> void: var ship := server.session.ships[id] check(ship.get_meta("docked") and not ship.visible and ship.collision_layer == 0, "Server docked ship is invisible and has no collision") var origin := ship.position - client.session.command_flight.rpc_id(1, Vector3(0, 0, -1), Vector3.ZERO, true, true) + client.session.send_command(Vector3(0, 0, -1), Vector3.ZERO, true, true) await settle() server.session.tick(0.1) check(ship.position == origin and not server.session.commands.has(id), "Forged movement and fire are rejected while docked") @@ -227,7 +227,7 @@ func run() -> void: check(server.session.ships.size() == 2, "Repeated launch creates no duplicate ship") await check_flight_pages(client, "connected") check(not ship.get_meta("docked") and ship.collision_layer == 2 and observer.session.ships.has(id), "Flight menus retain the live server ship and observer visibility") - client.session.command_flight.rpc_id(1, Vector3(0, 0, -1), Vector3.ZERO, true, false, int(client.player.get_meta("life", 0))) + client.session.send_command(Vector3(0, 0, -1), Vector3.ZERO, true, false, int(client.player.get_meta("life", 0))) await settle() server.session.tick(0.1) check(ship.position.z < origin.z, "Launched ship can fly") @@ -272,7 +272,7 @@ func run() -> void: check(id not in server.alien.contributors and observer.multiplayer.get_unique_id() in server.alien.contributors, "Leaving the map clears only the departing pilot's encounter contribution") client.session.snapshot({id: old_flight}, {}, client.session.player_sequences[id] + 1) check(not client.player.visible and client.player.collision_layer == 0 and client.player.position == origin, "Delayed flight snapshot cannot restore a docked ship") - client.session.command_flight.rpc_id(1, Vector3(0, 0, -1), Vector3.ZERO, true, true, old_life) + client.session.send_command(Vector3(0, 0, -1), Vector3.ZERO, true, true, old_life) await settle() check(not server.session.commands.has(id), "Old flight commands remain rejected after quitting") await click(client, menu.navigation["shop"]) @@ -298,7 +298,7 @@ func run() -> void: await click(client, menu.start_button) await replicate(server) check(not client.preflight and observer.session.ships.has(id) and ship.hull == 50000 and ship.shield == 350 and ship.energy == 42 and ship.laser_damage == 130 and client.credits == 9000 and not client.active_contracts.is_empty(), "Relaunch preserves ship state and progression and restores observer visibility") - client.session.command_flight.rpc_id(1, Vector3(0, 0, -1), Vector3.ZERO, true, true, old_life) + client.session.send_command(Vector3(0, 0, -1), Vector3.ZERO, true, true, old_life) await settle() check(not server.session.commands.has(id), "A previous flight's commands cannot control the relaunched ship") # Rescue remains authoritative even when the pilot quits during its countdown. diff --git a/tests/netcode_benchmark.gd b/tests/netcode_benchmark.gd index 62069c9..54138b9 100644 --- a/tests/netcode_benchmark.gd +++ b/tests/netcode_benchmark.gd @@ -32,19 +32,26 @@ extends "res://tests/network_test.gd" ## total sent bytes per second divided by the number of connected clients. ## - jitter_mean_ms / jitter_p95_ms / jitter_max_ms: |snapshot inter-arrival ## time - 50 ms| as handled by the client, so frame timing is included. -## - error_*_m: distance from the predicted local ship to the authoritative -## position in each applied snapshot, before reconciliation (mean/p95/max). -## - correction_*_m: distance reconciliation moved the local ship for each -## snapshot. The current reconciliation applies it within one frame, so this -## is also the visible jump beyond expected motion. +## - error_*_m: simulation error at each reconciliation: how far rewinding to +## the authoritative state and replaying unacknowledged inputs moved the +## predicted ship (mean/p95/max). Before phase 2 (network schema 23) this was +## the distance from the predicted ship to the round-trip-old authoritative +## position, which mostly measured latency rather than misprediction. +## - correction_*_m: the visual offset hiding corrections, sampled every client +## physics tick: how far the drawn ship is from the simulated one. Before +## phase 2 it was how far each snapshot's 20% lerp moved the ship, a visible +## jump within one frame. ## - gap_*_m: distance from the client's ship to the server's current position ## of the same ship, sampled every frame (possible because both run in this -## process). Accurate prediction leads the server by the upstream delay times -## speed; dragging the ship toward old snapshots shows up as error staying -## small while this gap reflects the delay instead. -## - commands_sent / commands_applied: flight commands the client sent and the -## server accepted; commands_lost is their difference, as a count and percent. -## ENet discards duplicated and out-of-order sequenced commands itself. +## process). Accurate prediction leads the server by the upstream delay and +## the server's input buffer times speed. +## - replay_mean / replay_max: unacknowledged inputs replayed per reconciliation. +## - depth_mean: inputs the server had buffered for this pilot, sampled every frame. +## - inputs_sent / inputs_applied / inputs_lost: inputs the client sampled, the +## server applied, and the server skipped because they never arrived. late, +## dropped (catch-up) and starved (ticks reusing the last input) are the +## server's InputBuffer counters. Before phase 2 these columns counted 20 Hz +## flight commands, each lost with its datagram. const BASE_PORT := 24911 # ENet smooths its RTT by 1/8 per reliable acknowledgement, about two per @@ -137,8 +144,9 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> net.keep_samples = true relay.reset_stats() var id := client.multiplayer.get_unique_id() - var sent_before := net.commands_sent - var applied_before: int = server.session.net_stats.commands_received.get(id, 0) + var sent_before := net.inputs_sent + var packets_before := net.input_packets_sent + var inputs_before: Dictionary = server.session.input_buffers[id].counters() var up_before := net.total_up_bytes var down_before := net.total_down_bytes var host: ENetConnection = (server.multiplayer.multiplayer_peer as ENetMultiplayerPeer).host @@ -151,8 +159,10 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> net.keep_samples = false var server_bytes := host.pop_statistic(ENetConnection.HOST_TOTAL_SENT_DATA) var relay_stats: Dictionary = relay.stats() - var sent := net.commands_sent - sent_before - var applied: int = server.session.net_stats.commands_received.get(id, 0) - applied_before + var sent := net.inputs_sent - sent_before + var inputs: Dictionary = server.session.input_buffers[id].counters() + for key: String in inputs: + inputs[key] -= inputs_before[key] return { "rtt_added_ms": condition[0], "jitter_ms": condition[1], "loss_percent": condition[2], "duplicate_percent": condition[3], "seconds": snappedf(seconds, 0.01), "rtt_ms": snappedf(NetStats.mean(rtts), 0.1), @@ -168,19 +178,25 @@ func measure(server: Sector, client: Sector, clients: int, condition: Array) -> "error_mean_m": snappedf(NetStats.mean(net.error_samples), 0.01), "error_p95_m": snappedf(NetStats.percentile(net.error_samples, 0.95), 0.01), "error_max_m": snappedf(NetStats.percentile(net.error_samples, 1.0), 0.01), - "correction_mean_m": snappedf(NetStats.mean(net.correction_samples), 0.01), - "correction_p95_m": snappedf(NetStats.percentile(net.correction_samples, 0.95), 0.01), - "correction_max_m": snappedf(NetStats.percentile(net.correction_samples, 1.0), 0.01), + "correction_mean_m": snappedf(NetStats.mean(net.offset_samples), 0.01), + "correction_p95_m": snappedf(NetStats.percentile(net.offset_samples, 0.95), 0.01), + "correction_max_m": snappedf(NetStats.percentile(net.offset_samples, 1.0), 0.01), + "replay_mean": snappedf(NetStats.mean(net.replay_samples), 0.1), + "replay_max": roundi(NetStats.percentile(net.replay_samples, 1.0)), + "depth_mean": snappedf(NetStats.mean(depths), 0.1), "gap_mean_m": snappedf(NetStats.mean(gaps), 0.01), "gap_p95_m": snappedf(NetStats.percentile(gaps, 0.95), 0.01), - "commands_sent": sent, "commands_applied": applied, "commands_lost": sent - applied, - "commands_lost_percent": snappedf(100.0 * (sent - applied) / maxi(sent, 1), 0.1), + "inputs_sent": sent, "inputs_applied": inputs["applied"], "inputs_lost": inputs["lost"], + "inputs_late": inputs["late"], "inputs_dropped": inputs["dropped"], "inputs_starved": inputs["starved"], + "inputs_duplicates": inputs["duplicates"], + "input_packets": net.input_packets_sent - packets_before, "relay_dropped": relay_stats["up"]["dropped_packets"] + relay_stats["down"]["dropped_packets"], } var speeds := PackedFloat32Array() var gaps := PackedFloat32Array() +var depths := PackedFloat32Array() ## Flies the input pattern for `seconds`; returns RTT samples taken every 0.5 s. @@ -188,6 +204,7 @@ func fly(client: Sector, seconds: float, server: Sector = null) -> PackedFloat32 var rtts := PackedFloat32Array() speeds = PackedFloat32Array() gaps = PackedFloat32Array() + depths = PackedFloat32Array() var id := client.multiplayer.get_unique_id() var started := Time.get_ticks_msec() var next_rtt := 500 @@ -219,6 +236,8 @@ func fly(client: Sector, seconds: float, server: Sector = null) -> PackedFloat32 speeds.append(client.player.velocity.length()) if server != null and server.session.ships.has(id): gaps.append(client.player.position.distance_to(server.session.ships[id].position)) + if server.session.input_buffers.has(id): + depths.append(server.session.input_buffers[id].depth()) if now - started >= next_rtt: next_rtt += 500 rtts.append(client.session.net_stats.rtt_ms) @@ -233,15 +252,16 @@ func release_inputs() -> void: func print_table(results: Array[Dictionary]) -> void: print("\nAdded RTT is split evenly per direction (100 ms = +50 ms each way); loss and duplication apply both ways.") - print("| Added RTT | Loss | RTT | Speed | Client up | Client down | Server to client | Snapshot jitter mean / p95 / max | Prediction error mean / p95 / max | Correction mean / p95 / max | Gap to server now mean / p95 | Commands sent / applied / lost |") - print("| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") + print("| Added RTT | Loss | RTT | Speed | Client up | Client down | Server to client | Snapshot jitter mean / p95 / max | Sim error mean / p95 / max | Visual offset mean / p95 / max | Gap to server now mean / p95 | Replay mean / max | Server buffer | Inputs sent / applied / lost | Late / dropped / starved |") + print("| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") for row: Dictionary in results: var jitter := "" if row["jitter_ms"] == 0.0 else " ± %d" % row["jitter_ms"] - print("| %d%s ms | %s%% | %.0f ms | %.1f m/s | %.1f KB/s | %.1f KB/s | %.1f KB/s | %.1f / %.1f / %.1f ms | %.2f / %.2f / %.2f m | %.2f / %.2f / %.2f m | %.2f / %.2f m | %d / %d / %d (%.1f%%) |" % [ + print("| %d%s ms | %s%% | %.0f ms | %.1f m/s | %.1f KB/s | %.1f KB/s | %.1f KB/s | %.1f / %.1f / %.1f ms | %.2f / %.2f / %.2f m | %.2f / %.2f / %.2f m | %.2f / %.2f m | %.1f / %d | %.1f | %d / %d / %d | %d / %d / %d |" % [ row["rtt_added_ms"], jitter, str(row["loss_percent"]), row["rtt_ms"], row["speed_mps"], row["up_bps"] / 1000.0, row["down_bps"] / 1000.0, row["server_bps"] / 1000.0, row["jitter_mean_ms"], row["jitter_p95_ms"], row["jitter_max_ms"], row["error_mean_m"], row["error_p95_m"], row["error_max_m"], row["correction_mean_m"], row["correction_p95_m"], row["correction_max_m"], - row["gap_mean_m"], row["gap_p95_m"], - row["commands_sent"], row["commands_applied"], row["commands_lost"], row["commands_lost_percent"]]) + row["gap_mean_m"], row["gap_p95_m"], row["replay_mean"], row["replay_max"], row["depth_mean"], + row["inputs_sent"], row["inputs_applied"], row["inputs_lost"], + row["inputs_late"], row["inputs_dropped"], row["inputs_starved"]]) diff --git a/tests/netsim_network_test.gd b/tests/netsim_network_test.gd index e43c664..3b9b614 100644 --- a/tests/netsim_network_test.gd +++ b/tests/netsim_network_test.gd @@ -29,9 +29,10 @@ func run() -> void: var stats: Dictionary = client.session.net_simulator.stats() var net := client.session.net_stats print("Relay stats: ", stats) - print("Client stats: rtt %.1f ms, up %.0f B/s, down %.0f B/s, snapshots %d, jitter %s, max error %.2f m, commands %d sent / %d accepted" % [ + var inputs: Dictionary = server.session.input_buffers[id].counters() if server.session.input_buffers.has(id) else {} + print("Client stats: rtt %.1f ms, up %.0f B/s, down %.0f B/s, snapshots %d, jitter %s, max sim error %.2f m, inputs %d sent, server %s" % [ net.rtt_ms, net.up_bytes_per_second, net.down_bytes_per_second, net.snapshots_received, - net.snapshot_jitter(), net.max_error_m, net.commands_sent, server.session.net_stats.commands_received.get(id, 0)]) + net.snapshot_jitter(), net.max_error_m, net.inputs_sent, inputs]) check(stats["up"]["forwarded_packets"] > 30 and stats["down"]["forwarded_packets"] > 30, "Traffic flows both ways through the relay") check(stats["up"]["dropped_packets"] + stats["down"]["dropped_packets"] > 0, "The relay drops datagrams") check(stats["up"]["duplicated_packets"] + stats["down"]["duplicated_packets"] > 0, "The relay duplicates datagrams") @@ -40,8 +41,9 @@ func run() -> void: check(net.up_bytes_per_second > 0.0 and net.down_bytes_per_second > net.up_bytes_per_second, "Client traffic rates are sampled") check(net.corrections > 0 and net.has_server_state, "Reconciliation against server state is measured") check(server.session.ships[id].position.z < Sector.SPAWN_POSITION.z, "Relayed flight commands move the pilot on the server") - var accepted: int = server.session.net_stats.commands_received.get(id, 0) - check(accepted > 0 and accepted <= net.commands_sent, "The server counts accepted flight commands") + var applied: int = inputs.get("applied", 0) + check(applied > 0 and applied <= net.inputs_sent, "The server applies relayed flight inputs") + check(inputs.get("lost", -1) == 0, "Redundant input packets lose no inputs at 5% loss") # The F8 overlay edits the running relay and shows the server ghost. var toggle := InputEventAction.new() toggle.action = "netcode" diff --git a/tests/network_combat_test.gd b/tests/network_combat_test.gd index fe346ac..0b756cb 100644 --- a/tests/network_combat_test.gd +++ b/tests/network_combat_test.gd @@ -13,11 +13,11 @@ func intent(fire: bool, life: int, encounter: int, target: int = 0, movement := ## Resend each client's unreliable flight intent, as production clients do every -## frame, until the server stores all of them in the same turn. command_flight +## frame, until the server stores all of them in the same turn. flight_inputs ## stores a new Dictionary per accepted packet, so a changed reference across this ## turn's server poll marks a receipt of a packet sent after the request, without -## judging freshness by wall-clock age. Callers assert or tick combat before -## another frame can age the receipt past COMMAND_TIMEOUT. Returns false and +## judging freshness by age. Fire intents age in server ticks, which these +## fixtures advance explicitly. Returns false and ## prints per-peer samples if the server never stores the intents. func deliver_intents(server: Sector, clients: Array[Sector], intents: Array[Dictionary], phase: String = "intent") -> bool: var samples: Array[Dictionary] = [] @@ -25,7 +25,7 @@ func deliver_intents(server: Sector, clients: Array[Sector], intents: Array[Dict await process_frame for index in range(clients.size()): var sent := intents[index] - clients[index].session.command_flight.rpc_id(1, sent["movement"], sent["angles"], sent["boost"], sent["fire"], sent["life"], sent["encounter"], sent["target"]) + clients[index].session.send_command(sent["movement"], sent["angles"], sent["boost"], sent["fire"], sent["life"], sent["encounter"], sent["target"]) # Flush clients before the authority so this turn's packets reach its poll. for client in clients: client.multiplayer.poll() @@ -40,9 +40,9 @@ func deliver_intents(server: Sector, clients: Array[Sector], intents: Array[Dict var sent := intents[index] var command: Dictionary = server.session.commands.get(id, {}) var received := not command.is_empty() and not is_same(command, prior[index]) - var facing := Vector3(clampf(sent["angles"].x, -1.48, 1.48), wrapf(sent["angles"].y, -PI, PI), 0) - var matches: bool = command.get("movement") == sent["movement"].limit_length() and command.get("rotation", Vector3.INF).is_equal_approx(facing) and command.get("boost") == sent["boost"] and command.get("fire") == sent["fire"] and command.get("encounter") == sent["encounter"] and command.get("target") == sent["target"] - # command_flight drops packets from missing, docked or dead ships and other lives. + var facing := FlightInput.quantize_facing(sent["angles"]) + var matches: bool = command.get("movement") == FlightInput.quantize_movement(sent["movement"]).limit_length() and command.get("rotation", Vector3.INF).is_equal_approx(facing) and command.get("boost") == sent["boost"] and command.get("fire") == sent["fire"] and command.get("encounter") == sent["encounter"] and command.get("target") == sent["target"] + # flight_inputs drops packets from missing, docked or dead ships and other lives. var ship: SpaceShip = server.session.ships.get(id) var blocker := "" if ship == null: @@ -72,7 +72,7 @@ func deliver_intents(server: Sector, clients: Array[Sector], intents: Array[Dict func send_fire(client: Sector, fire: bool = true, life: int = 0, encounter_id: int = 0) -> void: var server := authority_for(client) if server == null or server.session.combat.records.get(client.multiplayer.get_unique_id(), {}).get("life", -1) != life: - client.session.command_flight.rpc_id(1, Vector3.ZERO, Vector3.ZERO, false, fire, life, encounter_id, 0) + client.session.send_command(Vector3.ZERO, Vector3.ZERO, false, fire, life, encounter_id, 0) await settle(0.06) return check(await deliver_intents(server, [client], [intent(fire, life, encounter_id)], "send_fire"), "Server receives the client's fire intent") diff --git a/tests/network_test.gd b/tests/network_test.gd index a4e2663..dca987f 100644 --- a/tests/network_test.gd +++ b/tests/network_test.gd @@ -113,7 +113,7 @@ func run() -> void: check(host.alien.alive and client.alien.alive and not client.alien.simulation_authority, "Shared alien is simulated only by the host") check(client.player.camera.current, "The local camera stays active after remote ships spawn") var start := host.session.ships[id].position - client.session.command_flight.rpc_id(1, Vector3(0, 0, -99), Vector3.ZERO, true) + client.session.send_command(Vector3(0, 0, -99), Vector3.ZERO, true) await settle() for frame in range(12): host.session.tick(1.0 / 60.0) @@ -128,7 +128,7 @@ func run() -> void: # The server follows requested facing at a bounded rate instead of snapping to it. var remote := host.session.ships[id] remote.rotation = Vector3.ZERO - client.session.command_flight.rpc_id(1, Vector3.ZERO, Vector3(0, PI, 0), false) + client.session.send_command(Vector3.ZERO, Vector3(0, PI, 0), false) await settle(0.06) host.session.tick(1.0 / 60.0) var turn_limit := Pilot.MAX_TURN_RATE * (1.0 / 60.0 + Pilot.TURN_LATENCY_ALLOWANCE) + 0.001 @@ -140,18 +140,27 @@ func run() -> void: var tracked := true for step in range(1, 9): var angles := Vector3(clampf(0.25 * step, -1.48, 1.48), wrapf(PI + 0.4 * step, -PI, PI), 0) - client.session.command_flight.rpc_id(1, Vector3.ZERO, angles, false) + client.session.send_command(Vector3.ZERO, angles, false) await settle(0.06) for frame in range(3): host.session.tick(1.0 / 60.0) tracked = tracked and absf(angle_difference(remote.rotation.y, angles.y)) < 0.001 and absf(remote.rotation.x - angles.x) < 0.001 check(tracked, "Normal steering converges on every command without server lag") - client.session.command_flight.rpc_id(1, Vector3.ZERO, Vector3.ZERO, false) + client.session.send_command(Vector3.ZERO, Vector3.ZERO, false) await settle(0.06) var command_before: Dictionary = host.session.commands[id].duplicate() - client.session.command_flight.rpc_id(1, Vector3(NAN, 0, 0), Vector3.ZERO, true) + var valid := FlightInput.encode(0, false, 0, -1, 0, [{"seq": 1 << 20, "movement": Vector3.ONE, "boost": true, "facing": Vector3.ZERO}]) + client.session.flight_inputs.rpc_id(1, PackedByteArray([1, 2, 3])) + client.session.flight_inputs.rpc_id(1, valid + PackedByteArray([0])) + client.session.flight_inputs.rpc_id(1, valid.slice(0, valid.size() - 1)) + await settle() + check(host.session.commands[id] == command_before, "Host rejects malformed input packets") + client.session.send_command(Vector3(NAN, INF, -INF), Vector3(NAN, INF, 0), true) + await settle() + var forged: Dictionary = host.session.commands[id] + check(forged["movement"].is_finite() and forged["movement"].length() <= 1.0 and forged["rotation"].is_finite() and absf(forged["rotation"].x) <= 1.48, "Non-finite inputs decode to finite, bounded values") + client.session.send_command(Vector3.ZERO, Vector3.ZERO, false) await settle() - check(host.session.commands[id] == command_before, "Host rejects non-finite commands") await settle(0.6) for frame in range(30): host.session.tick(1.0 / 60.0) @@ -160,7 +169,7 @@ func run() -> void: await settle(0.5) check(host.session.ships.size() == 3 and client.session.ships.size() == 3 and late.session.ships.size() == 3, "Late join replicates all players to all peers") host.set_paused(true) - client.session.command_flight.rpc_id(1, Vector3(0, 1, 0), Vector3.ZERO, false) + client.session.send_command(Vector3(0, 1, 0), Vector3.ZERO, false) await settle() var before_pause := host.session.ships[id].position host._physics_process(0.1) diff --git a/tests/reconciliation_test.gd b/tests/reconciliation_test.gd new file mode 100644 index 0000000..1f8d601 --- /dev/null +++ b/tests/reconciliation_test.gd @@ -0,0 +1,177 @@ +extends "res://tests/network_test.gd" +## Client prediction and server reconciliation through the network simulator: +## a scripted pilot flies a dedicated server through the relay. Without added +## delay the replayed simulation matches the prediction; at 150 ± 30 ms with +## 5% loss corrections stay small and no input is lost. The server never takes +## a client position and still limits turn rates. + +const PORT := 24921 +## Largest simulation error at a reconciliation without added delay or loss. +## Straight flight replays exactly (0 m); turning leaves float-rounding +## differences of a few millimetres (measured p95 0.004 m, max 0.035 m). An +## isolated server starvation tick costs one tick of motion (under 1.5 m at +## boost speed), which smoothing hides. +const CLEAN_MAX_ERROR := 1.5 +const CLEAN_P95_ERROR := 0.02 +## Bounds at 150 ± 30 ms round trip with 5% loss in both directions. Measured +## p95 0.005 m and max 0.63 m (one catch-up drop) over 12 seconds. +const DEGRADED_MAX_ERROR := 3.0 +const DEGRADED_P95_ERROR := 0.25 +# Scripted input cycle: [seconds, actions, yaw radians per second]. +const PATTERN := [ + [0.7, ["forward"], 0.0], [0.5, ["forward", "boost"], 0.0], [0.4, ["strafe_right"], 0.0], + [0.6, ["forward", "strafe_left"], 1.6], [0.4, [], 0.0], + [0.7, ["backward"], 0.0], [0.5, ["backward", "boost"], 0.0], [0.4, ["strafe_left"], 0.0], + [0.6, ["backward", "strafe_right"], -1.6], [0.4, [], 0.0], +] +const ACTIONS := ["forward", "backward", "strafe_left", "strafe_right", "boost"] + + +func run() -> void: + var server := make_sector("ReconcileServer", true, PORT) + var client := make_sector("ReconcileClient") + client.session.credential_id = "pilot0" + client.session.credential_token = test_token(0) + server.set_physics_process(true) + client.set_physics_process(true) + await settle() + client.session.use_net_simulator = true + client.session.net_simulator.set_seed(11) + check(client.session.join("127.0.0.1", test_port(PORT)) == OK, "Client joins through the simulator") + var deadline := Time.get_ticks_msec() + 10000 + while not client.session.received_snapshot and Time.get_ticks_msec() < deadline: + await process_frame + check(client.session.received_snapshot, "Snapshots arrive through the relay") + var id := client.multiplayer.get_unique_id() + if not server.session.ships.has(id): + finish() + return + var remote := server.session.ships[id] + var net := client.session.net_stats + + # Clean link: replays reproduce the prediction. + var clean := await measure(server, client, 2.0, 6.0) + print("Clean link: ", clean) + check(clean["reconciliations"] > 60, "Snapshots reconcile the local ship repeatedly") + check(clean["error_p95"] <= CLEAN_P95_ERROR and clean["error_max"] <= CLEAN_MAX_ERROR, "Without added delay the replay matches the prediction (p95 %.4f m, max %.3f m)" % [clean["error_p95"], clean["error_max"]]) + check(clean["inputs"]["lost"] == 0 and clean["inputs"]["applied"] > 300, "Every input is applied without delay or loss") + + # Collisions replay identically: fly into Outpost 01's collision envelope. + client.player.look_at(Sector.STATION_POSITION, Vector3.UP) + await settle(0.4) + net.reset_extremes() + net.keep_samples = true + var collided := 0 + var started := Time.get_ticks_msec() + Input.action_press("forward") + Input.action_press("boost") + while Time.get_ticks_msec() - started < 3500: + keep_alive(server) + await physics_frame + if remote.get_slide_collision_count() > 0: + collided += 1 + release_inputs() + net.keep_samples = false + print("Collision run: %d colliding server ticks, max sim error %.4f m, p95 %.4f m" % [collided, net.max_error_m, NetStats.percentile(net.error_samples, 0.95)]) + check(collided > 10, "The pilot slides along the station's collision envelope") + check(NetStats.percentile(net.error_samples, 0.95) <= CLEAN_P95_ERROR and net.max_error_m <= CLEAN_MAX_ERROR, "Replays through move_and_slide collisions match the server") + + # Degraded link: bounded corrections and no lost inputs. + client.session.net_simulator.set_round_trip(150.0, 30.0, 5.0) + var degraded := await measure(server, client, 3.0, 12.0) + print("150 ± 30 ms, 5% loss: ", degraded) + check(degraded["relay_dropped"] > 20, "The relay drops datagrams in both directions") + check(degraded["replay_max"] >= 9, "Reconciliation replays a round trip of inputs") + check(degraded["error_p95"] <= DEGRADED_P95_ERROR and degraded["error_max"] <= DEGRADED_MAX_ERROR, "Corrections stay bounded at 150 ± 30 ms with 5%% loss (p95 %.3f m, max %.3f m)" % [degraded["error_p95"], degraded["error_max"]]) + check(degraded["inputs"]["lost"] == 0 and degraded["inputs"]["late"] == 0, "Redundant input packets lose no inputs") + check(degraded["offset_max"] <= FlightPrediction.SNAP_DISTANCE, "Corrections are smoothed rather than snapped") + + # The server never takes a client position: a local teleport is undone. + client.session.net_simulator.set_round_trip(0.0) + await settle(0.5) + var server_before := remote.position + client.player.position += Vector3(400, 0, 0) + await settle(0.6) + check(remote.position.distance_to(server_before) < 60.0, "A client-side teleport does not move the server ship") + check(client.player.position.distance_to(remote.position) < 20.0, "Reconciliation returns the local ship to the server's path") + + # Turn limits hold for a client requesting an instant 180-degree flip. + client.set_physics_process(false) + await settle(0.3) + var life := int(client.player.get_meta("life", 0)) + var start := remote.rotation + var flipped := Vector3(0.0, wrapf(start.y + PI, -PI, PI), 0.0) + var largest := 0.0 + var previous := start + for attempt in 30: + client.session.send_command(Vector3.ZERO, flipped, false, false, life) + await physics_frame + var turned := Vector2(angle_difference(previous.y, remote.rotation.y), remote.rotation.x - previous.x).length() + largest = maxf(largest, turned) + previous = remote.rotation + var limit := Pilot.MAX_TURN_RATE * (1.0 / Engine.physics_ticks_per_second + Pilot.TURN_LATENCY_ALLOWANCE) + 0.001 + check(largest <= limit, "No server tick turns faster than the limit (%.3f rad, limit %.3f)" % [largest, limit]) + check(absf(angle_difference(remote.rotation.y, flipped.y)) < 0.01, "The limited turn still reaches the requested facing") + client.set_physics_process(true) + client.session.disconnect_session("Test leave") + finish() + + +## Flies the pattern for a warm-up, then measures for `seconds`. +func measure(server: Sector, client: Sector, warm_up: float, seconds: float) -> Dictionary: + await fly(server, client, warm_up) + var id := client.multiplayer.get_unique_id() + var net := client.session.net_stats + net.reset_extremes() + net.keep_samples = true + client.session.net_simulator.reset_stats() + var before: Dictionary = server.session.input_buffers[id].counters() + await fly(server, client, seconds) + net.keep_samples = false + var inputs: Dictionary = server.session.input_buffers[id].counters() + for key: String in inputs: + inputs[key] -= before[key] + var relay: Dictionary = client.session.net_simulator.stats() + return {"reconciliations": net.error_samples.size(), "error_p95": NetStats.percentile(net.error_samples, 0.95), + "error_max": net.max_error_m, "error_mean": NetStats.mean(net.error_samples), "offset_max": net.max_offset_m, + "replay_max": net.max_replayed_ticks, "inputs": inputs, + "relay_dropped": relay["up"]["dropped_packets"] + relay["down"]["dropped_packets"]} + + +func fly(server: Sector, client: Sector, seconds: float) -> void: + var cycle := 0.0 + for segment: Array in PATTERN: + cycle += segment[0] + var started := Time.get_ticks_msec() + var last := started + while Time.get_ticks_msec() - started < seconds * 1000.0: + var now := Time.get_ticks_msec() + var phase := fmod((now - started) / 1000.0, cycle) + var segment: Array = PATTERN[-1] + for candidate: Array in PATTERN: + if phase < candidate[0]: + segment = candidate + break + phase -= candidate[0] + for action: String in ACTIONS: + if action in segment[1]: + Input.action_press(action) + else: + Input.action_release(action) + client.player.pending_look.x += segment[2] * (now - last) / 1000.0 + last = now + keep_alive(server) + await process_frame + release_inputs() + + +## Keeps combat from interrupting the flight; positions stay authoritative. +func keep_alive(server: Sector) -> void: + for ship: Pilot in server.session.ships.values(): + ship.hull = ship.max_hull + ship.shield = ship.max_shield + + +func release_inputs() -> void: + for action: String in ACTIONS: + Input.action_release(action) diff --git a/tests/reconciliation_test.gd.uid b/tests/reconciliation_test.gd.uid new file mode 100644 index 0000000..4f23274 --- /dev/null +++ b/tests/reconciliation_test.gd.uid @@ -0,0 +1 @@ +uid://6nbt5fvqute3 diff --git a/tests/resource_upgrades_test.gd b/tests/resource_upgrades_test.gd index bda30c7..4146ac3 100644 --- a/tests/resource_upgrades_test.gd +++ b/tests/resource_upgrades_test.gd @@ -234,6 +234,9 @@ func run() -> void: check(is_equal_approx(client.player.max_shield, 1100) and is_equal_approx(client.player.cruise_speed, ship.cruise_speed), "Effective timed stats replicate to clients") var payload: Dictionary = client.session.goals[id].duplicate(true) payload["contracts"] = {} + # Input acknowledgement fields travel as fixed binary owner fields; see snapshot_codec_test. + for key: String in ["ack", "input_depth", "turn_budget", "inputs"]: + payload.erase(key) for offer: String in HuntingContracts.OFFERS: payload["contracts"][offer] = HuntingContracts.accept(offer) print("Boosted pilot with three contracts: %d bytes" % var_to_bytes([{id: payload}, {}, 1]).size()) diff --git a/tests/rpc_compatibility_test.gd b/tests/rpc_compatibility_test.gd index b1908b9..96e8729 100644 --- a/tests/rpc_compatibility_test.gd +++ b/tests/rpc_compatibility_test.gd @@ -66,7 +66,7 @@ func run() -> void: # Schema 17 previews share this RPC table but pack world entries and profiles # without revisions, so only the schema separates their fingerprints. var preview := server.session.protocol_fingerprint(17) - check(preview != server.session.protocol_fingerprint() and FlightSession.NETWORK_SCHEMA == 23, "Profile revisions change the protocol fingerprint") + check(preview != server.session.protocol_fingerprint() and FlightSession.NETWORK_SCHEMA == 24, "Profile revisions change the protocol fingerprint") var preview_server := func(id: int): server.multiplayer.send_auth(id, JSON.stringify({"nonce": "00".repeat(32), "protocol": preview}).to_utf8_buffer()) server.multiplayer.peer_authenticating.connect(preview_server) client.session.join("127.0.0.1", test_port(24683)) diff --git a/tests/server_export_client_test.gd b/tests/server_export_client_test.gd index b30a1b4..f4e6f49 100644 --- a/tests/server_export_client_test.gd +++ b/tests/server_export_client_test.gd @@ -22,7 +22,7 @@ func run() -> void: await process_frame check(not client.preflight, "Exported server admits pilot to flight") var start := client.player.position - client.session.command_flight.rpc_id(1, Vector3(0, 0, -1), Vector3.ZERO, true) + client.session.send_command(Vector3(0, 0, -1), Vector3.ZERO, true) deadline = Time.get_ticks_msec() + 3000 while client.player.position.distance_to(start) < 1.0 and Time.get_ticks_msec() < deadline: await process_frame diff --git a/tests/server_workload.gd b/tests/server_workload.gd index 3bd67bb..0663121 100644 --- a/tests/server_workload.gd +++ b/tests/server_workload.gd @@ -261,7 +261,7 @@ func drive_client(delta: float) -> void: if direction.length_squared() > 0.01: facing = Basis.looking_at(direction, Vector3.RIGHT if absf(direction.normalized().dot(Vector3.UP)) > 0.98 else Vector3.UP) var movement := (facing.inverse() * (destination - location) / 25.0).limit_length() - sector.session.command_flight.rpc_id(1, movement, facing.get_euler(), false, + sector.session.send_command(movement, facing.get_euler(), false, enemy.available(), int(sector.player.get_meta("life", 0)), enemy.life, enemy.alien_id) rocket_clock += 0.05 launcher_clock += 0.05 diff --git a/tests/snapshot_codec_test.gd b/tests/snapshot_codec_test.gd index 0647688..2192c1c 100644 --- a/tests/snapshot_codec_test.gd +++ b/tests/snapshot_codec_test.gd @@ -16,7 +16,7 @@ func same(a: Variant, b: Variant) -> bool: func round_trip_player(id: int, data: Dictionary, extras: Dictionary = {}) -> Dictionary: - var packet := SnapshotCodec.world(7, 3, [SnapshotCodec.player_entry(id, data, 65535, extras)], []) + var packet := SnapshotCodec.world(7, 3, 4242, [SnapshotCodec.player_entry(id, data, 65535, extras)], []) var world := SnapshotCodec.decode_world(packet) check(world.get("sequence") == 7 and world.get("visit") == 3 and world["players"].has(id) and world["players"][id]["profile"] == 65535, "World header, player ID and profile revision decode") return world @@ -88,8 +88,13 @@ func run() -> void: ship.resource_boosts = {"lasers": {"resource": "seprom", "remaining": 1_500_000_001}, "shields": {"resource": "promerium", "remaining": 512.25}} var owner := session.player_state(id, true) var extras := session.owner_extras(id) + extras.merge({"ack": 4_000_000_000, "depth": 7, "turn_budget": 0.625, "inputs": {"applied": 9, "duplicates": 40, "late": 1, "lost": 2, "dropped": 3, "starved": 4}}, true) world = round_trip_player(id, owner, extras) decoded = SnapshotCodec.player_state(world["players"][id], SnapshotCodec.player_profile(owner)) + check(world["tick"] == 4242, "The world header carries the server tick") + check(decoded["ack"] == 4_000_000_000 and decoded["input_depth"] == 7 and decoded["turn_budget"] == 0.625 and decoded["inputs"] == extras["inputs"], "Owner entries carry the input acknowledgement, buffer depth, turn budget and input counters") + for key: String in ["ack", "input_depth", "turn_budget", "inputs"]: + decoded.erase(key) check(same(decoded, owner), "Owner player state packs and unpacks with private progress and contracts") var unpacked: Dictionary = world["owner"] check(unpacked.get("rounds") == extras["rounds"], "Owner ammunition counts and selection unpack exactly") @@ -104,7 +109,7 @@ func run() -> void: enemy.engaged = true enemy.respawn = 2.5 var alien := combat.pack_alien(enemy) - var alien_packet := SnapshotCodec.world(9, 0, [], [SnapshotCodec.alien_entry(alien, 9)]) + var alien_packet := SnapshotCodec.world(9, 0, 1, [], [SnapshotCodec.alien_entry(alien, 9)]) world = SnapshotCodec.decode_world(alien_packet) check(world["aliens"][enemy.alien_id]["profile"] == 9 and same(SnapshotCodec.alien_state(world["aliens"][enemy.alien_id], SnapshotCodec.alien_profile(alien)), alien), "Alien state and profile revision pack and unpack") check(SnapshotCodec.decode_world(alien_packet.slice(0, 8)).is_empty() and SnapshotCodec.decode_world(alien_packet + PackedByteArray([0])).is_empty(), "Short or oversized packets are rejected") @@ -116,7 +121,7 @@ func run() -> void: var aliens: Array[PackedByteArray] = [] for each: Alien in server.map_rosters[0].values(): aliens.append(SnapshotCodec.alien_entry(combat.pack_alien(each), 1)) - var batch := var_to_bytes(SnapshotCodec.world(1, 0, players, aliens)).size() + var batch := var_to_bytes(SnapshotCodec.world(1, 0, 1, players, aliens)).size() var legacy := legacy_bytes(server, id) + 8 * var_to_bytes([{other: session.player_state(other, false)}, {}, 1, 0]).size() print("SNAPSHOT_PAYLOAD=", JSON.stringify({"legacy_bytes": legacy, "batched_bytes": batch, "ratio": snappedf(float(legacy) / batch, 0.01)})) check(batch < 1200, "Ten pilots and five aliens fit below the ENet datagram budget") @@ -142,10 +147,10 @@ func run() -> void: var sequence := session.snapshot_sequence var applied: int = first.session.player_sequences.get(other, -1) var entry := SnapshotCodec.player_entry(other, changed, (cached[0] + 1) % 65536) - first.session.world_snapshot(SnapshotCodec.world(sequence + 1, ship.map_visit, [entry], [])) + first.session.world_snapshot(SnapshotCodec.world(sequence + 1, ship.map_visit, 0, [entry], [])) check(first.session.player_sequences.get(other, -1) == applied and first.session.ships[other].laser_damage == 4321.0, "State packed with a newer profile waits instead of using the cached profile") first.session.entity_profiles({other: [(cached[0] + 1) % 65536, SnapshotCodec.player_profile(changed)]}, {}) - first.session.world_snapshot(SnapshotCodec.world(sequence + 2, ship.map_visit, [entry], [])) + first.session.world_snapshot(SnapshotCodec.world(sequence + 2, ship.map_visit, 0, [entry], [])) check(first.session.player_sequences.get(other, -1) == sequence + 2 and first.session.ships[other].laser_damage == 5000.0, "State applies once its profile revision arrives") await replicate(server) check(session.profile_revision(Vector2i(0, other), SnapshotCodec.player_profile(session.player_state(other, false)))[0] == (cached[0] + 1) % 65536, "The server advances the profile revision once per change") diff --git a/tools/check-suites.json b/tools/check-suites.json index 35a5db6..585e80a 100644 --- a/tools/check-suites.json +++ b/tools/check-suites.json @@ -15,6 +15,7 @@ {"name": "network_test", "checks": [["network_test.gd"]]}, {"name": "network_combat_test", "checks": [["network_combat_test.gd"]]}, {"name": "net_simulator", "checks": [["net_simulator_test.gd"], ["netsim_network_test.gd"]]}, + {"name": "netcode_reconciliation", "checks": [["input_buffer_test.gd"], ["reconciliation_test.gd"]]}, {"name": "private_snapshot_test", "checks": [["private_snapshot_test.gd"]]}, {"name": "wallet_ordering_test", "checks": [["wallet_ordering_test.gd"]]}, {"name": "snapshot_codec_test", "checks": [["snapshot_codec_test.gd"]]}, @@ -67,6 +68,7 @@ {"name": "benchmark_packet_accounting", "checks": [["tests/benchmark_server_test.py"]]}, {"name": "dedicated_server_test", "checks": [["dedicated_server_test.gd"]]}, {"name": "net_simulator", "checks": [["net_simulator_test.gd"], ["netsim_network_test.gd"]]}, + {"name": "netcode_reconciliation", "checks": [["input_buffer_test.gd"], ["reconciliation_test.gd"]]}, {"name": "sector_visuals_test", "checks": [["sector_visuals_test.gd"]]}, {"name": "station_assets_test", "checks": [["station_assets_test.gd"]]}, {"name": "combat_effects_test", "checks": [["combat_effects_test.gd"]]},