Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
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:
1 parent
f6c2a17b4d
commit
c1a0049bcf
300 files changed
+1602
-1045
No files matched your search
@@ -0,0 +1,640 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Manutenzione della flotta (guida, sezione 10), una volta al giorno:
|
||||
/// - usura per componente dai km di servizio del giorno, con pendenza, alta velocità, carico, età e difficoltà;
|
||||
/// - rischio di guasto del componente più esposto: lieve (velocità dimezzata fino al deposito), grave
|
||||
/// (fermo in linea fino al soccorso), deragliamento (veicoli da ricostruire, binario chiuso, carico perso);
|
||||
/// - pianificatore predittivo: scadenze della politica e stima del giorno in cui un componente scende
|
||||
/// alla soglia; prenota il deposito con viaggio + attesa minimi tra quelli con ricambi sufficienti;
|
||||
/// - officine: stalli in ordine d'arrivo, ricambi prelevati all'inizio, durata allungata se manca il
|
||||
/// personale, treni di riserva sulle linee durante gli interventi lunghi;
|
||||
/// - avvisi sotto le soglie e quando un deposito resta senza ricambi.
|
||||
/// </summary>
|
||||
public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Maintenance";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
w.Alerts.Clear();
|
||||
RepairTrack(w, ctx.Day);
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (!t.Removed) Daily(ctx, t);
|
||||
}
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (w.Network.IsAlive(d)) Workshop(ctx, d);
|
||||
}
|
||||
if (ctx.IsNewYear && ctx.Day > 0) RollYear(w);
|
||||
}
|
||||
|
||||
private static void RepairTrack(World w, long day)
|
||||
{
|
||||
foreach (var e in w.Network.Edges)
|
||||
{
|
||||
if (e.DamagedUntilDay >= 0 && day >= e.DamagedUntilDay) e.DamagedUntilDay = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ giornata di un treno
|
||||
|
||||
private static void Daily(WorldContext ctx, Train t)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
double km = t.DayKm * m.Wear.DistanceScale;
|
||||
double grade = 0, fast = 0, load = 0;
|
||||
if (t.DayKm > 0)
|
||||
{
|
||||
grade = t.DayGradeKm / t.DayKm;
|
||||
fast = t.DayFastKm / t.DayKm;
|
||||
load = Math.Clamp(t.DayLoadKm / t.DayKm, 0, 1);
|
||||
}
|
||||
foreach (var id in t.Vehicles) Wear(w, w.Vehicles[id.Value], km, grade, fast, load);
|
||||
t.ServiceKmPerDay = Ema.Step(t.ServiceKmPerDay, km, m.Planner.AverageDays);
|
||||
bool ran = t.DayKm > 0;
|
||||
t.DayKm = t.DayGradeKm = t.DayFastKm = t.DayLoadKm = 0;
|
||||
if (t.Vehicles.Count == 0) return;
|
||||
|
||||
if (ran && !t.InWorkshop && t.State != TrainState.Broken) CheckFailure(ctx, t);
|
||||
UpdateSpeed(w, t);
|
||||
if (t.State == TrainState.InDepot && !t.InWorkshop && t.MaintenanceDepot.IsValid && t.PlannedIntervention >= 0
|
||||
&& w.Network.Depots[t.MaintenanceDepot.Value].Node == t.AtNode)
|
||||
Enqueue(w, t, w.Network.Depots[t.MaintenanceDepot.Value]);
|
||||
else
|
||||
Plan(ctx, t);
|
||||
Alert(ctx, t);
|
||||
}
|
||||
|
||||
private static void Wear(World w, Vehicle v, double km, double grade, double fast, double load)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
var comps = Fleet.ComponentsOf(w.Data, v.Def);
|
||||
if (v.WearEma.Length != v.Components.Length) v.WearEma = new double[v.Components.Length];
|
||||
double age = km > 0 ? Fleet.AgeFactor(w, v) : 1;
|
||||
for (int j = 0; j < v.Components.Length && j < comps.Count; j++)
|
||||
{
|
||||
double wear = 0;
|
||||
if (km > 0)
|
||||
{
|
||||
double basePer100 = comps[j].WearPer100Km * v.Def.Components.GetValueOrDefault(comps[j].Id, 1.0);
|
||||
wear = Fleet.DailyWear(basePer100, km, grade, fast, load, age, w.Difficulty.WearMultiplier, m.Wear);
|
||||
v.Components[j] = Math.Max(0, v.Components[j] - wear);
|
||||
}
|
||||
v.WearEma[j] = Ema.Step(v.WearEma[j], wear, m.Planner.AverageDays);
|
||||
}
|
||||
v.OdometerKm += km;
|
||||
}
|
||||
|
||||
/// <summary>Velocità massima ridotta dal motore usurato e dal guasto lieve; tetto del rimorchio.</summary>
|
||||
public static void UpdateSpeed(World w, Train t)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
double f = 1;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
if (v.Def.Kind != VehicleKind.Locomotive) continue;
|
||||
int engine = Fleet.ComponentIndex(Fleet.ComponentsOf(w.Data, v.Def), Fleet.Engine);
|
||||
if (engine < 0) continue;
|
||||
double c = v.Components[engine];
|
||||
if (c < m.Effects.EngineSpeedBelow) f = Math.Min(f, m.Effects.EngineSpeedBase + m.Effects.EngineSpeedSpan * c / 100);
|
||||
}
|
||||
if (t.Failure == FailureKind.Minor) f *= m.Failure.MinorSpeedFactor;
|
||||
t.SpeedFactor = f;
|
||||
t.SpeedCapKmh = t.Towed ? m.Failure.RescueSpeedKmh : double.PositiveInfinity;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ guasti e soccorso
|
||||
|
||||
private static void CheckFailure(WorldContext ctx, Train t)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
double best = -1;
|
||||
Vehicle? bv = null;
|
||||
int bc = -1;
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
for (int j = 0; j < v.Components.Length; j++)
|
||||
{
|
||||
double h = Fleet.Hazard(v.Components[j], m.Failure);
|
||||
if (ctx.Day < v.HazardReducedUntilDay) h *= m.Inspection.HazardFactor;
|
||||
if (h <= best) continue;
|
||||
best = h;
|
||||
bv = v;
|
||||
bc = j;
|
||||
}
|
||||
}
|
||||
if (bv is null) return;
|
||||
var rng = w.Stream("fleet");
|
||||
if (rng.NextDouble() >= best) return;
|
||||
double u = rng.NextDouble();
|
||||
var f = m.Failure;
|
||||
var kind = u < f.MinorShare ? FailureKind.Minor : u < f.MinorShare + f.MajorShare ? FailureKind.Major : FailureKind.Catastrophic;
|
||||
bool fast = t.IsRunning && !t.AtNode.IsValid && t.Speed * 3.6 > f.CatastrophicMinSpeedShare * t.MaxSpeedKmh;
|
||||
if (kind == FailureKind.Catastrophic && !(bv.Components[bc] < f.CatastrophicMaxCondition && fast)) kind = FailureKind.Major;
|
||||
Fail(ctx, t, kind, bv, bc);
|
||||
}
|
||||
|
||||
/// <summary>Applica un guasto al treno (usato anche dai test).</summary>
|
||||
public static void Fail(WorldContext ctx, Train t, FailureKind kind, Vehicle v, int component)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var f = w.Data.Maintenance.Failure;
|
||||
t.FailuresThisYear++;
|
||||
t.FailuresTotal++;
|
||||
string comp = Fleet.ComponentsOf(w.Data, v.Def)[component].NameIt.ToLowerInvariant();
|
||||
if (!t.InWorkshop) CancelBooking(t);
|
||||
if (kind == FailureKind.Minor)
|
||||
{
|
||||
if (t.Failure == FailureKind.None)
|
||||
{
|
||||
t.Failure = FailureKind.Minor;
|
||||
t.FailedVehicle = v.Id;
|
||||
t.FailedComponent = component;
|
||||
}
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Warning,
|
||||
$"{t.Name}: guasto lieve ({comp}), velocità dimezzata fino al deposito", EntityKind.Train, t.Id.Value, t.Owner));
|
||||
UpdateSpeed(w, t);
|
||||
return;
|
||||
}
|
||||
|
||||
t.Failure = kind;
|
||||
t.FailedVehicle = v.Id;
|
||||
t.FailedComponent = component;
|
||||
if (t.State == TrainState.InDepot || t.InWorkshop)
|
||||
{
|
||||
// scoperto in deposito: si ripara lì
|
||||
if (!t.InWorkshop && t.AtNode.IsValid && w.Network.Nodes[t.AtNode.Value].Depot is { IsValid: true } here)
|
||||
{
|
||||
t.MaintenanceDepot = here;
|
||||
t.PlannedIntervention = RepairIndex(w, kind);
|
||||
}
|
||||
return;
|
||||
}
|
||||
t.StateBeforeFailure = t.State;
|
||||
t.State = TrainState.Broken;
|
||||
t.Speed = 0;
|
||||
double hours = RescueHours(w, t);
|
||||
t.RescueTick = ctx.Tick + (long)Math.Ceiling(hours * 3600 / w.Calendar.TrainSecondsPerTick);
|
||||
if (kind == FailureKind.Catastrophic)
|
||||
{
|
||||
Derail(ctx, t);
|
||||
return;
|
||||
}
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Critical,
|
||||
$"{t.Name}: guasto grave ({comp}), fermo in linea; soccorso tra {hours:F1} ore", EntityKind.Train, t.Id.Value, t.Owner));
|
||||
}
|
||||
|
||||
private static int RepairIndex(World w, FailureKind kind) => w.Data.Maintenance.InterventionIndex(kind switch
|
||||
{
|
||||
FailureKind.Minor => "repair_minor",
|
||||
FailureKind.Major => "repair_major",
|
||||
_ => "repair_catastrophic",
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Ore (orologio dei treni) per l'arrivo del soccorso: squadra dal deposito più vicino a 40 km/h
|
||||
/// più 2 ore di preparazione, oppure una locomotiva di riserva già pronta, se arriva prima.
|
||||
/// </summary>
|
||||
public static double RescueHours(World w, Train t)
|
||||
{
|
||||
var f = w.Data.Maintenance.Failure;
|
||||
var pos = Fleet.Position(w, t);
|
||||
double best = double.MaxValue;
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (d.Owner != t.Owner || !w.Network.IsAlive(d)) continue;
|
||||
best = Math.Min(best, Vec2.Distance(d.Position, pos) / 1000 / f.RescueSpeedKmh + f.RescueExtraHours);
|
||||
}
|
||||
foreach (var r in w.Trains)
|
||||
{
|
||||
if (!IsFreeReserve(t.Owner, r)) continue;
|
||||
best = Math.Min(best, Vec2.Distance(Fleet.Position(w, r), pos) / 1000 / Math.Max(1, r.MaxSpeedKmh));
|
||||
}
|
||||
return best == double.MaxValue ? f.RescueExtraHours : best;
|
||||
}
|
||||
|
||||
private static bool IsFreeReserve(CompanyId owner, Train r) =>
|
||||
!r.Removed && r.Owner == owner && r.Reserve && r.State == TrainState.InDepot && !r.InWorkshop
|
||||
&& !r.Covering.IsValid && !r.Line.IsValid && r.Locomotives > 0 && r.Failure == FailureKind.None && !r.MaintenanceDepot.IsValid;
|
||||
|
||||
// deragliamento: carico perso, binario danneggiato, notizia negativa e insoddisfazione lungo la linea
|
||||
private static void Derail(WorldContext ctx, Train t)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var f = w.Data.Maintenance.Failure;
|
||||
var net = w.Network;
|
||||
foreach (var p in t.Cargo)
|
||||
{
|
||||
if (p.Kind != PacketKind.Freight) continue;
|
||||
w.Goods.Decayed[p.Good] += p.Units;
|
||||
if (!p.AwaitingConsumer && p.Destination.IsValid)
|
||||
{
|
||||
var dest = net.Stations[p.Destination.Value];
|
||||
dest.Incoming[p.Good] = Math.Max(0, dest.Incoming[p.Good] - p.Units);
|
||||
}
|
||||
}
|
||||
t.Cargo.Clear();
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
v.Load = 0;
|
||||
v.Good = -1;
|
||||
v.Pax = 0;
|
||||
}
|
||||
if (!t.AtNode.IsValid && t.RouteIndex < t.Route.Count)
|
||||
net.Edges[t.Route[t.RouteIndex].Edge.Value].DamagedUntilDay = ctx.Day + f.DerailmentTrackDays;
|
||||
if (t.Line.IsValid)
|
||||
{
|
||||
var touched = new List<int>();
|
||||
foreach (var stop in w.Lines[t.Line.Value].Stops)
|
||||
{
|
||||
foreach (var town in net.Stations[stop.Station.Value].Towns)
|
||||
{
|
||||
if (touched.Contains(town.Value)) continue;
|
||||
touched.Add(town.Value);
|
||||
var tw = w.Towns[town.Value];
|
||||
tw.WorkDissatisfaction = Math.Min(1, tw.WorkDissatisfaction + f.DerailmentSatisfaction);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Critical,
|
||||
$"Deragliamento di {t.Name}: carico perso, veicoli da ricostruire, binario chiuso per {f.DerailmentTrackDays} giorni",
|
||||
EntityKind.Train, t.Id.Value, t.Owner));
|
||||
}
|
||||
|
||||
/// <summary>Il soccorso è arrivato: il treno viene rimorchiato verso un deposito per la riparazione.</summary>
|
||||
public static void OnRescued(WorldContext ctx, Train t)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
t.RescueTick = -1;
|
||||
t.Towed = true;
|
||||
UpdateSpeed(w, t);
|
||||
int repair = RepairIndex(w, t.Failure == FailureKind.Catastrophic ? FailureKind.Catastrophic : FailureKind.Major);
|
||||
int parts = Fleet.PartsFor(w, t, m.Interventions[repair]);
|
||||
var depot = BestDepot(w, t, parts, requireParts: true) ?? BestDepot(w, t, 0, requireParts: false);
|
||||
if (depot is not null)
|
||||
{
|
||||
t.MaintenanceDepot = depot.Id;
|
||||
t.PlannedIntervention = repair;
|
||||
}
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
|
||||
depot is null ? $"Soccorso arrivato: {t.Name} senza un deposito raggiungibile" : $"Soccorso arrivato: {t.Name} rimorchiato verso {depot.Name}",
|
||||
EntityKind.Train, t.Id.Value, t.Owner));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ pianificatore
|
||||
|
||||
private static void Plan(WorldContext ctx, Train t)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
if (t.InWorkshop || t.State == TrainState.Broken) return;
|
||||
if (t.MaintenanceDepot.IsValid)
|
||||
{
|
||||
if (w.Network.IsAlive(w.Network.Depots[t.MaintenanceDepot.Value])) return;
|
||||
CancelBooking(t);
|
||||
}
|
||||
if (t.Failure != FailureKind.None)
|
||||
{
|
||||
int repair = RepairIndex(w, t.Failure);
|
||||
int parts = Fleet.PartsFor(w, t, m.Interventions[repair]);
|
||||
if (Book(ctx, t, repair, parts, requireParts: true)) return;
|
||||
if (t.Failure != FailureKind.Minor)
|
||||
{
|
||||
Book(ctx, t, repair, parts, requireParts: false);
|
||||
return;
|
||||
}
|
||||
// guasto lieve senza ricambi in nessun deposito: il treno resta in servizio a velocità ridotta
|
||||
}
|
||||
if (!t.Line.IsValid) return;
|
||||
var next = Fleet.Next(w, t);
|
||||
if (next.Intervention < 0 || next.Days > 0) return;
|
||||
var def = m.Interventions[next.Intervention];
|
||||
if (Book(ctx, t, next.Intervention, Fleet.PartsFor(w, t, def), requireParts: true)) return;
|
||||
// senza ricambi per tagliando o revisione: almeno l'ispezione prevista dalla politica, che non ne richiede
|
||||
if (def.Effect != InterventionEffect.Inspection && Fleet.Dues(w, t).Inspection <= 0)
|
||||
Book(ctx, t, m.InterventionIndex("inspection"), 0, requireParts: true);
|
||||
}
|
||||
|
||||
/// <summary>Prenota l'intervento nel deposito migliore; se il treno è già lì entra subito in officina.</summary>
|
||||
public static bool Book(WorldContext ctx, Train t, int intervention, int parts, bool requireParts)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var depot = BestDepot(w, t, parts, requireParts);
|
||||
if (depot is null) return false;
|
||||
t.MaintenanceDepot = depot.Id;
|
||||
t.PlannedIntervention = intervention;
|
||||
if (t.State == TrainState.InDepot && t.AtNode == depot.Node) Enqueue(w, t, depot);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void CancelBooking(Train t)
|
||||
{
|
||||
if (t.GoingToDepot == t.MaintenanceDepot) t.GoingToDepot = DepotId.None;
|
||||
t.MaintenanceDepot = DepotId.None;
|
||||
t.PlannedIntervention = -1;
|
||||
}
|
||||
|
||||
// buffer di lavoro della scelta del deposito (solo appoggio, mai stato: un mondo per thread)
|
||||
[ThreadStatic] private static List<(double Score, Depot Depot)>? _candidates;
|
||||
[ThreadStatic] private static List<RouteStep>? _scratchRoute;
|
||||
[ThreadStatic] private static double[]? _backlog;
|
||||
[ThreadStatic] private static int[]? _reserved;
|
||||
|
||||
/// <summary>
|
||||
/// Deposito con viaggio + attesa stimati minimi, raggiungibile sulla rete della compagnia e,
|
||||
/// se richiesto, con ricambi disponibili (scorta meno quelli già destinati ad altri lavori).
|
||||
/// </summary>
|
||||
public static Depot? BestDepot(World w, Train t, int parts, bool requireParts)
|
||||
{
|
||||
var net = w.Network;
|
||||
var pos = Fleet.Position(w, t);
|
||||
double speed = Math.Max(1, t.TopSpeedKmh);
|
||||
int n = net.Depots.Count;
|
||||
if (_backlog is null || _backlog.Length < n)
|
||||
{
|
||||
_backlog = new double[Math.Max(n, 16)];
|
||||
_reserved = new int[_backlog.Length];
|
||||
}
|
||||
DepotLoads(w, t, _backlog, _reserved!);
|
||||
var candidates = _candidates ??= [];
|
||||
candidates.Clear();
|
||||
foreach (var d in net.Depots)
|
||||
{
|
||||
if (d.Owner != t.Owner || !net.IsAlive(d)) continue;
|
||||
if (requireParts && parts > 0 && d.SpareParts - _reserved![d.Id.Value] < parts) continue;
|
||||
double travel = w.Calendar.TrainMinutesToDays(Vec2.Distance(pos, d.Position) / 1000 / speed * 60);
|
||||
double wait = _backlog[d.Id.Value] / Math.Max(1, d.Stalls);
|
||||
candidates.Add((travel + wait, d));
|
||||
}
|
||||
candidates.Sort((a, b) => a.Score != b.Score ? a.Score.CompareTo(b.Score) : a.Depot.Id.Value.CompareTo(b.Depot.Id.Value));
|
||||
var from = ReferenceNode(w, t);
|
||||
var scratch = _scratchRoute ??= [];
|
||||
foreach (var (_, d) in candidates)
|
||||
{
|
||||
if (!from.IsValid || from == d.Node) return d;
|
||||
if (w.Pathfinder.FindPath(net, t.Owner, from, EdgeId.None, d.Node, t.MaxSpeedKmh, t.NeedsElectrification,
|
||||
w.Data.Construction.Operations.MaxTurnDeg, scratch))
|
||||
return d;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giorni di lavoro in coda e ricambi già destinati, per deposito (indice = id): lavori presenti
|
||||
/// nelle officine e treni prenotati non ancora arrivati, escluso <paramref name="except"/>.
|
||||
/// </summary>
|
||||
public static void DepotLoads(World w, Train? except, double[] backlog, int[] reserved)
|
||||
{
|
||||
var net = w.Network;
|
||||
var m = w.Data.Maintenance;
|
||||
Array.Clear(backlog, 0, net.Depots.Count);
|
||||
Array.Clear(reserved, 0, net.Depots.Count);
|
||||
foreach (var d in net.Depots)
|
||||
{
|
||||
foreach (var j in d.Jobs)
|
||||
{
|
||||
backlog[d.Id.Value] += Math.Max(0, j.Days - j.Progress);
|
||||
if (!j.Started) reserved[d.Id.Value] += j.Parts;
|
||||
}
|
||||
}
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (t == except || t.Removed || t.InWorkshop || !t.MaintenanceDepot.IsValid || t.PlannedIntervention < 0) continue;
|
||||
var def = m.Interventions[t.PlannedIntervention];
|
||||
backlog[t.MaintenanceDepot.Value] += def.Days;
|
||||
reserved[t.MaintenanceDepot.Value] += Fleet.PartsFor(w, t, def);
|
||||
}
|
||||
}
|
||||
|
||||
// nodo da cui il treno partirà per il deposito: quello in cui si trova o la fine del percorso in corso
|
||||
private static NodeId ReferenceNode(World w, Train t)
|
||||
{
|
||||
if (t.AtNode.IsValid) return t.AtNode;
|
||||
if (t.Route.Count == 0) return NodeId.None;
|
||||
var last = t.Route[^1];
|
||||
var e = w.Network.Edges[last.Edge.Value];
|
||||
return last.Forward ? e.B : e.A;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ officina
|
||||
|
||||
private static void Enqueue(World w, Train t, Depot d)
|
||||
{
|
||||
var def = w.Data.Maintenance.Interventions[t.PlannedIntervention];
|
||||
d.Jobs.Add(new WorkshopJob
|
||||
{
|
||||
Train = t.Id,
|
||||
Intervention = t.PlannedIntervention,
|
||||
QueuedDay = w.Clock.Day,
|
||||
Days = def.Days,
|
||||
Parts = Fleet.PartsFor(w, t, def),
|
||||
});
|
||||
t.InWorkshop = true;
|
||||
t.GoingToDepot = DepotId.None;
|
||||
}
|
||||
|
||||
/// <summary>Fattore di velocità del lavoro: 1 a personale completo, 1/2 a metà personale, 1/3 senza.</summary>
|
||||
public static double WorkRate(World w, Depot d)
|
||||
{
|
||||
double slow = w.Data.Maintenance.Depots.SlowdownAtHalfStaff;
|
||||
return 1 / (1 + (slow - 1) * (1 - d.StaffRatio) / 0.5);
|
||||
}
|
||||
|
||||
private static void Workshop(WorldContext ctx, Depot d)
|
||||
{
|
||||
var w = ctx.World;
|
||||
double rate = WorkRate(w, d);
|
||||
int inStall = 0;
|
||||
foreach (var j in d.Jobs)
|
||||
{
|
||||
if (j.InStall) inStall++;
|
||||
}
|
||||
bool waitingParts = false;
|
||||
for (int i = 0; i < d.Jobs.Count; i++)
|
||||
{
|
||||
var job = d.Jobs[i];
|
||||
var t = w.Trains[job.Train.Value];
|
||||
if (t.Removed || !t.InWorkshop)
|
||||
{
|
||||
if (job.InStall) inStall--;
|
||||
d.Jobs.RemoveAt(i--);
|
||||
continue;
|
||||
}
|
||||
if (!job.InStall)
|
||||
{
|
||||
if (inStall >= d.Stalls) continue;
|
||||
job.InStall = true;
|
||||
inStall++;
|
||||
}
|
||||
if (!job.Started)
|
||||
{
|
||||
// l'intervento aspetta i ricambi occupando lo stallo
|
||||
if (d.SpareParts < job.Parts)
|
||||
{
|
||||
waitingParts = true;
|
||||
continue;
|
||||
}
|
||||
Start(ctx, d, job, t, rate);
|
||||
}
|
||||
job.Progress += rate;
|
||||
if (job.Progress + 1e-9 < job.Days) continue;
|
||||
Complete(ctx, d, job, t);
|
||||
d.Jobs.RemoveAt(i--);
|
||||
inStall--;
|
||||
}
|
||||
if (waitingParts && !d.PartsAlerted)
|
||||
{
|
||||
d.PartsAlerted = true;
|
||||
string text = $"{d.Name}: ricambi esauriti, interventi in attesa";
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Warning, text, EntityKind.Depot, d.Id.Value, d.Owner));
|
||||
w.Alerts.Add(new FleetAlert(d.Owner, TrainId.None, d.Id, "spare_parts", d.SpareParts, 0, text));
|
||||
}
|
||||
else if (!waitingParts) d.PartsAlerted = false;
|
||||
}
|
||||
|
||||
private static void Start(WorldContext ctx, Depot d, WorkshopJob job, Train t, double rate)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
var def = m.Interventions[job.Intervention];
|
||||
d.SpareParts -= job.Parts;
|
||||
w.Goods.Consumed[w.Data.SparePartsGood] += job.Parts;
|
||||
var cost = Fleet.CostOf(w, t, def, Fleet.PolicyOf(w, t));
|
||||
if (cost.IsPositive) w.Money.Transfer(Account.Of(t.Owner), Account.External, cost, LedgerEntry.FleetMaintenance);
|
||||
job.CostCents = cost.Cents;
|
||||
job.Started = true;
|
||||
t.MaintenanceThisYear += cost.Cents;
|
||||
if (job.Days / rate >= m.Planner.ReserveMinDays) Cover(ctx, t, d);
|
||||
}
|
||||
|
||||
private static void Complete(WorldContext ctx, Depot d, WorkshopJob job, Train t)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
var def = m.Interventions[job.Intervention];
|
||||
Fleet.Apply(w, t, def, Fleet.PolicyOf(w, t));
|
||||
bool repair = def.Effect is InterventionEffect.Repair or InterventionEffect.Replace;
|
||||
if (def.Effect != InterventionEffect.Inspection)
|
||||
{
|
||||
t.Failure = FailureKind.None;
|
||||
t.FailedVehicle = VehicleId.None;
|
||||
t.FailedComponent = -1;
|
||||
}
|
||||
t.History.Add(new MaintenanceRecord(ctx.Day, job.Intervention, job.CostCents, d.Id, job.Parts));
|
||||
while (t.History.Count > m.Planner.HistoryLength) t.History.RemoveAt(0);
|
||||
t.InWorkshop = false;
|
||||
t.MaintenanceDepot = DepotId.None;
|
||||
t.PlannedIntervention = -1;
|
||||
t.AlertLevel = AlertLevelOf(w, Fleet.TrainCondition(w, t));
|
||||
t.Towed = false;
|
||||
UpdateSpeed(w, t);
|
||||
if (t.CoveredBy.IsValid) Uncover(w, t);
|
||||
if (repair)
|
||||
{
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
|
||||
$"{t.Name}: {def.NameIt.ToLowerInvariant()} completata a {d.Name}", EntityKind.Train, t.Id.Value, t.Owner));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ riserve
|
||||
|
||||
private static void Cover(WorldContext ctx, Train t, Depot d)
|
||||
{
|
||||
var w = ctx.World;
|
||||
if (!t.Line.IsValid || t.CoveredBy.IsValid) return;
|
||||
Train? best = null;
|
||||
double bestDist = double.MaxValue;
|
||||
foreach (var r in w.Trains)
|
||||
{
|
||||
if (!IsFreeReserve(t.Owner, r)) continue;
|
||||
double dist = Vec2.Distance(Fleet.Position(w, r), d.Position);
|
||||
if (dist >= bestDist) continue;
|
||||
bestDist = dist;
|
||||
best = r;
|
||||
}
|
||||
if (best is null) return;
|
||||
best.Line = t.Line;
|
||||
best.StopIndex = t.StopIndex;
|
||||
best.Covering = t.Id;
|
||||
best.GoingToDepot = DepotId.None;
|
||||
t.CoveredBy = best.Id;
|
||||
w.LineGraphs.Touch();
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
|
||||
$"{best.Name} (riserva) copre {w.Lines[t.Line.Value].Name} durante l'intervento di {t.Name}", EntityKind.Train, best.Id.Value, t.Owner));
|
||||
}
|
||||
|
||||
/// <summary>Fine della copertura: la riserva lascia la linea e rientra al suo deposito.</summary>
|
||||
public static void Uncover(World w, Train t)
|
||||
{
|
||||
var r = w.Trains[t.CoveredBy.Value];
|
||||
t.CoveredBy = TrainId.None;
|
||||
if (r.Covering != t.Id) return;
|
||||
r.Covering = TrainId.None;
|
||||
r.Line = LineId.None;
|
||||
if (r.HomeDepot.IsValid && w.Network.IsAlive(w.Network.Depots[r.HomeDepot.Value]) && w.Network.Depots[r.HomeDepot.Value].Node != r.AtNode)
|
||||
r.GoingToDepot = r.HomeDepot;
|
||||
if (r.State == TrainState.NoRoute) r.State = TrainState.Waiting;
|
||||
w.LineGraphs.Touch();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ avvisi e anno
|
||||
|
||||
private static void Alert(WorldContext ctx, Train t)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var m = w.Data.Maintenance;
|
||||
var (v, comp, c) = Fleet.Weakest(w, t);
|
||||
if (v is null) return;
|
||||
int level = AlertLevelOf(w, c);
|
||||
// l'avviso si riarma solo dopo un intervento che riporta il treno sopra la soglia
|
||||
if (level <= t.AlertLevel) return;
|
||||
t.AlertLevel = level;
|
||||
var def = Fleet.ComponentsOf(w.Data, v.Def)[comp];
|
||||
var next = Fleet.Next(w, t);
|
||||
string plan;
|
||||
if (t.MaintenanceDepot.IsValid && t.PlannedIntervention >= 0)
|
||||
plan = $"{m.Interventions[t.PlannedIntervention].NameIt.ToLowerInvariant()} prenotata a {w.Network.Depots[t.MaintenanceDepot.Value].Name}";
|
||||
else if (next.Days > 0)
|
||||
plan = $"{m.Interventions[next.Intervention].NameIt.ToLowerInvariant()} entro {Math.Ceiling(next.Days):F0} giorni";
|
||||
else
|
||||
plan = "nessun deposito con ricambi disponibili";
|
||||
string text = $"{t.Name}: {def.NameIt.ToLowerInvariant()} al {c:F0} %, {plan}";
|
||||
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, level == 2 ? EventSeverity.Critical : EventSeverity.Warning,
|
||||
text, EntityKind.Train, t.Id.Value, t.Owner));
|
||||
w.Alerts.Add(new FleetAlert(t.Owner, t.Id, t.MaintenanceDepot, def.Id, c, (int)Math.Ceiling(Math.Max(0, next.Days)), text));
|
||||
}
|
||||
|
||||
private static int AlertLevelOf(World w, double condition)
|
||||
{
|
||||
var p = w.Data.Maintenance.Planner;
|
||||
return condition < p.CriticalCondition ? 2 : condition < p.AlertCondition ? 1 : 0;
|
||||
}
|
||||
|
||||
private static void RollYear(World w)
|
||||
{
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
t.MaintenanceLastYear = t.MaintenanceThisYear;
|
||||
t.MaintenanceThisYear = 0;
|
||||
t.FailuresThisYear = 0;
|
||||
t.RevenueLastYear = t.RevenueThisYear;
|
||||
t.RevenueThisYear = 0;
|
||||
t.KmThisYear = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user