Files
Rail_Enterprise/src/RailEnterprise.Core/Simulation/Systems/TrainSystem.cs
T
Alby96andClaude Opus 5.5 1f8da87e51 F6: eventi del mondo con effetti temporanei e notizie
Aggiunge gli eventi della F6: fatti del mondo che cambiano il gioco per
un periodo limitato, leggibili nel notiziario e reversibili.

- Catalogo data/events.json con schema e validazione: incidente e boom
  di un'industria, fiera ed epidemia, boom e crollo della domanda di un
  bene in una zona, maltempo su un'area, sciopero di città o deposito.
- Effetti come moltiplicatori letti da un'unica sorgente
  (World.WorldEvents) dai sistemi esistenti: capacità delle industrie,
  consumi delle città, presenze dei pendolari, velocità dei treni e usura
  del binario. A evento finito il moltiplicatore torna 1.
- EventSystem tra le IA e l'hash, con flusso Rng dedicato «events»,
  bersaglio in ordine di id, frequenza per mappa scalata dalla difficoltà
  (eventFrequencyMultiplier), tetto di 6, niente doppioni, notizie di
  inizio e fine in italiano (EventKind.World).
- Salvataggio corpo versione 5 con gli eventi nell'hash; le versioni 1-4
  si caricano senza eventi e con la frequenza del preset.
- Protocollo: eventi in corso nel DailyDigest e nel MarketReport; client
  con il riquadro «Eventi in corso», avvisi nelle schede e «evento in
  corso» nel Mercato globale.
- Lo scenario Valdoria disattiva gli eventi: con gli eventi attivi la
  flotta F4 senza linea dei ricambi non scendeva più sotto 40, e
  l'accettazione deve misurare la manutenzione, non la fortuna (ADR 0017).
  Accettazione F4 invariata: 35 / 20 guasti senza linea, 75 / 2 con.

Decisioni in docs/adr/0017-eventi-del-mondo.md; 17 test nuovi.

Refs #33.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:59:48 +01:00

