- Client Godot 4.7 .NET (Godot.NET.Sdk 4.7.2): menu, collegamento, partita locale con server figlio; mappa con terreno (fasce, ombreggiatura, rive curve con shader, curve di livello), opere, entità, alberi, treni interpolati con fumo; strumenti binari con profilo, stazione, deposito, segnali, demolizione; pannelli treni, linee, mercato, finanze, schede; barra superiore, minimappa, notiziario; italiano e inglese. - Pilota automatico del client e scripts/client-autopilot.sh: partita locale, linea con ponte, treni in moto e schermate (docs/screenshots). - Registro dei comandi del server (--record) e viaferrea-tools replay. - PROTOCOL.md normativo, ADR 0009, ARCHITECTURE, STATE e README aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
179 lines
11 KiB
Markdown
179 lines
11 KiB
Markdown
# Via Ferrea — Protocollo di rete
|
||
|
||
Stato: **normativo da F3**. Ogni messaggio e ogni comando ha un test di round-trip
|
||
(`tests/ViaFerrea.Tests/Protocol/ProtocolTests.cs`); decisioni in ADR 0009.
|
||
|
||
## 1. Trasporto
|
||
|
||
- WebSocket su `ws://<host>:<porta>/ws` (TLS a carico del reverse proxy: `wss://`).
|
||
- Solo messaggi binari. Un messaggio WebSocket contiene esattamente un frame.
|
||
- Porta predefinita 7400 (`VF_PORT`). Il primo messaggio del client dev'essere `Hello` entro 10 s.
|
||
|
||
## 2. Frame
|
||
|
||
```
|
||
offset tipo campo
|
||
0 u32 length lunghezza di messageId + payload (byte)
|
||
4 u16 messageId identificativo stabile del messaggio
|
||
6 ... payload corpo serializzato a mano
|
||
```
|
||
|
||
- Little endian. Dimensione massima 4 MB: frame più grandi chiudono la connessione (1009).
|
||
- `SpanWriter`/`SpanReader` con `Write(ref SpanWriter)` / `Read(ref SpanReader)` per ogni messaggio.
|
||
|
||
### Tipi elementari
|
||
|
||
| Tipo | Codifica |
|
||
|---|---|
|
||
| `bool` | 1 byte, 0 o 1 (altri valori: errore) |
|
||
| `u8/u16/u32/u64`, `i16/i32/i64` | little endian a larghezza fissa |
|
||
| `varuint` | LEB128 (lunghezze e conteggi) |
|
||
| `f32/f64` | IEEE 754 little endian |
|
||
| `string` | `varuint` lunghezza in byte + UTF-8 |
|
||
| `bytes` | `varuint` lunghezza + byte |
|
||
| `Money` | `i64` centesimi |
|
||
| `Vec2` | due `f64` (metri) |
|
||
| identità | `i32` (−1 = nessuna) |
|
||
| liste | `varuint` conteggio + elementi |
|
||
| `flags` | `u8` di estensione in coda a ogni messaggio e record (0 oggi) |
|
||
|
||
### Evoluzione
|
||
|
||
- Gli id dei messaggi, dei comandi e l'ordine dei campi non cambiano mai.
|
||
- I campi nuovi si aggiungono in coda, dopo il byte `flags`, che dice quali blocchi seguono. Un
|
||
lettore vecchio ignora i byte residui; un messaggio vecchio senza `flags` vale 0.
|
||
- `protocolVersion` (oggi 1) cresce solo per modifiche incompatibili.
|
||
|
||
## 3. Handshake
|
||
|
||
```
|
||
Client → Hello { protocolVersion: u16, clientVersion: string, token: string, resumeSessionId: u64, dataHash: u64 }
|
||
Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, difficulty: string }
|
||
| Reject { code: u16, reason: string }
|
||
```
|
||
|
||
- `resumeSessionId` ≠ 0 riprende una sessione disconnessa da meno di 120 s (stato rimandato per intero).
|
||
- `dataHash` ≠ 0 deve coincidere con l'hash dei dati del server.
|
||
- Codici di `Reject`: 1 versione del protocollo, 2 token errato, 3 dati diversi, 4 server pieno, 5 nessuna partita.
|
||
- `Welcome` può arrivare di nuovo durante la sessione (nuova partita o caricamento): il client azzera la copia del mondo.
|
||
|
||
`WorldSummary { seed: u64, sizeKm: i32, startYear: i32, tick: i64, date: string, companyId: i32, companyName: string,
|
||
regionId: string, widthCells: i32, heightCells: i32, cellSizeM: f64, chunkCells: i32, speed: u8, terrainHash: u64,
|
||
costMultiplier: f64 }`
|
||
|
||
## 4. Messaggi Client → Server
|
||
|
||
| id | Nome | Contenuto |
|
||
|---|---|---|
|
||
| 1 | Hello | vedi handshake |
|
||
| 2 | Ping | `nonce: u64` |
|
||
| 3 | Subscribe | `x0, y0, x1, y1: i32` (celle, estremi inclusi), `lod: u8` |
|
||
| 4 | Command | `seq: u32`, `type: u16`, `payload: bytes` (vedi sotto) |
|
||
| 5 | SetSpeed | `speed: u8` (0, 1, 2, 4, 8) |
|
||
| 6 | ListSaves | — |
|
||
| 7 | Save | `name: string` |
|
||
| 8 | Load | `saveId: string` |
|
||
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
|
||
|
||
### Comandi (`Command.type`, payload in ordine)
|
||
|
||
| type | Comando | Payload |
|
||
|---|---|---|
|
||
| 1 | BuildTrack | `polyline: [Vec2]`, `heightOffsetM: f64`, `allowBridges: bool`, `allowTunnels: bool`, `trackClass: string`, `doubleTrack: bool`, `electrified: bool`, `expectedCostCents: i64` (0 = non verificare) |
|
||
| 2 | RenewTrack | `edge: i32` |
|
||
| 3 | UpgradeTrack | `edge: i32`, `trackClass: string`, `doubleTrack: bool`, `electrified: bool` |
|
||
| 4 | Demolish | `target: u8` (0 arco, 1 stazione, 2 deposito, 3 segnali), `id: i32` |
|
||
| 5 | BuildStation | `position: Vec2`, `platforms: i32`, `name: bool + string` |
|
||
| 6 | BuildDepot | `position: Vec2`, `size: string`, `name: bool + string` |
|
||
| 7 | PlaceSignal | `edge: i32`, `positionM: f64` |
|
||
| 8 | BuyVehicle | `vehicleType: string`, `depot: i32`, `count: i32` |
|
||
| 9 | SellVehicle | `vehicle: i32` |
|
||
| 10 | ComposeTrain | `depot: i32`, `vehicles: [i32]`, `name: bool + string` |
|
||
| 11 | CreateLine | `name: string`, `color: string`, `stops: [LineStop]` |
|
||
| 12 | EditLine | `line: i32`, `stops: [LineStop]`, `name: bool + string` |
|
||
| 13 | AssignTrain | `train: i32`, `line: i32` (−1 = togli dal servizio) |
|
||
| 14 | SendToDepot | `train: i32`, `depot: i32` |
|
||
| 15 | SetReserve | `train: i32`, `reserve: bool` |
|
||
| 16 | SetMaintenancePolicy | `scope: u8` (0 compagnia, 1 linea, 2 treno), `target: i32`, `policy: string` |
|
||
| 17 | ScheduleService | `train: i32`, `intervention: string` |
|
||
| 18 | OrderParts | `depot: i32`, `quantity: i32` |
|
||
| 19 | TakeLoan | `amount: Money` |
|
||
| 20 | RepayLoan | `loan: i32`, `amount: Money` |
|
||
| 21 | AcceptAgreement | `agreement: i32` |
|
||
| 22 | RejectAgreement | `agreement: i32` |
|
||
| 23 | BuyGoods | `station: i32`, `good: string`, `units: i32`, `maxUnitPrice: Money` |
|
||
| 24 | SellGoods | `station: i32`, `good: string`, `units: i32`, `minUnitPrice: Money` |
|
||
| 25 | BuyIndustry | `industry: i32`, `offer: Money` |
|
||
| 26 | SetIndustryPolicy | `industry: i32`, `budget: u8` (0 nessuno, 1 base, 2 alto) |
|
||
| 27 | OverhaulIndustry | `industry: i32` |
|
||
| 28 | UpgradeIndustry | `industry: i32` |
|
||
| 29 | Ipo | `floatShare: f64` |
|
||
| 30 | BuyShares | `company: i32`, `shares: i64`, `maxPrice: Money` |
|
||
| 31 | SellShares | `company: i32`, `shares: i64`, `minPrice: Money` |
|
||
| 32 | PayDividend | `perShare: Money` |
|
||
| 33 | LaunchBid | `target: i32`, `pricePerShare: Money`, `targetShare: f64` |
|
||
| 34 | RespondBid | `bid: i32`, `accept: bool` |
|
||
| 35 | BuyConcession | `region: i32` |
|
||
| 36 | AcceptContract | `contract: i32` |
|
||
| 37 | FundResearch | `project: string`, `amount: Money` |
|
||
| 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` |
|
||
|
||
`LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`.
|
||
I codici coincidono con l'enum `CommandType` di Core. Fino alla loro fase i comandi 15–18 e 21–38
|
||
(tranne 26) rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
|
||
|
||
## 5. Messaggi Server → Client
|
||
|
||
| id | Nome | Contenuto |
|
||
|---|---|---|
|
||
| 101 | Welcome | vedi handshake |
|
||
| 102 | Reject | vedi handshake |
|
||
| 103 | Pong | `nonce: u64`, `serverTick: u64` |
|
||
| 110 | MapChunk | `cx, cy, width, height: i32`, `compression: u8` (1 = Brotli), `data: bytes` = altezze `u16` (dm) + tipi `u8` + larghezza fiumi `u8` |
|
||
| 111 | EntitySnapshot | `tick: i64`, `EntityLists` |
|
||
| 112 | EntityDelta | `tick: i64`, `EntityLists` (nuovi o cambiati), `removed: [(type: u8, id: i32)]` |
|
||
| 113 | TrackWorks | `edges: [EdgeInfo]`, `removed: [i32]` (lotti sotto 1 MB) |
|
||
| 114 | TrainMotion | `trainId: i32`, `tick: i64`, `state: u8`, `condition: f32`, `speed: f32` (m/s), `lengthM: f32`, `headDistance: f64`, `segments: [(edge: i32, forward: bool, fromS: f64, toS: f64)]` |
|
||
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32` |
|
||
| 121 | MaintenanceAlert | `train: i32`, `depot: i32`, `component: string`, `condition: f32`, `dueDays: i32`, `text: string` |
|
||
| 122 | EmploymentReport | `day: i64`, `rows: [EmploymentRow]` (mensile) |
|
||
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
|
||
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
|
||
| 131 | Notification | `EventInfo` |
|
||
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
|
||
| 133 | SaveList | `saves: [SaveInfo]` |
|
||
|
||
Record (ognuno chiude con `flags`):
|
||
|
||
- `EntityLists`: liste in quest'ordine di `CompanyInfo`, `TownInfo`, `IndustryInfo`, `HubInfo`, `NodeInfo`, `StationInfo`, `DepotInfo`, `LineInfo`, `VehicleInfo`, `TrainInfo`.
|
||
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`
|
||
- `TownInfo { id, name, position: Vec2, population: i32, radiusCells: f64, satisfaction: f32, services: i32 }`
|
||
- `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }`
|
||
- `HubInfo { id, kind: string, name, position }`
|
||
- `NodeInfo { id, position, heightM: f64, owner, station, depot, edges: [i32] }`
|
||
- `StationInfo { id, owner, name, node, position, platforms: i32, waitingUnits: i32, industries: [i32], towns: [i32] }`
|
||
- `DepotInfo { id, owner, name, node, position, size: string }`
|
||
- `LineInfo { id, owner, name, color, stops: [LineStop] }`
|
||
- `VehicleInfo { id, owner, type: string, depot, train, condition: f32 }`
|
||
- `TrainInfo { id, owner, name, line, state: u8, vehicles: [i32], maxSpeedKmh: f32, lengthM: f32, load: i32, capacity: i32, depot: i32 }`
|
||
- `EdgeInfo { id, owner, a, b, trackClass: u8, doubleTrack, electrified, state: u8, condition: f32, structureCondition: f32, progress: f32, samples: [(s, x, y, h, ground: f64, kind: u8, speedLimitKmh: f64)], signals: [f64] }`
|
||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`
|
||
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`
|
||
- `SharePrice { company, price: Money, change: f32, listed }`, `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }`
|
||
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
|
||
|
||
## 6. Flusso e interest management
|
||
|
||
- Dopo il `Welcome` il server manda `EntitySnapshot` e tutti i `TrackWorks`; i chunk arrivano dopo
|
||
il primo `Subscribe` (viewport con un chunk di margine), una volta per sessione, e si rimandano se
|
||
cambiano.
|
||
- `EntityDelta` e `TrackWorks` incrementali dopo ogni comando riuscito e a ogni cambio di giorno.
|
||
- `TrainMotion` ogni 100 ms per i treni in moto con la testa nel viewport (più un chunk), una volta
|
||
per quelli fermi: al massimo 10 aggiornamenti al secondo per treno. Il client avanza la testa a
|
||
velocità costante tra un moto e l'altro (fattore 60: un tick = 3 s di orologio dei treni).
|
||
- `DailyDigest` a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non
|
||
informativi della compagnia della sessione.
|
||
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
|
||
sessione si chiude (il client può riprenderla).
|
||
- Obiettivo di banda in regime: < 100 KB/s per client.
|