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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions GAME_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,48 @@ does not start at boot. No CPU or memory limits are needed for the current solo
development phase; both instances share host resources. Production deployment
remains a separate manual action. See DEPLOYMENT.md for setup and recovery.

### Real-time netcode rework

The user agreed to rework client/server movement networking into a measurable,
demonstrable system. The work spans six stacked PRs, measuring first. Gameplay
stays server-authoritative. Clients never send wallet, health, hit or reward
outcomes.

1. **Network simulator and netcode overlay.** An in-process threaded UDP relay
sits between the client's ENet socket and the server. It adds latency,
jitter, loss and duplication in both directions, so ENet's real reliability
and ordering still apply. It is opt-in: a debug setting or `--netsim`,
applied on the next connection. Once it's on, the sliders change conditions
live. F8 toggles an overlay in the F3 style showing the sliders, RTT, bytes/s
up and down, snapshot arrival jitter, the latest and largest correction, and
a translucent server ghost. Baseline numbers are recorded at 0, 100 and
200 ms, each with 0% and 5% loss.
2. **Ticks, input sequencing and reconciliation.** The 60 Hz simulation tick is
numbered. Each client input carries its tick, sequence number, movement,
boost and requested facing, and sends are redundant so loss doesn't drop
inputs. The server buffers inputs per pilot and consumes exactly one per
tick. Snapshots carry the server tick and each pilot's last processed
sequence. The client rewinds to the authoritative state, replays
unacknowledged inputs, and hides corrections with a decaying render offset.
The 720°/s facing limit and life checks remain.
3. **Snapshot interpolation.** Remote pilots and aliens render about 100 ms in
the past, between two buffered server-tick snapshots. When the buffer runs
dry they extrapolate for at most 250 ms. The overlay shows buffer depth and
underruns.
4. **Snapshot encoding.** Positions, angles and health are quantized. Each
viewer gets fields delta-encoded against the last snapshot it acknowledged,
falling back to full state, and packets stay under the ENet MTU. Bytes per
client per second are reported before and after.
5. **Degraded-network tests.** Headless multi-client playthroughs run through
the relay at 150 ± 30 ms with 5% loss in both CI jobs. They assert limits on
worst correction, lost inputs and bandwidth, and that hits and rewards stay
authoritative.
6. **docs/NETCODE.md.** Architecture, a timeline, tradeoffs and before/after
tables. The README portfolio section waits for the user's approval.

The interpolation delay, extrapolation cap, correction smoothing and the
redundancy count are playtesting settings. Each PR bumps the network schema.

## Ship visual refinement

The user requested a visual refinement of the existing twelve playable ships
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,9 @@ Esc opens the flight menu and releases the mouse. Choose **Settings** there or i

