Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s

Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-07 11:14:54 +01:00
1 parent f6c2a17b4d
commit c1a0049bcf
300 files changed
+1602 -1045

No files matched your search

@@ -0,0 +1,49 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Map;
using RailEnterprise.Core.Rail;
namespace RailEnterprise.Protocol.Client;
/// <summary>
/// Collaudi (railenterprise-tools smoke, pilota automatico del client): cerca sulla copia locale del
/// terreno un attraversamento di fiume rettilineo di 1,5–2,5 km con estremità e deposito su
/// terreno libero e un'anteprima valida con ponte.
/// </summary>
public static class BridgeSiteFinder
{
public readonly record struct Site(Vec2 A, Vec2 B, Vec2 Depot, Vec2 River);
public static Site? Find(ClientWorld w, ulong seed = 7, int attempts = 400, int maxDays = 120)
{
var t = w.Terrain ?? throw new InvalidOperationException("Terreno non ricevuto");
var rng = new Rng(seed);
bool Free(Vec2 p)
{
if (p.X < 2000 || p.Y < 2000 || p.X > t.WidthM - 2000 || p.Y > t.HeightM - 2000) return false;
var (x, y) = t.CellAt(p);
return (CellType)t.Types[y * t.Width + x] is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill;
}
var rivers = new List<int>();
for (int i = 0; i < t.RiverWidth.Length; i++)
{
if (t.RiverWidth[i] > 0) rivers.Add(i);
}
if (rivers.Count == 0) return null;
for (int attempt = 0; attempt < attempts; attempt++)
{
int cell = rivers[rng.NextInt(rivers.Count)];
var center = t.CellCenter(cell % t.Width, cell / t.Width);
double angle = rng.NextDouble(0, Math.PI);
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
double half = rng.NextDouble(750, 1250);
var a = center - dir * half;
var b = center + dir * half;
var depot = a - dir * 600;
if (!Free(a) || !Free(b) || !Free(depot)) continue;
var plan = w.PreviewTrack(new BuildTrackCommand([a, b]));
if (plan.Valid && plan.LengthOf(WorkKind.Bridge) > 0 && plan.Days <= maxDays) return new Site(a, b, depot, center);
}
return null;
}
}
@@ -0,0 +1,391 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Map;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Time;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Protocol.Client;
/// <summary>
/// Copia locale del mondo costruita dai messaggi del server: terreno a chunk, entità, rete dei
/// binari (con gli stessi id del server) e moto dei treni. Non simula nulla: serve a disegnare,
/// a interpolare i treni e a calcolare le anteprime con le classi di Core (il server ricalcola).
/// </summary>
public sealed class ClientWorld(GameData data)
{
public GameData Data { get; } = data;
public WorldSummary? Summary { get; private set; }
public Terrain? Terrain { get; private set; }
public TerrainSampler? Sampler { get; private set; }
public RailNetwork Network { get; private set; } = new();
public ulong SessionId { get; private set; }
public Dictionary<int, CompanyInfo> Companies { get; } = [];
public Dictionary<int, TownInfo> Towns { get; } = [];
public Dictionary<int, IndustryInfo> Industries { get; } = [];
public Dictionary<int, HubInfo> Hubs { get; } = [];
public Dictionary<int, StationInfo> Stations { get; } = [];
public Dictionary<int, DepotInfo> Depots { get; } = [];
public Dictionary<int, LineInfo> Lines { get; } = [];
public Dictionary<int, VehicleInfo> Vehicles { get; } = [];
public Dictionary<int, TrainInfo> Trains { get; } = [];
public Dictionary<int, EdgeInfo> Edges { get; } = [];
public Dictionary<int, TrainMotion> Motions { get; } = [];
public HashSet<(int Cx, int Cy)> Chunks { get; } = [];
public DailyDigest? LastDigest { get; private set; }
/// <summary>Dettagli ricevuti su richiesta (F4): cartelle dei treni, registri delle officine, registro degli impieghi.</summary>
public Dictionary<int, MaintenanceCard> Cards { get; } = [];
public Dictionary<int, WorkshopRegister> Workshops { get; } = [];
public EmploymentReport? Employment { get; private set; }
/// <summary>Dati della F5: listino di borsa, schede di compagnie e industrie, Cronaca finale.</summary>
public MarketTape? Tape { get; private set; }
public Dictionary<int, CompanyCard> CompanyCards { get; } = [];
public Dictionary<int, IndustryCard> IndustryCards { get; } = [];
public Chronicle? Chronicle { get; private set; }
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
public int TapeVersion { get; private set; }
/// <summary>Ultimi avvisi di manutenzione, dal più recente.</summary>
public List<MaintenanceAlert> Alerts { get; } = [];
private const int AlertCapacity = 50;
/// <summary>Contatore dei dettagli ricevuti (per aggiornare i pannelli).</summary>
public int DetailVersion { get; private set; }
public long Tick { get; private set; }
public byte Speed { get; private set; }
/// <summary>Contatori di modifica per il disegno (terreno, binari, entità).</summary>
public int TerrainVersion { get; private set; }
public int TrackVersion { get; private set; }
public int EntityVersion { get; private set; }
public CompanyId Company => Summary is null ? CompanyId.None : new CompanyId(Summary.CompanyId);
public Calendar? Calendar { get; private set; }
public int Year => Calendar is null ? 0 : Calendar.StartYear + (int)(Tick / Calendar.TicksPerDay / Calendar.DaysPerYear);
/// <summary>Applica un messaggio del server; restituisce false se non riguarda lo stato.</summary>
public bool Apply(IMessage message)
{
switch (message)
{
case Welcome m: Reset(m); return true;
case MapChunk m: ApplyChunk(m); return true;
case EntitySnapshot m:
ClearEntities();
ApplyEntities(m.Entities, m.Tick);
return true;
case EntityDelta m:
ApplyEntities(m.Changed, m.Tick);
foreach (var (type, id) in m.Removed) Remove(type, id);
EntityVersion++;
return true;
case TrackWorks m: ApplyTrack(m); return true;
case TrainMotion m:
Motions[m.TrainId] = m;
Tick = Math.Max(Tick, m.Tick);
return true;
case DailyDigest m:
LastDigest = m;
Tick = Math.Max(Tick, m.Tick);
Speed = m.Speed;
return true;
case Pong m:
Tick = Math.Max(Tick, (long)m.ServerTick);
return true;
case MaintenanceCard m:
Cards[m.Train] = m;
DetailVersion++;
return true;
case WorkshopRegister m:
Workshops[m.Depot] = m;
DetailVersion++;
return true;
case EmploymentReport m:
Employment = m;
DetailVersion++;
return true;
case MarketTape m:
Tape = m;
TapeVersion++;
return true;
case CompanyCard m:
CompanyCards[m.Company] = m;
DetailVersion++;
return true;
case IndustryCard m:
IndustryCards[m.Industry] = m;
DetailVersion++;
return true;
case Chronicle m:
Chronicle = m;
DetailVersion++;
return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
DetailVersion++;
return true;
default:
return false;
}
}
private void Reset(Welcome m)
{
Cards.Clear();
Workshops.Clear();
Employment = null;
Tape = null;
CompanyCards.Clear();
IndustryCards.Clear();
Chronicle = null;
Alerts.Clear();
Summary = m.Summary;
SessionId = m.SessionId;
Tick = m.Summary.Tick;
Speed = m.Summary.Speed;
Calendar = new Calendar(Data.Balance.Time, m.Summary.StartYear);
Terrain = new Terrain(m.Summary.WidthCells, m.Summary.HeightCells, m.Summary.CellSizeM, m.Summary.ChunkCells);
Sampler = new TerrainSampler(Terrain);
Chunks.Clear();
Network = new RailNetwork();
Edges.Clear();
ClearEntities();
LastDigest = null;
TerrainVersion++;
TrackVersion++;
}
private void ClearEntities()
{
Companies.Clear(); Towns.Clear(); Industries.Clear(); Hubs.Clear(); Stations.Clear(); Depots.Clear();
Lines.Clear(); Vehicles.Clear(); Trains.Clear(); Motions.Clear();
EntityVersion++;
}
private void ApplyChunk(MapChunk m)
{
if (Terrain is null) return;
int x0 = m.Cx * Terrain.ChunkCells, y0 = m.Cy * Terrain.ChunkCells;
if (x0 < 0 || y0 < 0 || x0 + m.Width > Terrain.Width || y0 + m.Height > Terrain.Height) throw new ProtocolException("chunk fuori dalla mappa");
for (int y = 0; y < m.Height; y++)
{
int dst = (y0 + y) * Terrain.Width + x0;
m.Heights.AsSpan(y * m.Width, m.Width).CopyTo(Terrain.Heights.AsSpan(dst));
m.Types.AsSpan(y * m.Width, m.Width).CopyTo(Terrain.Types.AsSpan(dst));
m.RiverWidth.AsSpan(y * m.Width, m.Width).CopyTo(Terrain.RiverWidth.AsSpan(dst));
}
Chunks.Add((m.Cx, m.Cy));
TerrainVersion++;
}
private void ApplyEntities(EntityLists e, long tick)
{
Tick = Math.Max(Tick, tick);
foreach (var x in e.Companies) Companies[x.Id] = x;
foreach (var x in e.Towns) Towns[x.Id] = x;
foreach (var x in e.Industries) Industries[x.Id] = x;
foreach (var x in e.Hubs) Hubs[x.Id] = x;
foreach (var x in e.Lines) Lines[x.Id] = x;
foreach (var x in e.Vehicles) Vehicles[x.Id] = x;
foreach (var x in e.Trains) Trains[x.Id] = x;
bool network = e.Nodes.Count + e.Stations.Count + e.Depots.Count > 0;
foreach (var n in e.Nodes) SetNode(n);
foreach (var s in e.Stations)
{
Stations[s.Id] = s;
SetStation(s);
}
foreach (var d in e.Depots)
{
Depots[d.Id] = d;
SetDepot(d);
}
if (network) Network.Touch();
EntityVersion++;
}
private void Remove(EntityType type, int id)
{
switch (type)
{
case EntityType.Company: Companies.Remove(id); break;
case EntityType.Town: Towns.Remove(id); break;
case EntityType.Industry: Industries.Remove(id); break;
case EntityType.Hub: Hubs.Remove(id); break;
case EntityType.Line: Lines.Remove(id); break;
case EntityType.Vehicle: Vehicles.Remove(id); break;
case EntityType.Train:
Trains.Remove(id);
Motions.Remove(id);
break;
case EntityType.Node:
if (id >= 0 && id < Network.Nodes.Count) Network.Nodes[id].Removed = true;
Network.Touch();
break;
case EntityType.Station:
Stations.Remove(id);
if (id >= 0 && id < Network.Stations.Count) Network.Stations[id] = PlaceholderStation(id);
Network.Touch();
break;
case EntityType.Depot:
Depots.Remove(id);
if (id >= 0 && id < Network.Depots.Count) Network.Depots[id] = PlaceholderDepot(id);
Network.Touch();
break;
case EntityType.Edge:
RemoveEdge(id);
break;
}
}
// ------------------------------------------------------------------ rete
private void SetNode(NodeInfo n)
{
while (Network.Nodes.Count <= n.Id)
Network.Nodes.Add(new TrackNode { Id = new NodeId(Network.Nodes.Count), Position = default, HeightM = 0, Removed = true });
var node = new TrackNode
{
Id = new NodeId(n.Id), Position = n.Position, HeightM = n.HeightM, Owner = new CompanyId(n.Owner),
Station = new StationId(n.Station), Depot = new DepotId(n.Depot),
};
foreach (int e in n.Edges) node.AddEdge(new EdgeId(e));
Network.Nodes[n.Id] = node;
}
private void SetStation(StationInfo s)
{
while (Network.Stations.Count <= s.Id) Network.Stations.Add(PlaceholderStation(Network.Stations.Count));
Network.Stations[s.Id] = new Station
{
Id = new StationId(s.Id), Owner = new CompanyId(s.Owner), Name = s.Name, Node = new NodeId(s.Node), Position = s.Position, Platforms = s.Platforms,
};
}
private void SetDepot(DepotInfo d)
{
while (Network.Depots.Count <= d.Id) Network.Depots.Add(PlaceholderDepot(Network.Depots.Count));
Network.Depots[d.Id] = new Depot { Id = new DepotId(d.Id), Owner = new CompanyId(d.Owner), Name = d.Name, Node = new NodeId(d.Node), Position = d.Position, Size = d.Size };
}
private static Station PlaceholderStation(int id) =>
new() { Id = new StationId(id), Owner = CompanyId.None, Name = "", Node = NodeId.None, Position = default, Platforms = 0 };
private static Depot PlaceholderDepot(int id) =>
new() { Id = new DepotId(id), Owner = CompanyId.None, Name = "", Node = NodeId.None, Position = default, Size = "" };
private void ApplyTrack(TrackWorks m)
{
foreach (var e in m.Edges)
{
Edges[e.Id] = e;
while (Network.Edges.Count <= e.Id) Network.Edges.Add(PlaceholderEdge(Network.Edges.Count));
var edge = new TrackEdge
{
Id = new EdgeId(e.Id), A = new NodeId(e.A), B = new NodeId(e.B), Owner = new CompanyId(e.Owner), TrackClass = e.TrackClass,
DoubleTrack = e.DoubleTrack, Electrified = e.Electrified, State = (EdgeState)e.State,
S = e.S, X = e.X, Y = e.Y, H = e.H, Ground = e.Ground, Kinds = e.Kinds.Select(k => (WorkKind)k).ToArray(), SpeedLimitKmh = e.SpeedLimitKmh,
Condition = e.Condition, StructureCondition = e.StructureCondition,
};
edge.Signals.AddRange(e.Signals);
Network.Edges[e.Id] = edge;
}
foreach (int id in m.Removed) RemoveEdge(id);
Network.Touch();
TrackVersion++;
}
private void RemoveEdge(int id)
{
Edges.Remove(id);
if (id >= 0 && id < Network.Edges.Count) Network.Edges[id] = PlaceholderEdge(id);
Network.Touch();
TrackVersion++;
}
private static TrackEdge PlaceholderEdge(int id) => new()
{
Id = new EdgeId(id), A = NodeId.None, B = NodeId.None, Owner = CompanyId.None, TrackClass = 0, DoubleTrack = false, Electrified = false,
State = EdgeState.Demolished, S = [0, 1], X = [0, 0], Y = [0, 0], H = [0, 0], Ground = [0, 0], Kinds = [WorkKind.Natural, WorkKind.Natural],
SpeedLimitKmh = [0, 0],
};
// ------------------------------------------------------------------ anteprime e treni
/// <summary>Distanza dal bordo dell'abitato più vicino, come <c>World.TownEdgeDistanceKm</c>.</summary>
public double NearestTownEdgeKm(Vec2 p)
{
if (Towns.Count == 0 || Terrain is null) return double.MaxValue;
double best = double.MaxValue;
foreach (var t in Towns.Values) best = Math.Min(best, Math.Max(0, (Vec2.Distance(t.Position, p) - t.RadiusCells * Terrain.CellSizeM) / 1000.0));
return best;
}
/// <summary>Ingressi del pianificatore per l'anteprima di un binario (stesso codice del server).</summary>
public TrackPreviewInputs PreviewInputs()
{
if (Summary is null || Sampler is null) throw new InvalidOperationException("Nessuna partita");
return new TrackPreviewInputs
{
Data = Data,
Sampler = Sampler,
Network = Network,
Year = Year,
CostMultiplier = Summary.CostMultiplier,
NearestTownEdgeKm = NearestTownEdgeKm,
};
}
/// <summary>Anteprima di un binario della compagnia della sessione.</summary>
public TrackPlan PreviewTrack(Core.Commands.BuildTrackCommand command) => TrackPreview.Prepare(PreviewInputs(), Company, command).Plan;
/// <summary>Punto alla distanza d lungo i tratti di un moto (estremi inclusi).</summary>
public Vec2? PointAlong(TrainMotion motion, double d)
{
if (motion.Segments.Count == 0) return null;
double acc = 0;
for (int i = 0; i < motion.Segments.Count; i++)
{
var seg = motion.Segments[i];
if (seg.Edge < 0 || seg.Edge >= Network.Edges.Count) return null;
double len = seg.Length;
if (d <= acc + len || i == motion.Segments.Count - 1)
{
double t = len <= 0 ? 0 : Math.Clamp((d - acc) / len, 0, 1);
return Network.Edges[seg.Edge].PointAt(seg.FromS + (seg.ToS - seg.FromS) * t);
}
acc += len;
}
return null;
}
/// <summary>Lunghezza totale dei tratti di un moto.</summary>
public static double TotalLength(TrainMotion motion)
{
double sum = 0;
foreach (var s in motion.Segments) sum += s.Length;
return sum;
}
/// <summary>
/// Testa del treno interpolata: avanza dalla posizione inviata alla velocità inviata per i
/// secondi di orologio dei treni trascorsi, senza superare il tratto prenotato.
/// </summary>
public Vec2? TrainHead(int trainId, double elapsedTrainSeconds = 0) =>
Motions.TryGetValue(trainId, out var m) ? TrainHead(m, elapsedTrainSeconds) : null;
/// <summary>Testa interpolata a partire da un moto qualsiasi.</summary>
public Vec2? TrainHead(TrainMotion m, double elapsedTrainSeconds)
{
double d = Math.Min(m.HeadDistance + m.Speed * Math.Max(0, elapsedTrainSeconds), TotalLength(m));
return PointAlong(m, d);
}
}
@@ -0,0 +1,155 @@
using System.Net.WebSockets;
using System.Threading.Channels;
using RailEnterprise.Core.Commands;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Protocol.Client;
/// <summary>Il server ha rifiutato la sessione.</summary>
public sealed class SessionRejectedException(Reject reject) : Exception($"{reject.Code}: {reject.Reason}")
{
public Reject Reject { get; } = reject;
}
/// <summary>
/// Connessione WebSocket al server: un frame per messaggio binario, ricezione su un task dedicato
/// con coda dei messaggi, invii serializzati. Usata dal client Godot e dai test di integrazione.
/// </summary>
public sealed class ProtocolClient : IAsyncDisposable
{
private readonly ClientWebSocket _socket;
private readonly Channel<IMessage> _incoming = Channel.CreateUnbounded<IMessage>(new UnboundedChannelOptions { SingleReader = false, SingleWriter = true });
private readonly SemaphoreSlim _sendLock = new(1, 1);
private readonly CancellationTokenSource _cts = new();
private Task? _receiveLoop;
private uint _seq;
public Exception? Fault { get; private set; }
public bool IsOpen => _socket.State == WebSocketState.Open;
private ProtocolClient(ClientWebSocket socket) => _socket = socket;
public static async Task<ProtocolClient> ConnectAsync(Uri uri, CancellationToken ct = default)
{
var socket = new ClientWebSocket();
await socket.ConnectAsync(uri, ct).ConfigureAwait(false);
var client = new ProtocolClient(socket);
client._receiveLoop = Task.Run(client.ReceiveLoopAsync);
return client;
}
/// <summary>Hello → Welcome; un Reject diventa <see cref="SessionRejectedException"/>.</summary>
public async Task<Welcome> HandshakeAsync(Hello hello, CancellationToken ct = default)
{
await SendAsync(hello, ct).ConfigureAwait(false);
var reply = await ReceiveAsync(ct).ConfigureAwait(false);
return reply switch
{
Welcome w => w,
Reject r => throw new SessionRejectedException(r),
_ => throw new ProtocolException($"risposta inattesa all'Hello: {reply.Id}"),
};
}
public async Task SendAsync(IMessage message, CancellationToken ct = default)
{
byte[] frame = Frame.Encode(message);
await _sendLock.WaitAsync(ct).ConfigureAwait(false);
try
{
await _socket.SendAsync(frame, WebSocketMessageType.Binary, true, ct).ConfigureAwait(false);
}
finally
{
_sendLock.Release();
}
}
/// <summary>Riserva un numero di sequenza (per registrare l'attesa dell'esito prima dell'invio).</summary>
public uint ReserveSeq() => Interlocked.Increment(ref _seq);
/// <summary>Invia un comando con un nuovo numero di sequenza e lo restituisce.</summary>
public async Task<uint> SendCommandAsync(GameCommand command, CancellationToken ct = default)
{
uint seq = Interlocked.Increment(ref _seq);
await SendAsync(new CommandMessage { Seq = seq, Command = command }, ct).ConfigureAwait(false);
return seq;
}
public async Task<IMessage> ReceiveAsync(CancellationToken ct = default)
{
try
{
return await _incoming.Reader.ReadAsync(ct).ConfigureAwait(false);
}
catch (ChannelClosedException) when (Fault is not null)
{
throw new ProtocolException($"connessione chiusa: {Fault.Message}");
}
}
/// <summary>Per il ciclo di disegno: prende un messaggio se ce n'è uno pronto.</summary>
public bool TryReceive(out IMessage message) => _incoming.Reader.TryRead(out message!);
private async Task ReceiveLoopAsync()
{
var buffer = new byte[64 * 1024];
var frame = new MemoryStream();
try
{
while (!_cts.IsCancellationRequested && _socket.State == WebSocketState.Open)
{
var result = await _socket.ReceiveAsync(buffer, _cts.Token).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close) break;
frame.Write(buffer, 0, result.Count);
if (frame.Length > Frame.MaxFrameBytes) throw new ProtocolException("frame oltre 4 MB");
if (!result.EndOfMessage) continue;
var message = Frame.Decode(frame.GetBuffer().AsSpan(0, (int)frame.Length));
frame.SetLength(0);
await _incoming.Writer.WriteAsync(message, _cts.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
Fault = e;
}
finally
{
_incoming.Writer.TryComplete(Fault);
}
}
public async ValueTask DisposeAsync()
{
try
{
if (_socket.State == WebSocketState.Open)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "fine", timeout.Token).ConfigureAwait(false);
}
}
catch (Exception)
{
// il server può aver già chiuso
}
_cts.Cancel();
if (_receiveLoop is not null)
{
try
{
await _receiveLoop.ConfigureAwait(false);
}
catch (Exception)
{
}
}
_socket.Dispose();
_cts.Dispose();
_sendLock.Dispose();
}
}