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>
342 lines
18 KiB
C#
342 lines
18 KiB
C#
using RailEnterprise.Core.Commands;
|
|
using RailEnterprise.Core.Common;
|
|
using RailEnterprise.Core.Data;
|
|
using RailEnterprise.Core.Economy;
|
|
using RailEnterprise.Core.Persistence;
|
|
using RailEnterprise.Core.Rail;
|
|
using RailEnterprise.Core.Simulation;
|
|
using RailEnterprise.Core.Simulation.Systems;
|
|
using RailEnterprise.Tests.Harness;
|
|
using static RailEnterprise.Tests.Rail.RailFixture;
|
|
|
|
namespace RailEnterprise.Tests.Rail;
|
|
|
|
public static class MaintenanceTests
|
|
{
|
|
private static MaintenanceFile M => TestData.Data.Maintenance;
|
|
|
|
[Test(Description = "Manutenzione (14.5): il rischio di guasto non cresce con la condizione")]
|
|
public static void HazardFallsAsConditionRises()
|
|
{
|
|
double previous = double.MaxValue;
|
|
for (double c = 0; c <= 100; c += 0.5)
|
|
{
|
|
double h = Fleet.Hazard(c, M.Failure);
|
|
Assert.True(h <= previous + 1e-15, $"rischio {h} a condizione {c} oltre {previous}");
|
|
Assert.True(h > 0, "rischio positivo");
|
|
previous = h;
|
|
}
|
|
Assert.Approx(M.Failure.H0 / M.Failure.HealthyDivisor, Fleet.Hazard(80, M.Failure), 1e-12);
|
|
Assert.Approx(M.Failure.H0 * Math.Exp(0.8), Fleet.Hazard(40, M.Failure), 1e-9);
|
|
}
|
|
|
|
[Test(Description = "Manutenzione (14.5): l'usura cresce con km, pendenza, alta velocità, carico, età e difficoltà")]
|
|
public static void WearGrowsWithEveryFactor()
|
|
{
|
|
var p = M.Wear;
|
|
double Wear(double km = 100, double grade = 0.2, double fast = 0.3, double load = 0.5, double age = 1, double diff = 1) =>
|
|
Fleet.DailyWear(0.25, km, grade, fast, load, age, diff, p);
|
|
Assert.Equal(0.0, Wear(km: 0));
|
|
Assert.Approx(0.25, Fleet.DailyWear(0.25, 100, 0, 0, 0, 1, 1, p), 1e-12);
|
|
double base0 = Wear();
|
|
Assert.True(Wear(km: 200) > base0);
|
|
Assert.True(Wear(grade: 0.5) > base0);
|
|
Assert.True(Wear(fast: 0.9) > base0);
|
|
Assert.True(Wear(load: 1) > base0);
|
|
Assert.True(Wear(age: 1.5) > base0);
|
|
Assert.True(Wear(diff: 1.3) > base0);
|
|
}
|
|
|
|
[Test(Description = "Manutenzione (14.5): senza interventi la condizione dei componenti non sale mai")]
|
|
public static void ComponentsNeverImproveWithoutAnIntervention()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
|
|
var w = f.W;
|
|
var trains = net.Trains.Select(id => w.Trains[id]).ToList();
|
|
var before = trains.SelectMany(t => t.Vehicles).ToDictionary(v => v.Value, v => (double[])w.Vehicles[v.Value].Components.Clone());
|
|
var records = trains.ToDictionary(t => t.Id.Value, t => t.History.Count > 0 ? t.History[^1] : default);
|
|
bool worn = false;
|
|
for (int d = 0; d < 150; d++)
|
|
{
|
|
w.RunDays(1);
|
|
foreach (var t in trains)
|
|
{
|
|
var last = t.History.Count > 0 ? t.History[^1] : default;
|
|
bool intervention = last != records[t.Id.Value];
|
|
records[t.Id.Value] = last;
|
|
foreach (var id in t.Vehicles)
|
|
{
|
|
var now = w.Vehicles[id.Value].Components;
|
|
for (int j = 0; j < now.Length; j++)
|
|
{
|
|
if (!intervention) Assert.True(now[j] <= before[id.Value][j] + 1e-12, $"{t.Name}: componente {j} risalito senza intervento");
|
|
if (now[j] < before[id.Value][j]) worn = true;
|
|
}
|
|
before[id.Value] = (double[])now.Clone();
|
|
}
|
|
}
|
|
}
|
|
Assert.True(worn, "i treni in servizio si usurano");
|
|
Assert.True(trains.Any(t => t.History.Count > 0), "il pianificatore ha mandato i treni in officina");
|
|
}
|
|
|
|
/// <summary>Treno fermo nel deposito (senza binari), con i componenti impostati.</summary>
|
|
private static (RailFixture F, Train Train, Depot Depot) TrainInDepot(params double[] components)
|
|
{
|
|
var f = Valdoria();
|
|
int depot = f.Ok(new BuildDepotCommand(K(13.2, 5.4), "medium", "Officina di Valdoria"));
|
|
int train = f.Train(depot, "Prova", ("loco_steam_1850", 1), ("wagon_box", 1));
|
|
var t = f.W.Trains[train];
|
|
foreach (var id in t.Vehicles)
|
|
{
|
|
var v = f.W.Vehicles[id.Value];
|
|
for (int j = 0; j < v.Components.Length; j++) v.Components[j] = components[j % components.Length];
|
|
}
|
|
return (f, t, f.W.Network.Depots[depot]);
|
|
}
|
|
|
|
[Test(Description = "Manutenzione (14.5): tagliando, revisione e ispezione riportano la condizione attesa, scalata dalla politica")]
|
|
public static void ServiceAndOverhaulRestoreTheExpectedCondition()
|
|
{
|
|
var (f, t, _) = TrainInDepot(20, 45, 70, 90);
|
|
var w = f.W;
|
|
var standard = M.Policy(MaintenancePolicy.Standard);
|
|
var economy = M.Policy(MaintenancePolicy.Economy);
|
|
var snapshot = t.Vehicles.Select(id => (double[])w.Vehicles[id.Value].Components.Clone()).ToList();
|
|
void Reset()
|
|
{
|
|
for (int k = 0; k < t.Vehicles.Count; k++) snapshot[k].CopyTo(w.Vehicles[t.Vehicles[k].Value].Components, 0);
|
|
}
|
|
|
|
Fleet.Apply(w, t, M.Intervention("service"), standard);
|
|
for (int k = 0; k < t.Vehicles.Count; k++)
|
|
{
|
|
var v = w.Vehicles[t.Vehicles[k].Value];
|
|
for (int j = 0; j < v.Components.Length; j++) Assert.Approx(Math.Min(100, snapshot[k][j] + 40), v.Components[j], 1e-9);
|
|
Assert.Equal(w.Clock.Day, v.LastServiceDay);
|
|
}
|
|
Reset();
|
|
Fleet.Apply(w, t, M.Intervention("service"), economy);
|
|
Assert.Approx(20 + 40 * 0.7, w.Vehicles[t.Vehicles[0].Value].Components[0], 1e-9);
|
|
|
|
Reset();
|
|
Fleet.Apply(w, t, M.Intervention("overhaul"), standard);
|
|
foreach (var id in t.Vehicles) Assert.True(w.Vehicles[id.Value].Components.All(c => Math.Abs(c - 100) < 1e-9), "revisione: tutto a 100");
|
|
Reset();
|
|
Fleet.Apply(w, t, M.Intervention("overhaul"), economy);
|
|
Assert.Approx(20 + 80 * 0.7, w.Vehicles[t.Vehicles[0].Value].Components[0], 1e-9);
|
|
|
|
Reset();
|
|
Fleet.Apply(w, t, M.Intervention("inspection"), standard);
|
|
var loco = w.Vehicles[t.Vehicles[0].Value];
|
|
var comps = Fleet.ComponentsOf(w.Data, loco.Def);
|
|
for (int j = 0; j < comps.Count; j++)
|
|
{
|
|
double expected = comps[j].Id == Fleet.Brakes ? 100 : Math.Min(100, snapshot[0][j] + 10);
|
|
Assert.Approx(expected, loco.Components[j], 1e-9, comps[j].Id);
|
|
}
|
|
Assert.Equal(w.Clock.Day + M.Inspection.HazardDays, loco.HazardReducedUntilDay);
|
|
|
|
// la revisione riduce il fattore d'età di un veicolo oltre la vita utile, senza scendere sotto 1
|
|
loco.BoughtDay = w.Clock.Day - 40L * w.Calendar.DaysPerYear;
|
|
Assert.Approx(2.5, Fleet.AgeFactor(w, loco), 1e-9);
|
|
Fleet.Apply(w, t, M.Intervention("overhaul"), standard);
|
|
Assert.Approx(2.0, Fleet.AgeFactor(w, loco), 1e-9);
|
|
for (int i = 0; i < 5; i++) Fleet.Apply(w, t, M.Intervention("overhaul"), standard);
|
|
Assert.Approx(1.0, Fleet.AgeFactor(w, loco), 1e-9);
|
|
}
|
|
|
|
[Test(Description = "Un tagliando programmato in officina preleva i ricambi, si paga e riporta la condizione attesa")]
|
|
public static void ScheduledServiceRunsInTheWorkshop()
|
|
{
|
|
var (f, t, depot) = TrainInDepot(30, 50, 65, 80);
|
|
var w = f.W;
|
|
var before = t.Vehicles.Select(id => (double[])w.Vehicles[id.Value].Components.Clone()).ToList();
|
|
int parts = depot.SpareParts;
|
|
long costs = w.Player.YearEntries[(int)LedgerEntry.FleetMaintenance];
|
|
var r = f.Do(new ScheduleServiceCommand(t.Id, "service"));
|
|
Assert.True(r.Ok, r.Message);
|
|
Assert.True(t.InWorkshop, "il treno è già nel deposito: entra subito in officina");
|
|
Assert.False(f.Do(new ScheduleServiceCommand(t.Id, "service")).Ok, "non si prenota due volte");
|
|
Assert.True(f.RunUntil(() => t.History.Count == 1, 20), "tagliando completato");
|
|
Assert.False(t.InWorkshop);
|
|
Assert.Equal(parts - t.Vehicles.Count, depot.SpareParts);
|
|
long price = t.Vehicles.Sum(id => w.Vehicles[id.Value].Def.Price);
|
|
Assert.Equal(-(long)Math.Round(price * M.Intervention("service").CostShare), w.Player.YearEntries[(int)LedgerEntry.FleetMaintenance] - costs);
|
|
for (int k = 0; k < t.Vehicles.Count; k++)
|
|
{
|
|
var v = w.Vehicles[t.Vehicles[k].Value];
|
|
for (int j = 0; j < v.Components.Length; j++) Assert.Approx(Math.Min(100, before[k][j] + 40), v.Components[j], 1e-9);
|
|
}
|
|
Assert.Equal(M.InterventionIndex("service"), t.History[0].Intervention);
|
|
Assert.False(f.Do(new ScheduleServiceCommand(t.Id, "repair_minor")).Ok, "le riparazioni non si programmano");
|
|
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
|
|
}
|
|
|
|
[Test(Description = "Manutenzione (14.5): con politica Standard e ricambi disponibili il pianificatore non lascia scendere un treno sotto 30")]
|
|
public static void PlannerKeepsTrainsAboveThirtyWithStandardPolicyAndParts()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
|
|
var w = f.W;
|
|
var officina = w.Network.Depots[net.Officina];
|
|
// ricambi abbondanti, contabilizzati come importati
|
|
w.Goods.Imported[w.Data.SparePartsGood] += 390;
|
|
officina.SpareParts += 390;
|
|
officina.PartsTarget = 400;
|
|
var trains = net.Trains.Select(id => w.Trains[id]).ToList();
|
|
double min = 100;
|
|
for (int d = 0; d < 2 * w.Calendar.DaysPerYear; d++)
|
|
{
|
|
w.RunDays(1);
|
|
foreach (var t in trains) min = Math.Min(min, Fleet.TrainCondition(w, t));
|
|
}
|
|
Assert.True(min >= w.Data.Maintenance.Planner.CriticalCondition, $"condizione minima {min:F1}");
|
|
Assert.True(trains.All(t => t.History.Count > 0));
|
|
Assert.True(trains.Sum(t => t.MaintenanceThisYear + t.MaintenanceLastYear) > 0, "interventi pagati");
|
|
}
|
|
|
|
/// <summary>Avanza a tick finché il treno non è in marcia in linea, carico se richiesto.</summary>
|
|
private static void RunUntilMoving(World w, Train t, bool loaded = false)
|
|
{
|
|
for (int i = 0; i < 400 * w.Calendar.TicksPerDay; i++)
|
|
{
|
|
w.RunTicks(1);
|
|
if (t.State == TrainState.Moving && !t.AtNode.IsValid && t.Speed > 1 && (!loaded || t.Cargo.Any(p => p.Kind == PacketKind.Freight)))
|
|
return;
|
|
}
|
|
throw new AssertionException($"{t.Name} non è mai in marcia");
|
|
}
|
|
|
|
[Test(Description = "Guasto grave: fermo in linea fino al soccorso, rimorchio all'officina, riserva sulla linea durante la riparazione")]
|
|
public static void MajorFailureRescueRepairAndReserveCover()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
|
|
var w = f.W;
|
|
int reserveId = f.Train(net.Officina, "Riserva 1", ("loco_steam_1850", 1));
|
|
Assert.True(f.Do(new SetReserveCommand(new TrainId(reserveId), true)).Ok);
|
|
var reserve = w.Trains[reserveId];
|
|
var t = w.Trains[net.Trains[0]];
|
|
RunUntilMoving(w, t);
|
|
|
|
double hours = FleetMaintenanceSystem.RescueHours(w, t);
|
|
var officina = w.Network.Depots[net.Officina];
|
|
double viaCrew = Vec2.Distance(Fleet.Position(w, t), officina.Position) / 1000 / M.Failure.RescueSpeedKmh + M.Failure.RescueExtraHours;
|
|
Assert.True(hours < viaCrew, "la locomotiva di riserva arriva prima della squadra");
|
|
var engine = w.Vehicles[t.Vehicles[0].Value];
|
|
FleetMaintenanceSystem.Fail(w.Context, t, FailureKind.Major, engine, 0);
|
|
Assert.Equal(TrainState.Broken, t.State);
|
|
Assert.True(t.Held.Count > 0, "il treno fermo tiene il binario");
|
|
long rescue = t.RescueTick;
|
|
Assert.True(rescue > w.Clock.Tick);
|
|
|
|
w.RunTicks(rescue - w.Clock.Tick + 1);
|
|
Assert.True(t.State != TrainState.Broken, "soccorso arrivato");
|
|
Assert.True(t.Towed && t.TopSpeedKmh <= M.Failure.RescueSpeedKmh + 1e-9, "rimorchiato a 40 km/h");
|
|
Assert.Equal(net.Officina, t.MaintenanceDepot.Value);
|
|
Assert.True(f.RunUntil(() => t.InWorkshop, 60), "in officina");
|
|
Assert.True(f.RunUntil(() => t.CoveredBy.IsValid, 5), "la riserva copre la linea");
|
|
Assert.Equal(t.Line, reserve.Line);
|
|
Assert.True(f.RunUntil(() => t.Failure == FailureKind.None && !t.InWorkshop, 60), "riparato");
|
|
Assert.Equal(M.InterventionIndex("repair_major"), t.History[^1].Intervention);
|
|
Assert.False(t.Towed);
|
|
Assert.Equal(TrainId.None, t.CoveredBy);
|
|
Assert.Equal(LineId.None, reserve.Line);
|
|
Assert.True(f.RunUntil(() => reserve.State == TrainState.InDepot, 30), "la riserva rientra in deposito");
|
|
Assert.True(t.FailuresTotal >= 1);
|
|
}
|
|
|
|
[Test(Description = "Deragliamento: carico perso (contabilizzato), binario chiuso tre giorni, notizia negativa")]
|
|
public static void DerailmentLosesCargoAndClosesTheTrack()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
|
|
var w = f.W;
|
|
var t = w.Trains[net.Trains[0]];
|
|
RunUntilMoving(w, t, loaded: true);
|
|
var edge = w.Network.Edges[t.Route[t.RouteIndex].Edge.Value];
|
|
int cargo = t.Cargo.Where(p => p.Kind == PacketKind.Freight).Sum(p => p.Units);
|
|
Assert.True(cargo > 0);
|
|
long decayed = w.Goods.Decayed.Sum();
|
|
FleetMaintenanceSystem.Fail(w.Context, t, FailureKind.Catastrophic, w.Vehicles[t.Vehicles[0].Value], 0);
|
|
Assert.Equal(TrainState.Broken, t.State);
|
|
Assert.Equal(0, t.Cargo.Count);
|
|
Assert.Equal(decayed + cargo, w.Goods.Decayed.Sum());
|
|
Assert.False(edge.IsUsable, "binario danneggiato");
|
|
Assert.True(w.Events.Recent.Any(e => e.Severity == EventSeverity.Critical && e.Text.Contains("Deragliamento", StringComparison.Ordinal)));
|
|
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
|
|
w.RunDays(M.Failure.DerailmentTrackDays + 1);
|
|
Assert.True(edge.IsUsable, "binario riaperto dopo tre giorni");
|
|
Assert.Equal(M.InterventionIndex("repair_catastrophic"), f.RunUntil(() => t.MaintenanceDepot.IsValid, 20) ? t.PlannedIntervention : -1);
|
|
}
|
|
|
|
[Test(Description = "I ricambi arrivano in treno dall'hub del porto fino all'officina e ne ricostituiscono la scorta")]
|
|
public static void SparePartsReachTheWorkshopByTrain()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: true, trainsPerLine: 1);
|
|
var w = f.W;
|
|
var officina = w.Network.Depots[net.Officina];
|
|
int good = w.Data.SparePartsGood;
|
|
long imported = w.Goods.Imported[good];
|
|
Assert.True(w.Network.Stations[net.Valdoria].Depots.Contains(officina.Id), "l'officina è nel bacino di Valdoria");
|
|
int maxStock = 0;
|
|
for (int d = 0; d < 120; d++)
|
|
{
|
|
w.RunDays(1);
|
|
maxStock = Math.Max(maxStock, officina.SpareParts);
|
|
}
|
|
Assert.True(w.Goods.Imported[good] > imported, "ricambi importati dal porto");
|
|
Assert.True(maxStock >= officina.PartsTarget, $"scorta massima {maxStock} su {officina.PartsTarget}");
|
|
Assert.True(w.Goods.Consumed[good] > 0, "ricambi usati dagli interventi");
|
|
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
|
|
Assert.Equal(0L, w.MoneyBalanceSum());
|
|
}
|
|
|
|
[Test(Description = "Politiche di manutenzione: treno, poi linea, poi compagnia; scorta desiderata dei ricambi")]
|
|
public static void PoliciesOverrideAndPartsOrders()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
|
|
var w = f.W;
|
|
var t = w.Trains[net.Trains[0]];
|
|
Assert.Equal(MaintenancePolicy.Standard, Fleet.PolicyOf(w, t).Id);
|
|
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, "economy"));
|
|
Assert.Equal(MaintenancePolicy.Economy, Fleet.PolicyOf(w, t).Id);
|
|
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Line, net.Lines[0], "thorough"));
|
|
Assert.Equal(MaintenancePolicy.Thorough, Fleet.PolicyOf(w, t).Id);
|
|
Assert.Equal(MaintenancePolicy.Economy, Fleet.PolicyOf(w, w.Trains[net.Trains[1]]).Id);
|
|
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Train, t.Id.Value, "standard"));
|
|
Assert.Equal(MaintenancePolicy.Standard, Fleet.PolicyOf(w, t).Id);
|
|
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Train, t.Id.Value, "inherit"));
|
|
Assert.Equal(MaintenancePolicy.Thorough, Fleet.PolicyOf(w, t).Id);
|
|
Assert.False(f.Do(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, "inherit")).Ok);
|
|
Assert.False(f.Do(new SetMaintenancePolicyCommand(MaintenanceScope.Line, 99, "standard")).Ok);
|
|
Assert.False(f.Do(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, "lusso")).Ok);
|
|
|
|
f.Ok(new OrderPartsCommand(new DepotId(net.Officina), 120));
|
|
Assert.Equal(120, w.Network.Depots[net.Officina].PartsTarget);
|
|
Assert.False(f.Do(new OrderPartsCommand(new DepotId(net.Officina), M.Depots.MaxSpareParts + 1)).Ok);
|
|
Assert.False(f.Do(new OrderPartsCommand(new DepotId(net.Officina), -1)).Ok);
|
|
}
|
|
|
|
[Test(Description = "Lo stato della manutenzione (officine, prenotazioni, guasti) sopravvive al salvataggio")]
|
|
public static void MaintenanceStateSurvivesSaveAndLoad()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: true, trainsPerLine: 1);
|
|
var w = f.W;
|
|
Assert.True(f.RunUntil(() => w.Network.Depots[net.Officina].Jobs.Any(j => j.Started), 120), "un lavoro in officina");
|
|
var t = w.Trains[net.Trains[1]];
|
|
FleetMaintenanceSystem.Fail(w.Context, t, FailureKind.Minor, w.Vehicles[t.Vehicles[0].Value], 0);
|
|
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
|
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
|
|
Assert.Equal(w.Network.Depots[net.Officina].Jobs.Count, loaded.Network.Depots[net.Officina].Jobs.Count);
|
|
w.RunDays(60);
|
|
loaded.RunDays(60);
|
|
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
|
|
}
|
|
}
|