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);
}
}