The Audio tab has master/effects volume, mute and a test sound. The Graphics tab contains fullscreen, VSync, a typed frame rate limit, antialiasing, the performance overlay and window resolution. Enter a whole-number FPS limit from 1 to 1000, or 0 for unlimited, then press Enter or leave the field to apply and save it. The default is unlimited. VSync is off by default; enable it to synchronize rendering with your screen's refresh rate and reduce tearing. VSync may limit FPS below the entered cap. Resolution choices fit the current screen with room for borders and the taskbar. Selecting one switches to windowed mode; fullscreen uses the desktop resolution. You can also resize the window manually. Mouse steering uses unscaled screen motion so viewport scaling does not change sensitivity.

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, 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.
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.

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
Expand Down
54 changes: 54 additions & 0 deletions docs/netcode-baseline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Netcode baseline

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`.

```
godot --headless --path . --script res://tests/netcode_benchmark.gd -- --scenario=baseline
```

Setup: one dedicated server, one measured client routed through the relay and
three clients connected directly, all in one headless process on a Windows 11
desktop (129–139 frames per second). Every pilot flies the same scripted input:
thrust, boost, strafe and turns in a mirrored 6-second cycle, about 30 m/s on
average. Each condition gets a 15-second warm-up and is then measured for
20 seconds. Added RTT is split evenly per direction (100 ms adds 50 ms each
way); loss applies independently in both directions. Metric definitions are in
the header of `tests/netcode_benchmark.gd`.

| Added RTT | Loss | ENet RTT | 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 |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 0 ms | 0% | 28 ms | 1.1 KB/s | 13.6 KB/s | 13.6 KB/s | 5.7 / 16.0 / 30.5 ms | 0.24 / 0.55 / 0.87 m | 0.05 / 0.11 / 0.17 m | 0.20 / 0.47 m | 400 / 400 / 0 (0.0%) |
| 100 ms | 0% | 105 ms | 1.1 KB/s | 14.0 KB/s | 14.0 KB/s | 5.7 / 13.7 / 58.7 ms | 0.15 / 0.45 / 0.81 m | 0.03 / 0.09 / 0.16 m | 1.55 / 2.77 m | 401 / 400 / 1 (0.2%) |
| 200 ms | 0% | 206 ms | 0.7 KB/s | 6.3 KB/s | 6.3 KB/s | 61.3 / 156.8 / 175.0 ms | 0.82 / 1.81 / 2.78 m | 0.16 / 0.36 / 0.56 m | 3.26 / 6.11 m | 400 / 261 / 139 (34.8%) |
| 0 ms | 5% | 32 ms | 1.1 KB/s | 12.8 KB/s | 13.6 KB/s | 9.6 / 45.9 / 107.8 ms | 0.24 / 0.55 / 0.79 m | 0.05 / 0.11 / 0.16 m | 0.22 / 0.51 m | 400 / 385 / 15 (3.8%) |
| 100 ms | 5% | 105 ms | 1.1 KB/s | 13.5 KB/s | 14.4 KB/s | 7.3 / 30.6 / 98.8 ms | 0.15 / 0.39 / 1.57 m | 0.03 / 0.08 / 0.31 m | 1.55 / 2.74 m | 400 / 389 / 11 (2.8%) |
| 200 ms | 5% | 202 ms | 0.8 KB/s | 10.0 KB/s | 10.6 KB/s | 21.2 / 64.1 / 157.9 ms | 0.37 / 0.96 / 1.42 m | 0.07 / 0.19 / 0.28 m | 3.05 / 5.45 m | 400 / 299 / 101 (25.3%) |

## Observations

- **Prediction error looks small because reconciliation hides latency.** Each
snapshot pulls the local ship 20% toward the authoritative position, which
is about one round trip old. At steady speed this drags the predicted ship
back onto the delayed server path instead of correcting real mispredictions.
The gap to the server's current position grows with latency (0.2 m at 0 ms,
1.6 m at 100 ms, 3.3 m at 200 ms), so the controls feel delayed even though
the per-snapshot correction stays under 0.6 m.
- **ENet's packet throttle drops unreliable traffic at 200 ms.** Commands and
snapshots are unreliable, and ENet discards unreliable packets at the sender
when its round-trip variance suggests congestion. At 200 ms added RTT, 25–35%
of flight commands never left the client and the server sent up to half its usual
snapshot bytes, even with no simulated loss. Snapshot jitter rises
accordingly. Phase 2's redundant inputs, and possibly ENet throttle settings,
need to account for this.
- **Lost datagrams lose inputs.** At 5% loss, 3–4% of flight commands never
reach the server. Commands are not resent, so each loss leaves the server on
the previous input until the next command 50 ms later.
- **ENet RTT is a smoothed estimate.** ENet adjusts it by 1/8 per reliable
acknowledgement, about two per second here, so it lags condition changes by
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.
36 changes: 35 additions & 1 deletion scripts/flight_session.gd
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ var lab_clock: float = 0.0
var jump_pending := false
var jump_cover: CanvasLayer
var jump_until: Dictionary[int, int] = {}
## Netcode measurements; see NetStats. Clients feed and the F8 overlay reads them.
var net_stats := NetStats.new()
## Debug relay between this client and the server. Its conditions persist
## between connections; it runs only while a connection uses it.
var net_simulator := NetSimulator.new()
## Route the next join() through net_simulator. Off for normal play.
var use_net_simulator := false


func _ready() -> void:
Expand All @@ -79,6 +86,7 @@ func _ready() -> void:
multiplayer.connection_failed.connect(func(): disconnect_session("Connection failed. Check the address and UDP port, then try again."))
multiplayer.server_disconnected.connect(func(): disconnect_session("Connection to the server was lost. You can try connecting again."))
if not sector.dedicated_server:
use_net_simulator = net_simulator.configure_from_args(OS.get_cmdline_user_args())
build_menu()
if "--print-protocol" in OS.get_cmdline_user_args():
# Operator/CI diagnostic. No network connection or pilot credentials are needed.
Expand Down Expand Up @@ -180,11 +188,15 @@ func _process(_delta: float) -> void:
print("Server shutdown requested; closing pilot store.")
get_tree().quit()
return
if active and not multiplayer.is_server():
net_stats.sample_transport(multiplayer.multiplayer_peer)
if menu.visible:
layout_menu()
status_label.text = status
if not attempted_address.is_empty():
status_label.text = "%s | UDP %d\n%s" % [attempted_address, attempted_port, status]
if net_simulator.is_running():
status_label.text += "\nRouted through the network simulator (debug)."
if connecting:
status_label.text += "\nWaiting for the server, up to %d seconds." % int(CONNECT_TIMEOUT)
preference_label.text = "Could not save this connection for the next launch." if preferences.save_failed else "Remembers the last successful connection on this device."
Expand Down Expand Up @@ -263,11 +275,23 @@ func join(host_address: String, port: int = PORT) -> Error:
if sector.client_only and (not PilotStore.valid_id(credential_id) or not PilotStore.valid_hex(credential_token)):
status = "Set DORBIT_PILOT_FILE to the pilot credential file supplied by the server operator."
return ERR_UNAUTHORIZED
# The debug relay is opt-in; the menu and status keep the real address.
var connect_address := host_address
var connect_port := port
if use_net_simulator:
var relay_error := net_simulator.start(host_address, port)
if relay_error != OK:
status = "Could not start the network simulator: %s." % error_string(relay_error)
return relay_error
connect_address = "127.0.0.1"
connect_port = net_simulator.listen_port
var peer := ENetMultiplayerPeer.new()
var error := peer.create_client(host_address, port)
var error := peer.create_client(connect_address, connect_port)
if error != OK:
net_simulator.stop()
status = "Could not start the connection: %s. Check the address and UDP port." % error_string(error)
return error
net_stats.reset()
multiplayer.multiplayer_peer = peer
connecting = true
auth_proof_sent = false
Expand Down Expand Up @@ -762,6 +786,7 @@ func tick(delta: float) -> void:
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)
combat.interpolate(delta)
for id: int in goals:
Expand Down Expand Up @@ -878,6 +903,7 @@ func command_flight(movement: Vector3, angles: Vector3, boost: bool, fire: bool
return
if not ships[id].alive or combat.records[id]["life"] != 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),
Expand All @@ -900,6 +926,7 @@ func entity_profiles(players: Dictionary, aliens: Dictionary) -> void:
func world_snapshot(packet: PackedByteArray) -> void:
if not active:
return
net_stats.record_snapshot_arrival()
var world := SnapshotCodec.decode_world(packet)
if world.is_empty() or not receives_map(world["visit"]):
return
Expand Down Expand Up @@ -956,10 +983,14 @@ func snapshot(state: Dictionary, alien_state: Dictionary, sequence: int, visit:
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
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
received_snapshot = true
status = "Connected. Players: %d/%d" % [ships.size(), MAX_PLAYERS]
Expand All @@ -983,6 +1014,8 @@ func disconnect_session(message: String) -> void:
combat.finish()
multiplayer.multiplayer_peer.close()
multiplayer.multiplayer_peer = OfflineMultiplayerPeer.new()
net_simulator.stop()
net_stats.has_server_state = false
for ship: Pilot in ships.values():
if ship != sector.player:
ship.queue_free()
Expand Down Expand Up @@ -1020,6 +1053,7 @@ func _exit_tree() -> void:
if not store.close() and not already_failed: get_tree().quit(1)
if active or connecting:
multiplayer.multiplayer_peer.close()
net_simulator.stop()


func receives_map(visit: int) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion scripts/game_settings.gd
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const SHORTCUTS := {
"quality": KEY_F4, "quit_game": KEY_F10, "resolution_down": KEY_F5,
"resolution_up": KEY_F6, "multiplayer_menu": KEY_F7,
"contracts": KEY_C, "station_shop": KEY_B, "ship_equipment": KEY_I,
"sector_map": KEY_M,
"sector_map": KEY_M, "netcode": KEY_F8,
}

var sensitivity: float = DEFAULT_SENSITIVITY
Expand Down
6 changes: 6 additions & 0 deletions scripts/hud.gd
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ var tip_keys: Array[Array] = []
var tip_keys_key := Vector2i(-1, -1)
var navigation: FlightNavigation
var ammo_bar: AmmoBar
var netcode: NetcodeOverlay
var layout: HudLayout
# Binding phrases and control hints are rebuilt after any rebind.
var phrases: Dictionary[String, String] = {}
Expand All @@ -89,6 +90,9 @@ func _ready() -> void:
ammo_bar = AmmoBar.new()
ammo_bar.sector = sector
add_child(ammo_bar)
netcode = NetcodeOverlay.new()
netcode.hud = self
add_child(netcode)
layout = HudLayout.new()
layout.hud = self
add_child(layout)
Expand Down Expand Up @@ -764,6 +768,8 @@ func _draw() -> void:
draw_gate_countdown()
draw_tutorial()
draw_performance()
if netcode.visible:
marker_labels.append(layout.rect_for("netcode"))
if layout.begin_draw(self, "ship"):
draw_ship_panel()
layout.end_draw(self)
Expand Down
5 changes: 4 additions & 1 deletion scripts/hud_layout.gd
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const ITEMS := {
"station": ["Station actions", "shop"], "radiation": ["Radiation", "shield"],
"reticle": ["Reticle", "damage"], "autopilot": ["Autopilot status", "speed"],
"performance": ["Performance", "settings"], "ammo": ["Quickslots", "damage"],
"tutorial": ["Control tips", "settings"]
"tutorial": ["Control tips", "settings"], "netcode": ["Netcode", "connection"]
}
# Read-only default, so per-frame layout lookups do not allocate a Dictionary.
const NO_ENTRY := {}
Expand Down Expand Up @@ -108,6 +108,7 @@ func default_rect(id: String) -> Rect2:
"autopilot": return Rect2(hud.navigation.radar_rect().position + Vector2(14, 190), Vector2(170, 26))
"performance": return Rect2(FlightHud.SIDE_MARGIN, hud.objectives_rect().end.y + 192, 350, 26)
"tutorial": return hud.tutorial_rect()
"netcode": return Rect2(Vector2(size.x - FlightHud.SIDE_MARGIN - NetcodeOverlay.SIZE.x, hud.navigation.radar_rect().end.y + 14), NetcodeOverlay.SIZE)
return Rect2()


Expand Down Expand Up @@ -198,6 +199,8 @@ func reopen(id: String) -> void:
hud.sector.settings.show_performance = true
hud.sector.show_performance = true
hud.sector.settings.save()
if id == "netcode":
hud.sector.show_netcode = true
# Hide the rail when it covers the selected panel, so its full saved position
# can be edited without relocating it just by opening the editor.
if rect_for(id).intersects(sidebar.get_rect()):
Expand Down
Loading
Loading