703 lines
29 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 RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>
/// Marcia dei treni (guida 8.4) con il segnalamento a blocchi:
/// - percorsi A* fino alla prossima fermata;
/// - autorizzazione al movimento: sezioni di blocco prenotate davanti alla testa; su binario
/// semplice si blocca il verso di tutti gli archi fino al primo punto sicuro (stazione con
/// binario libero, deposito, doppio binario, destinazione), così due treni non si trovano mai
/// faccia a faccia;
/// - fisica: a = (Ft − R)/m con Ft = min(P/v, sforzo di trazione, aderenza) e
/// R = m·g·(attrito + pendenza) + 0,6·v²·cx; frenata costante con anticipo sui limiti;
/// - le risorse si liberano quando la coda le ha superate.
/// Nessuna allocazione nel ciclo per treno: liste del treno riutilizzate.
/// </summary>
public sealed class TrainSystem : ISimSystem
{
public string Name => "Trains";
private const byte HeldBlock = 0;
private const byte HeldPlatform = 1;
private const byte HeldLock = 2;
private double _dt, _brake, _g, _rolling, _aero, _adhesion, _stallSpeed, _stallSeconds, _margin, _maxTurn, _cosTurn, _gradeThreshold, _fastShare;
private int _ticksPerDay;
public void Step(WorldContext ctx)
{
var w = ctx.World;
var phys = w.Data.Construction.Physics;
_dt = w.Calendar.TrainSecondsPerTick;
_brake = phys.BrakingMs2;
_g = phys.Gravity;
_rolling = phys.RollingResistance;
_aero = phys.AeroCoefficient;
_adhesion = phys.Adhesion * phys.AdhesionFactor;
_stallSpeed = phys.StallSpeedKmh / 3.6;
_stallSeconds = phys.StallSeconds;
_margin = w.Data.Construction.Operations.LookaheadMarginM;
_maxTurn = w.Data.Construction.Operations.MaxTurnDeg;
_ticksPerDay = w.Calendar.TicksPerDay;
_cosTurn = DMath.Cos(_maxTurn * Math.PI / 180);
_gradeThreshold = w.Data.Maintenance.Wear.GradientThreshold;
_fastShare = w.Data.Maintenance.Wear.HighSpeedThreshold;
foreach (var t in w.Trains)
{
if (t.Removed) continue;
switch (t.State)
{
case TrainState.InDepot:
if (WantsToLeaveDepot(w, t)) TryPlanLeg(ctx, t);
break;
case TrainState.Loading:
StationWork.Dwell(ctx, t);
if (t.State == TrainState.Loading && StationWork.ReadyToDepart(ctx, t))
{
StationWork.Depart(ctx, t);
TryPlanLeg(ctx, t);
}
break;
case TrainState.NoRoute:
if ((ctx.Tick + t.Id.Value) % _ticksPerDay == 0) TryPlanLeg(ctx, t);
break;
case TrainState.Waiting:
case TrainState.Moving:
case TrainState.Stalled:
Move(ctx, t);
break;
case TrainState.Broken:
if (t.RescueTick >= 0 && ctx.Tick >= t.RescueTick) Rescue(ctx, t);
break;
}
}
}
private static bool WantsToLeaveDepot(World w, Train t)
{
if (t.InWorkshop) return false;
if (t.MaintenanceDepot.IsValid) return w.Network.Depots[t.MaintenanceDepot.Value].Node != t.AtNode;
if (t.GoingToDepot.IsValid) return w.Network.Depots[t.GoingToDepot.Value].Node != t.AtNode;
return t.Line.IsValid && !w.Lines[t.Line.Value].Removed && w.Lines[t.Line.Value].Stops.Count > 0;
}
// il soccorso è arrivato: il treno riprende la marcia rimorchiato verso il deposito della riparazione
private void Rescue(WorldContext ctx, Train t)
{
FleetMaintenanceSystem.OnRescued(ctx, t);
switch (t.StateBeforeFailure)
{
case TrainState.Loading:
t.State = TrainState.Loading;
t.DwellTicks = 0;
break;
case TrainState.Moving:
case TrainState.Waiting:
case TrainState.Stalled:
if (t.Route.Count > 0 && !t.AtNode.IsValid)
{
t.State = TrainState.Waiting;
t.WaitingSinceTick = ctx.Tick;
t.StallSeconds = 0;
break;
}
t.State = TrainState.Waiting;
TryPlanLeg(ctx, t);
break;
default:
t.State = TrainState.Waiting;
TryPlanLeg(ctx, t);
break;
}
}
// ------------------------------------------------------------------ pianificazione
/// <summary>Calcola il percorso verso la prossima destinazione del treno fermo in un nodo.</summary>
public void TryPlanLeg(WorldContext ctx, Train t)
{
var w = ctx.World;
var net = w.Network;
// intervento prenotato dal pianificatore: dopo la fermata corrente si va in officina
if (t.MaintenanceDepot.IsValid && !t.InWorkshop && !t.GoingToDepot.IsValid) t.GoingToDepot = t.MaintenanceDepot;
NodeId target;
if (t.GoingToDepot.IsValid) target = net.Depots[t.GoingToDepot.Value].Node;
else if (t.Line.IsValid && !w.Lines[t.Line.Value].Removed && w.Lines[t.Line.Value].Stops.Count > 0)
{
var line = w.Lines[t.Line.Value];
if (t.StopIndex >= line.Stops.Count) t.StopIndex = 0;
target = net.Stations[line.Stops[t.StopIndex].Station.Value].Node;
}
else if (t.HomeDepot.IsValid && net.Depots[t.HomeDepot.Value].Node != t.AtNode) target = net.Depots[t.HomeDepot.Value].Node;
else
{
if (t.AtNode.IsValid && net.Nodes[t.AtNode.Value].Depot.IsValid) t.State = TrainState.InDepot;
return;
}
if (t.AtNode == target)
{
t.Route.Clear();
Arrive(ctx, t, target);
return;
}
var arrived = Pathfinder.IsTurningPoint(net, net.Nodes[t.AtNode.Value]) ? EdgeId.None : t.ArrivedVia;
if (!w.Pathfinder.FindPath(net, t.Owner, t.AtNode, arrived, target, t.MaxSpeedKmh, t.NeedsElectrification, _maxTurn, t.Route))
{
if (t.MaintenanceDepot.IsValid && t.GoingToDepot == t.MaintenanceDepot)
{
// officina irraggiungibile da qui: la prenotazione salta e il treno torna alla linea
FleetMaintenanceSystem.CancelBooking(t);
TryPlanLeg(ctx, t);
return;
}
if (t.State != TrainState.NoRoute)
{
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Train, EventSeverity.Warning,
$"{t.Name}: nessun percorso verso la prossima fermata", EntityKind.Train, t.Id.Value, t.Owner));
}
t.State = TrainState.NoRoute;
return;
}
CutAtReversal(net, t);
// lascia il nodo di partenza: deposito (nessuna risorsa) o stazione (il binario resta tenuto finché la coda non esce)
for (int i = 0; i < t.Held.Count; i++)
{
var h = t.Held[i];
if (h.Kind == HeldPlatform && double.IsNaN(h.LeftAt))
{
h.LeftAt = t.Odometer;
t.Held[i] = h;
}
}
t.RouteIndex = 0;
t.StepPos = 0;
t.Speed = 0;
t.ReservedStep = -1;
t.ReservedBlock = -1;
t.ArrivalPlatform = -1;
t.State = TrainState.Waiting;
t.WaitingSinceTick = ctx.Tick;
t.WaitWarned = false;
t.StallSeconds = 0;
t.AtNode = NodeId.None;
}
/// <summary>
/// Se il percorso inverte la marcia in un nodo intermedio (stazione, deposito o binario morto),
/// lo tronca lì: il treno vi entra tutto, libera l'arco d'arrivo e riparte nel verso opposto
/// con un nuovo percorso. Senza la sosta il treno terrebbe il verso dell'arco da cui è arrivato
/// mentre chiede quello opposto, bloccando chi lo segue.
/// </summary>
private void CutAtReversal(RailNetwork net, Train t)
{
for (int k = 0; k < t.Route.Count - 1; k++)
{
var a = t.Route[k];
var b = t.Route[k + 1];
var ea = net.Edges[a.Edge.Value];
var node = a.Forward ? ea.B : ea.A;
var dirIn = -ea.DirectionFrom(node);
var dirOut = net.Edges[b.Edge.Value].DirectionFrom(node);
if (Vec2.Dot(dirIn, dirOut) >= _cosTurn) continue;
t.Route.RemoveRange(k + 1, t.Route.Count - k - 1);
return;
}
}
/// <summary>Nodo di destinazione corrente (fermata della linea, deposito o deposito di casa).</summary>
private static NodeId TargetNode(World w, Train t)
{
var net = w.Network;
if (t.GoingToDepot.IsValid) return net.Depots[t.GoingToDepot.Value].Node;
if (t.Line.IsValid && !w.Lines[t.Line.Value].Removed && w.Lines[t.Line.Value].Stops.Count > 0)
{
var line = w.Lines[t.Line.Value];
return net.Stations[line.Stops[t.StopIndex % line.Stops.Count].Station.Value].Node;
}
return t.HomeDepot.IsValid ? net.Depots[t.HomeDepot.Value].Node : NodeId.None;
}
// ------------------------------------------------------------------ marcia
private void Move(WorldContext ctx, Train t)
{
var w = ctx.World;
var net = w.Network;
if (t.Route.Count == 0)
{
t.State = TrainState.NoRoute;
return;
}
// 1. estende l'autorizzazione al movimento fino alla distanza di frenata con margine
double needed = t.Speed * t.Speed / (2 * _brake) + t.Speed * _dt * 2 + _margin;
double ma = MaDistance(net, t);
while (ma < needed && TryReserveNext(w, t))
ma = MaDistance(net, t);
// 2. velocità obiettivo: limiti presenti e futuri, fine dell'autorizzazione, fermata
var step = t.Route[t.RouteIndex];
var edge = net.Edges[step.Edge.Value];
// condizione del binario e maltempo sull'area (ADR 0017)
double cond = ConstructionSystem.ConditionFactor(w, edge) * w.WorldEvents.EdgeSpeed(edge);
double limit = Math.Min(t.TopSpeedKmh, LimitAt(edge, step.Forward, t.StepPos) * cond) / 3.6;
double target = Math.Min(limit, Math.Sqrt(2 * _brake * Math.Max(0, ma - 1)));
target = Math.Min(target, LookaheadCap(w, t, needed + 500));
// 3. dinamica
double cargoT = CargoMassT(w, t);
double mass = (t.EmptyMassT + cargoT) * 1000;
double grade = step.Forward ? edge.GradeAt(t.StepPos) : -edge.GradeAt(edge.Length - t.StepPos);
double v = t.Speed;
double resist = mass * _g * (_rolling + grade) + _aero * v * v * t.Cx;
double traction = Math.Min(Math.Min(t.PowerKw * 1000 / Math.Max(v, 1), t.TractiveKn * 1000), _adhesion * t.LocoMassT * 1000 * _g);
double a = (traction - resist) / mass;
double vNew;
if (v < target - 1e-3) vNew = Math.Min(target, v + a * _dt);
else vNew = Math.Max(target, v - _brake * _dt);
if (vNew < 0) vNew = 0;
// stallo: vuole muoversi ma non riesce a vincere la salita
if (target > _stallSpeed && vNew < _stallSpeed && a <= 0)
{
t.StallSeconds += _dt;
if (t.StallSeconds >= _stallSeconds && t.State != TrainState.Stalled)
{
t.State = TrainState.Stalled;
w.Events.Add(new GameEvent(ctx.Day, EventKind.Train, EventSeverity.Critical,
$"{t.Name} non supera la salita del {Math.Abs(grade) * 100:F1}%: aggiungi una locomotiva o cambia tracciato",
EntityKind.Train, t.Id.Value, t.Owner));
}
}
else if (vNew > _stallSpeed)
{
t.StallSeconds = 0;
if (t.State == TrainState.Stalled) t.State = TrainState.Moving;
}
double dist = (v + vNew) / 2 * _dt;
if (dist >= ma)
{
dist = Math.Max(0, ma);
vNew = 0;
}
t.Speed = vNew;
if (t.State != TrainState.Stalled) t.State = vNew > 0.01 || dist > 0.01 ? TrainState.Moving : TrainState.Waiting;
if (t.State == TrainState.Moving) t.WaitingSinceTick = ctx.Tick;
else if (!t.WaitWarned && ctx.Tick - t.WaitingSinceTick > (long)w.Data.Construction.Operations.WaitWarningDays * _ticksPerDay)
{
t.WaitWarned = true;
w.Events.Add(new GameEvent(ctx.Day, EventKind.Train, EventSeverity.Warning,
$"{t.Name} è fermo da {w.Data.Construction.Operations.WaitWarningDays} giorni in attesa di via libera: possibile stallo della rete",
EntityKind.Train, t.Id.Value, t.Owner));
}
// 4. avanzamento lungo il percorso
if (dist > 0) Advance(ctx, t, dist, v, cargoT);
ReleaseBehind(net, t);
}
private void Advance(WorldContext ctx, Train t, double dist, double v, double cargoT)
{
var w = ctx.World;
var net = w.Network;
while (dist > 1e-9)
{
var step = t.Route[t.RouteIndex];
var edge = net.Edges[step.Edge.Value];
double remaining = edge.Length - t.StepPos;
double move = Math.Min(dist, remaining);
double before = t.StepPos;
t.StepPos += move;
t.Odometer += move;
t.KmThisYear += move / 1000;
dist -= move;
// usura: tonnellate × fattori, ripartite sulla frazione d'arco percorsa
double grade = Math.Abs(step.Forward ? edge.GradeAt(before) : edge.GradeAt(edge.Length - before));
// chilometri del giorno per l'usura dei veicoli (sezione 10.1)
double km = move / 1000;
t.DayKm += km;
if (grade > _gradeThreshold) t.DayGradeKm += km;
if (v * 3.6 > _fastShare * t.MaxSpeedKmh) t.DayFastKm += km;
if (t.CapacityT > 0) t.DayLoadKm += km * Math.Min(1, cargoT / t.CapacityT);
double vmaxEdge = Math.Max(1, w.Data.Eras.TrackClasses[edge.TrackClass].SpeedKmh / 3.6);
var tw = w.Data.Construction.TrackWear;
edge.WearToday += (t.EmptyMassT + cargoT) * (move / edge.Length) * (1 + tw.GradientWeight * grade) * (1 + tw.SpeedWeight * v / vmaxEdge);
// sezioni di blocco superate dalla testa
int blockBefore = BlockOf(edge, step.Forward, before);
int blockAfter = BlockOf(edge, step.Forward, Math.Min(t.StepPos, edge.Length - 1e-6));
for (int b = blockBefore; b < blockAfter; b++) MarkLeft(t, HeldBlock, edge.Id.Value, b, step.Forward, t.Odometer);
if (t.StepPos < edge.Length - 1e-6) break;
// la testa lascia l'arco
MarkLeft(t, HeldBlock, edge.Id.Value, LastBlock(edge), step.Forward, t.Odometer);
MarkLeft(t, HeldLock, edge.Id.Value, 0, step.Forward, t.Odometer);
var node = step.Forward ? edge.B : edge.A;
if (t.RouteIndex == t.Route.Count - 1)
{
Arrive(ctx, t, node);
return;
}
// stazione o deposito attraversati (punto sicuro intermedio): come all'arrivo, il treno è tutto
// dentro e l'arco d'arrivo si libera subito; il binario di stazione resta tenuto finché la coda
// non esce. Altrimenti un treno fermo in attesa del tratto successivo terrebbe il verso
// dell'arco da cui è arrivato e chi incrocia in stazione resterebbe bloccato.
var through = net.Nodes[node.Value];
if (through.Station.IsValid || through.Depot.IsValid)
{
if (through.Station.IsValid) MarkLeft(t, HeldPlatform, through.Station.Value, -1, true, t.Odometer);
for (int i = 0; i < t.Held.Count; i++)
{
var h = t.Held[i];
if (double.IsNaN(h.LeftAt) || (h.Kind == HeldPlatform && h.Id == through.Station.Value)) continue;
h.LeftAt -= t.LengthM;
t.Held[i] = h;
}
ReleaseBehind(net, t);
}
t.RouteIndex++;
t.StepPos = 0;
}
}
private static void MarkLeft(Train t, byte kind, int id, int index, bool forward, double odometer)
{
for (int i = 0; i < t.Held.Count; i++)
{
var h = t.Held[i];
if (h.Kind != kind || h.Id != id || !double.IsNaN(h.LeftAt)) continue;
if (kind == HeldBlock && (h.Index != index || h.Forward != forward)) continue;
if (kind == HeldLock && h.Forward != forward) continue;
h.LeftAt = odometer;
t.Held[i] = h;
return;
}
}
/// <summary>Libera le risorse superate dalla coda.</summary>
private static void ReleaseBehind(RailNetwork net, Train t)
{
for (int i = t.Held.Count - 1; i >= 0; i--)
{
var h = t.Held[i];
if (double.IsNaN(h.LeftAt) || t.Odometer - h.LeftAt < t.LengthM) continue;
Release(net, t, h);
t.Held.RemoveAt(i);
}
}
private static void Release(RailNetwork net, Train t, HeldResource h)
{
switch (h.Kind)
{
case HeldBlock:
{
var e = net.Edges[h.Id];
var blocks = h.Forward ? e.BlocksForward : e.BlocksBackward;
if (h.Index < blocks.Length && blocks[h.Index] == t.Id.Value) blocks[h.Index] = -1;
break;
}
case HeldLock:
{
var e = net.Edges[h.Id];
if (e.LockCount > 0) e.LockCount--;
if (e.LockCount == 0) e.LockDir = -1;
break;
}
default:
{
var s = net.Stations[h.Id];
for (int p = 0; p < s.PlatformTrain.Length; p++)
{
if (s.PlatformTrain[p] == t.Id.Value && (h.Index < 0 || h.Index == p)) s.PlatformTrain[p] = -1;
}
break;
}
}
}
/// <summary>Libera immediatamente tutto (treno rimosso o rientrato in deposito).</summary>
public static void ReleaseAll(RailNetwork net, Train t)
{
foreach (var h in t.Held) Release(net, t, h);
t.Held.Clear();
}
private void Arrive(WorldContext ctx, Train t, NodeId node)
{
var w = ctx.World;
var net = w.Network;
var n = net.Nodes[node.Value];
// in stazione e in deposito il treno è tutto dentro: le risorse dell'arco d'arrivo si liberano
for (int i = 0; i < t.Held.Count; i++)
{
var h = t.Held[i];
if (h.Kind == HeldPlatform && h.Id == n.Station.Value && n.Station.IsValid) continue;
if (double.IsNaN(h.LeftAt)) h.LeftAt = t.Odometer;
h.LeftAt -= t.LengthM;
t.Held[i] = h;
}
ReleaseBehind(net, t);
if (t.Route.Count > 0) t.ArrivedVia = t.Route[^1].Edge;
t.Route.Clear();
t.RouteIndex = 0;
t.StepPos = 0;
t.Speed = 0;
t.AtNode = node;
t.ReservedStep = -1;
t.ReservedBlock = -1;
if (n.Depot.IsValid && (t.GoingToDepot == n.Depot || (!t.Line.IsValid && t.HomeDepot == n.Depot)))
{
ReleaseAll(net, t);
t.State = TrainState.InDepot;
t.GoingToDepot = DepotId.None;
return;
}
if (n.Station.IsValid)
{
t.Platform = t.ArrivalPlatform;
t.ArrivalPlatform = -1;
if (node != TargetNode(w, t))
{
// sosta tecnica per invertire la marcia: niente carico né scarico
t.State = TrainState.Waiting;
TryPlanLeg(ctx, t);
return;
}
StationWork.Arrive(ctx, t, net.Stations[n.Station.Value]);
return;
}
// nodo qualunque (deposito di passaggio, binario morto): ripianifica
t.State = TrainState.Waiting;
TryPlanLeg(ctx, t);
}
// ------------------------------------------------------------------ prenotazioni
/// <summary>Distanza dalla testa alla fine dell'autorizzazione al movimento.</summary>
private static double MaDistance(RailNetwork net, Train t)
{
if (t.ReservedStep < t.RouteIndex) return 0;
double dist = 0;
for (int s = t.RouteIndex; s <= t.ReservedStep; s++)
{
var step = t.Route[s];
var e = net.Edges[step.Edge.Value];
double from = s == t.RouteIndex ? t.StepPos : 0;
double to = s == t.ReservedStep ? BlockEnd(e, step.Forward, t.ReservedBlock) : e.Length;
dist += Math.Max(0, to - from);
}
return dist;
}
private bool TryReserveNext(World w, Train t)
{
var net = w.Network;
if (t.ReservedStep >= 0)
{
var cur = t.Route[t.ReservedStep];
var ce = net.Edges[cur.Edge.Value];
if (t.ReservedBlock < LastBlock(ce))
{
// sezione successiva sullo stesso arco
var blocks = cur.Forward ? ce.BlocksForward : ce.BlocksBackward;
int next = t.ReservedBlock + 1;
if (blocks[next] >= 0 && blocks[next] != t.Id.Value) return false;
blocks[next] = t.Id.Value;
t.Held.Add(new HeldResource { Kind = HeldBlock, Id = ce.Id.Value, Index = next, Forward = cur.Forward, LeftAt = double.NaN });
t.ReservedBlock = next;
return true;
}
if (t.ReservedStep >= t.Route.Count - 1) return false; // tutto prenotato fino alla destinazione
}
int s = t.ReservedStep + 1;
return EnterStep(w, t, s);
}
// prenota la prima sezione del passo s; su binario semplice blocca il verso fino a un punto sicuro
private bool EnterStep(World w, Train t, int s)
{
var net = w.Network;
var step = t.Route[s];
var edge = net.Edges[step.Edge.Value];
if (!edge.IsUsable) return false;
var blocks = step.Forward ? edge.BlocksForward : edge.BlocksBackward;
if (blocks[0] >= 0 && blocks[0] != t.Id.Value) return false;
int dir = step.Forward ? 0 : 1;
// catena di archi a binario semplice da bloccare insieme
int last = s;
if (!edge.DoubleTrack)
{
while (last < t.Route.Count - 1 && !IsSafePoint(net, t, last))
{
var ne = net.Edges[t.Route[last + 1].Edge.Value];
if (ne.DoubleTrack) break;
last++;
}
}
// verifica tutto prima di prenotare
for (int k = s; k <= last; k++)
{
var e = net.Edges[t.Route[k].Edge.Value];
if (e.DoubleTrack || HoldsLock(t, e.Id.Value)) continue;
int d = t.Route[k].Forward ? 0 : 1;
if (!e.IsUsable || (e.LockDir >= 0 && e.LockDir != d)) return false;
}
int platform = -1;
StationId platformStation = StationId.None;
var endNode = net.Nodes[(t.Route[last].Forward ? net.Edges[t.Route[last].Edge.Value].B : net.Edges[t.Route[last].Edge.Value].A).Value];
bool chainNeedsPlatform = endNode.Station.IsValid && (last == t.Route.Count - 1 || !edge.DoubleTrack);
if (chainNeedsPlatform && !HoldsPlatform(t, endNode.Station.Value))
{
var st = net.Stations[endNode.Station.Value];
platform = Array.IndexOf(st.PlatformTrain, -1);
if (platform < 0) return false;
platformStation = st.Id;
}
// prenota
for (int k = s; k <= last; k++)
{
var e = net.Edges[t.Route[k].Edge.Value];
if (e.DoubleTrack || HoldsLock(t, e.Id.Value)) continue;
int d = t.Route[k].Forward ? 0 : 1;
e.LockDir = d;
e.LockCount++;
t.Held.Add(new HeldResource { Kind = HeldLock, Id = e.Id.Value, Forward = t.Route[k].Forward, LeftAt = double.NaN });
}
blocks[0] = t.Id.Value;
t.Held.Add(new HeldResource { Kind = HeldBlock, Id = edge.Id.Value, Index = 0, Forward = step.Forward, LeftAt = double.NaN });
if (platformStation.IsValid)
{
var st = net.Stations[platformStation.Value];
st.PlatformTrain[platform] = t.Id.Value;
t.Held.Add(new HeldResource { Kind = HeldPlatform, Id = st.Id.Value, Index = platform, Forward = true, LeftAt = double.NaN });
if (last == t.Route.Count - 1) t.ArrivalPlatform = platform;
}
t.ReservedStep = s;
t.ReservedBlock = 0;
_ = dir;
return true;
}
// punto sicuro alla fine del passo k: stazione o deposito, destinazione, o arco successivo a doppio binario
private static bool IsSafePoint(RailNetwork net, Train t, int k)
{
if (k >= t.Route.Count - 1) return true;
var e = net.Edges[t.Route[k].Edge.Value];
var node = net.Nodes[(t.Route[k].Forward ? e.B : e.A).Value];
if (node.Station.IsValid || node.Depot.IsValid) return true;
return net.Edges[t.Route[k + 1].Edge.Value].DoubleTrack;
}
private static bool HoldsLock(Train t, int edge)
{
foreach (var h in t.Held)
{
if (h.Kind == HeldLock && h.Id == edge && double.IsNaN(h.LeftAt)) return true;
}
return false;
}
private static bool HoldsPlatform(Train t, int station)
{
foreach (var h in t.Held)
{
if (h.Kind == HeldPlatform && h.Id == station && double.IsNaN(h.LeftAt)) return true;
}
return false;
}
// ------------------------------------------------------------------ geometria dei blocchi
/// <summary>Indice dell'ultima sezione di blocco dell'arco.</summary>
public static int LastBlock(TrackEdge e) => e.Signals.Count;
/// <summary>Fine (progressiva nel verso di marcia) della sezione j.</summary>
public static double BlockEnd(TrackEdge e, bool forward, int j)
{
int n = e.Signals.Count;
if (j >= n) return e.Length;
return forward ? e.Signals[j] : e.Length - e.Signals[n - 1 - j];
}
/// <summary>Sezione che contiene la progressiva pos (nel verso di marcia).</summary>
public static int BlockOf(TrackEdge e, bool forward, double pos)
{
int j = 0;
while (j < e.Signals.Count && pos >= BlockEnd(e, forward, j)) j++;
return j;
}
// ------------------------------------------------------------------ limiti e anticipo
private static double LimitAt(TrackEdge e, bool forward, double pos)
{
double s = forward ? pos : e.Length - pos;
return e.SpeedLimitKmh[e.SampleIndex(s)];
}
// velocità massima compatibile con i limiti più bassi entro la distanza di osservazione
private double LookaheadCap(World w, Train t, double horizon)
{
var net = w.Network;
double cap = double.MaxValue;
double dist = 0;
for (int s = t.RouteIndex; s < t.Route.Count && dist < horizon; s++)
{
var step = t.Route[s];
var e = net.Edges[step.Edge.Value];
double cond = ConstructionSystem.ConditionFactor(w, e) * w.WorldEvents.EdgeSpeed(e);
double start = s == t.RouteIndex ? t.StepPos : 0;
int n = e.S.Length;
if (step.Forward)
{
for (int i = e.SampleIndex(start) + 1; i < n - 1; i++)
{
double d = dist + e.S[i] - start;
if (d > horizon) break;
double vl = Math.Min(t.TopSpeedKmh, e.SpeedLimitKmh[i] * cond) / 3.6;
cap = Math.Min(cap, Math.Sqrt(vl * vl + 2 * _brake * Math.Max(0, d)));
}
}
else
{
double sGeo = e.Length - start;
for (int i = e.SampleIndex(sGeo); i > 0; i--)
{
double d = dist + (sGeo - e.S[i]);
if (d > horizon) break;
double vl = Math.Min(t.TopSpeedKmh, e.SpeedLimitKmh[i - 1] * cond) / 3.6;
cap = Math.Min(cap, Math.Sqrt(vl * vl + 2 * _brake * Math.Max(0, d)));
}
}
dist += e.Length - start;
}
// fermata a fine percorso
if (dist < horizon) cap = Math.Min(cap, Math.Sqrt(2 * _brake * Math.Max(0, dist)));
return cap;
}
private static double CargoMassT(World w, Train t)
{
double m = 0;
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
m += v.Load + v.Pax * w.Data.Construction.Physics.PassengerMassT;
}
return m;
}
}