diff --git a/data/balance.json b/data/balance.json
index 9f22fcf..93163ac 100644
--- a/data/balance.json
+++ b/data/balance.json
@@ -108,7 +108,9 @@
"migration": { "share": 0.01, "satisfactionThreshold": 0.4, "maxDistanceKm": 60, "emigrationShareWhenNoTarget": 0.5 },
"employment": { "walkRadiusKm": 1.5, "workerMaxMinutes": 60, "staffMaxMinutes": 90, "coverageEmaDays": 30,
"dissolveCoverage": 0.5, "dissolveDays": 90, "walkSpeedKmh": 4.5, "boardDays": 2, "returnBoardDays": 2,
- "railStartCoverage": 0.5, "lineCapacityUtilization": 0.85 },
+ "railStartCoverage": 0.5, "lineCapacityUtilization": 0.85,
+ "agreements": { "minSeats": 20, "proposalChance": 0.5, "feePerSeatPerMonth": 2500, "proposalDays": 30,
+ "durationMonths": 24, "cooldownMonths": 6, "minCoverage": 0.9, "breakDays": 30, "penaltyMonths": 3 } },
"localTransport": { "enabled": true, "radiusKm": 3.0, "dailyShare": 0.25, "maxUnitsPerDay": 6 },
"hubs": {
"port": { "name_it": "Porto", "monthlyCapacity": 3000, "duty": 0.08, "footprint": "large" },
diff --git a/data/maintenance.json b/data/maintenance.json
index ab0c5ce..fcc2460 100644
--- a/data/maintenance.json
+++ b/data/maintenance.json
@@ -21,7 +21,8 @@
"highSpeedWeight": 0.5,
"loadWeight": 0.3,
"ageStepYears": 5,
- "ageStepFactor": 0.5
+ "ageStepFactor": 0.5,
+ "distanceScale": 30
},
"failure": {
"h0": 0.002,
@@ -64,7 +65,9 @@
"staffPerStall": 4,
"slowdownAtHalfStaff": 2.0,
"initialSpareParts": 10,
- "jobsWorkersPerStall": 6
+ "jobsWorkersPerStall": 6,
+ "targetSpareParts": 40,
+ "maxSpareParts": 400
},
"policies": [
{ "id": "economy", "name_it": "Economica", "intervalFactor": 1.5, "effectFactor": 0.7, "costFactor": 0.6 },
@@ -81,6 +84,8 @@
"averageDays": 15,
"marginDays": 5,
"alertCondition": 40,
- "criticalCondition": 30
+ "criticalCondition": 30,
+ "reserveMinDays": 5,
+ "historyLength": 12
}
}
diff --git a/src/ViaFerrea.Core/Data/BalanceDefs.cs b/src/ViaFerrea.Core/Data/BalanceDefs.cs
index f67c6f2..4d013b7 100644
--- a/src/ViaFerrea.Core/Data/BalanceDefs.cs
+++ b/src/ViaFerrea.Core/Data/BalanceDefs.cs
@@ -284,6 +284,30 @@ public sealed class EmploymentBalance
public required double RailStartCoverage { get; init; }
/// Quota della capacità stimata delle linee assegnabile ai contratti (margine per ritardi e soste).
public required double LineCapacityUtilization { get; init; }
+
+ /// Convenzioni di pendolarismo proposte dalle industrie ai vettori (sezione 9).
+ public required AgreementBalance Agreements { get; init; }
+}
+
+public sealed class AgreementBalance
+{
+ /// Pendolari su rotaia con lo stesso vettore oltre i quali un'industria propone una convenzione.
+ public required int MinSeats { get; init; }
+ /// Probabilità mensile che un'industria idonea proponga una convenzione.
+ public required double ProposalChance { get; init; }
+ /// Canone mensile per posto garantito (centesimi).
+ public required long FeePerSeatPerMonth { get; init; }
+ /// Giorni per accettare una proposta prima che decada.
+ public required int ProposalDays { get; init; }
+ public required int DurationMonths { get; init; }
+ /// Mesi senza nuove proposte dopo un rifiuto o una rottura.
+ public required int CooldownMonths { get; init; }
+ /// Copertura media (arrivati/posti) sotto la quale la capacità manca.
+ public required double MinCoverage { get; init; }
+ /// Giorni consecutivi di capacità mancante dopo cui la convenzione salta.
+ public required int BreakDays { get; init; }
+ /// Penale alla rottura, in mensilità del canone.
+ public required double PenaltyMonths { get; init; }
}
public sealed class LocalTransportBalance
diff --git a/src/ViaFerrea.Core/Data/MaintenanceDefs.cs b/src/ViaFerrea.Core/Data/MaintenanceDefs.cs
index 3b44f3b..f0e2daa 100644
--- a/src/ViaFerrea.Core/Data/MaintenanceDefs.cs
+++ b/src/ViaFerrea.Core/Data/MaintenanceDefs.cs
@@ -20,6 +20,15 @@ public sealed class MaintenanceFile
public required List Policies { get; init; }
public required ServiceIntervals Intervals { get; init; }
public required PlannerParams Planner { get; init; }
+
+ /// Intervento per id (inspection, service, overhaul, repair_*).
+ public InterventionDef Intervention(string id) =>
+ Interventions.FirstOrDefault(i => i.Id == id) ?? throw new KeyNotFoundException($"Intervento sconosciuto: {id}");
+
+ /// Indice dell'intervento per id, −1 se non esiste.
+ public int InterventionIndex(string id) => Interventions.FindIndex(i => i.Id == id);
+
+ public PolicyDef Policy(MaintenancePolicy id) => Policies.First(p => p.Id == id);
}
public sealed class ComponentSets
@@ -45,6 +54,13 @@ public sealed class WearParams
public required double LoadWeight { get; init; }
public required int AgeStepYears { get; init; }
public required double AgeStepFactor { get; init; }
+
+ ///
+ /// Km di servizio per km percorso sull'orologio dei treni: un giorno di calendario contiene pochi
+ /// minuti di marcia, ogni km simulato rappresenta l'esercizio di tutta la giornata (ADR 0010).
+ /// Vale per l'usura, per il contachilometri dei veicoli e per gli intervalli in km.
+ ///
+ public required double DistanceScale { get; init; }
}
public sealed class FailureParams
@@ -112,6 +128,12 @@ public sealed class DepotParams
public required double SlowdownAtHalfStaff { get; init; }
public required int InitialSpareParts { get; init; }
public required int JobsWorkersPerStall { get; init; }
+
+ /// Scorta desiderata di un deposito nuovo: i ricambi in arrivo in treno la ricostituiscono.
+ public required int TargetSpareParts { get; init; }
+
+ /// Scorta massima ordinabile per deposito.
+ public required int MaxSpareParts { get; init; }
}
public sealed class PolicyDef
@@ -139,4 +161,10 @@ public sealed class PlannerParams
public required int MarginDays { get; init; }
public required double AlertCondition { get; init; }
public required double CriticalCondition { get; init; }
+
+ /// Durata minima (giorni) di un intervento per cui il pianificatore impiega un treno di riserva.
+ public required double ReserveMinDays { get; init; }
+
+ /// Interventi conservati nella cartella di manutenzione di ogni treno.
+ public required int HistoryLength { get; init; }
}
diff --git a/src/ViaFerrea.Core/Economy/Company.cs b/src/ViaFerrea.Core/Economy/Company.cs
index f822c59..77d6a2b 100644
--- a/src/ViaFerrea.Core/Economy/Company.cs
+++ b/src/ViaFerrea.Core/Economy/Company.cs
@@ -56,6 +56,9 @@ public sealed class Company
public Money BaseCredit { get; set; }
public CreditRating Rating { get; set; } = CreditRating.BB;
+
+ /// Politica di manutenzione della flotta (10.2), con eccezioni per linea o treno.
+ public MaintenancePolicy MaintenancePolicy { get; set; } = MaintenancePolicy.Standard;
public int Tier { get; set; } = 1;
public int NegativeCashDays { get; set; }
public bool Bankrupt { get; set; }
diff --git a/src/ViaFerrea.Core/Economy/Employment.cs b/src/ViaFerrea.Core/Economy/Employment.cs
index ede7522..f287648 100644
--- a/src/ViaFerrea.Core/Economy/Employment.cs
+++ b/src/ViaFerrea.Core/Economy/Employment.cs
@@ -6,6 +6,43 @@ namespace ViaFerrea.Core.Economy;
/// Tipo di posto di lavoro.
public enum WorkplaceKind : byte { Industry = 0, Depot = 1 }
+/// Perché dei posti restano scoperti (Registro degli impieghi, sezione 9).
+public enum UncoveredReason : byte
+{
+ None = 0,
+ /// Nessuna stazione ha il posto di lavoro nel bacino.
+ NoStation = 1,
+ /// Nessuna città raggiungibile entro il tempo massimo (60 o 90 minuti).
+ NoTownInReach = 2,
+ /// Le città raggiungibili non hanno lavoratori liberi.
+ NoFreeWorkers = 3,
+ /// Le città raggiungibili non hanno servizi sufficienti per il personale qualificato.
+ NoStaffServices = 4,
+ /// Capacità delle carrozze insufficiente sulla linea indicata.
+ LineCapacity = 5,
+}
+
+///
+/// Posto di lavoro che assume pendolari: industria o deposito della compagnia. Il pendolarismo
+/// lo tratta in modo uniforme; il Registro degli impieghi mostra presenze e motivi dei posti scoperti.
+///
+public interface IWorkplace
+{
+ WorkplaceRef Ref { get; }
+ string Name { get; }
+ Vec2 Position { get; }
+ int JobsWorkers { get; }
+ int JobsStaff { get; }
+ int ContractedWorkers { get; set; }
+ int ContractedStaff { get; set; }
+ double WorkersPresent { get; set; }
+ double StaffPresent { get; set; }
+ UncoveredReason WorkersReason { get; set; }
+ UncoveredReason StaffReason { get; set; }
+ LineId WorkersReasonLine { get; set; }
+ LineId StaffReasonLine { get; set; }
+}
+
/// Riferimento a un posto di lavoro (industria o deposito della compagnia).
public readonly record struct WorkplaceRef(WorkplaceKind Kind, int Index)
{
@@ -47,3 +84,31 @@ public sealed class CommuteContract
public bool Walking => !Carrier.IsValid;
}
+
+/// Stato di una convenzione di pendolarismo.
+public enum AgreementState : byte { Proposed = 0, Active = 1, Rejected = 2, Expired = 3, Broken = 4, Ended = 5 }
+
+///
+/// Convenzione (sezione 9): l'industria paga al vettore un canone mensile in cambio di una
+/// capacità garantita di posti al giorno; se la capacità manca troppo a lungo salta con penale.
+///
+public sealed class CommuteAgreement
+{
+ public required AgreementId Id { get; init; }
+ public required IndustryId Industry { get; init; }
+ public required CompanyId Carrier { get; init; }
+ public required int SeatsPerDay { get; init; }
+ public required Money MonthlyFee { get; init; }
+ public required long ProposedDay { get; init; }
+ public AgreementState State { get; set; }
+ public long StartDay { get; set; } = -1;
+ public long EndDay { get; set; } = -1;
+ /// Copertura media (EMA) dei posti garantiti: arrivati/posti.
+ public double Coverage { get; set; } = 1;
+ /// Giorni consecutivi con capacità mancante.
+ public int ShortDays { get; set; }
+ /// Arrivati oggi con il vettore (accumulato dai contratti).
+ public int ArrivedToday { get; set; }
+
+ public bool Open => State is AgreementState.Proposed or AgreementState.Active;
+}
diff --git a/src/ViaFerrea.Core/Economy/Industry.cs b/src/ViaFerrea.Core/Economy/Industry.cs
index 2db0b27..06496e5 100644
--- a/src/ViaFerrea.Core/Economy/Industry.cs
+++ b/src/ViaFerrea.Core/Economy/Industry.cs
@@ -10,7 +10,7 @@ public enum IndustryBudget : byte { None = 0, Base = 1, High = 2 }
/// Industria: produce secondo la ricetta del suo tipo, con efficienza
/// e = min(copertura input, lavoratori, personale) × fattore di profitto × condizione impianti.
///
-public sealed class Industry
+public sealed class Industry : IWorkplace
{
public required IndustryId Id { get; init; }
public required IndustryDef Def { get; init; }
@@ -122,6 +122,14 @@ public sealed class Industry
public int JobsWorkers => Level <= 0 ? 0 : Def.Workers(Level);
public int JobsStaff => Level <= 0 ? 0 : Def.Staff(Level);
+ public WorkplaceRef Ref => WorkplaceRef.Of(Id);
+
+ /// Motivi dei posti scoperti all'ultimo abbinamento mensile (Registro degli impieghi).
+ public UncoveredReason WorkersReason { get; set; }
+ public UncoveredReason StaffReason { get; set; }
+ public LineId WorkersReasonLine { get; set; } = LineId.None;
+ public LineId StaffReasonLine { get; set; } = LineId.None;
+
/// Indice dell'input che usa il bene dato, o −1.
public int InputIndexOf(int good)
{
diff --git a/src/ViaFerrea.Core/Persistence/MaintenanceSerializer.cs b/src/ViaFerrea.Core/Persistence/MaintenanceSerializer.cs
new file mode 100644
index 0000000..d46d48b
--- /dev/null
+++ b/src/ViaFerrea.Core/Persistence/MaintenanceSerializer.cs
@@ -0,0 +1,325 @@
+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;
+
+namespace ViaFerrea.Core.Persistence;
+
+///
+/// Stato della fase F4 (corpo del salvataggio dalla versione 2): manutenzione di veicoli e treni,
+/// officine e personale dei depositi, politiche, convenzioni e motivi dei posti scoperti.
+/// I salvataggi della versione 1 si migrano con valori iniziali coerenti.
+///
+public static class MaintenanceSerializer
+{
+ public static void Write(World w, SaveWriter s)
+ {
+ foreach (var c in w.Companies) s.Write((byte)c.MaintenancePolicy);
+ foreach (var l in w.Lines) WritePolicy(s, l.Policy);
+
+ s.Write(w.Vehicles.Count);
+ foreach (var v in w.Vehicles)
+ {
+ s.Write(v.WearEma);
+ s.Write(v.LastInspectionDay);
+ s.Write(v.LastInspectionKm);
+ s.Write(v.LastServiceDay);
+ s.Write(v.LastServiceKm);
+ s.Write(v.LastOverhaulDay);
+ s.Write(v.AgeFactorOffset);
+ s.Write(v.HazardReducedUntilDay);
+ }
+
+ s.Write(w.Trains.Count);
+ foreach (var t in w.Trains)
+ {
+ s.Write(t.DayKm);
+ s.Write(t.DayGradeKm);
+ s.Write(t.DayFastKm);
+ s.Write(t.DayLoadKm);
+ s.Write(t.ServiceKmPerDay);
+ s.Write(t.CapacityT);
+ s.Write(t.SpeedFactor);
+ s.Write(t.SpeedCapKmh);
+ WritePolicy(s, t.Policy);
+ s.Write(t.MaintenanceDepot.Value);
+ s.Write(t.PlannedIntervention);
+ s.Write(t.InWorkshop);
+ s.Write((byte)t.Failure);
+ s.Write(t.FailedVehicle.Value);
+ s.Write(t.FailedComponent);
+ s.Write(t.RescueTick);
+ s.Write((byte)t.StateBeforeFailure);
+ s.Write(t.Towed);
+ s.Write(t.CoveredBy.Value);
+ s.Write(t.Covering.Value);
+ s.Write(t.AlertLevel);
+ s.Write(t.MaintenanceThisYear);
+ s.Write(t.MaintenanceLastYear);
+ s.Write(t.FailuresThisYear);
+ s.Write(t.FailuresTotal);
+ s.Write(t.History.Count);
+ foreach (var h in t.History)
+ {
+ s.Write(h.Day);
+ s.Write(h.Intervention);
+ s.Write(h.CostCents);
+ s.Write(h.Depot.Value);
+ s.Write(h.Parts);
+ }
+ }
+
+ s.Write(w.Network.Depots.Count);
+ foreach (var d in w.Network.Depots)
+ {
+ s.Write(d.PartsTarget);
+ s.Write(d.Stalls);
+ s.Write(d.JobsWorkers);
+ s.Write(d.JobsStaff);
+ WriteWorkplace(s, d);
+ s.Write(d.PartsAlerted);
+ s.Write(d.Jobs.Count);
+ foreach (var j in d.Jobs)
+ {
+ s.Write(j.Train.Value);
+ s.Write(j.Intervention);
+ s.Write(j.QueuedDay);
+ s.Write(j.Days);
+ s.Write(j.Parts);
+ s.Write(j.InStall);
+ s.Write(j.Started);
+ s.Write(j.Progress);
+ s.Write(j.CostCents);
+ }
+ }
+
+ s.Write(w.Network.Stations.Count);
+ foreach (var st in w.Network.Stations)
+ {
+ s.Write(st.Depots.Count);
+ foreach (var d in st.Depots) s.Write(d.Value);
+ }
+
+ s.Write(w.Network.Edges.Count);
+ foreach (var e in w.Network.Edges) s.Write(e.DamagedUntilDay);
+
+ s.Write(w.Industries.Count);
+ foreach (var ind in w.Industries)
+ {
+ s.Write((byte)ind.WorkersReason);
+ s.Write((byte)ind.StaffReason);
+ s.Write(ind.WorkersReasonLine.Value);
+ s.Write(ind.StaffReasonLine.Value);
+ }
+
+ s.Write(w.Agreements.Count);
+ foreach (var a in w.Agreements)
+ {
+ s.Write(a.Id.Value);
+ s.Write(a.Industry.Value);
+ s.Write(a.Carrier.Value);
+ s.Write(a.SeatsPerDay);
+ s.Write(a.MonthlyFee.Cents);
+ s.Write(a.ProposedDay);
+ s.Write((byte)a.State);
+ s.Write(a.StartDay);
+ s.Write(a.EndDay);
+ s.Write(a.Coverage);
+ s.Write(a.ShortDays);
+ s.Write(a.ArrivedToday);
+ }
+ }
+
+ public static void Read(World w, SaveReader r)
+ {
+ foreach (var c in w.Companies) c.MaintenancePolicy = (MaintenancePolicy)r.ReadByte();
+ foreach (var l in w.Lines) l.Policy = ReadPolicy(r);
+
+ Expect(r, w.Vehicles.Count, "veicoli");
+ foreach (var v in w.Vehicles)
+ {
+ v.WearEma = r.ReadDoubleArray();
+ v.LastInspectionDay = r.ReadInt64();
+ v.LastInspectionKm = r.ReadDouble();
+ v.LastServiceDay = r.ReadInt64();
+ v.LastServiceKm = r.ReadDouble();
+ v.LastOverhaulDay = r.ReadInt64();
+ v.AgeFactorOffset = r.ReadDouble();
+ v.HazardReducedUntilDay = r.ReadInt64();
+ }
+
+ Expect(r, w.Trains.Count, "treni");
+ foreach (var t in w.Trains)
+ {
+ t.DayKm = r.ReadDouble();
+ t.DayGradeKm = r.ReadDouble();
+ t.DayFastKm = r.ReadDouble();
+ t.DayLoadKm = r.ReadDouble();
+ t.ServiceKmPerDay = r.ReadDouble();
+ t.CapacityT = r.ReadDouble();
+ t.SpeedFactor = r.ReadDouble();
+ t.SpeedCapKmh = r.ReadDouble();
+ t.Policy = ReadPolicy(r);
+ t.MaintenanceDepot = new DepotId(r.ReadInt32());
+ t.PlannedIntervention = r.ReadInt32();
+ t.InWorkshop = r.ReadBool();
+ t.Failure = (FailureKind)r.ReadByte();
+ t.FailedVehicle = new VehicleId(r.ReadInt32());
+ t.FailedComponent = r.ReadInt32();
+ t.RescueTick = r.ReadInt64();
+ t.StateBeforeFailure = (TrainState)r.ReadByte();
+ t.Towed = r.ReadBool();
+ t.CoveredBy = new TrainId(r.ReadInt32());
+ t.Covering = new TrainId(r.ReadInt32());
+ t.AlertLevel = r.ReadInt32();
+ t.MaintenanceThisYear = r.ReadInt64();
+ t.MaintenanceLastYear = r.ReadInt64();
+ t.FailuresThisYear = r.ReadInt32();
+ t.FailuresTotal = r.ReadInt32();
+ int history = r.ReadInt32();
+ for (int k = 0; k < history; k++)
+ t.History.Add(new MaintenanceRecord(r.ReadInt64(), r.ReadInt32(), r.ReadInt64(), new DepotId(r.ReadInt32()), r.ReadInt32()));
+ }
+
+ Expect(r, w.Network.Depots.Count, "depositi");
+ foreach (var d in w.Network.Depots)
+ {
+ d.PartsTarget = r.ReadInt32();
+ d.Stalls = r.ReadInt32();
+ d.JobsWorkers = r.ReadInt32();
+ d.JobsStaff = r.ReadInt32();
+ ReadWorkplace(r, d);
+ d.PartsAlerted = r.ReadBool();
+ int jobs = r.ReadInt32();
+ for (int k = 0; k < jobs; k++)
+ {
+ d.Jobs.Add(new WorkshopJob
+ {
+ Train = new TrainId(r.ReadInt32()),
+ Intervention = r.ReadInt32(),
+ QueuedDay = r.ReadInt64(),
+ Days = r.ReadDouble(),
+ Parts = r.ReadInt32(),
+ InStall = r.ReadBool(),
+ Started = r.ReadBool(),
+ Progress = r.ReadDouble(),
+ CostCents = r.ReadInt64(),
+ });
+ }
+ }
+
+ Expect(r, w.Network.Stations.Count, "stazioni");
+ foreach (var st in w.Network.Stations)
+ {
+ int n = r.ReadInt32();
+ for (int k = 0; k < n; k++) st.Depots.Add(new DepotId(r.ReadInt32()));
+ }
+
+ Expect(r, w.Network.Edges.Count, "archi");
+ foreach (var e in w.Network.Edges) e.DamagedUntilDay = r.ReadInt64();
+
+ Expect(r, w.Industries.Count, "industrie");
+ foreach (var ind in w.Industries)
+ {
+ ind.WorkersReason = (UncoveredReason)r.ReadByte();
+ ind.StaffReason = (UncoveredReason)r.ReadByte();
+ ind.WorkersReasonLine = new LineId(r.ReadInt32());
+ ind.StaffReasonLine = new LineId(r.ReadInt32());
+ }
+
+ int agreements = r.ReadInt32();
+ for (int k = 0; k < agreements; k++)
+ {
+ var a = new CommuteAgreement
+ {
+ Id = new AgreementId(r.ReadInt32()),
+ Industry = new IndustryId(r.ReadInt32()),
+ Carrier = new CompanyId(r.ReadInt32()),
+ SeatsPerDay = r.ReadInt32(),
+ MonthlyFee = new Money(r.ReadInt64()),
+ ProposedDay = r.ReadInt64(),
+ };
+ a.State = (AgreementState)r.ReadByte();
+ a.StartDay = r.ReadInt64();
+ a.EndDay = r.ReadInt64();
+ a.Coverage = r.ReadDouble();
+ a.ShortDays = r.ReadInt32();
+ a.ArrivedToday = r.ReadInt32();
+ w.Agreements.Add(a);
+ }
+ }
+
+ ///
+ /// Migrazione dalla versione 1: officine e posti di lavoro dai dati, intervalli che partono
+ /// dall'acquisto, scorta iniziale dei depositi contabilizzata, bacini con i depositi.
+ ///
+ public static void Migrate(World w)
+ {
+ var dp = w.Data.Maintenance.Depots;
+ foreach (var v in w.Vehicles)
+ {
+ v.WearEma = new double[v.Components.Length];
+ v.LastInspectionDay = v.LastServiceDay = v.LastOverhaulDay = v.BoughtDay;
+ v.LastInspectionKm = v.LastServiceKm = 0;
+ }
+ foreach (var t in w.Trains)
+ {
+ if (!t.Removed && t.Vehicles.Count > 0) RailCommandHandlers.RecomputeTrain(w, t);
+ }
+ foreach (var d in w.Network.Depots)
+ {
+ RailCommandHandlers.InitDepot(w.Data, d);
+ d.PartsTarget = dp.TargetSpareParts;
+ w.Goods.Imported[w.Data.SparePartsGood] += d.SpareParts;
+ }
+ double km = w.Data.Construction.Stations.CatchmentKm * 1000;
+ foreach (var st in w.Network.Stations)
+ {
+ if (!w.Network.IsAlive(st)) continue;
+ foreach (var d in w.Network.Depots)
+ {
+ if (d.Owner == st.Owner && w.Network.IsAlive(d) && Vec2.Distance(d.Position, st.Position) <= km) st.Depots.Add(d.Id);
+ }
+ }
+ }
+
+ private static void WriteWorkplace(SaveWriter s, IWorkplace p)
+ {
+ s.Write(p.ContractedWorkers);
+ s.Write(p.ContractedStaff);
+ s.Write(p.WorkersPresent);
+ s.Write(p.StaffPresent);
+ s.Write((byte)p.WorkersReason);
+ s.Write((byte)p.StaffReason);
+ s.Write(p.WorkersReasonLine.Value);
+ s.Write(p.StaffReasonLine.Value);
+ }
+
+ private static void ReadWorkplace(SaveReader r, IWorkplace p)
+ {
+ p.ContractedWorkers = r.ReadInt32();
+ p.ContractedStaff = r.ReadInt32();
+ p.WorkersPresent = r.ReadDouble();
+ p.StaffPresent = r.ReadDouble();
+ p.WorkersReason = (UncoveredReason)r.ReadByte();
+ p.StaffReason = (UncoveredReason)r.ReadByte();
+ p.WorkersReasonLine = new LineId(r.ReadInt32());
+ p.StaffReasonLine = new LineId(r.ReadInt32());
+ }
+
+ private static void WritePolicy(SaveWriter s, MaintenancePolicy? p) => s.Write(p is { } v ? (byte)v : byte.MaxValue);
+
+ private static MaintenancePolicy? ReadPolicy(SaveReader r)
+ {
+ byte b = r.ReadByte();
+ return b == byte.MaxValue ? null : (MaintenancePolicy)b;
+ }
+
+ private static void Expect(SaveReader r, int expected, string what)
+ {
+ int n = r.ReadInt32();
+ if (n != expected) throw new InvalidDataException($"Salvataggio incoerente: {n} {what} nella sezione di manutenzione, {expected} attesi");
+ }
+}
diff --git a/src/ViaFerrea.Core/Persistence/WorldSerializer.cs b/src/ViaFerrea.Core/Persistence/WorldSerializer.cs
index aa56b75..04b9b6f 100644
--- a/src/ViaFerrea.Core/Persistence/WorldSerializer.cs
+++ b/src/ViaFerrea.Core/Persistence/WorldSerializer.cs
@@ -14,7 +14,7 @@ namespace ViaFerrea.Core.Persistence;
public static class WorldSerializer
{
/// Versione del corpo del salvataggio (migrazioni in ).
- public const int BodyVersion = 1;
+ public const int BodyVersion = 2;
/// Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).
public static void Write(World w, SaveWriter s)
@@ -234,6 +234,7 @@ public static class WorldSerializer
}
RailSerializer.Write(w, s);
+ MaintenanceSerializer.Write(w, s);
}
private static void WriteRecipeStock(List items, int[] stock, SaveWriter s)
@@ -331,7 +332,7 @@ public static class WorldSerializer
var settings = ReadSettings(r);
var (terrain, seaSide) = ReadTerrain(r);
var w = new World(data, settings, terrain, seaSide);
- ReadDynamic(w, r, goodMap);
+ ReadDynamic(w, r, goodMap, version);
w.LastStateHash = r.ReadUInt64();
w.LastHashDay = r.ReadInt64();
ReadEvents(w.Events, r);
@@ -390,7 +391,7 @@ public static class WorldSerializer
return (t, side);
}
- private static void ReadDynamic(World w, SaveReader r, int[] goodMap)
+ private static void ReadDynamic(World w, SaveReader r, int[] goodMap, int version)
{
var data = w.Data;
int goods = data.GoodCount;
@@ -669,6 +670,9 @@ public static class WorldSerializer
}
RailSerializer.Read(w, r, goodMap);
+ // versione 2 (F4): manutenzione, officine, convenzioni; la versione 1 si migra
+ if (version >= 2) MaintenanceSerializer.Read(w, r);
+ else MaintenanceSerializer.Migrate(w);
}
private static void ReadRecipeStock(List items, int[] stock, SaveReader r)
diff --git a/src/ViaFerrea.Core/Rail/Network.cs b/src/ViaFerrea.Core/Rail/Network.cs
index 8b39aec..b8016b3 100644
--- a/src/ViaFerrea.Core/Rail/Network.cs
+++ b/src/ViaFerrea.Core/Rail/Network.cs
@@ -1,4 +1,5 @@
using ViaFerrea.Core.Common;
+using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Rail;
@@ -105,7 +106,10 @@ public sealed class TrackEdge
/// Tonnellate transitate nell'ultimo anno (statistica).
public double TonnesThisYear { get; set; }
- public bool IsUsable => State == EdgeState.Active;
+ /// Danneggiato da un deragliamento fino al giorno indicato (−1 integro): nessun treno può entrarvi.
+ public long DamagedUntilDay { get; set; } = -1;
+
+ public bool IsUsable => State == EdgeState.Active && DamagedUntilDay < 0;
public NodeId Other(NodeId n) => n == A ? B : A;
@@ -213,6 +217,8 @@ public sealed class Station
public List Industries { get; } = [];
public List Towns { get; } = [];
public List Hubs { get; } = [];
+ /// Depositi nel bacino: ricevono i ricambi consegnati alla stazione e il loro personale vi scende.
+ public List Depots { get; } = [];
public int FreePlatforms
{
@@ -225,8 +231,31 @@ public sealed class Station
}
}
-/// Deposito e officina della compagnia: qui nascono i treni e si fa manutenzione (F4).
-public sealed class Depot
+/// Lavoro d'officina: un treno in coda o in uno stallo per un intervento (10.2).
+public sealed class WorkshopJob
+{
+ public required TrainId Train { get; init; }
+ /// Indice dell'intervento in maintenance.json.
+ public required int Intervention { get; init; }
+ public required long QueuedDay { get; init; }
+ /// Giorni di lavoro richiesti a personale completo.
+ public required double Days { get; init; }
+ /// Ricambi necessari (per veicolo, sommati sul treno).
+ public required int Parts { get; init; }
+ /// In uno stallo (altrimenti in coda).
+ public bool InStall { get; set; }
+ /// Ricambi prelevati e intervento pagato: il lavoro avanza.
+ public bool Started { get; set; }
+ /// Giorni di lavoro svolti.
+ public double Progress { get; set; }
+ public long CostCents { get; set; }
+}
+
+///
+/// Deposito e officina della compagnia: qui nascono i treni e si fa manutenzione (sezione 10).
+/// È anche un posto di lavoro: il personale qualificato degli stalli arriva col pendolarismo.
+///
+public sealed class Depot : IWorkplace
{
public required DepotId Id { get; init; }
public required CompanyId Owner { get; init; }
@@ -237,8 +266,36 @@ public sealed class Depot
public long BuiltDay { get; init; }
public long BuildCostCents { get; set; }
- /// Scorta di ricambi (sezione 10, F4).
+ /// Scorta di ricambi.
public int SpareParts { get; set; }
+
+ /// Scorta desiderata: la differenza è la domanda di ricambi sul grafo delle linee.
+ public int PartsTarget { get; set; }
+
+ /// Stalli dell'officina e posti di lavoro (da maintenance.json per la dimensione).
+ public int Stalls { get; set; }
+ public int JobsWorkers { get; set; }
+ public int JobsStaff { get; set; }
+
+ public int ContractedWorkers { get; set; }
+ public int ContractedStaff { get; set; }
+ public double WorkersPresent { get; set; }
+ public double StaffPresent { get; set; }
+ public UncoveredReason WorkersReason { get; set; }
+ public UncoveredReason StaffReason { get; set; }
+ public LineId WorkersReasonLine { get; set; } = LineId.None;
+ public LineId StaffReasonLine { get; set; } = LineId.None;
+
+ /// Coda dell'officina nell'ordine d'arrivo; i primi «Stalls» lavori occupano gli stalli.
+ public List Jobs { get; } = [];
+
+ /// Avviso «ricambi esauriti» già dato (si riarma quando la scorta torna a bastare).
+ public bool PartsAlerted { get; set; }
+
+ public WorkplaceRef Ref => WorkplaceRef.Of(Id);
+
+ /// Quota di personale qualificato presente (0–1).
+ public double StaffRatio => JobsStaff <= 0 ? 1 : Math.Clamp(StaffPresent / JobsStaff, 0, 1);
}
/// Tipo di progetto di cantiere.
diff --git a/src/ViaFerrea.Core/Rail/Pathfinder.cs b/src/ViaFerrea.Core/Rail/Pathfinder.cs
index 9b6a2a5..d090074 100644
--- a/src/ViaFerrea.Core/Rail/Pathfinder.cs
+++ b/src/ViaFerrea.Core/Rail/Pathfinder.cs
@@ -35,7 +35,7 @@ public sealed class Pathfinder
}
_run++;
_open.Clear();
- double cosLimit = Math.Cos(maxTurnDeg * Math.PI / 180);
+ double cosLimit = DMath.Cos(maxTurnDeg * Math.PI / 180);
var target = net.Nodes[to.Value].Position;
double vmax = Math.Max(1, maxSpeedKmh / 3.6);
diff --git a/src/ViaFerrea.Core/Rail/Trains.cs b/src/ViaFerrea.Core/Rail/Trains.cs
index 40ab763..e9dffd9 100644
--- a/src/ViaFerrea.Core/Rail/Trains.cs
+++ b/src/ViaFerrea.Core/Rail/Trains.cs
@@ -9,7 +9,7 @@ public sealed class Vehicle
public required VehicleId Id { get; init; }
public required VehicleDef Def { get; init; }
public required CompanyId Owner { get; init; }
- public required long BoughtDay { get; init; }
+ public required long BoughtDay { get; set; }
public TrainId Train { get; set; } = TrainId.None;
public DepotId Depot { get; set; } = DepotId.None;
public bool Sold { get; set; }
@@ -17,9 +17,36 @@ public sealed class Vehicle
/// Condizione dei componenti 0–100 (sezione 10; ordine dei componenti di maintenance.json).
public double[] Components { get; set; } = [];
- /// Chilometri percorsi.
+ /// Km di servizio percorsi (km dell'orologio dei treni × wear.distanceScale, ADR 0010).
public double OdometerKm { get; set; }
+ /// Usura giornaliera media per componente (EMA su planner.averageDays): serve al pianificatore.
+ public double[] WearEma { get; set; } = [];
+
+ /// Ultimi interventi: giorno e km di servizio.
+ public long LastInspectionDay { get; set; }
+ public double LastInspectionKm { get; set; }
+ public long LastServiceDay { get; set; }
+ public double LastServiceKm { get; set; }
+ public long LastOverhaulDay { get; set; }
+
+ /// Riduzione del fattore d'età accumulata con le revisioni generali.
+ public double AgeFactorOffset { get; set; }
+
+ /// Fino a questo giorno il rischio di guasto è ridotto (difetti nascosti azzerati dall'ispezione).
+ public long HazardReducedUntilDay { get; set; } = -1;
+
+ /// Condizione del componente più debole (0–100).
+ public double Condition
+ {
+ get
+ {
+ double min = 100;
+ foreach (double c in Components) min = Math.Min(min, c);
+ return min;
+ }
+ }
+
/// Carico corrente dei carri: bene (−1 vuoto) e unità.
public int Good { get; set; } = -1;
public int Load { get; set; }
@@ -39,12 +66,18 @@ public enum TrainState : byte
Loading = 3,
/// Non riesce a superare la salita (8.4).
Stalled = 4,
- /// Guasto in linea (F4).
+ /// Guasto grave o deragliamento: fermo in linea in attesa del soccorso (10.1).
Broken = 5,
/// Senza percorso verso la prossima fermata.
NoRoute = 6,
}
+/// Guasto in corso di un treno (10.1).
+public enum FailureKind : byte { None = 0, Minor = 1, Major = 2, Catastrophic = 3 }
+
+/// Voce della cartella di manutenzione di un treno.
+public readonly record struct MaintenanceRecord(long Day, int Intervention, long CostCents, DepotId Depot, int Parts);
+
/// Passo del percorso: un arco nel verso indicato (Forward = da A a B).
public readonly record struct RouteStep(EdgeId Edge, bool Forward);
@@ -124,6 +157,55 @@ public sealed class Train
public long RevenueLastYear { get; set; }
public double KmThisYear { get; set; }
+ // ---- manutenzione (sezione 10)
+ /// Km del giorno corrente (orologio dei treni) e quote per l'usura: in pendenza, ad alta velocità, pesati col carico.
+ public double DayKm { get; set; }
+ public double DayGradeKm { get; set; }
+ public double DayFastKm { get; set; }
+ public double DayLoadKm { get; set; }
+ /// Km di servizio medi al giorno (EMA), per tradurre gli intervalli in km in giorni.
+ public double ServiceKmPerDay { get; set; }
+ /// Capacità di carico in tonnellate (merci + passeggeri), ricalcolata alla composizione.
+ public double CapacityT { get; set; }
+
+ /// Fattore sulla velocità massima dovuto a motore usurato e guasti lievi; tetto se rimorchiato.
+ public double SpeedFactor { get; set; } = 1;
+ public double SpeedCapKmh { get; set; } = double.PositiveInfinity;
+ public double TopSpeedKmh => Math.Min(MaxSpeedKmh * SpeedFactor, SpeedCapKmh);
+
+ /// Politica di manutenzione propria del treno (null = quella della linea o della compagnia).
+ public MaintenancePolicy? Policy { get; set; }
+
+ /// Deposito prenotato e intervento pianificato (−1 nessuno): il treno ci va dopo la fermata corrente.
+ public DepotId MaintenanceDepot { get; set; } = DepotId.None;
+ public int PlannedIntervention { get; set; } = -1;
+ /// Nella coda o in uno stallo dell'officina.
+ public bool InWorkshop { get; set; }
+
+ public FailureKind Failure { get; set; }
+ /// Veicolo e componente guasti.
+ public VehicleId FailedVehicle { get; set; } = VehicleId.None;
+ public int FailedComponent { get; set; } = -1;
+ /// Tick d'arrivo del soccorso per un treno fermo in linea.
+ public long RescueTick { get; set; } = -1;
+ /// Stato prima del guasto grave (per riprendere la sosta in stazione).
+ public TrainState StateBeforeFailure { get; set; }
+ /// Rimorchiato verso il deposito dopo il soccorso.
+ public bool Towed { get; set; }
+
+ /// Treno di riserva che copre la linea durante l'intervento, e treno coperto da questa riserva.
+ public TrainId CoveredBy { get; set; } = TrainId.None;
+ public TrainId Covering { get; set; } = TrainId.None;
+
+ /// Livello d'avviso già notificato: 0 nessuno, 1 sotto la soglia d'avviso, 2 sotto la soglia critica.
+ public int AlertLevel { get; set; }
+
+ public long MaintenanceThisYear { get; set; }
+ public long MaintenanceLastYear { get; set; }
+ public int FailuresThisYear { get; set; }
+ public int FailuresTotal { get; set; }
+ public List History { get; } = [];
+
public bool IsRunning => State is TrainState.Moving or TrainState.Waiting or TrainState.Stalled;
}
@@ -139,6 +221,9 @@ public sealed class Line
public required string Color { get; set; }
public List Stops { get; } = [];
public bool Removed { get; set; }
+
+ /// Politica di manutenzione dei treni della linea (null = quella della compagnia).
+ public MaintenancePolicy? Policy { get; set; }
}
/// Tipo di carico di un pacchetto.
diff --git a/src/ViaFerrea.Core/Simulation/CommandProcessor.cs b/src/ViaFerrea.Core/Simulation/CommandProcessor.cs
index 8b224e3..cc99701 100644
--- a/src/ViaFerrea.Core/Simulation/CommandProcessor.cs
+++ b/src/ViaFerrea.Core/Simulation/CommandProcessor.cs
@@ -39,6 +39,12 @@ public static class CommandProcessor
EditLineCommand c => RailCommandHandlers.EditLine(w, company, c, Reply),
AssignTrainCommand c => RailCommandHandlers.AssignTrain(w, company, c, Reply),
SendToDepotCommand c => RailCommandHandlers.SendToDepot(w, company, c, Reply),
+ SetReserveCommand c => MaintenanceCommandHandlers.SetReserve(w, company, c, Reply),
+ SetMaintenancePolicyCommand c => MaintenanceCommandHandlers.SetPolicy(w, company, c, Reply),
+ ScheduleServiceCommand c => MaintenanceCommandHandlers.ScheduleService(w, company, c, ctx, Reply),
+ OrderPartsCommand c => MaintenanceCommandHandlers.OrderParts(w, company, c, Reply),
+ AcceptAgreementCommand c => MaintenanceCommandHandlers.AcceptAgreement(w, company, c, Reply),
+ RejectAgreementCommand c => MaintenanceCommandHandlers.RejectAgreement(w, company, c, Reply),
_ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"),
};
}
diff --git a/src/ViaFerrea.Core/Simulation/GameEvents.cs b/src/ViaFerrea.Core/Simulation/GameEvents.cs
index 9cbb9a3..7762c5d 100644
--- a/src/ViaFerrea.Core/Simulation/GameEvents.cs
+++ b/src/ViaFerrea.Core/Simulation/GameEvents.cs
@@ -27,6 +27,9 @@ public enum EntityKind : byte { None = 0, Town = 1, Industry = 2, Hub = 3, Compa
public sealed record GameEvent(long Day, EventKind Kind, EventSeverity Severity, string Text,
EntityKind Entity = EntityKind.None, int EntityIndex = -1, CompanyId Company = default);
+/// Avviso di manutenzione (10.3): treno sotto soglia, intervento in scadenza, ricambi esauriti.
+public sealed record FleetAlert(CompanyId Company, TrainId Train, DepotId Depot, string Component, double Condition, int DueDays, string Text);
+
/// Coda degli eventi in uscita: il server la svuota a ogni tick, i test la ispezionano.
public sealed class EventLog
{
diff --git a/src/ViaFerrea.Core/Simulation/MaintenanceCommandHandlers.cs b/src/ViaFerrea.Core/Simulation/MaintenanceCommandHandlers.cs
new file mode 100644
index 0000000..2c698d4
--- /dev/null
+++ b/src/ViaFerrea.Core/Simulation/MaintenanceCommandHandlers.cs
@@ -0,0 +1,135 @@
+using ViaFerrea.Core.Commands;
+using ViaFerrea.Core.Common;
+using ViaFerrea.Core.Data;
+using ViaFerrea.Core.Economy;
+using ViaFerrea.Core.Rail;
+using ViaFerrea.Core.Simulation.Systems;
+
+namespace ViaFerrea.Core.Simulation;
+
+/// Comandi della manutenzione della flotta (10.2–10.3) e delle convenzioni di pendolarismo (9).
+public static class MaintenanceCommandHandlers
+{
+ public static CommandResult SetReserve(World w, Company company, SetReserveCommand c, RailCommandHandlers.Reply reply)
+ {
+ if (!TryTrain(w, c.Train, company, out var train)) return reply(CommandError.NotFound, "Treno inesistente");
+ if (!c.Reserve)
+ {
+ train.Reserve = false;
+ return reply(CommandError.None, $"{train.Name} non è più una riserva");
+ }
+ if (train.Covering.IsValid) return reply(CommandError.NotAllowed, $"{train.Name} sta già coprendo una linea");
+ if (!train.HomeDepot.IsValid || !w.Network.IsAlive(w.Network.Depots[train.HomeDepot.Value]))
+ return reply(CommandError.NotAllowed, "Il treno non ha un deposito di appartenenza");
+ train.Reserve = true;
+ if (train.Line.IsValid)
+ {
+ train.Line = LineId.None;
+ w.LineGraphs.Touch();
+ }
+ var home = w.Network.Depots[train.HomeDepot.Value];
+ if (train.AtNode != home.Node && !train.InWorkshop && !train.MaintenanceDepot.IsValid)
+ {
+ train.GoingToDepot = home.Id;
+ if (train.State == TrainState.NoRoute) train.State = TrainState.Waiting;
+ }
+ return reply(CommandError.None, $"{train.Name} è una riserva del {home.Name}");
+ }
+
+ public static CommandResult SetPolicy(World w, Company company, SetMaintenancePolicyCommand c, RailCommandHandlers.Reply reply)
+ {
+ MaintenancePolicy? policy = c.Policy switch
+ {
+ "economy" => MaintenancePolicy.Economy,
+ "standard" => MaintenancePolicy.Standard,
+ "thorough" => MaintenancePolicy.Thorough,
+ "" or "inherit" => null,
+ _ => (MaintenancePolicy)255,
+ };
+ if (policy == (MaintenancePolicy)255) return reply(CommandError.InvalidArgument, "Politica: economy, standard, thorough o inherit");
+ string name = policy is { } p ? w.Data.Maintenance.Policy(p).NameIt : "quella generale";
+ switch (c.Scope)
+ {
+ case MaintenanceScope.Company:
+ if (policy is null) return reply(CommandError.InvalidArgument, "La flotta richiede una politica");
+ company.MaintenancePolicy = policy.Value;
+ return reply(CommandError.None, $"Politica di manutenzione della flotta: {name}");
+ case MaintenanceScope.Line:
+ if (c.Target < 0 || c.Target >= w.Lines.Count || w.Lines[c.Target].Owner != company.Id || w.Lines[c.Target].Removed)
+ return reply(CommandError.NotFound, "Linea inesistente");
+ w.Lines[c.Target].Policy = policy;
+ return reply(CommandError.None, $"{w.Lines[c.Target].Name}: politica {name}");
+ case MaintenanceScope.Train:
+ if (!TryTrain(w, new TrainId(c.Target), company, out var train)) return reply(CommandError.NotFound, "Treno inesistente");
+ train.Policy = policy;
+ return reply(CommandError.None, $"{train.Name}: politica {name}");
+ default:
+ return reply(CommandError.InvalidArgument, "Ambito sconosciuto");
+ }
+ }
+
+ public static CommandResult ScheduleService(World w, Company company, ScheduleServiceCommand c, WorldContext ctx, RailCommandHandlers.Reply reply)
+ {
+ if (!TryTrain(w, c.Train, company, out var train)) return reply(CommandError.NotFound, "Treno inesistente");
+ var m = w.Data.Maintenance;
+ int idx = m.InterventionIndex(c.Intervention);
+ if (idx < 0 || m.Interventions[idx].Effect is not (InterventionEffect.Inspection or InterventionEffect.Service or InterventionEffect.Overhaul))
+ return reply(CommandError.InvalidArgument, "Intervento: inspection, service o overhaul");
+ if (train.Vehicles.Count == 0) return reply(CommandError.NotAllowed, "Treno senza veicoli");
+ if (train.InWorkshop) return reply(CommandError.NotAllowed, $"{train.Name} è già in officina");
+ if (train.State == TrainState.Broken) return reply(CommandError.NotAllowed, $"{train.Name} attende il soccorso");
+ if (train.Failure != FailureKind.None) return reply(CommandError.NotAllowed, $"{train.Name} ha un guasto: prima la riparazione");
+ var def = m.Interventions[idx];
+ int parts = Fleet.PartsFor(w, train, def);
+ FleetMaintenanceSystem.CancelBooking(train);
+ if (!FleetMaintenanceSystem.Book(ctx, train, idx, parts, requireParts: true))
+ return reply(CommandError.Blocked, parts > 0 ? $"Nessun deposito raggiungibile con {parts} ricambi" : "Nessun deposito raggiungibile");
+ var depot = w.Network.Depots[train.MaintenanceDepot.Value];
+ return reply(CommandError.None, $"{train.Name}: {def.NameIt.ToLowerInvariant()} prenotato a {depot.Name}", depot.Id.Value);
+ }
+
+ public static CommandResult OrderParts(World w, Company company, OrderPartsCommand c, RailCommandHandlers.Reply reply)
+ {
+ if (!c.Depot.IsValid || c.Depot.Value >= w.Network.Depots.Count) return reply(CommandError.NotFound, "Deposito inesistente");
+ var d = w.Network.Depots[c.Depot.Value];
+ if (d.Owner != company.Id || !w.Network.IsAlive(d)) return reply(CommandError.NotFound, "Deposito inesistente");
+ int max = w.Data.Maintenance.Depots.MaxSpareParts;
+ if (c.Quantity < 0 || c.Quantity > max) return reply(CommandError.InvalidArgument, $"Scorta tra 0 e {max} casse");
+ d.PartsTarget = c.Quantity;
+ string unit = w.Data.Goods[w.Data.SparePartsGood].Unit;
+ return reply(CommandError.None, $"{d.Name}: scorta desiderata di ricambi {c.Quantity} {unit} (oggi {d.SpareParts})");
+ }
+
+ public static CommandResult AcceptAgreement(World w, Company company, AcceptAgreementCommand c, RailCommandHandlers.Reply reply)
+ {
+ var a = w.Agreements.FirstOrDefault(x => x.Id == c.Agreement);
+ if (a is null || a.Carrier != company.Id) return reply(CommandError.NotFound, "Convenzione inesistente");
+ if (a.State != AgreementState.Proposed) return reply(CommandError.NotAllowed, "La convenzione non è più in attesa di risposta");
+ var ab = w.Data.Balance.Employment.Agreements;
+ a.State = AgreementState.Active;
+ a.StartDay = w.Clock.Day;
+ a.EndDay = w.Clock.Day + (long)ab.DurationMonths * w.Calendar.DaysPerMonth;
+ a.Coverage = 1;
+ a.ShortDays = 0;
+ var ind = w.Industries[a.Industry.Value];
+ return reply(CommandError.None, $"Convenzione con {ind.Name}: {a.SeatsPerDay} posti al giorno per {a.MonthlyFee} al mese");
+ }
+
+ public static CommandResult RejectAgreement(World w, Company company, RejectAgreementCommand c, RailCommandHandlers.Reply reply)
+ {
+ var a = w.Agreements.FirstOrDefault(x => x.Id == c.Agreement);
+ if (a is null || a.Carrier != company.Id) return reply(CommandError.NotFound, "Convenzione inesistente");
+ if (a.State != AgreementState.Proposed) return reply(CommandError.NotAllowed, "La convenzione non è più in attesa di risposta");
+ a.State = AgreementState.Rejected;
+ a.EndDay = w.Clock.Day;
+ return reply(CommandError.None, $"Convenzione con {w.Industries[a.Industry.Value].Name} rifiutata");
+ }
+
+ private static bool TryTrain(World w, TrainId id, Company company, out Train train)
+ {
+ train = null!;
+ if (!id.IsValid || id.Value >= w.Trains.Count) return false;
+ train = w.Trains[id.Value];
+ return train.Owner == company.Id && !train.Removed;
+ }
+}
diff --git a/src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs b/src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs
index 340f127..268a462 100644
--- a/src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs
+++ b/src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs
@@ -4,6 +4,7 @@ using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Rail;
+using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
@@ -169,15 +170,33 @@ public static class RailCommandHandlers
BuiltDay = w.Clock.Day,
BuildCostCents = cost.Cents,
SpareParts = w.Data.Maintenance.Depots.InitialSpareParts,
+ PartsTarget = w.Data.Maintenance.Depots.TargetSpareParts,
};
+ InitDepot(w.Data, depot);
+ // la scorta iniziale è compresa nel prezzo del deposito
+ w.Goods.Imported[w.Data.SparePartsGood] += depot.SpareParts;
node.Depot = depot.Id;
w.Network.Depots.Add(depot);
w.NextIds.Depot = w.Network.Depots.Count;
+ foreach (var st in w.Network.Stations)
+ {
+ if (st.Owner == company.Id && w.Network.IsAlive(st) && Vec2.Distance(st.Position, depot.Position) <= sp.CatchmentKm * 1000)
+ UpdateCatchment(w, st);
+ }
w.Network.Touch();
w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.Construction);
return reply(CommandError.None, $"{name} costruito", depot.Id.Value, node.Id.Value);
}
+ /// Stalli e posti di lavoro del deposito secondo la dimensione (maintenance.json).
+ public static void InitDepot(GameData data, Depot depot)
+ {
+ var dp = data.Maintenance.Depots;
+ depot.Stalls = dp.StallsBySize.GetValueOrDefault(depot.Size, 0);
+ depot.JobsStaff = depot.Stalls * dp.StaffPerStall;
+ depot.JobsWorkers = depot.Stalls * dp.JobsWorkersPerStall;
+ }
+
public static CommandResult PlaceSignal(World w, Company company, PlaceSignalCommand c, Reply reply)
{
if (!TryEdge(w, c.Edge, company, out var edge)) return reply(CommandError.NotFound, "Binario inesistente");
@@ -244,6 +263,7 @@ public static class RailCommandHandlers
st.Industries.Clear();
st.Towns.Clear();
st.Hubs.Clear();
+ st.Depots.Clear();
net.Touch();
var refund = new Money(st.BuildCostCents) * refundShare;
w.Money.Transfer(Account.External, Account.Of(company.Id), refund, LedgerEntry.Construction);
@@ -257,7 +277,15 @@ public static class RailCommandHandlers
if (node.Depot != depot.Id) return reply(CommandError.NotFound, "Deposito già demolito");
if (w.Vehicles.Any(v => !v.Sold && v.Depot == depot.Id) || w.Trains.Any(t => !t.Removed && t.AtNode == depot.Node))
return reply(CommandError.Blocked, "Ci sono veicoli nel deposito");
+ if (depot.Jobs.Count > 0) return reply(CommandError.Blocked, "L'officina ha lavori in corso");
node.Depot = DepotId.None;
+ // prenotazioni verso l'officina demolita: il pianificatore ne sceglierà un'altra
+ foreach (var t in w.Trains)
+ {
+ if (!t.Removed && t.MaintenanceDepot == depot.Id && !t.InWorkshop) FleetMaintenanceSystem.CancelBooking(t);
+ if (!t.Removed && t.GoingToDepot == depot.Id) t.GoingToDepot = DepotId.None;
+ }
+ foreach (var st in net.Stations) st.Depots.Remove(depot.Id);
net.Touch();
var refund = new Money(depot.BuildCostCents) * refundShare;
w.Money.Transfer(Account.External, Account.Of(company.Id), refund, LedgerEntry.Construction);
@@ -343,7 +371,6 @@ public static class RailCommandHandlers
var cost = new Money(def.Price) * c.Count;
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}");
var created = new int[c.Count];
- var components = def.Kind == VehicleKind.Locomotive ? w.Data.Maintenance.Components.Locomotive : w.Data.Maintenance.Components.Car;
for (int i = 0; i < c.Count; i++)
{
var v = new Vehicle
@@ -353,8 +380,8 @@ public static class RailCommandHandlers
Owner = company.Id,
BoughtDay = w.Clock.Day,
Depot = c.Depot,
- Components = Enumerable.Repeat(100.0, components.Count).ToArray(),
};
+ Fleet.InitVehicle(w.Data, v, w.Clock.Day);
w.Vehicles.Add(v);
created[i] = v.Id.Value;
}
@@ -428,7 +455,7 @@ public static class RailCommandHandlers
public static void RecomputeTrain(World w, Train t)
{
var cx = w.Data.Construction.Physics.CxByKind;
- double mass = 0, locoMass = 0, power = 0, te = 0, length = 0, drag = 0, vmax = double.MaxValue;
+ double mass = 0, locoMass = 0, power = 0, te = 0, length = 0, drag = 0, vmax = double.MaxValue, capacity = 0;
bool electric = false;
int locos = 0;
foreach (var id in t.Vehicles)
@@ -438,6 +465,7 @@ public static class RailCommandHandlers
length += d.LengthM;
vmax = Math.Min(vmax, d.MaxSpeedKmh);
drag += cx[d.Kind.ToString().ToLowerInvariant()];
+ capacity += (d.Capacity ?? 0) + (d.PaxCapacity ?? 0) * w.Data.Construction.Physics.PassengerMassT;
if (d.Kind != VehicleKind.Locomotive) continue;
locos++;
locoMass += d.MassT;
@@ -454,6 +482,7 @@ public static class RailCommandHandlers
t.MaxSpeedKmh = vmax == double.MaxValue ? 0 : vmax;
t.NeedsElectrification = electric;
t.Locomotives = locos;
+ t.CapacityT = capacity;
}
public static CommandResult CreateLine(World w, Company company, CreateLineCommand c, Reply reply)
@@ -507,9 +536,17 @@ public static class RailCommandHandlers
if (!TryTrain(w, c.Train, company, out var train)) return reply(CommandError.NotFound, "Treno inesistente");
if (c.Line.IsValid && (c.Line.Value >= w.Lines.Count || w.Lines[c.Line.Value].Owner != company.Id || w.Lines[c.Line.Value].Removed))
return reply(CommandError.NotFound, "Linea inesistente");
+ // un'assegnazione esplicita chiude la copertura di una riserva
+ if (train.Covering.IsValid)
+ {
+ var covered = w.Trains[train.Covering.Value];
+ if (covered.CoveredBy == train.Id) covered.CoveredBy = TrainId.None;
+ train.Covering = TrainId.None;
+ }
+ if (c.Line.IsValid) train.Reserve = false;
train.Line = c.Line;
train.StopIndex = 0;
- train.GoingToDepot = DepotId.None;
+ if (!train.MaintenanceDepot.IsValid || train.GoingToDepot != train.MaintenanceDepot) train.GoingToDepot = DepotId.None;
if (train.State == TrainState.NoRoute) train.State = TrainState.Waiting;
w.LineGraphs.Touch();
return reply(CommandError.None, c.Line.IsValid ? $"{train.Name} assegnato a {w.Lines[c.Line.Value].Name}" : $"{train.Name} tolto dal servizio");
@@ -520,6 +557,16 @@ public static class RailCommandHandlers
if (!TryTrain(w, c.Train, company, out var train)) return reply(CommandError.NotFound, "Treno inesistente");
if (!c.Depot.IsValid || c.Depot.Value >= w.Network.Depots.Count || w.Network.Depots[c.Depot.Value].Owner != company.Id)
return reply(CommandError.NotFound, "Deposito inesistente");
+ if (train.InWorkshop) return reply(CommandError.NotAllowed, $"{train.Name} è in officina");
+ if (train.State == TrainState.Broken) return reply(CommandError.NotAllowed, $"{train.Name} attende il soccorso");
+ // il rientro voluto dal giocatore sostituisce l'intervento prenotato (il pianificatore lo riproporrà)
+ FleetMaintenanceSystem.CancelBooking(train);
+ if (train.Covering.IsValid)
+ {
+ var covered = w.Trains[train.Covering.Value];
+ if (covered.CoveredBy == train.Id) covered.CoveredBy = TrainId.None;
+ train.Covering = TrainId.None;
+ }
train.GoingToDepot = c.Depot;
train.Line = LineId.None;
if (train.State == TrainState.NoRoute) train.State = TrainState.Waiting;
@@ -534,6 +581,7 @@ public static class RailCommandHandlers
s.Industries.Clear();
s.Towns.Clear();
s.Hubs.Clear();
+ s.Depots.Clear();
if (w.Network.Nodes[s.Node.Value].Station != s.Id) return;
foreach (var i in w.Industries)
{
@@ -547,6 +595,10 @@ public static class RailCommandHandlers
{
if (Vec2.Distance(h.Position, s.Position) <= km * 1000) s.Hubs.Add(h.Id);
}
+ foreach (var d in w.Network.Depots)
+ {
+ if (d.Owner == s.Owner && w.Network.IsAlive(d) && Vec2.Distance(d.Position, s.Position) <= km * 1000) s.Depots.Add(d.Id);
+ }
}
private static string DefaultName(World w, Vec2 p, string kind)
diff --git a/src/ViaFerrea.Core/Simulation/SystemPipeline.cs b/src/ViaFerrea.Core/Simulation/SystemPipeline.cs
index c6c48e6..691c67c 100644
--- a/src/ViaFerrea.Core/Simulation/SystemPipeline.cs
+++ b/src/ViaFerrea.Core/Simulation/SystemPipeline.cs
@@ -31,6 +31,7 @@ public sealed class SystemPipeline(IReadOnlyList systems)
new TrainSystem(),
new StationSystem(),
new LocalTransportSystem(),
+ new FleetMaintenanceSystem(),
new DemandSystem(),
new EmploymentSystem(),
new IndustrySystem(),
diff --git a/src/ViaFerrea.Core/Simulation/Systems/EmploymentSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/EmploymentSystem.cs
index 45e66b0..cc929ab 100644
--- a/src/ViaFerrea.Core/Simulation/Systems/EmploymentSystem.cs
+++ b/src/ViaFerrea.Core/Simulation/Systems/EmploymentSystem.cs
@@ -8,9 +8,10 @@ namespace ViaFerrea.Core.Simulation.Systems;
///
/// Pendolarismo (guida, sezione 9): servizi cittadini, lavoratori in sede, contratti a piedi entro
/// il raggio pedonale e contratti su rotaia sul grafo delle linee (entro 60 minuti di orologio dei
-/// treni per i lavoratori, 90 per il personale, tratto a piedi compreso). Ogni mese ricostruisce i
-/// contratti a piedi, verifica quelli su rotaia e ne crea di nuovi; ogni giorno genera i pacchetti
-/// di passeggeri e aggiorna presenze e coperture.
+/// treni per i lavoratori, 90 per il personale, tratto a piedi compreso). I posti di lavoro sono le
+/// industrie e i depositi delle compagnie. Ogni mese ricostruisce i contratti a piedi, verifica quelli
+/// su rotaia, ne crea di nuovi, annota il motivo dei posti scoperti e gestisce le convenzioni; ogni
+/// giorno genera i pacchetti di passeggeri e aggiorna presenze, coperture e convenzioni attive.
///
public sealed class EmploymentSystem : ISimSystem
{
@@ -20,16 +21,57 @@ public sealed class EmploymentSystem : ISimSystem
{
if (!ctx.IsNewDay) return;
UpdatePresence(ctx);
- if (ctx.IsNewMonth) Rematch(ctx);
+ UpdateAgreements(ctx);
+ if (ctx.IsNewMonth)
+ {
+ Rematch(ctx);
+ MonthlyAgreements(ctx);
+ }
GeneratePassengers(ctx);
}
- /// Ricostruisce servizi cittadini e contratti a piedi.
+ /// Posti di lavoro che assumono, in ordine fisso: industrie attive, poi depositi esistenti.
+ public static void Workplaces(World w, List into)
+ {
+ into.Clear();
+ foreach (var ind in w.Industries)
+ {
+ if (!ind.Closed && ind.Level > 0) into.Add(ind);
+ }
+ foreach (var d in w.Network.Depots)
+ {
+ if (w.Network.IsAlive(d)) into.Add(d);
+ }
+ }
+
+ public static IWorkplace Workplace(World w, WorkplaceRef r) =>
+ r.Kind == WorkplaceKind.Industry ? w.Industries[r.Index] : w.Network.Depots[r.Index];
+
+ private static bool Hiring(World w, WorkplaceRef r) => r.Kind == WorkplaceKind.Industry
+ ? !w.Industries[r.Index].Closed && w.Industries[r.Index].Level > 0
+ : w.Network.IsAlive(w.Network.Depots[r.Index]);
+
+ /// Quota dei posti coperta da chi vive in sede: solo le industrie hanno alloggi propri.
+ private static double OnSiteShare(World w, IWorkplace p, PaxClass cls)
+ {
+ if (p is not Industry) return 0;
+ var ib = w.Data.Balance.Industry;
+ return cls == PaxClass.Staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare;
+ }
+
+ /// Vero se la stazione ha il posto di lavoro nel bacino.
+ private static bool Serves(Station s, IWorkplace p) => p switch
+ {
+ Industry ind => s.Industries.Contains(ind.Id),
+ Depot d => s.Depots.Contains(d.Id),
+ _ => false,
+ };
+
+ /// Ricostruisce servizi cittadini e contratti a piedi, poi abbina su rotaia.
public static void Rematch(WorldContext ctx)
{
var w = ctx.World;
var tb = w.Data.Balance.Town;
- var ib = w.Data.Balance.Industry;
var eb = w.Data.Balance.Employment;
w.Commutes.RemoveAll(c => c.Walking);
@@ -42,7 +84,7 @@ public sealed class EmploymentSystem : ISimSystem
town.EmployedWorkers = town.ServiceJobs;
town.EmployedStaff = 0;
}
- // i contratti su rotaia (F4) restano validi e occupano forza lavoro
+ // i contratti su rotaia restano validi e occupano forza lavoro
foreach (var c in w.Commutes)
{
var town = w.Towns[c.Town.Value];
@@ -55,29 +97,42 @@ public sealed class EmploymentSystem : ISimSystem
ind.ContractedWorkers = 0;
ind.ContractedStaff = 0;
}
+ foreach (var d in w.Network.Depots)
+ {
+ d.ContractedWorkers = 0;
+ d.ContractedStaff = 0;
+ }
foreach (var c in w.Commutes)
{
- if (c.Workplace.Kind != WorkplaceKind.Industry) continue;
- var ind = w.Industries[c.Workplace.Index];
- if (c.Category == PaxClass.Staff) ind.ContractedStaff += c.Headcount;
- else ind.ContractedWorkers += c.Headcount;
+ var p = Workplace(w, c.Workplace);
+ if (c.Category == PaxClass.Staff) p.ContractedStaff += c.Headcount;
+ else p.ContractedWorkers += c.Headcount;
+ }
+
+ var places = new List();
+ Workplaces(w, places);
+ foreach (var p in places)
+ {
+ p.WorkersReason = UncoveredReason.None;
+ p.StaffReason = UncoveredReason.None;
+ p.WorkersReasonLine = LineId.None;
+ p.StaffReasonLine = LineId.None;
}
var nearby = new List<(double Km, Town Town)>();
- foreach (var ind in w.Industries)
+ foreach (var p in places)
{
- if (ind.Closed || ind.Level <= 0) continue;
nearby.Clear();
foreach (var town in w.Towns)
{
- double km = w.TownEdgeDistanceKm(town, ind.Position);
+ double km = w.TownEdgeDistanceKm(town, p.Position);
if (km <= eb.WalkRadiusKm) nearby.Add((km, town));
}
if (nearby.Count == 0) continue;
nearby.Sort((a, b) => a.Km != b.Km ? a.Km.CompareTo(b.Km) : a.Town.Id.Value.CompareTo(b.Town.Id.Value));
- int openWorkers = OpenJobs(ind.JobsWorkers, ib.OnSiteWorkerShare, ind.ContractedWorkers);
- int openStaff = OpenJobs(ind.JobsStaff, ib.OnSiteStaffShare, ind.ContractedStaff);
+ int openWorkers = OpenJobs(p.JobsWorkers, OnSiteShare(w, p, PaxClass.Worker), p.ContractedWorkers);
+ int openStaff = OpenJobs(p.JobsStaff, OnSiteShare(w, p, PaxClass.Staff), p.ContractedStaff);
foreach (var (km, town) in nearby)
{
if (openWorkers > 0)
@@ -85,9 +140,9 @@ public sealed class EmploymentSystem : ISimSystem
int take = Math.Min(openWorkers, town.FreeWorkers(tb));
if (take > 0)
{
- AddWalking(w, town, ind, PaxClass.Worker, take, km, eb);
+ AddWalking(w, town, p, PaxClass.Worker, take, km, eb);
town.EmployedWorkers += take;
- ind.ContractedWorkers += take;
+ p.ContractedWorkers += take;
openWorkers -= take;
}
}
@@ -96,20 +151,20 @@ public sealed class EmploymentSystem : ISimSystem
int take = Math.Min(openStaff, town.FreeStaff(tb));
if (take > 0)
{
- AddWalking(w, town, ind, PaxClass.Staff, take, km, eb);
+ AddWalking(w, town, p, PaxClass.Staff, take, km, eb);
town.EmployedStaff += take;
- ind.ContractedStaff += take;
+ p.ContractedStaff += take;
openStaff -= take;
}
}
}
}
- MatchRail(ctx);
+ MatchRail(ctx, places);
}
///
- /// I contratti su rotaia restano validi se il percorso esiste ancora e la copertura non è
- /// rimasta sotto la soglia troppo a lungo; altrimenti si sciolgono e la città se ne lamenta.
+ /// I contratti su rotaia restano validi se il posto esiste, il percorso esiste ancora e la copertura
+ /// non è rimasta sotto la soglia troppo a lungo; altrimenti si sciolgono e la città se ne lamenta.
///
private static void ValidateRailContracts(WorldContext ctx)
{
@@ -120,32 +175,34 @@ public sealed class EmploymentSystem : ISimSystem
{
var c = w.Commutes[i];
if (c.Walking) continue;
+ bool hiring = Hiring(w, c.Workplace);
bool routeOk = c.HomeStation.IsValid && c.WorkStation.IsValid
&& w.LineGraphs.For(w, c.Carrier).From(c.HomeStation, LineGraph.PaxCargo(c.Category)).ContainsKey(c.WorkStation.Value);
bool coverageOk = c.LowCoverageDays < eb.DissolveDays;
- if (routeOk && coverageOk) continue;
+ if (hiring && routeOk && coverageOk) continue;
w.Commutes.RemoveAt(i);
var town = w.Towns[c.Town.Value];
town.WorkDissatisfaction = Math.Min(1, town.WorkDissatisfaction + tb.WorkSatisfactionPenalty);
+ string why = !hiring ? "il posto di lavoro non esiste più" : routeOk ? "i treni non li portano al lavoro" : "il collegamento non esiste più";
w.Events.Add(new GameEvent(ctx.Day, EventKind.Employment, EventSeverity.Warning,
- $"{c.Headcount} {(c.Category == PaxClass.Staff ? "tecnici" : "lavoratori")} di {town.Name} perdono il posto: " +
- (routeOk ? "i treni non li portano al lavoro" : "il collegamento non esiste più"), EntityKind.Town, town.Id.Value, c.Carrier));
+ $"{c.Headcount} {(c.Category == PaxClass.Staff ? "tecnici" : "lavoratori")} di {town.Name} perdono il posto: {why}",
+ EntityKind.Town, town.Id.Value, c.Carrier));
}
}
+ private readonly record struct Candidate(double Minutes, Town Town, Station Home, Station Work, Connection Conn);
+
///
/// Abbinamento su rotaia: per ogni posto scoperto, città con lavoratori liberi raggiungibili
/// entro il tempo massimo; in ordine di tempo di viaggio, senza superare la capacità residua
- /// delle linee del percorso.
+ /// delle linee del percorso. Se restano posti scoperti se ne annota il motivo.
///
- private static void MatchRail(WorldContext ctx)
+ private static void MatchRail(WorldContext ctx, List places)
{
var w = ctx.World;
var eb = w.Data.Balance.Employment;
var tb = w.Data.Balance.Town;
- var ib = w.Data.Balance.Industry;
var net = w.Network;
- if (w.Lines.Count == 0) return;
// posti già occupati sulle linee per classe
var usedWorkers = new Dictionary();
@@ -157,35 +214,35 @@ public sealed class EmploymentSystem : ISimSystem
foreach (var l in c.Route) used[l.Value] = used.GetValueOrDefault(l.Value) + c.Headcount;
}
- var candidates = new List<(double Minutes, Town Town, Station Home, Station Work, Connection Conn)>();
+ var candidates = new List();
var quota = new Dictionary();
- foreach (var ind in w.Industries)
+ foreach (var p in places)
{
- if (ind.Closed || ind.Level <= 0) continue;
- int openWorkers = OpenJobs(ind.JobsWorkers, ib.OnSiteWorkerShare, ind.ContractedWorkers);
- int openStaff = OpenJobs(ind.JobsStaff, ib.OnSiteStaffShare, ind.ContractedStaff);
- if (openWorkers <= 0 && openStaff <= 0) continue;
foreach (PaxClass cls in new[] { PaxClass.Worker, PaxClass.Staff })
{
- int open = cls == PaxClass.Staff ? openStaff : openWorkers;
+ int open = cls == PaxClass.Staff
+ ? OpenJobs(p.JobsStaff, OnSiteShare(w, p, cls), p.ContractedStaff)
+ : OpenJobs(p.JobsWorkers, OnSiteShare(w, p, cls), p.ContractedWorkers);
if (open <= 0) continue;
double maxMinutes = cls == PaxClass.Staff ? eb.StaffMaxMinutes : eb.WorkerMaxMinutes;
candidates.Clear();
+ bool anyStation = false;
foreach (var work in net.Stations)
{
- if (net.Nodes[work.Node.Value].Station != work.Id || !work.Industries.Contains(ind.Id)) continue;
+ if (!net.IsAlive(work) || !Serves(work, p)) continue;
+ anyStation = true;
var graph = w.LineGraphs.For(w, work.Owner);
- double walkWork = Vec2.Distance(work.Position, ind.Position) / 1000 / eb.WalkSpeedKmh * 60;
+ double walkWork = Vec2.Distance(work.Position, p.Position) / 1000 / eb.WalkSpeedKmh * 60;
foreach (var home in net.Stations)
{
- if (home.Owner != work.Owner || home.Id == work.Id || net.Nodes[home.Node.Value].Station != home.Id) continue;
+ if (home.Owner != work.Owner || home.Id == work.Id || !net.IsAlive(home)) continue;
if (!graph.From(home.Id, LineGraph.PaxCargo(cls)).TryGetValue(work.Id.Value, out var conn)) continue;
foreach (var tid in home.Towns)
{
var town = w.Towns[tid.Value];
double walkHome = w.TownEdgeDistanceKm(town, home.Position) / eb.WalkSpeedKmh * 60;
double minutes = conn.Minutes + walkHome + walkWork;
- if (minutes <= maxMinutes) candidates.Add((minutes, town, home, work, conn));
+ if (minutes <= maxMinutes) candidates.Add(new Candidate(minutes, town, home, work, conn));
}
}
}
@@ -197,52 +254,102 @@ public sealed class EmploymentSystem : ISimSystem
// in ordine di tempo di viaggio. Mai oltre la capacità residua delle linee del percorso.
quota.Clear();
int totalFree = 0;
+ bool anyServices = false;
foreach (var cand in candidates)
{
if (quota.ContainsKey(cand.Town.Id.Value)) continue;
int free = cls == PaxClass.Staff ? cand.Town.FreeStaff(tb) : cand.Town.FreeWorkers(tb);
quota[cand.Town.Id.Value] = free;
totalFree += free;
+ if (cand.Town.StaffPool(tb) > 0) anyServices = true;
+ }
+ if (totalFree <= 0)
+ {
+ // personale: mancano i servizi se nessuna città raggiungibile (in treno o a piedi) ne ha abbastanza
+ bool noServices = cls == PaxClass.Staff && !anyServices && (candidates.Count > 0 || NearbyTownsWithoutServices(w, p));
+ var reason = noServices ? UncoveredReason.NoStaffServices
+ : candidates.Count == 0 ? (anyStation ? UncoveredReason.NoTownInReach : UncoveredReason.NoStation)
+ : UncoveredReason.NoFreeWorkers;
+ SetReason(p, cls, reason, LineId.None);
+ continue;
}
- if (totalFree <= 0) continue;
int open0 = open;
+ var binding = LineId.None;
foreach (var cand in candidates)
{
int townQuota = (int)Math.Ceiling((double)open0 * quota[cand.Town.Id.Value] / totalFree);
- open -= Assign(w, ind, cls, cand, Math.Min(open, townQuota), usedWorkers, usedStaff, eb, tb);
+ open -= Assign(w, p, cls, cand, Math.Min(open, townQuota), usedWorkers, usedStaff, eb, tb, ref binding);
}
foreach (var cand in candidates)
{
if (open <= 0) break;
- open -= Assign(w, ind, cls, cand, open, usedWorkers, usedStaff, eb, tb);
+ open -= Assign(w, p, cls, cand, open, usedWorkers, usedStaff, eb, tb, ref binding);
}
+ if (open > 0)
+ SetReason(p, cls, binding.IsValid ? UncoveredReason.LineCapacity : UncoveredReason.NoFreeWorkers, binding);
}
}
}
- /// Crea un contratto per al più pendolari della città candidata.
- private static int Assign(World w, Industry ind, PaxClass cls,
- (double Minutes, Town Town, Station Home, Station Work, Connection Conn) cand, int limit,
- Dictionary usedWorkers, Dictionary usedStaff, EmploymentBalance eb, TownBalance tb)
+ // città a distanza pedonale prive di personale qualificato (servizi insufficienti)
+ private static bool NearbyTownsWithoutServices(World w, IWorkplace p)
+ {
+ var eb = w.Data.Balance.Employment;
+ var tb = w.Data.Balance.Town;
+ foreach (var town in w.Towns)
+ {
+ if (w.TownEdgeDistanceKm(town, p.Position) <= eb.WalkRadiusKm && town.StaffPool(tb) == 0) return true;
+ }
+ return false;
+ }
+
+ private static void SetReason(IWorkplace p, PaxClass cls, UncoveredReason reason, LineId line)
+ {
+ if (cls == PaxClass.Staff)
+ {
+ p.StaffReason = reason;
+ p.StaffReasonLine = line;
+ }
+ else
+ {
+ p.WorkersReason = reason;
+ p.WorkersReasonLine = line;
+ }
+ }
+
+ ///
+ /// Crea un contratto per al più pendolari della città candidata; se la
+ /// capacità di una linea limita l'assegnazione, la annota in .
+ ///
+ private static int Assign(World w, IWorkplace p, PaxClass cls, Candidate cand, int limit,
+ Dictionary usedWorkers, Dictionary usedStaff, EmploymentBalance eb, TownBalance tb, ref LineId binding)
{
if (limit <= 0) return 0;
int free = cls == PaxClass.Staff ? cand.Town.FreeStaff(tb) : cand.Town.FreeWorkers(tb);
var graph = w.LineGraphs.For(w, cand.Work.Owner);
var used = cls == PaxClass.Staff ? usedStaff : usedWorkers;
double capacity = double.MaxValue;
+ var tightest = LineId.None;
foreach (var hop in cand.Conn.Hops)
{
- if (!graph.DailyCapacity.TryGetValue(hop.Line.Value, out var cap)) { capacity = 0; break; }
- double seats = (cls == PaxClass.Staff ? cap.Staff : cap.Workers) * eb.LineCapacityUtilization;
- capacity = Math.Min(capacity, seats - used.GetValueOrDefault(hop.Line.Value));
+ double seats = 0;
+ if (graph.DailyCapacity.TryGetValue(hop.Line.Value, out var cap))
+ seats = (cls == PaxClass.Staff ? cap.Staff : cap.Workers) * eb.LineCapacityUtilization;
+ double residual = seats - used.GetValueOrDefault(hop.Line.Value);
+ if (residual < capacity)
+ {
+ capacity = residual;
+ tightest = hop.Line;
+ }
}
+ if (capacity < Math.Min(limit, free)) binding = tightest;
int take = Math.Min(limit, Math.Min(free, (int)Math.Floor(Math.Max(0, capacity))));
if (take <= 0) return 0;
var contract = new CommuteContract
{
Id = new ContractId(w.NextIds.Contract++),
Town = cand.Town.Id,
- Workplace = WorkplaceRef.Of(ind.Id),
+ Workplace = p.Ref,
Category = cls,
Headcount = take,
Carrier = cand.Work.Owner,
@@ -260,12 +367,12 @@ public sealed class EmploymentSystem : ISimSystem
if (cls == PaxClass.Staff)
{
cand.Town.EmployedStaff += take;
- ind.ContractedStaff += take;
+ p.ContractedStaff += take;
}
else
{
cand.Town.EmployedWorkers += take;
- ind.ContractedWorkers += take;
+ p.ContractedWorkers += take;
}
return take;
}
@@ -295,13 +402,13 @@ public sealed class EmploymentSystem : ISimSystem
}
}
- private static void AddWalking(World w, Town town, Industry ind, PaxClass category, int headcount, double km, EmploymentBalance eb)
+ private static void AddWalking(World w, Town town, IWorkplace p, PaxClass category, int headcount, double km, EmploymentBalance eb)
{
w.Commutes.Add(new CommuteContract
{
Id = new ContractId(w.NextIds.Contract++),
Town = town.Id,
- Workplace = WorkplaceRef.Of(ind.Id),
+ Workplace = p.Ref,
Category = category,
Headcount = headcount,
ExpectedMinutes = km / eb.WalkSpeedKmh * 60.0,
@@ -325,6 +432,11 @@ public sealed class EmploymentSystem : ISimSystem
ind.WorkersPresent = OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare);
ind.StaffPresent = OnSite(ind.JobsStaff, ib.OnSiteStaffShare);
}
+ foreach (var d in w.Network.Depots)
+ {
+ d.WorkersPresent = 0;
+ d.StaffPresent = 0;
+ }
foreach (var c in w.Commutes)
{
// a piedi si arriva sempre; su rotaia contano i pendolari consegnati, mediati su 30 giorni
@@ -334,18 +446,122 @@ public sealed class EmploymentSystem : ISimSystem
c.Coverage = Ema.Step(c.Coverage, ratio, eb.CoverageEmaDays);
if (!c.Walking) c.LowCoverageDays = c.Coverage < eb.DissolveCoverage ? c.LowCoverageDays + 1 : 0;
double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
+ var p = Workplace(w, c.Workplace);
+ if (c.Category == PaxClass.Staff) p.StaffPresent += present;
+ else p.WorkersPresent += present;
+ if (c.Walking) continue;
if (c.Workplace.Kind == WorkplaceKind.Industry)
{
- var ind = w.Industries[c.Workplace.Index];
- if (c.Category == PaxClass.Staff) ind.StaffPresent += present;
- else ind.WorkersPresent += present;
+ foreach (var a in w.Agreements)
+ {
+ if (a.State != AgreementState.Active || a.Industry.Value != c.Workplace.Index || a.Carrier != c.Carrier) continue;
+ a.ArrivedToday += c.ArrivedToday;
+ break;
+ }
}
- if (!c.Walking) c.ArrivedToday = 0;
+ c.ArrivedToday = 0;
}
foreach (var ind in w.Industries)
{
ind.WorkersPresent = Math.Min(ind.WorkersPresent, ind.JobsWorkers);
ind.StaffPresent = Math.Min(ind.StaffPresent, ind.JobsStaff);
}
+ foreach (var d in w.Network.Depots)
+ {
+ d.WorkersPresent = Math.Min(d.WorkersPresent, d.JobsWorkers);
+ d.StaffPresent = Math.Min(d.StaffPresent, d.JobsStaff);
+ }
+ }
+
+ // ------------------------------------------------------------------ convenzioni
+
+ /// Ogni giorno: copertura dei posti garantiti, rottura con penale, scadenze.
+ private static void UpdateAgreements(WorldContext ctx)
+ {
+ var w = ctx.World;
+ var eb = w.Data.Balance.Employment;
+ var ab = eb.Agreements;
+ foreach (var a in w.Agreements)
+ {
+ var ind = w.Industries[a.Industry.Value];
+ if (a.State == AgreementState.Proposed && ctx.Day - a.ProposedDay >= ab.ProposalDays)
+ {
+ a.State = AgreementState.Expired;
+ a.EndDay = ctx.Day;
+ continue;
+ }
+ if (a.State != AgreementState.Active) continue;
+ if (ind.Closed || ctx.Day >= a.EndDay)
+ {
+ a.State = AgreementState.Ended;
+ a.EndDay = ctx.Day;
+ w.Events.Add(new GameEvent(ctx.Day, EventKind.Employment, EventSeverity.Info,
+ $"Conclusa la convenzione con {ind.Name}", EntityKind.Industry, ind.Id.Value, a.Carrier));
+ continue;
+ }
+ double ratio = a.SeatsPerDay > 0 ? (double)a.ArrivedToday / a.SeatsPerDay : 1;
+ a.ArrivedToday = 0;
+ a.Coverage = Ema.Step(a.Coverage, ratio, eb.CoverageEmaDays);
+ a.ShortDays = a.Coverage < ab.MinCoverage ? a.ShortDays + 1 : 0;
+ if (a.ShortDays < ab.BreakDays) continue;
+ a.State = AgreementState.Broken;
+ a.EndDay = ctx.Day;
+ var penalty = a.MonthlyFee * ab.PenaltyMonths;
+ w.Money.Transfer(Account.Of(a.Carrier), Account.Of(ind.Id), penalty, LedgerEntry.Penalties);
+ w.Events.Add(new GameEvent(ctx.Day, EventKind.Employment, EventSeverity.Warning,
+ $"Convenzione con {ind.Name} saltata: capacità mancante per {ab.BreakDays} giorni, penale di {penalty}",
+ EntityKind.Industry, ind.Id.Value, a.Carrier));
+ }
+ }
+
+ /// Ogni mese: canoni delle convenzioni attive, pulizia di quelle vecchie, nuove proposte.
+ private static void MonthlyAgreements(WorldContext ctx)
+ {
+ var w = ctx.World;
+ var ab = w.Data.Balance.Employment.Agreements;
+ foreach (var a in w.Agreements)
+ {
+ if (a.State != AgreementState.Active) continue;
+ w.Money.Transfer(Account.Of(a.Industry), Account.Of(a.Carrier), a.MonthlyFee, LedgerEntry.Contracts);
+ }
+ long keep = (long)ab.CooldownMonths * w.Calendar.DaysPerMonth;
+ w.Agreements.RemoveAll(a => !a.Open && ctx.Day - a.EndDay > keep);
+
+ var rng = w.Stream("agreements");
+ foreach (var ind in w.Industries)
+ {
+ if (ind.Closed || ind.Level <= 0) continue;
+ foreach (var company in w.Companies)
+ {
+ if (company.Bankrupt) continue;
+ int seats = 0;
+ foreach (var c in w.Commutes)
+ {
+ if (!c.Walking && c.Carrier == company.Id && c.Workplace == ind.Ref) seats += c.Headcount;
+ }
+ if (seats < ab.MinSeats) continue;
+ bool known = false;
+ foreach (var a in w.Agreements)
+ {
+ if (a.Industry == ind.Id && a.Carrier == company.Id) known = true;
+ }
+ if (known || rng.NextDouble() >= ab.ProposalChance) continue;
+ var fee = new Money(ab.FeePerSeatPerMonth) * seats;
+ var agreement = new CommuteAgreement
+ {
+ Id = new AgreementId(w.NextIds.Agreement++),
+ Industry = ind.Id,
+ Carrier = company.Id,
+ SeatsPerDay = seats,
+ MonthlyFee = fee,
+ ProposedDay = ctx.Day,
+ State = AgreementState.Proposed,
+ };
+ w.Agreements.Add(agreement);
+ w.Events.Add(new GameEvent(ctx.Day, EventKind.Employment, EventSeverity.Opportunity,
+ $"{ind.Name} propone una convenzione: {seats} posti al giorno garantiti per {fee} al mese (Registro degli impieghi)",
+ EntityKind.Industry, ind.Id.Value, company.Id));
+ }
+ }
}
}
diff --git a/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs
index ba8f8ad..a0c5470 100644
--- a/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs
+++ b/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs
@@ -58,7 +58,8 @@ public sealed class FinanceSystem : ISimSystem
double days = w.Calendar.DaysPerYear;
foreach (var v in w.Vehicles)
{
- if (!v.Sold) _running[v.Owner.Value] += v.Def.RunningCostPerYear / days;
+ // il motore usurato consuma di più (10.1)
+ if (!v.Sold) _running[v.Owner.Value] += v.Def.RunningCostPerYear / days * Fleet.FuelFactor(w, v);
}
var sp = w.Data.Construction.Stations;
foreach (var s in w.Network.Stations)
diff --git a/src/ViaFerrea.Core/Simulation/Systems/Fleet.cs b/src/ViaFerrea.Core/Simulation/Systems/Fleet.cs
new file mode 100644
index 0000000..60cf018
--- /dev/null
+++ b/src/ViaFerrea.Core/Simulation/Systems/Fleet.cs
@@ -0,0 +1,313 @@
+using ViaFerrea.Core.Common;
+using ViaFerrea.Core.Data;
+using ViaFerrea.Core.Rail;
+
+namespace ViaFerrea.Core.Simulation.Systems;
+
+/// Scadenze di un treno in giorni (negative se già scadute).
+public readonly record struct FleetDues(double Inspection, double Service, double Overhaul, double Condition, bool ConditionIsBrakes);
+
+/// Prossimo intervento di un treno: indice in maintenance.json e giorni alla scadenza.
+public readonly record struct NextIntervention(int Intervention, double Days);
+
+///
+/// Formule della manutenzione della flotta (guida, sezione 10), senza stato: usura, rischio di
+/// guasto, effetti degli interventi, scadenze della politica e stima del pianificatore. Le usano
+/// il sistema di manutenzione, i comandi, il server (cartelle e registri) e i test.
+///
+public static class Fleet
+{
+ public const string Engine = "engine";
+ public const string Brakes = "brakes";
+ public const string Body = "body";
+
+ /// Componenti del tipo di veicolo (locomotiva o carro/carrozza).
+ public static List ComponentsOf(GameData d, VehicleDef def) =>
+ def.Kind == VehicleKind.Locomotive ? d.Maintenance.Components.Locomotive : d.Maintenance.Components.Car;
+
+ public static int ComponentIndex(List comps, string id)
+ {
+ for (int i = 0; i < comps.Count; i++)
+ {
+ if (comps[i].Id == id) return i;
+ }
+ return -1;
+ }
+
+ ///
+ /// Usura giornaliera di un componente: wBase × km/100 × (1 + 2·pendenza) × (1 + 0,5·alta velocità)
+ /// × (1 + 0,3·carico) × fattore d'età × difficoltà (km di servizio).
+ ///
+ public static double DailyWear(double wearPer100Km, double serviceKm, double gradeShare, double fastShare, double load,
+ double ageFactor, double difficulty, WearParams p) =>
+ wearPer100Km * serviceKm / 100 * (1 + p.GradientWeight * gradeShare) * (1 + p.HighSpeedWeight * fastShare)
+ * (1 + p.LoadWeight * load) * ageFactor * difficulty;
+
+ /// Rischio giornaliero di guasto: h0·exp(0,8·(50 − c)/10) sotto 50, altrimenti h0/4.
+ public static double Hazard(double condition, FailureParams f) =>
+ condition < f.Pivot ? f.H0 * DMath.Exp(f.Slope * (f.Pivot - condition) / f.Scale) : f.H0 / f.HealthyDivisor;
+
+ /// Fattore d'età: 1 fino alla vita utile, poi +0,5 ogni 5 anni, meno le riduzioni delle revisioni (minimo 1).
+ public static double AgeFactor(World w, Vehicle v) => AgeFactor(w.Data.Maintenance.Wear, v, w.Clock.Day, w.Calendar.DaysPerYear);
+
+ public static double AgeFactor(WearParams p, Vehicle v, long today, int daysPerYear)
+ {
+ double raw = RawAgeFactor(p, v, today, daysPerYear);
+ return Math.Max(1, raw - v.AgeFactorOffset);
+ }
+
+ private static double RawAgeFactor(WearParams p, Vehicle v, long today, int daysPerYear)
+ {
+ double age = (today - v.BoughtDay) / (double)daysPerYear;
+ double over = Math.Max(0, age - v.Def.LifeYears);
+ return 1 + p.AgeStepFactor * Math.Floor(over / p.AgeStepYears);
+ }
+
+ /// Condizione del treno: il componente più debole di tutti i suoi veicoli.
+ public static double TrainCondition(World w, Train t)
+ {
+ double min = 100;
+ foreach (var id in t.Vehicles) min = Math.Min(min, w.Vehicles[id.Value].Condition);
+ return min;
+ }
+
+ /// Veicolo e componente più deboli del treno.
+ public static (Vehicle? Vehicle, int Component, double Condition) Weakest(World w, Train t)
+ {
+ Vehicle? best = null;
+ int comp = -1;
+ double min = double.MaxValue;
+ foreach (var id in t.Vehicles)
+ {
+ var v = w.Vehicles[id.Value];
+ for (int j = 0; j < v.Components.Length; j++)
+ {
+ if (v.Components[j] >= min) continue;
+ min = v.Components[j];
+ best = v;
+ comp = j;
+ }
+ }
+ return (best, comp, best is null ? 100 : min);
+ }
+
+ /// Condizione media della flotta di una compagnia (media dei treni, ciascuno col suo componente più debole).
+ public static double FleetCondition(World w, CompanyId company)
+ {
+ double sum = 0;
+ int n = 0;
+ foreach (var t in w.Trains)
+ {
+ if (t.Removed || t.Owner != company || t.Vehicles.Count == 0) continue;
+ sum += TrainCondition(w, t);
+ n++;
+ }
+ return n == 0 ? 100 : sum / n;
+ }
+
+ /// Politica effettiva: quella del treno, altrimenti della linea, altrimenti della compagnia.
+ public static PolicyDef PolicyOf(World w, Train t)
+ {
+ var id = t.Policy ?? (t.Line.IsValid && t.Line.Value < w.Lines.Count ? w.Lines[t.Line.Value].Policy : null)
+ ?? w.Companies[t.Owner.Value].MaintenancePolicy;
+ return w.Data.Maintenance.Policy(id);
+ }
+
+ /// Scadenze della politica (ispezione, tagliando, revisione) e stima del pianificatore sulla condizione.
+ public static FleetDues Dues(World w, Train t)
+ {
+ var m = w.Data.Maintenance;
+ var policy = PolicyOf(w, t);
+ double f = policy.IntervalFactor;
+ long today = w.Clock.Day;
+ double kmPerDay = Math.Max(t.ServiceKmPerDay, 1e-6);
+ double ins = double.MaxValue, ser = double.MaxValue, ov = double.MaxValue, cond = double.MaxValue;
+ bool condBrakes = false;
+ foreach (var id in t.Vehicles)
+ {
+ var v = w.Vehicles[id.Value];
+ ins = Math.Min(ins, Math.Min((m.Intervals.InspectionKm * f - (v.OdometerKm - v.LastInspectionKm)) / kmPerDay,
+ m.Intervals.InspectionDays * f - (today - v.LastInspectionDay)));
+ ser = Math.Min(ser, Math.Min((m.Intervals.ServiceKm * f - (v.OdometerKm - v.LastServiceKm)) / kmPerDay,
+ m.Intervals.ServiceDays * f - (today - v.LastServiceDay)));
+ ov = Math.Min(ov, m.Intervals.OverhaulYears * f * w.Calendar.DaysPerYear - (today - v.LastOverhaulDay));
+ var comps = ComponentsOf(w.Data, v.Def);
+ for (int j = 0; j < v.Components.Length && j < comps.Count; j++)
+ {
+ double rate = j < v.WearEma.Length ? v.WearEma[j] : 0;
+ double c = v.Components[j];
+ double days;
+ if (c <= m.Planner.TargetCondition) days = -m.Planner.MarginDays;
+ else if (rate > 1e-9) days = (c - m.Planner.TargetCondition) / rate - m.Planner.MarginDays;
+ else continue;
+ if (days < cond)
+ {
+ cond = days;
+ condBrakes = comps[j].Id == Brakes;
+ }
+ }
+ }
+ return new FleetDues(ins, ser, ov, cond, condBrakes);
+ }
+
+ ///
+ /// Intervento che il pianificatore sceglierebbe: tra quelli scaduti il più completo (revisione,
+ /// tagliando, ispezione); se nessuno è scaduto, il più vicino. La stima sulla condizione chiede
+ /// un'ispezione se il componente critico sono i freni, altrimenti un tagliando.
+ ///
+ public static NextIntervention Next(World w, Train t)
+ {
+ var m = w.Data.Maintenance;
+ var d = Dues(w, t);
+ double service = Math.Min(d.Service, d.ConditionIsBrakes ? double.MaxValue : d.Condition);
+ double inspection = Math.Min(d.Inspection, d.ConditionIsBrakes ? d.Condition : double.MaxValue);
+ int ov = m.InterventionIndex("overhaul"), sv = m.InterventionIndex("service"), ins = m.InterventionIndex("inspection");
+ if (d.Overhaul <= 0) return new NextIntervention(ov, d.Overhaul);
+ if (service <= 0) return new NextIntervention(sv, service);
+ if (inspection <= 0) return new NextIntervention(ins, inspection);
+ if (d.Overhaul <= service && d.Overhaul <= inspection) return new NextIntervention(ov, d.Overhaul);
+ return service <= inspection ? new NextIntervention(sv, service) : new NextIntervention(ins, inspection);
+ }
+
+ /// Ricambi necessari per l'intervento: per veicolo; le riparazioni solo per il veicolo guasto.
+ public static int PartsFor(World w, Train t, InterventionDef def) =>
+ def.Effect == InterventionEffect.Repair ? def.SpareParts : def.SpareParts * t.Vehicles.Count;
+
+ /// Costo dell'intervento: quota del prezzo dei veicoli interessati × fattore di costo della politica.
+ public static Money CostOf(World w, Train t, InterventionDef def, PolicyDef policy)
+ {
+ long price = 0;
+ if (def.Effect == InterventionEffect.Repair)
+ {
+ if (t.FailedVehicle.IsValid) price = w.Vehicles[t.FailedVehicle.Value].Def.Price;
+ }
+ else
+ {
+ foreach (var id in t.Vehicles) price += w.Vehicles[id.Value].Def.Price;
+ }
+ return Money.FromCentsRounded(price * def.CostShare * policy.CostFactor);
+ }
+
+ /// Applica gli effetti dell'intervento ai veicoli del treno (10.2), scalati dalla politica.
+ public static void Apply(World w, Train t, InterventionDef def, PolicyDef policy)
+ {
+ var m = w.Data.Maintenance;
+ long today = w.Clock.Day;
+ double ef = policy.EffectFactor;
+ foreach (var id in t.Vehicles)
+ {
+ var v = w.Vehicles[id.Value];
+ var comps = ComponentsOf(w.Data, v.Def);
+ switch (def.Effect)
+ {
+ case InterventionEffect.Inspection:
+ for (int j = 0; j < v.Components.Length; j++)
+ {
+ if (comps[j].Id == Brakes) Raise(v, j, m.Inspection.BrakesTo, ef);
+ else Add(v, j, m.Inspection.OthersPlus * ef);
+ }
+ v.HazardReducedUntilDay = today + m.Inspection.HazardDays;
+ MarkInspection(v, today);
+ break;
+ case InterventionEffect.Service:
+ for (int j = 0; j < v.Components.Length; j++) Add(v, j, m.Service.Plus * ef);
+ MarkInspection(v, today);
+ MarkService(v, today);
+ break;
+ case InterventionEffect.Overhaul:
+ for (int j = 0; j < v.Components.Length; j++) Raise(v, j, 100, ef);
+ double raw = RawAgeFactor(m.Wear, v, today, w.Calendar.DaysPerYear);
+ v.AgeFactorOffset = Math.Min(v.AgeFactorOffset + m.Overhaul.AgeFactorReduction, Math.Max(0, raw - 1));
+ MarkInspection(v, today);
+ MarkService(v, today);
+ v.LastOverhaulDay = today;
+ break;
+ case InterventionEffect.Repair:
+ if (v.Id == t.FailedVehicle && t.FailedComponent >= 0 && t.FailedComponent < v.Components.Length)
+ Raise(v, t.FailedComponent, def.RestoreTo ?? 100, ef);
+ break;
+ case InterventionEffect.Replace:
+ // veicolo sostituito: nuovo di fabbrica
+ for (int j = 0; j < v.Components.Length; j++) v.Components[j] = 100;
+ v.BoughtDay = today;
+ v.OdometerKm = 0;
+ v.AgeFactorOffset = 0;
+ Array.Clear(v.WearEma);
+ MarkInspection(v, today);
+ MarkService(v, today);
+ v.LastOverhaulDay = today;
+ break;
+ }
+ }
+ }
+
+ private static void Raise(Vehicle v, int j, double target, double ef)
+ {
+ double c = v.Components[j];
+ if (target > c) v.Components[j] = Math.Min(100, c + (target - c) * ef);
+ }
+
+ private static void Add(Vehicle v, int j, double plus) => v.Components[j] = Math.Min(100, v.Components[j] + plus);
+
+ private static void MarkInspection(Vehicle v, long today)
+ {
+ v.LastInspectionDay = today;
+ v.LastInspectionKm = v.OdometerKm;
+ }
+
+ private static void MarkService(Vehicle v, long today)
+ {
+ v.LastServiceDay = today;
+ v.LastServiceKm = v.OdometerKm;
+ }
+
+ /// Prepara un veicolo nuovo: componenti a 100 e intervalli che partono dall'acquisto.
+ public static void InitVehicle(GameData d, Vehicle v, long today)
+ {
+ int n = ComponentsOf(d, v.Def).Count;
+ v.Components = Enumerable.Repeat(100.0, n).ToArray();
+ v.WearEma = new double[n];
+ v.LastInspectionDay = v.LastServiceDay = v.LastOverhaulDay = today;
+ v.LastInspectionKm = v.LastServiceKm = v.OdometerKm;
+ }
+
+ /// Fattore di comfort delle carrozze (cassa) sulla tariffa: 0,8 + 0,25·c/100.
+ public static double Comfort(World w, Train t, PaxClass cls)
+ {
+ var e = w.Data.Maintenance.Effects;
+ double sum = 0;
+ int n = 0;
+ foreach (var id in t.Vehicles)
+ {
+ var v = w.Vehicles[id.Value];
+ if (v.Def.Kind != VehicleKind.Coach || (v.Def.Class == PaxClass.Staff) != (cls == PaxClass.Staff)) continue;
+ int body = ComponentIndex(ComponentsOf(w.Data, v.Def), Body);
+ if (body < 0) continue;
+ sum += v.Components[body];
+ n++;
+ }
+ double c = n == 0 ? 100 : sum / n;
+ return e.ComfortMin + (e.ComfortMax - e.ComfortMin) * c / 100;
+ }
+
+ /// Moltiplicatore del consumo (costo d'esercizio) della locomotiva: 1 + 0,4·(1 − cMotore/100).
+ public static double FuelFactor(World w, Vehicle v)
+ {
+ if (v.Def.Kind != VehicleKind.Locomotive) return 1;
+ int engine = ComponentIndex(ComponentsOf(w.Data, v.Def), Engine);
+ if (engine < 0 || engine >= v.Components.Length) return 1;
+ return 1 + w.Data.Maintenance.Effects.FuelPenalty * (1 - v.Components[engine] / 100);
+ }
+
+ /// Posizione della testa del treno (nodo o punto lungo l'arco).
+ public static Vec2 Position(World w, Train t)
+ {
+ var net = w.Network;
+ if (t.AtNode.IsValid) return net.Nodes[t.AtNode.Value].Position;
+ if (t.Route.Count == 0 || t.RouteIndex >= t.Route.Count)
+ return t.HomeDepot.IsValid ? net.Depots[t.HomeDepot.Value].Position : default;
+ var step = t.Route[t.RouteIndex];
+ var e = net.Edges[step.Edge.Value];
+ return e.PointAt(step.Forward ? t.StepPos : e.Length - t.StepPos);
+ }
+}
diff --git a/src/ViaFerrea.Core/Simulation/Systems/FleetMaintenanceSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/FleetMaintenanceSystem.cs
new file mode 100644
index 0000000..ec9315f
--- /dev/null
+++ b/src/ViaFerrea.Core/Simulation/Systems/FleetMaintenanceSystem.cs
@@ -0,0 +1,640 @@
+using ViaFerrea.Core.Common;
+using ViaFerrea.Core.Data;
+using ViaFerrea.Core.Economy;
+using ViaFerrea.Core.Rail;
+
+namespace ViaFerrea.Core.Simulation.Systems;
+
+///
+/// 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.
+///
+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;
+ }
+
+ /// Velocità massima ridotta dal motore usurato e dal guasto lieve; tetto del rimorchio.
+ 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);
+ }
+
+ /// Applica un guasto al treno (usato anche dai test).
+ 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",
+ });
+
+ ///
+ /// 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.
+ ///
+ 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();
+ 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));
+ }
+
+ /// Il soccorso è arrivato: il treno viene rimorchiato verso un deposito per la riparazione.
+ 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);
+ }
+
+ /// Prenota l'intervento nel deposito migliore; se il treno è già lì entra subito in officina.
+ 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? _scratchRoute;
+ [ThreadStatic] private static double[]? _backlog;
+ [ThreadStatic] private static int[]? _reserved;
+
+ ///
+ /// 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).
+ ///
+ 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;
+ }
+
+ ///
+ /// Giorni di lavoro in coda e ricambi già destinati, per deposito (indice = id): lavori presenti
+ /// nelle officine e treni prenotati non ancora arrivati, escluso .
+ ///
+ 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;
+ }
+
+ /// Fattore di velocità del lavoro: 1 a personale completo, 1/2 a metà personale, 1/3 senza.
+ 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));
+ }
+
+ /// Fine della copertura: la riserva lascia la linea e rientra al suo deposito.
+ 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;
+ }
+ }
+}
diff --git a/src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs
index b93ec0e..b5f9d35 100644
--- a/src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs
+++ b/src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs
@@ -131,6 +131,72 @@ public sealed class StationSystem : ISimSystem
if (o == 0) ind.ShippedToday += units;
}
}
+ if (s.Hubs.Count > 0) ImportSpareParts(ctx, s, graph);
+ }
+
+ ///
+ /// Un hub nel bacino importa i ricambi richiesti dalle officine raggiungibili sulle linee (10.2):
+ /// li spedisce verso la stazione con più bisogno, entro la capacità mensile dell'hub.
+ ///
+ private void ImportSpareParts(WorldContext ctx, Station s, LineGraph graph)
+ {
+ var w = ctx.World;
+ int good = w.Data.SparePartsGood;
+ var reach = graph.From(s.Id, LineGraph.GoodCargo(good));
+ if (reach.Count == 0) return;
+ _candidates.Clear();
+ foreach (var key in reach.Keys) _candidates.Add((key, 0));
+ _candidates.Sort((a, b) => a.Station.CompareTo(b.Station));
+ Connection? best = null;
+ int bestNeed = 0;
+ foreach (var (sid, _) in _candidates)
+ {
+ var dest = w.Network.Stations[sid];
+ int need = DepotNeed(w, dest) - dest.Incoming[good];
+ if (need <= bestNeed) continue;
+ bestNeed = need;
+ best = reach[sid];
+ }
+ if (best is null) return;
+ foreach (var id in s.Hubs)
+ {
+ if (bestNeed <= 0) return;
+ var hub = w.Hubs[id.Value];
+ int units = Math.Min(bestNeed, hub.RemainingCapacity);
+ if (units <= 0) continue;
+ hub.UsedThisMonth += units;
+ hub.ImportedThisMonth[good] += units;
+ w.Goods.Imported[good] += units;
+ bestNeed -= units;
+ s.Waiting.Add(new Packet
+ {
+ Id = w.NextIds.Packet++,
+ Kind = PacketKind.Freight,
+ Good = good,
+ Units = units,
+ Origin = s.Id,
+ Destination = best.Destination,
+ HopLine = best.First.Line,
+ HopEnd = best.First.To,
+ CreatedTick = ctx.Tick,
+ ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay,
+ ExpectedDays = w.Calendar.TrainMinutesToDays(best.Minutes),
+ Contract = -1,
+ });
+ w.Network.Stations[best.Destination.Value].Incoming[good] += units;
+ }
+ }
+
+ /// Ricambi mancanti alle officine nel bacino della stazione (scorta desiderata − scorta).
+ private static int DepotNeed(World w, Station s)
+ {
+ int need = 0;
+ foreach (var id in s.Depots)
+ {
+ var d = w.Network.Depots[id.Value];
+ if (w.Network.IsAlive(d)) need += Math.Max(0, d.PartsTarget - d.SpareParts);
+ }
+ return need;
}
private Connection? BestDestination(World w, Station from, IReadOnlyDictionary reach, int good)
@@ -168,6 +234,11 @@ public sealed class StationSystem : ISimSystem
consumer = true;
need += w.Hubs[id.Value].RemainingCapacity;
}
+ if (good == w.Data.SparePartsGood && dest.Depots.Count > 0)
+ {
+ consumer = true;
+ need += DepotNeed(w, dest);
+ }
if (!consumer) continue;
need -= dest.Incoming[good];
double score = need / (1 + conn.Minutes / 60);
diff --git a/src/ViaFerrea.Core/Simulation/Systems/StationWork.cs b/src/ViaFerrea.Core/Simulation/Systems/StationWork.cs
index 63d16a1..16c70b1 100644
--- a/src/ViaFerrea.Core/Simulation/Systems/StationWork.cs
+++ b/src/ViaFerrea.Core/Simulation/Systems/StationWork.cs
@@ -29,7 +29,8 @@ public static class StationWork
t.ArrivedTick = ctx.Tick;
var stop = CurrentStop(w, t, s);
int moved = Unload(ctx, t, s, stop?.Unload ?? true);
- if (stop is null || stop.Load) moved += Load(ctx, t, s);
+ // un treno rimorchiato scarica ma non carica
+ if ((stop is null || stop.Load) && !t.Towed) moved += Load(ctx, t, s);
var sp = w.Data.Construction.Stations;
double minDwell = sp.MinDwellMinutes * 60 / w.Calendar.TrainSecondsPerTick;
t.DwellTicks = Math.Max(minDwell, moved / Math.Max(0.001, UnitsPerTick(w, t)));
@@ -140,7 +141,8 @@ public static class StationWork
}
// passeggeri
var cls = p.Kind == PacketKind.Staff ? PaxClass.Staff : PaxClass.Worker;
- var fareP = Tariffs.Passenger(p.Units, km, cls, days, p.ExpectedDays, tariffs, w.Difficulty.TariffMultiplier);
+ // il comfort delle carrozze (condizione della cassa) modula la tariffa (10.1)
+ var fareP = Tariffs.Passenger(p.Units, km, cls, days, p.ExpectedDays, tariffs, w.Difficulty.TariffMultiplier) * Fleet.Comfort(w, t, cls);
w.Money.Transfer(Account.External, Account.Of(company.Id), fareP, LedgerEntry.PassengerRevenue);
t.RevenueThisYear += fareP.Cents;
if (p.ReturnTrip || p.Contract < 0) return;
@@ -229,6 +231,22 @@ public static class StationWork
town.Stock[good] += take;
units -= take;
}
+ if (good == w.Data.SparePartsGood)
+ {
+ // ricambi per le officine del bacino: la compagnia li paga al prezzo globale
+ foreach (var id in s.Depots)
+ {
+ if (units <= 0) return 0;
+ var depot = w.Network.Depots[id.Value];
+ if (!w.Network.IsAlive(depot)) continue;
+ int take = Math.Min(units, Math.Max(0, depot.PartsTarget - depot.SpareParts));
+ if (take <= 0) continue;
+ depot.SpareParts += take;
+ units -= take;
+ var cost = Money.FromCentsRounded(take * w.Market.GlobalPrice[good]);
+ w.Money.Transfer(Account.Of(depot.Owner), Account.External, cost, LedgerEntry.FleetMaintenance);
+ }
+ }
foreach (var id in s.Hubs)
{
if (units <= 0) return 0;
diff --git a/src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs
index 5c84f11..1248f87 100644
--- a/src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs
+++ b/src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs
@@ -24,7 +24,7 @@ public sealed class TrainSystem : ISimSystem
private const byte HeldPlatform = 1;
private const byte HeldLock = 2;
- private double _dt, _brake, _g, _rolling, _aero, _adhesion, _stallSpeed, _stallSeconds, _margin, _maxTurn;
+ private double _dt, _brake, _g, _rolling, _aero, _adhesion, _stallSpeed, _stallSeconds, _margin, _maxTurn, _cosTurn, _gradeThreshold, _fastShare;
private int _ticksPerDay;
public void Step(WorldContext ctx)
@@ -42,6 +42,9 @@ public sealed class TrainSystem : ISimSystem
_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)
{
@@ -67,16 +70,51 @@ public sealed class TrainSystem : ISimSystem
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
/// Calcola il percorso verso la prossima destinazione del treno fermo in un nodo.
@@ -84,6 +122,8 @@ public sealed class TrainSystem : ISimSystem
{
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)
@@ -108,6 +148,13 @@ public sealed class TrainSystem : ISimSystem
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,
@@ -116,6 +163,7 @@ public sealed class TrainSystem : ISimSystem
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++)
{
@@ -139,6 +187,41 @@ public sealed class TrainSystem : ISimSystem
t.AtNode = NodeId.None;
}
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+ }
+
+ /// Nodo di destinazione corrente (fermata della linea, deposito o deposito di casa).
+ 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)
@@ -161,7 +244,7 @@ public sealed class TrainSystem : ISimSystem
var step = t.Route[t.RouteIndex];
var edge = net.Edges[step.Edge.Value];
double cond = ConstructionSystem.ConditionFactor(w, edge);
- double limit = Math.Min(t.MaxSpeedKmh, LimitAt(edge, step.Forward, t.StepPos) * cond) / 3.6;
+ 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));
@@ -236,6 +319,13 @@ public sealed class TrainSystem : ISimSystem
// 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);
@@ -256,9 +346,23 @@ public sealed class TrainSystem : ISimSystem
Arrive(ctx, t, node);
return;
}
- // binario di stazione attraversato (punto sicuro intermedio)
+ // 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) MarkLeft(t, HeldPlatform, through.Station.Value, -1, true, t.Odometer);
+ 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;
}
@@ -362,6 +466,13 @@ public sealed class TrainSystem : ISimSystem
{
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;
}
@@ -555,7 +666,7 @@ public sealed class TrainSystem : ISimSystem
{
double d = dist + e.S[i] - start;
if (d > horizon) break;
- double vl = Math.Min(t.MaxSpeedKmh, e.SpeedLimitKmh[i] * cond) / 3.6;
+ 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)));
}
}
@@ -566,7 +677,7 @@ public sealed class TrainSystem : ISimSystem
{
double d = dist + (sGeo - e.S[i]);
if (d > horizon) break;
- double vl = Math.Min(t.MaxSpeedKmh, e.SpeedLimitKmh[i - 1] * cond) / 3.6;
+ 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)));
}
}
diff --git a/src/ViaFerrea.Core/Simulation/World.cs b/src/ViaFerrea.Core/Simulation/World.cs
index 65a4929..26ca1e8 100644
--- a/src/ViaFerrea.Core/Simulation/World.cs
+++ b/src/ViaFerrea.Core/Simulation/World.cs
@@ -57,6 +57,9 @@ public sealed class World
public List Companies { get; } = [];
public List Commutes { get; } = [];
+ /// Convenzioni di pendolarismo (proposte, attive e concluse di recente).
+ public List Agreements { get; } = [];
+
/// Rete ferroviaria di tutte le compagnie.
public RailNetwork Network { get; } = new();
public List Vehicles { get; } = [];
@@ -74,6 +77,9 @@ public sealed class World
public GoodsCounters Goods { get; }
public EventLog Events { get; } = new();
+ /// Avvisi di manutenzione del giorno (non salvati): il server li inoltra come MaintenanceAlert.
+ public List Alerts { get; } = [];
+
public WorldContext Context { get; }
public SystemPipeline Pipeline { get; }
@@ -169,6 +175,10 @@ public sealed class World
}
}
foreach (var t in Towns) sum += t.Stock[good];
+ if (good == Data.SparePartsGood)
+ {
+ foreach (var d in Network.Depots) sum += d.SpareParts;
+ }
foreach (var ind in Industries)
{
int i = ind.InputIndexOf(good);
diff --git a/src/ViaFerrea.Server/GameHost.cs b/src/ViaFerrea.Server/GameHost.cs
index e46ddf8..4051f50 100644
--- a/src/ViaFerrea.Server/GameHost.cs
+++ b/src/ViaFerrea.Server/GameHost.cs
@@ -83,7 +83,7 @@ public sealed class GameHost : IDisposable
public long NowMs => _clock.ElapsedMilliseconds;
public bool Healthy => _thread is { IsAlive: true } && NowMs - Interlocked.Read(ref _lastHeartbeatMs) < 5000;
public double TickMs => BitConverter.Int64BitsToDouble(Interlocked.Read(ref _tickMsBits));
- public byte Speed => _speed;
+ public byte Speed => Volatile.Read(ref _speed);
private World InitialWorld()
{
diff --git a/src/ViaFerrea.Tools/Commands/BenchCommand.cs b/src/ViaFerrea.Tools/Commands/BenchCommand.cs
index 2d95af3..a807790 100644
--- a/src/ViaFerrea.Tools/Commands/BenchCommand.cs
+++ b/src/ViaFerrea.Tools/Commands/BenchCommand.cs
@@ -61,13 +61,20 @@ public sealed class BenchCommand : IToolCommand
Array.Clear(w.Pipeline.AllocatedBytes);
long gc0 = GC.CollectionCount(0);
long allocDay = 0, allocOther = 0;
+ var dayElapsed = new long[w.Pipeline.Systems.Count];
+ var snapshot = new long[w.Pipeline.Systems.Count];
for (int i = 0; i < ticks; i++)
{
bool dayTick = w.Clock.IsNewDay;
+ if (dayTick) Array.Copy(w.Pipeline.ElapsedTicks, snapshot, snapshot.Length);
long before = GC.GetAllocatedBytesForCurrentThread();
long start = Stopwatch.GetTimestamp();
w.Tick();
samples[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
+ if (dayTick)
+ {
+ for (int k = 0; k < snapshot.Length; k++) dayElapsed[k] += w.Pipeline.ElapsedTicks[k] - snapshot[k];
+ }
long bytes = GC.GetAllocatedBytesForCurrentThread() - before;
if (dayTick) allocDay += bytes;
else allocOther += bytes;
@@ -87,7 +94,9 @@ public sealed class BenchCommand : IToolCommand
{
double ms = w.Pipeline.ElapsedTicks[i] * 1000.0 / Stopwatch.Frequency / ticks;
double kb = w.Pipeline.AllocatedBytes[i] / 1024.0 / ticks;
- if (ms >= 0.005 || kb >= 0.01) Console.WriteLine($" {w.Pipeline.Systems[i].Name,-16} {ms,8:F3} ms/tick {kb,8:F2} KB/tick");
+ double dayMs = dayElapsed[i] * 1000.0 / Stopwatch.Frequency / days;
+ if (ms >= 0.005 || kb >= 0.01 || dayMs >= 0.5)
+ Console.WriteLine($" {w.Pipeline.Systems[i].Name,-16} {ms,8:F3} ms/tick {kb,8:F2} KB/tick {dayMs,8:F2} ms al cambio di giorno");
}
bool stalls = w.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal));
Console.WriteLine($" invarianti: denaro {(w.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}; avvisi di stallo: {(stalls ? "sì" : "no")}");
diff --git a/src/ViaFerrea.Tools/Commands/SimulateCommand.cs b/src/ViaFerrea.Tools/Commands/SimulateCommand.cs
index 037141e..4c3e85f 100644
--- a/src/ViaFerrea.Tools/Commands/SimulateCommand.cs
+++ b/src/ViaFerrea.Tools/Commands/SimulateCommand.cs
@@ -5,6 +5,7 @@ using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
+using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Tools.Commands;
@@ -91,8 +92,9 @@ public sealed class SimulateCommand : IToolCommand
long revenue = Company.Revenue(c.LastYearEntries);
double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0;
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}";
- csv.AppendLine(string.Join(';', year.ToString(It), c.Name, "", "", "", "", population.ToString(It), "", "", "",
- Dec(c.Cash.Lire), Dec(c.NetWorth.Lire), Dec(share), note));
+ bool fleet = w.Trains.Any(t => !t.Removed && t.Owner == c.Id && t.Vehicles.Count > 0);
+ csv.AppendLine(string.Join(';', year.ToString(It), c.Name, "", "", "", "", population.ToString(It), "",
+ fleet ? Dec(Fleet.FleetCondition(w, c.Id)) : "", "", Dec(c.Cash.Lire), Dec(c.NetWorth.Lire), Dec(share), note));
}
}
diff --git a/tests/ViaFerrea.Tests/Rail/CommutingTests.cs b/tests/ViaFerrea.Tests/Rail/CommutingTests.cs
index 8beaa20..cf708c9 100644
--- a/tests/ViaFerrea.Tests/Rail/CommutingTests.cs
+++ b/tests/ViaFerrea.Tests/Rail/CommutingTests.cs
@@ -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");
+ }
+ }
}
diff --git a/tests/ViaFerrea.Tests/Rail/MaintenanceTests.cs b/tests/ViaFerrea.Tests/Rail/MaintenanceTests.cs
new file mode 100644
index 0000000..587adbc
--- /dev/null
+++ b/tests/ViaFerrea.Tests/Rail/MaintenanceTests.cs
@@ -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");
+ }
+
+ /// Treno fermo nel deposito (senza binari), con i componenti impostati.
+ 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");
+ }
+
+ /// Avanza a tick finché il treno non è in marcia in linea, carico se richiesto.
+ 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));
+ }
+}
diff --git a/tests/ViaFerrea.Tests/Rail/RailFixture.cs b/tests/ViaFerrea.Tests/Rail/RailFixture.cs
index 6382512..eae7b12 100644
--- a/tests/ViaFerrea.Tests/Rail/RailFixture.cs
+++ b/tests/ViaFerrea.Tests/Rail/RailFixture.cs
@@ -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);
}
+
+ ///
+ /// 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 treni ciascuna,
+ /// tutti comprati nell'officina.
+ ///
+ 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();
+ 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);
+ }
}
+
+/// Identificativi della rete di prova della manutenzione.
+public sealed record MaintenanceNet(int Mine, int Mill, int Borgo, int Valdoria, int Officina, int Port, int[] Lines, List Trains, int PartsTrain);
diff --git a/tests/ViaFerrea.Tests/Scenarios/CommutingAcceptanceTests.cs b/tests/ViaFerrea.Tests/Scenarios/CommutingAcceptanceTests.cs
index 36e5ca2..51a1ebe 100644
--- a/tests/ViaFerrea.Tests/Scenarios/CommutingAcceptanceTests.cs
+++ b/tests/ViaFerrea.Tests/Scenarios/CommutingAcceptanceTests.cs
@@ -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).
///
- 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);
diff --git a/tests/ViaFerrea.Tests/Scenarios/MaintenanceAcceptanceTests.cs b/tests/ViaFerrea.Tests/Scenarios/MaintenanceAcceptanceTests.cs
new file mode 100644
index 0000000..4fbdae2
--- /dev/null
+++ b/tests/ViaFerrea.Tests/Scenarios/MaintenanceAcceptanceTests.cs
@@ -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
+{
+ /// Esito di tre anni di esercizio della rete di prova con due treni per linea.
+ 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");
+ }
+}
diff --git a/tests/ViaFerrea.Tests/Server/ServerTests.cs b/tests/ViaFerrea.Tests/Server/ServerTests.cs
index 53a4572..5ce89bf 100644
--- a/tests/ViaFerrea.Tests/Server/ServerTests.cs
+++ b/tests/ViaFerrea.Tests/Server/ServerTests.cs
@@ -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)