F4: manutenzione della flotta, officine, ricambi via treno e pendolarismo completo nel motore
- FleetMaintenanceSystem: usura per componente in km di servizio, rischio e guasti (lieve, grave con soccorso, deragliamento), pianificatore predittivo con scelta del deposito, officine con stalli, ricambi e personale, riserve, avvisi. - Depositi come posti di lavoro; motivi dei posti scoperti; convenzioni di pendolarismo. - Ricambi consegnati alle officine nel bacino e importati dagli hub. - Inversione di marcia in stazione come sosta tecnica e transito in stazione che libera l'arco d'arrivo (eliminano due stalli della circolazione). - Salvataggio versione 2 con migrazione dalla versione 1; test di 14.5 e accettazione F4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
34 files changed
+2854
-94
No files matched your search
@@ -3,6 +3,8 @@ using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ViaFerrea.Core.Simulation.Systems;
|
||||
using ViaFerrea.Tests.Harness;
|
||||
using static ViaFerrea.Tests.Rail.RailFixture;
|
||||
|
||||
@@ -100,4 +102,103 @@ public static class CommutingTests
|
||||
Assert.False(f.W.Commutes.Any(c => !c.Walking && c.Category == PaxClass.Staff));
|
||||
Assert.True(mill.StaffPresent < mill.JobsStaff, "il personale resta scoperto");
|
||||
}
|
||||
|
||||
[Test(Description = "I depositi assumono pendolari: senza servizi in città manca il personale e l'officina rallenta")]
|
||||
public static void DepotsHireCommutersAndExplainMissingStaff()
|
||||
{
|
||||
// il deposito di Borgo Ceresio: la città è troppo piccola per avere personale qualificato
|
||||
var (f, _, _, _) = WorkersLine(coaches: 2);
|
||||
var officina = f.W.Network.Depots[0];
|
||||
Assert.True(officina.JobsWorkers > 0 && officina.JobsStaff == officina.Stalls * f.W.Data.Maintenance.Depots.StaffPerStall);
|
||||
RunToNextMonth(f);
|
||||
var borgo = f.W.Towns.First(t => t.Name == "Borgo Ceresio");
|
||||
Assert.Equal(0, borgo.StaffPool(f.W.Data.Balance.Town));
|
||||
Assert.Equal(officina.JobsWorkers, officina.ContractedWorkers);
|
||||
Assert.True(f.W.Commutes.Any(c => c.Walking && c.Workplace == officina.Ref && c.Category == PaxClass.Worker), "lavoratori a piedi");
|
||||
Assert.Approx(officina.JobsWorkers, officina.WorkersPresent, 1e-9);
|
||||
Assert.Equal(UncoveredReason.NoStaffServices, officina.StaffReason);
|
||||
Assert.True(FleetMaintenanceSystem.WorkRate(f.W, officina) < 0.5, "senza personale l'officina lavora a un terzo");
|
||||
|
||||
// quando la città ha i servizi, il personale arriva a piedi e l'officina lavora a pieno ritmo
|
||||
var g = Valdoria();
|
||||
var net = g.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 0);
|
||||
var full = g.W.Network.Depots[net.Officina];
|
||||
Assert.True(g.W.Towns.First(t => t.Name == "Valdoria").StaffPool(g.W.Data.Balance.Town) > 0);
|
||||
RunToNextMonth(g);
|
||||
Assert.Equal(full.JobsStaff, full.ContractedStaff);
|
||||
Assert.Approx(full.JobsStaff, full.StaffPresent, 1e-9);
|
||||
Assert.Equal(UncoveredReason.None, full.StaffReason);
|
||||
Assert.Approx(1.0, FleetMaintenanceSystem.WorkRate(g.W, full), 1e-12);
|
||||
}
|
||||
|
||||
[Test(Description = "Registro degli impieghi: posti scoperti per mancanza di stazioni o di capacità delle carrozze")]
|
||||
public static void RegisterExplainsUncoveredJobs()
|
||||
{
|
||||
var bare = Valdoria();
|
||||
RunToNextMonth(bare);
|
||||
var lonelyMill = bare.W.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
Assert.Equal(UncoveredReason.NoStation, lonelyMill.WorkersReason);
|
||||
|
||||
var (f, mill, _, line) = WorkersLine(coaches: 1);
|
||||
mill.Level = 3;
|
||||
RunToNextMonth(f);
|
||||
Assert.Equal(UncoveredReason.LineCapacity, mill.WorkersReason);
|
||||
Assert.Equal(line, mill.WorkersReasonLine.Value);
|
||||
// la linea non ha carrozze per tecnici e nessuna città è a distanza pedonale
|
||||
Assert.Equal(UncoveredReason.NoTownInReach, mill.StaffReason);
|
||||
}
|
||||
|
||||
[Test(Description = "Convenzioni: l'industria propone, il vettore accetta e incassa il canone; senza capacità salta con penale")]
|
||||
public static void AgreementIsProposedPaidAndBrokenWithPenalty()
|
||||
{
|
||||
var (f, mill, train, _) = WorkersLine(coaches: 2);
|
||||
CommuteAgreement? proposal = null;
|
||||
for (int m = 0; m < 12 && proposal is null; m++)
|
||||
{
|
||||
RunToNextMonth(f);
|
||||
proposal = f.W.Agreements.FirstOrDefault(a => a.State == AgreementState.Proposed);
|
||||
}
|
||||
Assert.True(proposal is not null, "proposta entro un anno");
|
||||
Assert.Equal(mill.Id, proposal!.Industry);
|
||||
Assert.True(proposal.SeatsPerDay >= f.W.Data.Balance.Employment.Agreements.MinSeats);
|
||||
Assert.True(f.W.Events.Recent.Any(e => e.Severity == EventSeverity.Opportunity && e.Text.Contains("convenzione", StringComparison.Ordinal)));
|
||||
Assert.False(f.Do(new AcceptAgreementCommand(new AgreementId(999))).Ok);
|
||||
f.Ok(new AcceptAgreementCommand(proposal.Id));
|
||||
Assert.Equal(AgreementState.Active, proposal.State);
|
||||
Assert.False(f.Do(new RejectAgreementCommand(proposal.Id)).Ok, "non si rifiuta una convenzione attiva");
|
||||
|
||||
long fees = f.W.Player.YearEntries[(int)LedgerEntry.Contracts] + f.W.Player.LastYearEntries[(int)LedgerEntry.Contracts];
|
||||
RunToNextMonth(f);
|
||||
long feesAfter = f.W.Player.YearEntries[(int)LedgerEntry.Contracts] + f.W.Player.LastYearEntries[(int)LedgerEntry.Contracts];
|
||||
Assert.True(feesAfter - fees >= proposal.MonthlyFee.Cents, "canone mensile incassato");
|
||||
Assert.Equal(AgreementState.Active, proposal.State);
|
||||
|
||||
// senza treni la capacità garantita manca: dopo 30 giorni la convenzione salta con penale
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), LineId.None));
|
||||
Assert.True(f.RunUntil(() => proposal.State == AgreementState.Broken, 90), $"convenzione ancora {proposal.State}");
|
||||
Assert.True(f.W.Player.YearEntries[(int)LedgerEntry.Penalties] < 0, "penale pagata");
|
||||
Assert.True(f.W.Events.Recent.Any(e => e.Text.Contains("saltata", StringComparison.Ordinal)));
|
||||
Assert.Equal(0L, f.W.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "Una convenzione rifiutata non viene riproposta prima del periodo di attesa")]
|
||||
public static void RejectedAgreementWaitsBeforeANewProposal()
|
||||
{
|
||||
var (f, _, _, _) = WorkersLine(coaches: 2);
|
||||
CommuteAgreement? proposal = null;
|
||||
for (int m = 0; m < 12 && proposal is null; m++)
|
||||
{
|
||||
RunToNextMonth(f);
|
||||
proposal = f.W.Agreements.FirstOrDefault(a => a.State == AgreementState.Proposed);
|
||||
}
|
||||
Assert.True(proposal is not null);
|
||||
f.Ok(new RejectAgreementCommand(proposal!.Id));
|
||||
Assert.Equal(AgreementState.Rejected, proposal.State);
|
||||
int cooldown = f.W.Data.Balance.Employment.Agreements.CooldownMonths;
|
||||
for (int m = 0; m < cooldown - 1; m++)
|
||||
{
|
||||
RunToNextMonth(f);
|
||||
Assert.False(f.W.Agreements.Any(a => a.State == AgreementState.Proposed), "nessuna nuova proposta durante l'attesa");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
using ViaFerrea.Core.Persistence;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ViaFerrea.Core.Simulation.Systems;
|
||||
using ViaFerrea.Tests.Harness;
|
||||
using static ViaFerrea.Tests.Rail.RailFixture;
|
||||
|
||||
namespace ViaFerrea.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));
|
||||
}
|
||||
}
|
||||
@@ -86,4 +86,63 @@ public sealed class RailFixture
|
||||
Assert.True(RunUntil(() => W.Network.Edges.All(e => e.State == EdgeState.Active), 400), "cantieri completati");
|
||||
return (mine, mill, depot);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rete di Valdoria dimensionata per la manutenzione (F4): miniere, acciaieria (6 binari), Borgo
|
||||
/// Ceresio, Valdoria (4 binari), officina media di Valdoria sulla diramazione a sud-est della
|
||||
/// stazione; facoltativamente la stazione del Porto di Levante con la linea dei ricambi verso
|
||||
/// Valdoria. Tre linee (merci, operai, tecnici) con <paramref name="trainsPerLine"/> treni ciascuna,
|
||||
/// tutti comprati nell'officina.
|
||||
/// </summary>
|
||||
public MaintenanceNet BuildMaintenanceNetwork(bool partsLine, int trainsPerLine)
|
||||
{
|
||||
W.Money.Transfer(Core.Economy.Account.External, Core.Economy.Account.Of(Me), new Money(50_000_000_00), Core.Economy.LedgerEntry.Other);
|
||||
int mine = Ok(new BuildStationCommand(K(2.2, 2.6), 3, "Rocca Bruna"));
|
||||
int mill = Ok(new BuildStationCommand(K(10.6, 5.4), 6, "Acciaieria"));
|
||||
int borgo = Ok(new BuildStationCommand(K(12.4, 8.0), 2, "Borgo Ceresio"));
|
||||
int valdoria = Ok(new BuildStationCommand(K(12.8, 4.9), 4, "Valdoria"));
|
||||
int officina = Ok(new BuildDepotCommand(K(13.2, 5.4), "medium", "Officina di Valdoria"));
|
||||
Ok(new BuildTrackCommand(Scenario!.Route("valico", Me).Polyline, AllowTunnels: false));
|
||||
Ok(new BuildTrackCommand(Scenario!.Route("borgo", Me).Polyline));
|
||||
Ok(new BuildTrackCommand(Scenario!.Route("valdoria", Me).Polyline));
|
||||
Ok(new BuildTrackCommand(new[] { K(13.2, 5.4), K(12.8, 4.9) }));
|
||||
int port = -1;
|
||||
if (partsLine)
|
||||
{
|
||||
port = Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
|
||||
Ok(new BuildTrackCommand(new[] { K(14.5, 6.3), K(13.7, 6.0), K(13.2, 5.4) }));
|
||||
}
|
||||
Assert.True(RunUntil(() => W.Network.Edges.All(e => e.State == EdgeState.Active), 500), "cantieri completati");
|
||||
var lines = new[]
|
||||
{
|
||||
Ok(new CreateLineCommand("Linea 1, minerale e acciaio", "#e0a526",
|
||||
new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)), new LineStop(new StationId(valdoria)) })),
|
||||
Ok(new CreateLineCommand("Linea 2, operai di Borgo", "#4f7cac",
|
||||
new[] { new LineStop(new StationId(borgo)), new LineStop(new StationId(mill)) })),
|
||||
Ok(new CreateLineCommand("Linea 3, tecnici di Valdoria", "#b3573e",
|
||||
new[] { new LineStop(new StationId(valdoria)), new LineStop(new StationId(mill)) })),
|
||||
};
|
||||
var trains = new List<int>();
|
||||
for (int n = 1; n <= trainsPerLine; n++)
|
||||
{
|
||||
trains.Add(Train(officina, $"Merci {n}", ("loco_steam_1850", 1), ("wagon_hopper", 6), ("wagon_flat", 2)));
|
||||
Ok(new AssignTrainCommand(new TrainId(trains[^1]), new LineId(lines[0])));
|
||||
trains.Add(Train(officina, $"Operai {n}", ("loco_steam_1850", 1), ("coach_worker", 2)));
|
||||
Ok(new AssignTrainCommand(new TrainId(trains[^1]), new LineId(lines[1])));
|
||||
trains.Add(Train(officina, $"Tecnici {n}", ("loco_steam_1850", 1), ("coach_staff", 1)));
|
||||
Ok(new AssignTrainCommand(new TrainId(trains[^1]), new LineId(lines[2])));
|
||||
}
|
||||
int partsTrain = -1;
|
||||
if (partsLine)
|
||||
{
|
||||
partsTrain = Train(officina, "Ricambi 1", ("loco_steam_1850", 1), ("wagon_box", 2));
|
||||
int line = Ok(new CreateLineCommand("Linea 4, ricambi dal porto", "#7a5c9e",
|
||||
new[] { new LineStop(new StationId(port)), new LineStop(new StationId(valdoria)) }));
|
||||
Ok(new AssignTrainCommand(new TrainId(partsTrain), new LineId(line)));
|
||||
}
|
||||
return new MaintenanceNet(mine, mill, borgo, valdoria, officina, port, lines, trains, partsTrain);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Identificativi della rete di prova della manutenzione.</summary>
|
||||
public sealed record MaintenanceNet(int Mine, int Mill, int Borgo, int Valdoria, int Officina, int Port, int[] Lines, List<int> Trains, int PartsTrain);
|
||||
@@ -14,7 +14,7 @@ public static class CommutingAcceptanceTests
|
||||
/// Rete di Valdoria con tre linee: merci (miniere → acciaieria → Valdoria, con minerale, carbone
|
||||
/// e acciaio), lavoratori (Borgo Ceresio → acciaieria) e personale (Valdoria → acciaieria).
|
||||
/// </summary>
|
||||
private static (RailFixture F, Core.Economy.Industry Mill) ThreeLines()
|
||||
internal static (RailFixture F, Core.Economy.Industry Mill) ThreeLines()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork(waitForConstruction: false);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Simulation.Systems;
|
||||
using ViaFerrea.Tests.Harness;
|
||||
using ViaFerrea.Tests.Rail;
|
||||
using static ViaFerrea.Tests.Rail.RailFixture;
|
||||
|
||||
namespace ViaFerrea.Tests.Scenarios;
|
||||
|
||||
public static class MaintenanceAcceptanceTests
|
||||
{
|
||||
/// <summary>Esito di tre anni di esercizio della rete di prova con due treni per linea.</summary>
|
||||
private sealed record FleetRun(double MinFleet, int FirstDayBelow40, int Failures, double ServiceKm, bool Stalls)
|
||||
{
|
||||
public double FailuresPerMillionKm => Failures / ServiceKm * 1e6;
|
||||
}
|
||||
|
||||
private static FleetRun Run(bool partsLine)
|
||||
{
|
||||
var f = Valdoria();
|
||||
var net = f.BuildMaintenanceNetwork(partsLine, trainsPerLine: 2);
|
||||
var w = f.W;
|
||||
var trains = net.Trains.Select(id => w.Trains[id]).ToList();
|
||||
var lastOdo = new double[trains.Count];
|
||||
double minFleet = 100, km = 0;
|
||||
int firstBelow = -1;
|
||||
int days = 3 * w.Calendar.DaysPerYear;
|
||||
for (int d = 0; d < days; d++)
|
||||
{
|
||||
w.RunDays(1);
|
||||
// flotta: media sui treni del componente più debole di ciascuno (ADR 0010)
|
||||
double fleet = trains.Average(t => Fleet.TrainCondition(w, t));
|
||||
minFleet = Math.Min(minFleet, fleet);
|
||||
if (fleet < 40 && firstBelow < 0) firstBelow = d;
|
||||
for (int k = 0; k < trains.Count; k++)
|
||||
{
|
||||
double odo = w.Vehicles[trains[k].Vehicles[0].Value].OdometerKm;
|
||||
if (odo >= lastOdo[k]) km += odo - lastOdo[k];
|
||||
lastOdo[k] = odo;
|
||||
}
|
||||
}
|
||||
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());
|
||||
bool stalls = w.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal));
|
||||
return new FleetRun(minFleet, firstBelow, trains.Sum(t => t.FailuresTotal), km, stalls);
|
||||
}
|
||||
|
||||
[Test(Description = "Accettazione F4: senza linea dei ricambi la flotta scende sotto 40 entro 3 anni e i guasti raddoppiano; con la linea resta sopra 60")]
|
||||
public static void WithoutSparePartsTheFleetDecaysWithTheLineItStaysAboveSixty()
|
||||
{
|
||||
var without = Run(partsLine: false);
|
||||
var with = Run(partsLine: true);
|
||||
Console.WriteLine($" senza linea: flotta minima {without.MinFleet:F0} (sotto 40 dal giorno {without.FirstDayBelow40}), {without.Failures} guasti, {without.FailuresPerMillionKm:F1} per milione di km");
|
||||
Console.WriteLine($" con la linea: flotta minima {with.MinFleet:F0}, {with.Failures} guasti, {with.FailuresPerMillionKm:F1} per milione di km");
|
||||
|
||||
Assert.True(without.FirstDayBelow40 >= 0, $"senza ricambi la flotta resta a {without.MinFleet:F0}");
|
||||
Assert.True(with.MinFleet > 60, $"con la linea dei ricambi la flotta scende a {with.MinFleet:F0}");
|
||||
Assert.True(without.Failures >= 2 * Math.Max(1, with.Failures), $"guasti {without.Failures} senza linea contro {with.Failures} con la linea");
|
||||
Assert.True(without.FailuresPerMillionKm >= 2 * with.FailuresPerMillionKm, "il tasso di guasto per km almeno raddoppia");
|
||||
Assert.False(with.Stalls, "nessuno stallo della rete con la linea dei ricambi");
|
||||
}
|
||||
}
|
||||
@@ -187,6 +187,9 @@ public static class ServerTests
|
||||
|
||||
// in pausa: la posizione disegnata dal client coincide con quella del server
|
||||
await client.Connection.SendAsync(new SetSpeed { Speed = 0 });
|
||||
// la pausa vale da quando il ciclo di gioco ha elaborato SetSpeed (sotto carico può tardare)
|
||||
for (int i = 0; i < 500 && server.Host.Speed != 0; i++) await Task.Delay(10);
|
||||
Assert.Equal((byte)0, server.Host.Speed);
|
||||
long tick;
|
||||
Vec2? head;
|
||||
while (true)
|
||||
|
||||
Reference in new issue
Block a user