Files
tidewall/docs/ARCHITECTURE.md
T
claudeandClaude Opus 5.5 4a2d0b4031 H6: Full visual QA pass, with a checklist and make qa-captures
Rendered all 82 capture scenarios and the HUD at 3840x2160, and viewed
every one against a checklist covering menus, the lobby, the drop, every
biome, points of interest, building, players and items, combat, the HUD,
the chart, each tide phase, the gale, under water and results
(docs/VISUAL_QA.md). Two defects were filed and fixed: H15 (#84) and H16
(#85).

- make qa-captures (tools/qa_captures.sh) renders the whole set one
  container at a time, waiting when the host is short of memory, and
  tools/contact_sheet.gd lays them out four to a sheet for a first look.
- No placeholder art or text remains: ARCHITECTURE.md no longer calls the
  figures, barge and items stand-ins. The plain shapes in the camera*
  scenarios are test cards under test/, which isn't exported.

Closes #59

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:08:55 -05:00

683 lines
41 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Tidewall architecture
Tidewall is **server-authoritative from day one**. A match is always a server plus
clients. Offline play starts a local server with bots and connects to it through the
same interfaces, so there is one code path, and multiplayer is never a retrofit.
## Rules that do not bend
1. The simulation decides everything that affects the match. Clients ask; the server rules.
2. **Simulation code has no dependency on rendering, audio or UI.** `src/sim/` doesn't
use any nodes or servers from those engine areas, and a test scans it to enforce this.
3. The simulation advances only in fixed ticks of 30 Hz, and takes no input other than
commands and the seed.
4. Gameplay numbers live in `src/sim/tuning.gd`.
## Simulation and presentation
```
commands snapshots, events
Humans ─┐ ┌─ Renderer
Bots ──┼──> Server simulation (30 Hz, authoritative) ──> ├─ Audio
Net ──┘ └─ UI / HUD
```
- **Simulation (`src/sim/`)**: plain `RefCounted` objects and data arrays. Testable
without a scene tree. Runs identically on the server and in prediction on clients.
- **Presentation (`src/client/`, `src/ui/`, `src/audio/`)**: reads snapshots and events
and draws them, interpolating between ticks. It never changes simulation state.
- The simulation emits **events** (shot fired, piece built, player downed) in a per-tick
list. Presentation turns them into effects and sound.
## Tick rate
The simulation runs at `Tuning.TICK_RATE_HZ` (30 Hz, 33.33 ms). The server runs a fixed
accumulator and may run several ticks to catch up, with no more than 5 per frame.
Snapshots go out every second tick, 15 a second. The client renders at any frame rate,
predicts its own player and draws everyone else about 130 ms in the past.
## Player command stream
A `PlayerCommand` is one tick of one player's intent. Humans, bots and the network all
produce the same struct, so the simulation can't tell them apart.
| Field | Type | Meaning |
|---|---|---|
| `tick` | u32 | Tick the command applies to |
| `move_x`, `move_y` | i8 | Movement axes, scaled to -1..1 |
| `yaw` | u16 | Look yaw, full turn over 65536 steps |
| `pitch` | i16 | Look pitch, ±90° over ±32767 steps |
| `buttons` | u16 | Bit flags: fire, aim, jump, crouch, sprint, reload, interact, build |
| `selection` | u8 | Active inventory slot or build piece |
| `material` | u8 | Active build material |
| `view_lag` | u8 | How far in the past the player was seeing everyone else, back from `tick`, in quarter ticks. 0 for bots and local play |
Clients stamp commands for the tick they predict, and each packet repeats recent
commands to survive loss. The server applies the command for each tick, or a neutral
command with the player's last look direction if none has arrived.
**Look convention.** At yaw 0 the player faces +z; forward is `(sin yaw, 0, cos yaw)`.
Right is forward × up, `(-cos yaw, 0, sin yaw)`, matching Godot's right-handed, y-up
frame, so turning right *decreases* yaw. Positive pitch looks up. `Movement` and the
client's `CameraRig` both follow this, and a test checks that strafing right moves
towards the camera's screen-right.
The binary encoding is a fixed 15 bytes per command, little-endian, in the order of
the table above. See `src/sim/player_command.gd`. Decoding a truncated buffer returns
nothing, and out-of-range values are clamped, so bad input can't reach the simulation.
The player a command belongs to comes from its connection, never from the packet.
## Entity IDs
Every entity has a `u32` ID, allocated from a counter starting at 1 and **never reused
within a match**. ID 0 means "none". Snapshots refer only to IDs, which removes a whole
class of stale-reference bugs. Iteration is always in ascending ID order, so it's
deterministic.
## Seeded RNG rules
- A match has one `u64` seed, always logged.
- Gameplay randomness comes only from named streams, created from the match seed and a
stable name: `rng.stream("loot")`, `"weapons"`, `"drop"`, `"worldgen"`, and so on, on one `SimRng`.
One system's extra rolls can't disturb another's.
- Bots don't draw from those streams. Each bot has its own generator, seeded from the
match seed and its player ID, so nothing a bot thinks changes the simulation's state.
- Simulation code **never** calls `randf`, `randi`, `Time`, or anything else that varies
between runs. Presentation can use whatever randomness it likes, for effects.
- The same seed and the same command log produce the same state hash, on the same engine
build. Worldgen runs on both ends from the same seed, so the terrain itself is never sent.
`Simulation.state_hash()` is a SHA-256 over a canonical encoding of the tick, the next
entity ID, every RNG stream's state and every entity in ID order, with positions rounded
to millimetres.
Determinism is for tests, replays and worldgen. Clients don't rely on bit-exact matches
with the server. Reconciliation corrects any difference.
## Command log and replay
`CommandLog` (`src/server/`) holds a match's seed, its rules and every command the
server was given: the simulation tick it arrived on, the handle it came from and the
command's 15 bytes. `ServerLoop.submit()` is the one way commands get in, for people,
scripts and bots alike, so a recording server logs them all, accepted or not. On disk
it is a JSON header and the records compressed with Zstandard, about 0.6 MB for a
24-player match.
`MatchReplay` plays a log again: the same seed and rules, the same commands on the same
ticks, and nobody thinking. It ends on the same state hash as the recording, which
`make match` checks after every run. A replay can stop at any tick, which is how the
match captures draw a moment of a real match. Replays are exact only on the same engine
build, like everything else that relies on determinism.
`ScriptedPlayer` (`src/bots/`) is a stand-in for a person at the controls. It plays a
human seat as a bot would, and also cuts driftwood and builds a breakwater and a wall,
so a scripted match covers the drop, loot, combat, harvesting, building and the tide
from a player's seat. `ServerLoop.play_humans_by_script()` turns it on; no shipped mode
uses it.
## Transport and handshake
The transport is ENet over UDP, used directly through `ENetConnection` (not Godot's
high-level multiplayer API, so the server controls every byte it accepts). Channel 0
is reliable control traffic; channel 1 is for commands and snapshots.
`NetServer` and `NetClient` (`src/net/`) own the two ends, and `NetProtocol` the
message layouts and the protocol version. A new connection is a guest until its HELLO
is accepted:
1. The client sends HELLO: a magic number, its protocol version and the name it wants.
2. The server answers WELCOME (the player's handle, the match seed, tick rate, player
limit and the name as accepted) or REJECT with a reason, then disconnects.
A guest gets one try. A HELLO that is malformed, on the wrong channel or too long is
refused as such; a different protocol version, a full server and silence past the
handshake timeout each have their own reason, and the client turns the reason into a
sentence for the player (`NetProtocol.reason_text`). The reason also rides on the
disconnect itself, in case the REJECT is lost. Names are cleaned on both ends: control
and invisible characters removed, 16 characters at most, never empty, and a number
added if someone already has it. Handles are positive, count up and are never reused
while the server runs.
Leaving cleanly tells the server at once. A client that vanishes is dropped by ENet's
timeout (5 to 15 seconds without an acknowledgement), and the owner sees the same
"left" event with a different reason. Decoders return nothing for bad input and never
raise an engine error; anything a joined player sends that isn't understood is counted
and dropped.
## Finding and joining games
People join a server three ways, none needing a third-party service:
- **By address.** `--connect=HOST[:PORT]`; the game port defaults to 24650.
- **On the LAN.** A listening server answers discovery QUERY packets on its game port
plus one (`ServerBeacon`), unless started with `--no-lan`. A scan
(`ServerBrowser.scan_lan()`) broadcasts a QUERY to the discovery ports of eight game
ports, 24650 and the next seven even ports, so several servers on one machine are
found.
- **Through a list server.** Anyone can run one: `--list-server [--port=N]`
(`ListServer`, default UDP 24660). A game server started with `--list=HOST[:PORT]`
sends a REGISTER every 15 s. The list server answers an unknown or wrong token with
a CHALLENGE carrying a token derived from a per-start secret and the sender's
address and port, and lists the server only when a REGISTER echoes it. Servers are
listed under the address their packets come from, never a claimed one. Entries
expire after 45 s, with at most 8 per address (per /64 for IPv6) and 256 in all. Clients ask for the
list four servers per page, one page after another.
The messages are in `NetDiscovery`. Every QUERY is padded to 512 bytes and no answer
is larger, so neither the beacon nor the list server can amplify a spoofed request.
Both rate-limit each source (`SourceLimiter`: 20 packets a second, at most 4,096
sources tracked per second). A source is an IPv4 address, or an IPv6 address's whole
/64, since one ordinary connection is handed a /64 (H5).
**Lobby, backfill and late arrivals.** People who connect during the lobby or the
countdown take places (`Match.join()`); bots are only added when the match starts,
into whatever places are still empty, so people joining and leaving in the lobby
never displace or strand a bot. Someone who connects after the barge leaves, or
during results, becomes a watcher (`Match.watch()`): they spectate a living player
(the winner during results) through the same snapshots an eliminated player gets,
and take a place ahead of any bots when the next lobby opens. The server still turns
people away when `NetServer.max_players` people are connected.
## Trusting nothing from clients
Tidewall is open source, so anyone can build a client that sends whatever bytes it
likes. The server's defences, and the tests that attack them
(`test/server/test_hostile_client.gd`, `test/net/test_net_handshake.gd`,
`test/net/test_parser_fuzz.gd`, `make fuzz`):
- **Intent only.** A command carries movement axes, look, buttons, a slot, a
material and a view lag. There is no position, velocity, hit, target or item in
it, so speed, teleport, aimbot-by-claim and duplication can't even be expressed.
Every field is clamped on decode, and the simulation applies its own limits:
sprint speed, the weapon's fire interval, build reach (`Tuning.BUILD_RANGE`) and
material cost, pickup reach, one pickup or drop per press, lag compensation at
most `Tuning.LAG_COMPENSATION_MAX_TICKS`.
- **One command per tick.** Each tick's command is taken once, the first time it
arrives. A tick already past or more than `Tuning.MAX_COMMAND_LEAD_TICKS` ahead is
ignored, and a far-future tick can't move the dedupe marker and lock out the real
ones.
- **Bounded messages.** An INPUT has at most `NetSnapshot.MAX_INPUT_COMMANDS`
commands and an exact length, or it is dropped whole. At most 32 game packets per
player are kept per poll. Anything on the control channel after the handshake is
dropped.
- **Bounded connections.** At most 32 new connections per source per 10 s and 8
handshakes in progress per source (`REASON_BUSY`), and a 5 s handshake timeout.
No slot is left to a silent stranger for long (H5): a connection turned away for
flooding is dropped at once, with the reason only in the disconnect's data; a peer
told to leave has 1 s to acknowledge before it is cut off; and when ENet's slots
run short, the guest that has waited longest for its HELLO makes room. The host
has 512 slots whatever the player limit, because ENet takes a slot for every
CONNECT before the sender has proved its address and never reports those
half-open slots to the script; see docs/SECURITY_REVIEW.md.
- **Parsers.** Every decoder refuses malformed input by returning an empty result,
never by raising an error. `make fuzz` feeds 1,000,000 mutated and random messages
to all of them, the snapshot receiver and the list server, and checks for engine
errors and memory growth.
## Snapshot format
`NetSnapshot` (`src/net/`) owns the layouts. An entity travels as a **record**: a list
of whole numbers, already quantized, laid out per archetype. The server compares
records to see what changed, the wire carries only the changed field groups, and the
client keeps records as its picture of the world.
A snapshot is a binary, little-endian packet on channel 1, unreliable:
| Part | Contents |
|---|---|
| Header | Message type (u8), server tick (u32), baseline tick (u32, 0 = builds on nothing), simulation tick (u32), the newest command tick received from this client plus one (u32, 0 = none yet), the number of the newest world message made (u32), the entity the client is watching (varint) |
| Match and tide | Match phase (u8), tide phase (u8), sea level in centimetres (s16) |
| Own block | A flag (u8), then, while the client's own player is alive and is who it watches, 37 bytes nobody else is sent: position and velocity as f32, the water level around the player as f64, which of the nine flood cells around the player that water reaches (u16), swimming stamina (u16) and state flags (u8) |
| Removed | Count (u8), then IDs (varint) |
| Entities | Count (u16), then records of ID (varint), archetype and changed-group mask (u8), then only the groups that changed |
The server tick counts every tick the server has run and never goes back, so it
orders snapshots across matches; the simulation tick is the clock commands name.
Positions are quantized to 1/64 m (u16 per axis: 1,024 m across, heights from -128 m),
yaw to u16, pitch to s8, health and armour to u8. Field groups: players have position,
look, vitals, state flags and held item; pickups and shots have position and item.
**Deltas and loss.** `SnapshotSender` remembers what it told each client in its last 40
snapshots. Each snapshot is a delta against the newest one that client has
acknowledged (its input packets carry that tick), or builds on nothing if there is
none or it is too old. A delta only ever builds on something the client confirmed
holding, so a lost snapshot is never resent: the next one covers it.
`SnapshotReceiver` ignores snapshots older than its newest, and if it is ever sent a
delta on something it doesn't hold, acknowledges 0 to ask for a fresh start.
**Interest.** A client is told only about entities near the player it is watching
(its own, or the one it spectates): players and shots within
`Tuning.NET_INTEREST_PLAYERS_METRES` (380 m, a little past the longest weapon) and
items on the ground within `NET_INTEREST_PICKUPS_METRES` (90 m), measured on the map.
An entity that leaves range is removed from the client's picture and nothing more is
said about it. Outside a match there is no viewer and a snapshot is only its header.
**Budget.** A snapshot is at most `Tuning.NET_SNAPSHOT_MAX_BYTES` (1,200), so 15 a
second is at most 18 KB/s before packet headers and never fragments. When more has
changed than fits, the client's own player goes first, then the nearest, and each
snapshot an update has waited counts as 6 m closer, so nothing waits for ever. What
didn't fit is still owed and goes in a later snapshot.
**Cost.** Building 24 snapshots is the largest part of a busy server's tick, more
than the simulation. Records are made once a tick and shared, each (entity, mask)
encoding is made once a tick and shared, an unchanged record is skipped with one
native comparison, and clients are spread over the ticks of the snapshot interval by
handle (`NetGame.snapshot_due_for()`), so each tick builds half of them.
**Input.** The client answers on channel 1 with the snapshot tick it holds and its
last few commands (`Tuning.NET_INPUT_REDUNDANCY`), oldest first. `NetGame`
(`src/server/`) offers each tick's command to `ServerLoop.submit()` once, and echoes
the newest tick it has received in every snapshot, taken or not.
**Match notice.** On joining and at every change of phase the server sends, reliably
on channel 0, the match phase, index and seed, so the client can generate the island.
## World messages
Built pieces, props, chests and the tide's schedule aren't entities and don't go in
snapshots. A wall the client never heard about is a lie it would keep walking into,
so they travel on channel 0, reliably and in order, as **WORLD** messages (`NetWorld`,
`src/net/`).
| Part | Contents |
|---|---|
| Header | Message type (u8), flags (u8: whole state, loot placed, tide follows), sequence number (u32), simulation tick (u32) |
| Tide | Only when it starts: the tick it started (u32) and each phase's level (f32) |
| New pieces | ID, kind, material and facing in one byte, slot (s16, s8, s16, u8), owner, tick placed (u32), ticks of building done, damage taken |
| Damaged pieces | ID and damage taken so far |
| Removed pieces | IDs |
| Props | Prop and health left, for each one damaged |
| Chests | Indices of chests opened |
Counts and IDs are varints. `WorldSender` makes one message after each tick in which
something changed and everyone is sent the same one; a quiet tick makes none. The
simulation keeps the lists it reads (`StructureSet.changed` and `.removed`,
`PropSet.changed`), so nothing is scanned. Someone joining is sent the **whole state**
in one message after the MATCH notice, and so is everyone when a new match's
simulation appears.
What isn't sent: props, chests' places and their contents, which the client rolls
itself from the seed, as it does the island; and a piece's health, which follows from
how far its building had got, the ticks since, and the damage it has taken. So a
piece being built costs nothing on the wire. A scripted match of 12,198 ticks with 24
players made 121 messages, 2.3 KB in all. Bots don't build yet, so a match of people
building will make far more: a new piece is about 16 bytes to each client.
`ClientWorld` applies them to the client's world. `NetWorld.world_hash()` covers
everything replicated this way, and a client that has applied every message up to a
tick agrees with the server's simulation at that tick, which a test checks through a
whole match.
Each player is also told what they carry, as an **OWN** message on the same channel
whenever it changes: held selection, materials, the five slots and ammunition.
**Placing ahead of the server.** When the player's command places a piece and the
client's own run of `Building.check` passes, `ClientWorld` puts a provisional piece
in its world at once, under an ID the server never uses, and holds its cost back from
the materials shown. The server's piece arriving in that slot replaces it. Every
snapshot carries the number of the newest WORLD message made, so the client knows
when it has heard everything that snapshot's world had in it: once a snapshot from
after the placing tick has come, and the world messages up to its number have too,
and no piece came, the server turned it down (or never got the command) and the
provisional piece is taken away. Losing a race for a slot ends the same way, with
the winner's piece standing.
## Lag compensation
A client draws other players about 130 ms in the past, and its commands take the
trip to the server and wait their turn, so when the server fires a shot the target is
no longer where the shooter saw it: 8 ticks on at a 50 ms round trip, 12 at 200 ms.
Without help, nobody could hit a walking target.
So every command says how far back its player was seeing (`view_lag`), and the
simulation keeps where every player's body has been for the last
`Tuning.LAG_COMPENSATION_MAX_TICKS` (15 ticks, half a second) in `HitHistory`
(`src/sim/`). A hitscan shot is traced against other players where they were at the
moment the shooter saw, between ticks if need be, and against terrain, props and built
pieces as they are now. Projectiles fly in the server's present and aren't rewound.
The client claims only *when* it was looking and where it aimed. Whether that is a
hit is worked out by the server, from its own record. Three limits bound the claim:
- Never more than the cap back. A round trip much over 300 ms needs more than the
cap, and that shooter has to lead the target.
- Never the future: the lag can't be negative.
- Never earlier than a moment the same player has already claimed. A view only moves
forward, so nobody can fire at the present and the past by turns and keep whichever
hits.
Because the lag travels in the command, it is in the command log, and a replay
judges every shot exactly as the match did. `HitHistory` itself isn't in the state
hash: a replay rebuilds it from the same ticks.
Measured (`test/net/test_lag_compensation_link.gd`, simulated link, headless): a
client firing a signal revolver once a second at the middle of a target walking
across at 4 m/s, 25 m away, as drawn on its own screen. At 50, 100 and 200 ms round
trips, 41 of 41 shots hit; with the lag ignored, 0 of 41. At 500 ms, past the cap,
0 of 41.
## The client: prediction, reconciliation and interpolation
`ClientGame` (`src/net/`) is a client's side of a match. It works on packets, so it
runs the same over a `NetClient` or a test's simulated link. From the seed in the
MATCH notice it generates the island itself (a `Simulation` it never steps) and plans
the same barge route, so it can run the server's movement code on the server's ground.
**The command clock.** A command must reach the server before the tick it names, so
the client's tick runs ahead of the server's by the trip there plus a margin. Nobody
measures the trip. Each snapshot says which tick the server was about to run and the
newest command tick it had received; the difference is how many commands were
waiting. `ClientClock` holds that at `Tuning.NET_COMMAND_MARGIN_TICKS` (3): it jumps
ahead if commands arrive late two snapshots running, waits if they are far too early,
and otherwise runs up to 2% fast or slow. With three commands waiting and each packet
repeating the last three, jitter and a lost packet or two cost nothing.
**Prediction.** `ClientPrediction` keeps a copy of the client's own player and runs
every command on it as it is made, through `Movement.step`, `Water.update` and
`Drop.ride`, the same code the server runs. The player moves at once, not a round trip
later.
**Reconciliation.** The own block in each snapshot is the player's exact state before
the snapshot's simulation tick: 32-bit floats, as the server holds them, not the
quantized record. If that equals what was predicted before that tick, nothing happens,
which is the normal case. If not, the copy is put where the server says, every command
since is run again, and the distance the player's present position moved is the
correction. A correction is never shown at once: the drawn position keeps an offset
that fades at `NET_CORRECTION_SMOOTH_RATE`, unless it is over 3 m, which is shown as
the teleport it is. Built pieces and broken props are solid on the client as soon as
their WORLD message arrives, a moment after they are on the server, so a client
running into a wall that new is corrected. What the client can't predict: a basin
still filling after a breach, and anything another player does to it.
**Interpolation.** `SnapshotInterpolator` draws every other entity
`Tuning.NET_INTERP_DELAY_TICKS` (4 ticks, two snapshots) in the past, on a straight
line between the snapshots either side of that moment, with yaw turning the short way.
The moment drawn is a clock of its own, steered gently towards where arrivals say it
should be, so jitter in the network never becomes jitter on screen. When a snapshot is
lost the entity carries on along its last heading for up to 3 ticks; if that guess was
wrong, the difference is blended away when the news arrives.
**Measured** (`test/net/test_prediction_link.gd`, simulated link, headless): two
players through the drop and 75 s of walking, sprinting, strafing, jumping and
crouching on a real island, each with 100 ms of latency each way, 20 ms of jitter and
2% loss. Own movement: about 1,400 snapshots compared per client and none needed a
correction. The other player was drawn on average 0.4 mm from where a perfect link
would draw them, and 9 mm from where the server had them at that moment; a lost
snapshot during a sudden stop or start showed as at most 13 cm of drift, eased out. At
150 ms, 40 ms and 10% loss a client took 3 to 7 corrections of at most 22 cm, all
blended. These are measurements of the netcode's arithmetic, not of how it feels in
the hand, which needs a real playtest.
## Module map
| Path | Holds | May depend on |
|---|---|---|
| `src/sim/` | Tick loop, entities, RNG, commands, tide, combat and its lag compensation, building | `src/sim/` only |
| `src/bots/` | Bot brains that produce `PlayerCommand`s | `src/sim/` |
| `src/net/` | Transport, snapshot encoding, the client's side of a match (prediction, interpolation) | `src/sim/` |
| `src/server/` | Headless and listening servers, joining the network to the match | `src/sim/`, `src/bots/`, `src/net/` |
| `src/client/` | World rendering, camera, input, effects | `src/sim/`, `src/net/` |
| `src/ui/` | HUD, menus, map | `src/sim/` (read only), `src/client/` |
| `src/audio/` | Sound playback, music (A8) | `src/sim/` and `src/net/` (read only) |
| `src/app/` | Startup and mode selection | Everything |
## Bots
Bots live in `src/bots/` and play through the same door as humans: each tick a bot
reads the simulation and returns one `PlayerCommand`, which the server submits like
any other. They never write to the simulation.
`NavGrid` is the shared map they plan on: one point per 2 m terrain sample, solid
where the ground is a cliff or a solid stands between step and head height, and eight
times as costly where the water is deeper than wading. Path search is Godot's
`AStarGrid2D`. The server builds the grid while the lobby waits (about 0.4 s, next to
the island's own generation) and syncs it every tick before bots think: new solids
block points at once, removed solids are found by a rolling scan within a few ticks,
and points turn wet as the tide and flood reach them. Every change is stamped with its
tick, and each bot checks its remaining path against the stamps twice a second, so a
new wall or rising water across a path makes it plan again. Only one path is planned
per server tick across all bots; others wait their turn.
`NavBot` follows a path: it steers at the next waypoint, sprints on long dry stretches,
jumps when it stops making progress, and after a few tries marks the point blocked and
plans around it. A goal the grid's regions show to be cut off (inside a ring of rock,
behind a hut's walls) is turned down without a search, which would otherwise cover the
whole island before giving up.
`BotBrain` decides where a bot goes and what it presses, and gives `NavBot` its goals.
It knows what a player would: the map (`BotWorld`: loot markers at the points of
interest and the ground each tide level will leave dry), the tide forecast, items
within a few metres, opponents in view with a clear line to them, and who just hit it.
Each tick, in order of urgency, it gets to ground the coming tide won't reach, fights a
visible opponent if it is armed, bandages itself when nobody is in view, picks up
useful items and opens chests, walks to the next loot marker, and otherwise wanders the
safe ground. Difficulty (`Tuning.BOT_DIFFICULTIES`) sets its reaction time, how far it
sees and how far its aim wanders.
Two things the brain handles itself, because the grid is flat terrain only:
- Huts, lofts and piers. Their doors and steps are finer than the grid, so a bot walks
to the foot of the point of interest's own walking route and follows its points in,
then back out the same way, before anything else, even if it must flee.
- Safe ground. For each tide phase it is the dry land joined to the island's highest
walkable ground, so it only shrinks, each phase's inside the last. A bot off it
leaves when the time before the next rise only just covers the walk.
`tools/bot_matches.gd` (`make bot-matches`) plays whole bot-only matches on a run of
seeds and reports winners, causes of death and how each difficulty placed.
## Terrain
The island's heightfield (`Island`, in `src/sim/`) is the only terrain collision, on
the server and in client prediction. Nothing in the renderer is ever used for collision.
The client draws it with `TerrainView` (`src/client/terrain/`): 64 m chunks at four
levels of detail chosen by distance to the camera. `TerrainChunkBuilder` builds chunk
geometry on `WorkerThreadPool` threads, and the main thread only uploads finished meshes,
within a per-frame budget. Each chunk hangs skirts from its edges deeper than any two
levels can disagree, so a level boundary never opens a crack. Normals come from the
full-resolution heightfield at every level, so lighting doesn't change across a boundary.
The terrain shader blends procedural sand, marsh, grass and rock layers using splat
weights from the island's elevation bands, with rock on steep ground.
## The match view
`MatchView` (`src/client/`) is the client's picture of one match: sky, sun, terrain,
sea, points of interest, props, built pieces and `EntityView`, which draws players, the
barge, items and chests. All of it reads one `Simulation` and never writes to it, and a
new match gets a new view. The camera sits on a player's shoulder through `CameraRig`.
`EffectsView` (`src/client/effects/`, A7) draws the match's visual effects from the
server's FX records and from changes it sees in the world (pieces gone, players in the
water, surges). Its particles are simulated on the CPU in packed arrays and drawn by
two MultiMeshes (blended and added) of camera-facing quads, sized per instance by a
small shader, with tracers as a third; everything is allocated once at the preset's
budget, so a big fight costs a fixed three draw calls and never adds nodes or grows buffers.
The figure (`FigureRig`), items (`ItemModels`) and barge and chests (`VesselModels`) are
the generated art described in assets/PROVENANCE.md; `test_world_art` fails on any
primitive stand-in mesh.
In play, the simulation it reads is the client's own copy of the world: the
`Simulation` that `ClientGame` generates from the match's seed and never steps.
`ClientWorld` keeps its pieces, props, chests and tide in line with the server, and
`ClientMirror` (`src/net/`) writes the rest of the picture into it every frame: each
entity the server has told this client about, where it is being drawn now (everyone
else from the recent past, the client's own player where it was predicted), the barge,
the clock and the sea level. So the same views draw a networked match, a local
server's simulation in a test, or a replay in a capture, and there is one set of
drawing code. Captures and tests still point a `MatchView` straight at a server's
simulation.
## The client program
`ClientSession` (`src/app/`) is the game while it is in a match: a `ClientGame`, a
`ClientInput` turning the keyboard and mouse into one command a tick, a `ClientMirror`
and a `MatchView`. Its `pump()` does a frame's work and needs no scene tree, so tests
drive it.
The server is either across the network (`--connect=HOST:PORT`, a `NetClient`) or in
the same process (`LocalServer`, `src/server/`): the same `ServerLoop` and `NetGame` a
dedicated server runs, with the packets handed across in memory, reliable ones first,
in the order a socket would deliver them. The client can't tell the difference, so
offline play is the network path with no network, as "Rules that do not bend" asks.
`src/app/main.gd` picks the mode: `--server` runs the dedicated server; otherwise the
game starts an offline match, or joins a server with `--connect`. Without a window
(`tools/godot.sh` is always headless) a mode has to be asked for. `--autoplay` puts a
small script at the controls and `--client-seconds=N` quits after N seconds with one
JSON line saying how far the client got, which is what `make client-check` reads.
There are no menus yet (N6, A10) and no HUD (A9): one line of text says when the
client is connecting, in the lobby or watching.
## Performance budgets
| Budget | Target |
|---|---|
| Server tick | Under **12 ms** with 24 players, including the network's share (`make soak` checks the p99) |
| Client | **60 fps** on a GTX 1060-class GPU at medium settings |
| Terrain streaming | Under **8 ms** of main-thread work in any frame (measured headless; GPU upload unmeasured) |
| Client draw calls | At most **2,000** per frame, every pass counted (shadows included) |
| Client primitives | At most **2,000,000** triangles per frame, every pass counted |
| Client memory | At most **1 GiB** of video memory and **512 MiB** of the engine's static memory |
Software rendering in CI can't verify the frame-rate budget. It needs a real GPU playtest
(R6). What it can count is what a frame asks the GPU to do, so the draw-call, triangle
and memory budgets stand in for it until then. They are set for the GTX 1060 class with
room left for effects and the HUD.
`make bench` (`tools/bench.sh`, H1) measures both sides and fails when a number is over
budget:
- **Server:** the headless server with 24 bots, unthrottled, for 12,000 ticks (a whole
match and the start of the next) on three seeds, reporting p50, p99 and max tick time.
The max includes one long tick per match: unthrottled, the 15 s results screen passes
in a fraction of a second, so the main thread waits for the worker still building the
next island. At the real 30 Hz the worker finishes long before the lobby opens.
- **Client:** the match `make match` saved, rendered at the whole island, the barge (24
figures together, the worst case for draw calls), landed, a build and the final
players, and a crowded pine forest. Each capture reports its frame's draw calls,
primitives, objects, nodes and memory (`tools/capture.gd`'s `render` field).
Results go to `build/bench/report.txt` and `report.json`. The numbers from each pass are
in the DEVLOG.
## Soak testing
`make soak` (`tools/soak.sh`) is the multiplayer gate: a real server process and 24
headless clients in three processes, each client behind its own `UdpRelay`, a UDP
relay that delays, jitters and loses datagrams both ways, so ENet runs unchanged over
a bad link. `SoakPlayer` plays each client from what a client knows: it drops, glides,
heads for high ground, harvests and tries to build.
Desync is checked by hash: the server, started with `--world-hash-every=N`, logs
`NetWorld.world_hash()` on the simulation ticks from each multiple of N to the snapshot
interval, and each client hashes its own world on the snapshots at those ticks when its
world messages have caught up exactly (`world_seq`) and it has no provisional pieces.
Tick 0 is never compared: it lasts the whole lobby while the world is set up.
`tools/soak_report.gd` compares them and checks errors, unreadable packets, that every
client played every match, the p99 tick, and memory from one match to the next.
`make soak-selfcheck` tampers with one client's world to prove a drift is caught.
A client process holds back a new match's notice until it has made that client's
island, at most one a frame: a dozen clients making islands in one frame starved
their connections of service for long enough that ENet dropped them.
## Audio (A8)
Every sound is synthesized offline by `tools/audio/` and committed as a WAV in
`assets/audio/`, with `manifest.json` recording each file's hash and levels and
`assets/PROVENANCE.md` naming the generators. `make audio` regenerates them; the same
engine build gives the same bytes, and `test_audio_assets` regenerates every file and
compares hashes. `make audio-check` (and that test) holds each sound to its category's
loudness (`tools/audio/loudness.gd`) and the mix order: the tide loudest, ambience,
music and menus under the effects.
In the client:
- `SoundDirector` (a child of `ClientSession`) reads the client's world each frame and
turns what changed into sounds: FX records (shots, impacts, harvesting), footsteps by
surface for every walking player near the camera, landings and splashes, pieces built
and broken, the tide's bell, foghorn, surge and lighthouse, the own player's hurts and
the feed. Placed sounds play on `AudioStreamPlayer3D` voices at the event's position,
so the camera's listener pans and attenuates them. It never changes the world, and the
server plays no sound.
- `MusicDirector` (a child of `AppShell`) plays the score's four layers in step on an
`AudioStreamSynchronized` and fades them by intensity: full in menus and results,
the drone alone while the first tide holds, building to the whole tune for the last
land.
- `MenuSounds` hooks every menu button for a hover tick and a press knock.
Effects play on the `Effects` bus and music on `Music`; the settings' volume sliders
set those buses.
## Item models (A4)
`tools/models/items.py` builds every item from primitives in headless Blender and
writes `assets/models/items/<id>.obj` (OBJ: the Debian Blender's glTF exporter needs
numpy), a `.json` with the grip (the origin), the left hand's support point and the
bounds, and a 128 px Cycles icon in `assets/icons/items/`. Each surface's material is
a `Palette` name; `TRIM2_`/`TRIM3_` surfaces are the tier treatment. `ItemModels`
loads them, keeps the surfaces a tier shows and paints them from `Palette` (tier 0
faded). `EntityView` puts the held item in each figure's right hand, pointed along
the player's look, and draws items lying in the world with one MultiMesh per
model and tier. The hotbar shows the icons.
## Player figure (A2)
`tools/models/figure.py` builds the islander in headless Blender as twelve rigid
parts (pelvis, torso, head, upper arms, forearms, thighs, shins and the wing-sail),
each an OBJ whose origin is the joint it turns about, plus `figure.json` with the
joints and hand points (`make art` rebuilds these and the items). OBJ has no
skeleton, so the figure is jointed rather than skinned.
`FigureRig` hangs the parts on a tree of pivot nodes (`hips/waist/spine/...`) and
paints them from `Palette`, `COAT` in the player's own oilskin. `FigurePoses` holds
every animation as key poses (joint rotations in degrees and a hip lift) and turns
them into `Animation` resources with position and rotation tracks. One
`AnimationTree`, in manual mode, plays them:
- `move`: a Transition between ground (a BlendSpace1D of idle, walk and run by speed,
time-scaled with speed), crouch (still and creeping), air, skydive, glide, swim and
aboard;
- `holding`: the arms' carry for the held item (long in both hands, short in one, or
carried in front), filtered to the arms and off while the hands are busy;
- `reload` and `use`: arm-and-head layers faded in while the FLAG_ bits say so;
- `act`: a OneShot on the upper body for fire (long or short), a boathook swing, a
keg throw and building;
- `hit`: a OneShot flinch of the chest and head when health drops.
The spine takes a third of the look's pitch and the hand is turned so the item points
along the whole of it, whatever the arm is doing.
Figures animate from replicated state only. `FigureRig.drive()` reads a `SimEntity`
as `ClientMirror` fills it from snapshots: position (speed comes from movement when
velocity isn't replicated), look, health, the held item and the FLAG_ bits, with
reloading and using now copied into `reload_ticks` and `use_ticks` as 1 or 0. One-off
actions come from FX records (`EntityView.hear()`, fed by `ClientSession`): a SHOT
with an item fires it, a SHOT with no item is a boathook swing (`Harvest.swing` now
reports every swing as a `swing` event, hit or miss), and PLACE (new in protocol 4)
is a piece placed. Being in the air waits `AIR_DELAY` before it shows, so steps down a
slope don't flicker. `EntityView.animate_live = false` lets captures pose figures
exactly.
## Sea, sky and weather (A6)
`Weather.at(tide, tick)` works out the moment's weather from the tide's schedule alone,
so every client agrees with nothing new on the wire: `storm` builds from calm at the
first tide to a gale at sudden death, and `day` runs from mid-afternoon to dusk at the
time limit. Sky colours, the sun's height, colour and strength, fog, rain and wind all
follow from those two (colours from `Palette`). Before the tide starts it's a clear
afternoon.
`WeatherView`, made by `MatchView`, applies a Weather on every sync: the procedural
sky's colours, the sun, the environment's fog and ambient light, `WaterView`'s
`sea_state`, and rain as `CPUParticles3D` around the camera, which works in both
renderers. When the camera is below the drawn sea (`WaterView.is_under`), the fog
turns to `SEA_MURK` and closes in, and the rain stops. `ClientSession` passes the rain
and wind to `SoundDirector`'s rain and wind beds.
The sea shader darkens open water toward `SEA_STORM`, lengthens and steepens the chop
and raises whitecaps with `sea_state`, and keeps a breathing foam band at the
waterline with a fainter second line beyond it. Water depth comes from the depth
buffer in Forward+ (which also sees pieces and props) and from a texture of the
terrain's heights (`WaterView.set_ground`) in the Compatibility renderer, whose depth
texture the shader can't read. Seen from below, the surface is drawn as a rippled
ceiling of murk.