Files
Rail_Enterprise/src/ViaFerrea.Core/Rail/LineGraph.cs
T
Claude 18b5e2c2e1 F2: rete ferroviaria, cantieri, treni con fisica e blocchi, merci in stazione
- RailNetwork: nodi, archi con profilo campionato, divisione degli archi agli
  agganci (anche in cantiere), indice spaziale, cavalcavia sui binari altrui
- Comandi: binari, stazioni, depositi, segnali, demolizioni, rinnovi,
  ammodernamenti, veicoli, composizioni, linee, assegnazioni, rientro
- ConstructionSystem: squadre per livello, avanzamento, usura dei binari e
  invecchiamento delle strutture; costi d'esercizio e valore contabile
- TrainSystem: A* con vincolo di svolta, prenotazione a blocchi con catena
  fino a un punto sicuro sul binario semplice, fisica 8.4, stallo in salita
- StationSystem e StationWork: bacini, merci con destinazione sul grafo
  delle linee, carico sui carri, consegne con tariffa, trasbordi
- Salvataggi estesi a tutto lo stato ferroviario; 11 nuovi test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
2026-10-01 23:19:34 +00:00

171 lines
7.6 KiB
C#
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.
using ViaFerrea.Core.Common;
namespace ViaFerrea.Core.Rail;
/// <summary>Tratto continuo su una linea: si sale in From e si scende in To.</summary>
public readonly record struct Hop(LineId Line, StationId From, StationId To, double Minutes);
/// <summary>Collegamento migliore verso una stazione: minuti di orologio dei treni e tratti.</summary>
public sealed record Connection(StationId Destination, double Minutes, Hop[] Hops)
{
public Hop First => Hops[0];
}
/// <summary>
/// Grafo delle linee di una compagnia (guida 7, 9): nodi = stazioni, archi = fermate
/// consecutive di una linea con il tempo di percorrenza stimato. Dijkstra sugli stati
/// (stazione, linea) con penalità di cambio. Ricostruito quando cambiano rete, linee o treni.
/// </summary>
public sealed class LineGraph
{
private readonly record struct Segment(int From, int To, LineId Line, double Minutes);
private readonly Dictionary<int, List<Segment>> _out = new();
private readonly Dictionary<int, Dictionary<int, Connection>> _reach = new();
private readonly double _transferMinutes;
public CompanyId Company { get; }
public int Version { get; }
/// <summary>Capacità giornaliera stimata per linea e classe (posti, unità merci).</summary>
public Dictionary<int, (double Workers, double Staff, double Freight)> DailyCapacity { get; } = new();
/// <summary>Durata di un giro completo per linea (minuti di orologio dei treni).</summary>
public Dictionary<int, double> CycleMinutes { get; } = new();
public LineGraph(Simulation.World w, CompanyId company, int version)
{
Company = company;
Version = version;
var ops = w.Data.Construction.Operations;
double dwell = w.Data.Construction.Stations.MinDwellMinutes;
_transferMinutes = dwell * 2;
var net = w.Network;
var path = new List<RouteStep>();
foreach (var line in w.Lines)
{
if (line.Removed || line.Owner != company || line.Stops.Count < 2) continue;
var trains = w.Trains.Where(t => !t.Removed && t.Line == line.Id).ToList();
double speed = trains.Count > 0 ? trains.Min(t => t.MaxSpeedKmh) : 60;
bool electric = trains.Any(t => t.NeedsElectrification);
double cycle = 0;
bool complete = true;
for (int i = 0; i < line.Stops.Count; i++)
{
var a = net.Stations[line.Stops[i].Station.Value];
var b = net.Stations[line.Stops[(i + 1) % line.Stops.Count].Station.Value];
if (a.Id == b.Id) continue;
if (!w.Pathfinder.FindPath(net, company, a.Node, EdgeId.None, b.Node, speed, electric, ops.MaxTurnDeg, path))
{
complete = false;
continue;
}
double seconds = 0;
foreach (var step in path) seconds += Pathfinder.EdgeTime(net.Edges[step.Edge.Value], speed / 3.6);
double minutes = seconds / 60 * 1.15 + dwell; // margine per accelerazioni e frenate
cycle += minutes;
if (!_out.TryGetValue(a.Id.Value, out var list)) _out[a.Id.Value] = list = [];
list.Add(new Segment(a.Id.Value, b.Id.Value, line.Id, minutes));
}
if (!complete || cycle <= 0) continue;
CycleMinutes[line.Id.Value] = cycle;
double tripsPerDay = w.Calendar.TrainMinutesPerDay / cycle;
double workers = 0, staff = 0, freight = 0;
foreach (var t in trains)
{
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
if (v.Def.Kind == Data.VehicleKind.Coach)
{
if (v.Def.Class == Data.PaxClass.Staff) staff += v.Def.PaxCapacity ?? 0;
else workers += v.Def.PaxCapacity ?? 0;
}
else if (v.Def.Kind == Data.VehicleKind.Wagon) freight += v.Def.Capacity ?? 0;
}
}
DailyCapacity[line.Id.Value] = (workers * tripsPerDay, staff * tripsPerDay, freight * tripsPerDay);
}
foreach (var list in _out.Values) list.Sort((x, y) => x.To != y.To ? x.To.CompareTo(y.To) : x.Line.Value.CompareTo(y.Line.Value));
}
/// <summary>Collegamenti migliori da una stazione verso tutte le stazioni raggiungibili.</summary>
public IReadOnlyDictionary<int, Connection> From(StationId origin)
{
if (_reach.TryGetValue(origin.Value, out var cached)) return cached;
var result = new Dictionary<int, Connection>();
// stato = (stazione, linea su cui si viaggia); linea −1 = a terra all'origine
var best = new Dictionary<(int, int), double>();
var came = new Dictionary<(int, int), ((int, int) Prev, Segment Seg)>();
var open = new PriorityQueue<(int Station, int Line), (double, int, int)>();
best[(origin.Value, -1)] = 0;
open.Enqueue((origin.Value, -1), (0, origin.Value, -1));
while (open.TryDequeue(out var state, out var pri))
{
double cost = pri.Item1;
if (best.TryGetValue(state, out double known) && known < cost) continue;
if (state.Station != origin.Value && !result.ContainsKey(state.Station))
result[state.Station] = BuildConnection(state, cost, came, origin.Value);
if (!_out.TryGetValue(state.Station, out var segs)) continue;
foreach (var seg in segs)
{
double c = cost + seg.Minutes + (state.Line >= 0 && state.Line != seg.Line.Value ? _transferMinutes : 0);
var next = (seg.To, seg.Line.Value);
if (best.TryGetValue(next, out double old) && old <= c) continue;
best[next] = c;
came[next] = (state, seg);
open.Enqueue(next, (c, seg.To, seg.Line.Value));
}
}
_reach[origin.Value] = result;
return result;
}
private static Connection BuildConnection((int Station, int Line) state, double cost,
Dictionary<(int, int), ((int, int) Prev, Segment Seg)> came, int origin)
{
var segs = new List<Segment>();
var s = state;
while (came.TryGetValue(s, out var link))
{
segs.Add(link.Seg);
s = link.Prev;
}
segs.Reverse();
var hops = new List<Hop>();
foreach (var seg in segs)
{
if (hops.Count > 0 && hops[^1].Line == seg.Line)
{
var last = hops[^1];
hops[^1] = last with { To = new StationId(seg.To), Minutes = last.Minutes + seg.Minutes };
}
else
{
hops.Add(new Hop(seg.Line, new StationId(seg.From), new StationId(seg.To), seg.Minutes));
}
}
return new Connection(new StationId(state.Station), cost, hops.ToArray());
}
}
/// <summary>Grafi delle linee per compagnia, ricostruiti quando cambia la versione della rete o delle linee.</summary>
public sealed class LineGraphCache
{
private readonly Dictionary<int, LineGraph> _graphs = new();
/// <summary>Contatore delle modifiche a linee, treni assegnati e composizioni.</summary>
public int LinesVersion { get; private set; }
public void Touch() => LinesVersion++;
public LineGraph For(Simulation.World w, CompanyId company)
{
int version = w.Network.Version * 100_003 + LinesVersion;
if (_graphs.TryGetValue(company.Value, out var g) && g.Version == version) return g;
g = new LineGraph(w, company, version);
_graphs[company.Value] = g;
return g;
}
}