294 lines
14 KiB
Markdown
294 lines
14 KiB
Markdown
# WebSocket Deterministic Lockstep Networking
|
|
|
|
## Scope
|
|
|
|
The Windows WebSocket transport uses Boost.Asio and Boost.Beast to run a
|
|
server-sequenced deterministic lockstep simulation. A client receives one
|
|
authoritative state at a completed tick boundary. After that, the server sends
|
|
only numbered tick messages containing ordered destination, combat-intent,
|
|
and presence commands (or an empty command list).
|
|
|
|
Client intent is intentionally limited to
|
|
`SetCharacterDestinationCommand`, `SetCharacterTargetCommand`,
|
|
`ClearCharacterAttackTargetCommand`, and
|
|
`TryCharacterAttackComboCommand`.
|
|
The server also sends `SetCharacterEnabledCommand` in tick bundles when a
|
|
configured player slot connects or disconnects.
|
|
|
|
## Runtime Architecture
|
|
|
|
### Server
|
|
|
|
`WebsocketGameServer` wraps the headless `InternalGameServer`.
|
|
|
|
- The simulation tick is fixed at 100 ms.
|
|
- Each accepted connection is assigned the first free character ID from the
|
|
campaign's `networkPlayerSlots`; the connection is rejected when all slots
|
|
are occupied.
|
|
- Player slots start disabled. The server consumes and broadcasts an enabled
|
|
command on the next tick for each connection and disconnection, including to
|
|
the newly connected client.
|
|
- The initial message contains the state, completed snapshot tick, assigned
|
|
player ID, tick duration, two-tick input delay, and compatibility fingerprint.
|
|
- Destination and character-action inputs cross from the Asio thread through a
|
|
queue. The simulation thread validates client sequence numbers, replaces
|
|
client identity with the assigned slot, and schedules commands two ticks in
|
|
the future.
|
|
- Every tick is broadcast, including ticks with no commands. No periodic state
|
|
snapshots are sent.
|
|
|
|
### Client
|
|
|
|
`WebsocketGameClient` implements `IGameServer`.
|
|
|
|
- It connects asynchronously to a `ws://` or `wss://` endpoint (`WebsocketEndpoint::parse`).
|
|
- Received messages are queued by the network thread and applied on the game
|
|
thread from `update()`.
|
|
- It maintains an internal `InternalGameServer` replica so existing snapshot
|
|
consumers and transitional runtime-state bindings continue to work.
|
|
- Camera orientation lives in host-owned `LocationLocalState`, so incoming
|
|
authoritative snapshots cannot overwrite camera movement.
|
|
- `submit()` serializes destination and tagged character-action intent. Other
|
|
command variants remain local no-ops for a remote connection.
|
|
- Tick bundles are buffered by ID. The replica advances only while the next
|
|
contiguous tick is available, applying its commands before one exact 100 ms
|
|
simulation step.
|
|
- Completed simulation events are passed to the runtime `Location` for
|
|
presentation, and ordinary server events are drainable through `IGameServer`.
|
|
- Client-side save and load calls are ignored because persistence remains
|
|
server-side.
|
|
|
|
`RemoteGameServerHost` prepares local presentation resources and runtime
|
|
locations against the replica and presents completed-tick events. It never
|
|
advances simulation from a render-frame delta.
|
|
|
|
## Delayed Ticks and Connection Loss
|
|
|
|
- **Delay.** The client never advances simulation from wall-clock time. If tick N
|
|
is missing it stalls: the world looks frozen, but input is still sent (the
|
|
server schedules it two ticks after it arrives). When the missing ticks arrive
|
|
the client applies all contiguous buffered ticks in one `update()` call, so
|
|
the game visibly fast-forwards. There is no timeout or resynchronization.
|
|
- **Connection lost.** `WebsocketGameClient::connectionFailed()` becomes true
|
|
on any socket error, any close after connecting (including a clean server
|
|
close), a `server_full`/`incompatible` rejection, or a compatibility
|
|
fingerprint mismatch. `Game` then unloads the campaign and returns to the main
|
|
menu / campaign selection (checked once loading has completed).
|
|
- **Server side.** A read error, close, or write error releases the slot, closes
|
|
the socket, and schedules `SetCharacterEnabledCommand(enabled=false)` for the
|
|
next tick, which is broadcast so every replica disables that character.
|
|
Inputs queued from a released slot in the same update are discarded.
|
|
- There is no application-level heartbeat; a silently dead peer is detected by
|
|
Beast's idle timeout.
|
|
|
|
## Message Signing and Rate Limiting
|
|
|
|
- **Session secret.** On connect the server generates 32 random bytes and sends
|
|
them hex-encoded as `sessionSecret` in `initial_state`. The client must receive
|
|
a valid 64-hex-character secret or the message is rejected.
|
|
- **Per-message key.** `key = SHA-256(sessionSecret || appPepper || bigEndian(clientSequence))`.
|
|
The pepper is rebuilt at run time from three masked fragments in separate
|
|
functions (`MessageAuth.h`); it is never one contiguous constant. This raises
|
|
the cost of extraction but cannot stop a determined reverse engineer, since the
|
|
client must hold it. Change the fragments for each release if desired.
|
|
- **Signature.** Every client input envelope carries `signature =
|
|
hex(HMAC-SHA256(key, "type|clientSequence|payload"))`, where `payload` is the
|
|
canonical JSON dump. `clientSequence` starts at 1 per connection and must
|
|
strictly increase (replay protection).
|
|
- **Validation order (server, per session, on the network thread).** rate limit,
|
|
then signature, then sequence, then payload parsing.
|
|
- **Rate limit.** More than `kMaxCommandsPerSecond` (20) messages inside a
|
|
sliding one-second window counts every message, valid or not.
|
|
- **Kick.** A rate-limit, signature or replay failure makes the server send a
|
|
final `error` (`rate_limited`, `invalid_signature` or `replayed_message`),
|
|
ignore the session, and close it. The slot is released and
|
|
`SetCharacterEnabledCommand(enabled=false)` is broadcast like any disconnect.
|
|
The client treats any error other than `invalid_input` as a lost connection and
|
|
returns to the menu. A malformed but correctly signed payload only yields
|
|
`invalid_input` and does not kick.
|
|
- **Primitives.** SHA-256/HMAC are implemented in the header-only
|
|
`src/game_server/MessageAuth.h`, because the standalone server and the web
|
|
client do not link OpenSSL. It is checked against the standard test vectors.
|
|
- **Limits.** Over plain `ws://` the secret travels in cleartext, so use `wss://`
|
|
(the reverse proxy). Only client inputs are signed; the server's tick messages
|
|
are not.
|
|
|
|
## Multiple Commands per Frame
|
|
|
|
A client may send several inputs in one frame; each is a separate message. The
|
|
server keeps, per player and per scheduled tick, only the **last order**, where
|
|
an order is `destination_input`, `set_target`, or `clear_attack_target`.
|
|
`try_attack_combo` and presence commands are never dropped. Orders are applied
|
|
by the shared `applyScheduledCommand()` (`LockstepApply.h`) on the server and on
|
|
every replica:
|
|
|
|
- destination: clear the attack target, then walk to the point;
|
|
- `set_target`: stop the current walk, then attack (the chase path is planned by
|
|
the simulation);
|
|
- `clear_attack_target`: clear the attack target only.
|
|
|
|
So "walk to A, then attack NPC 1" attacks, and "attack NPC 1, then walk to A"
|
|
walks. The client therefore sends the destination before `set_target` when a
|
|
hostile NPC is clicked, and no longer sends redundant trailing clears.
|
|
|
|
## Campaign Routing
|
|
|
|
The graphical game uses stable router objects for `IGameServer` and
|
|
`IGameServerHost`, allowing existing UI and runtime references to remain valid.
|
|
|
|
When `NETWORK` is defined:
|
|
|
|
- `battle_zone_multiplayer` uses `WebsocketGameClient` and `RemoteGameServerHost`.
|
|
- `main`, `battle_zone`, and every other campaign use `InternalGameServer` and
|
|
`LocalGameServerHost`.
|
|
|
|
The WebSocket client is created only when `battle_zone_multiplayer` is selected
|
|
and is destroyed when that campaign is unloaded. The single-player and
|
|
multiplayer Battle Zone entries share location content but use separate
|
|
start-state files. At startup, the standalone server loads the multiplayer
|
|
start state; each remote client restores the received authoritative state and
|
|
its own local presentation state. The multiplayer campaign currently declares the
|
|
pre-existing `player` and `player2` state entries as connection
|
|
slots; the random test-bot controller is disabled.
|
|
The campaign's `networkCompatibility` token is the fingerprint (currently
|
|
`battle-zone-lockstep-v5`); release builds must bump it whenever deterministic
|
|
content changes.
|
|
|
|
If DNS resolution, TCP connection, the WebSocket handshake, or the active socket
|
|
fails, the client unloads the remote campaign and returns to the campaign
|
|
selection screen.
|
|
|
|
## JSON Protocol v2
|
|
|
|
Every message uses a versioned JSON envelope:
|
|
|
|
```json
|
|
{
|
|
"protocolVersion": 2,
|
|
"type": "tick",
|
|
"payload": {
|
|
"tickId": 81,
|
|
"commands": [],
|
|
"stateHash": "0123456789abcdef"
|
|
}
|
|
}
|
|
```
|
|
|
|
Message types are:
|
|
|
|
- `initial_state` (server to client): one state snapshot and lockstep metadata;
|
|
- `destination_input` (client to server): monotonic client sequence and a
|
|
centimetre-normalized finite target;
|
|
- `character_action` (client to server): monotonic client sequence, an action
|
|
tag (`set_target`, `clear_attack_target`, or `try_attack_combo`), and a
|
|
target ID for `set_target`;
|
|
- `tick` (server to client): tick ID, globally sequenced destination,
|
|
character-action, and character-presence commands, and post-tick diagnostic
|
|
state hash;
|
|
- `error` (server to client): invalid input, incompatibility, full server, or a
|
|
kick (`rate_limited`, `invalid_signature`, `replayed_message`).
|
|
|
|
Protocol v1 is not compatible. Malformed payloads, non-finite or out-of-range
|
|
coordinates, duplicate client sequences, empty action IDs, and unsupported
|
|
commands cannot enter the authoritative command stream. The server derives the
|
|
location and player character from the assigned connection slot; clients cannot
|
|
use these actions to control another player or an NPC.
|
|
|
|
WebSocket ordering is not used as simulation time. Integer tick IDs are the
|
|
only authoritative clock. The server uses `steady_clock` only to pace its loop,
|
|
and clients may have different wall clocks without affecting the result. A
|
|
client stalls on a missing tick instead of predicting or rolling back.
|
|
|
|
Single-player persistence remains a separate envelope combining authoritative
|
|
and client-local state. `savedAt`, camera state, and presentation objects are
|
|
excluded from the diagnostic deterministic hash.
|
|
|
|
## Build Configuration
|
|
|
|
Networking is enabled for Windows and the Emscripten web client:
|
|
|
|
- `proj-windows/CMakeLists.txt` defines `NETWORK`, compiles the WebSocket client
|
|
and remote host, and links `ws2_32` and `mswsock`.
|
|
- `server/CMakeLists.txt` defines `NETWORK` for the Windows `GameServer`, compiles
|
|
the WebSocket server, and links the Windows socket libraries.
|
|
- `proj-web/CMakeLists.txt` defines `NETWORK`, compiles the shared protocol,
|
|
replica, and remote-host code, and links Emscripten's `websocket.js` library.
|
|
`WebsocketGameClient.cpp` selects the browser WebSocket API on Emscripten; it
|
|
does not use Boost.Asio, Boost.Beast, or OpenSSL there. The browser performs
|
|
the TLS handshake and certificate/hostname validation for `wss://`.
|
|
- `proj-windows` defines
|
|
`NETWORK_TLS` and links static OpenSSL 3.4.1, which CMake downloads and builds
|
|
automatically at configure time (`cmake/ThirdParty.cmake`, section 12) using a
|
|
downloaded portable Strawberry Perl and the nmake from the installed Visual Studio
|
|
(located through `vswhere`). Builds go to `thirdparty/openssl-3.4.1/install-Debug`
|
|
and `install-Release`; later configures skip them. `NETWORK_TLS` unset (server tests)
|
|
means native `wss://` endpoints fail with a logged error.
|
|
- Linux and Android builds do not define `NETWORK` and do not compile the
|
|
network transport.
|
|
|
|
## Running
|
|
|
|
Build the server:
|
|
|
|
```powershell
|
|
cmake -S server -B server/build
|
|
cmake --build server/build --config Debug --target GameServer
|
|
```
|
|
|
|
Run it from the repository root:
|
|
|
|
```powershell
|
|
.\server\build\Debug\GameServer.exe --campaign battle_zone_multiplayer --location uni_exterior
|
|
```
|
|
|
|
The listener defaults to `0.0.0.0:8080` and serves plain WebSocket traffic. It can be changed with:
|
|
|
|
```text
|
|
--address IP
|
|
--port N
|
|
```
|
|
|
|
Launch the Windows game and select `battle_zone_multiplayer`. The production client
|
|
default is `wss://api.shadowoverbishkek.com/server001/`; the endpoint is currently
|
|
configured in `Game.cpp`. Selecting another campaign continues to use the local
|
|
server.
|
|
|
|
For the Web build, serve the page over HTTPS and ensure the TLS-terminating reverse
|
|
proxy presents a valid certificate for `api.shadowoverbishkek.com`, accepts the
|
|
WebSocket upgrade at `/server001/`, and forwards the upgraded connection to the
|
|
plain server listener. A page served over HTTPS cannot connect to a `ws://` endpoint
|
|
because browsers block that mixed-content request. Certificate and hostname errors
|
|
are enforced by the browser and cannot be bypassed by the C++ client.
|
|
|
|
## Verification
|
|
|
|
CTest covers protocol-v2 round trips and validation, input-delay ordering,
|
|
fixed-tick replica behavior, campaign slot metadata, initial connection and
|
|
slot assignment, connection/disconnection presence propagation, destination
|
|
submission, and contiguous tick consumption.
|
|
|
|
## Current Limitations
|
|
|
|
- Paths are calculated independently on every lockstep participant from the
|
|
same ordered commands and tick-start occupancy. Integer A* costs, stable
|
|
character IDs, serialized previous-tick movement and blocked/retry state, and deterministic
|
|
nearest-reachable ties keep route selection aligned.
|
|
- Moving characters are omitted from A* but remain solid to the authoritative
|
|
movement guard. After three blocked ticks, players/bots cancel movement while
|
|
NPCs stop and consume the next serialized cooldown from their deterministic
|
|
retry sequence before replanning around the blocker.
|
|
- Opposing traffic can wait in a one-character-wide corridor because the
|
|
current policy does not reserve future space-time cells.
|
|
- Only preconfigured player slots can connect; dynamic join/spawn commands are
|
|
not implemented.
|
|
- There is no authentication or reconnect/replay history.
|
|
- A hash mismatch is logged but does not yet trigger checkpoint resynchronization.
|
|
- The endpoint is hardcoded in the graphical client (`kMultiplayerServerUrl` in
|
|
`Game.cpp`, currently `wss://api.shadowoverbishkek.com/server001/`).
|
|
- TLS certificate or hostname problems are logged but deliberately do not abort the
|
|
connection. `GameServer` itself has no TLS; it must sit behind a TLS-terminating proxy.
|
|
- Multiplayer Lua and dialogue behavior remains unsupported.
|
|
- Determinism is supported for identical executable/content builds. The
|
|
floating-point simulation is not guaranteed bit-identical across platforms
|
|
or compilers.
|