Merge remote-tracking branch 'origin/main' into claude/f6-pannelli
CI / Build e test (pull_request) Successful in 1m35s
CI / Immagine Docker (pull_request) Successful in 36s

# Conflicts:
#	client/RailEnterprise.Client/assets/i18n/strings.csv
#	client/RailEnterprise.Client/scripts/Main.cs
#	client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs
#	docs/ARCHITECTURE.md
#	docs/PROTOCOL.md
#	docs/STATE.md
#	src/RailEnterprise.Protocol/Client/ClientWorld.cs
This commit is contained in:
Alby96 committed 2026-11-08 14:38:09 +01:00
commit 767661957b
52 files changed
+4074 -91

No files matched your search

+17
View File
@@ -10,6 +10,8 @@ public sealed class AiFile
public required int Version { get; init; }
public required AiPlanningParams Planning { get; init; }
public required AiMarketParams Market { get; init; }
/// <summary>Rinnovo dei treni con veicoli superati (F6, ADR 0020).</summary>
public required AiRenewalParams Renewal { get; init; }
public required List<AiPersonalityDef> Personalities { get; init; }
public required List<string> CompanyNames { get; init; }
public required List<string> Colors { get; init; }
@@ -77,6 +79,21 @@ public sealed class AiPlanningParams
public required int FailedMemory { get; init; }
}
/// <summary>
/// Rinnovo della flotta delle IA (ADR 0020): ogni mese al più <see cref="MaxTrainsPerMonth"/> treni in
/// servizio con un veicolo superato vanno in officina per il rinnovo, se il veicolo è superato da almeno
/// <see cref="MinSupersededYears"/> anni o ha già consumato <see cref="MinAgeShareOfLife"/> della vita
/// utile, e se dopo la spesa netta (successori − rivendite) la cassa resta sopra
/// <see cref="CashReserveMultiple"/> volte la riserva dell'IA.
/// </summary>
public sealed class AiRenewalParams
{
public required double MinSupersededYears { get; init; }
public required double MinAgeShareOfLife { get; init; }
public required double CashReserveMultiple { get; init; }
public required int MaxTrainsPerMonth { get; init; }
}
/// <summary>Comportamento in borsa delle IA (12.1–12.2).</summary>
public sealed class AiMarketParams
{
@@ -97,6 +97,23 @@ public static class DataValidator
break;
}
}
// successori (ADR 0020): stessa categoria, introdotti dopo, senza richiedere la linea elettrificata in più
var vehicleById = new Dictionary<string, VehicleDef>(StringComparer.Ordinal);
foreach (var v in d.Vehicles) vehicleById.TryAdd(v.Id, v);
bool Electric(VehicleDef v) => v.Traction is { } tr && d.Eras.Tractions.Any(x => x.Id == tr && x.NeedsElectrification);
foreach (var v in d.Vehicles)
{
if (v.Successor is not { } sid) continue;
if (!vehicleById.TryGetValue(sid, out var next))
{
Err("vehicles.json", $"{v.Id}: successore sconosciuto «{sid}»");
continue;
}
if (next.Kind != v.Kind || next.WagonType != v.WagonType || next.Class != v.Class)
Err("vehicles.json", $"{v.Id}: il successore «{sid}» non è della stessa categoria");
if (next.EraFrom <= v.EraFrom) Err("vehicles.json", $"{v.Id}: il successore «{sid}» deve essere introdotto dopo");
if (Electric(next) && !Electric(v)) Err("vehicles.json", $"{v.Id}: il successore «{sid}» richiede la linea elettrificata");
}
foreach (var g in d.Goods)
{
bool carried = d.Vehicles.Any(v => v.Kind == VehicleKind.Wagon && v.WagonType == g.Wagon && (v.Goods?.Contains(g.Id) ?? false));
@@ -251,6 +268,8 @@ public static class DataValidator
{
if (i.Effect == InterventionEffect.Repair && i.RestoreTo is null) Err("maintenance.json", $"{i.Id}: una riparazione richiede restoreTo");
}
if (m.Interventions.Count(i => i.Effect == InterventionEffect.Renew) != 1)
Err("maintenance.json", "serve esattamente un intervento con effetto «renew» (rinnovo dei veicoli superati)");
RequireKeys("maintenance.json", "depots.stallsBySize", m.Depots.StallsBySize.Keys, SizeKeys, errors);
// --- IA, contratti, regioni
+2 -1
View File
@@ -28,7 +28,8 @@ public enum IronmanRule { No, Optional, Yes }
public enum DepletionRate { Slow, Normal, Fast }
public enum InterventionEffect { Inspection, Service, Overhaul, Repair, Replace }
/// <summary>Effetto di un intervento; Renew sostituisce i veicoli superati con il successore consigliato (ADR 0020).</summary>
public enum InterventionEffect { Inspection, Service, Overhaul, Repair, Replace, Renew }
public enum MaintenancePolicy { Economy, Standard, Thorough }
+4
View File
@@ -23,6 +23,8 @@ public sealed class GameData
public required IReadOnlyList<GoodDef> Goods { get; init; }
public required IReadOnlyList<IndustryDef> Industries { get; init; }
public required IReadOnlyList<VehicleDef> Vehicles { get; init; }
/// <summary>Obsolescenza dei modelli superati (vehicles.json, ADR 0020).</summary>
public required ObsolescenceParams Obsolescence { get; init; }
public required ErasFile Eras { get; init; }
public required TiersFile Tiers { get; init; }
public required BalanceFile Balance { get; init; }
@@ -114,6 +116,7 @@ public sealed class GameData
Goods = goods!.Goods,
Industries = industries!.Industries,
Vehicles = vehicles!.Vehicles,
Obsolescence = vehicles.Obsolescence,
Eras = eras!,
Tiers = tiers!,
Balance = balance!,
@@ -197,6 +200,7 @@ public sealed class GameData
_vehicleIndex[def.Id] = i;
def.GoodIndices = def.Goods?.Select(g => _goodIndex[g]).ToArray() ?? [];
}
foreach (var def in Vehicles) def.SuccessorDef = def.Successor is { } succ ? Vehicles[_vehicleIndex[succ]] : null;
for (int i = 0; i < Eras.TrackClasses.Count; i++) Eras.TrackClasses[i].Index = i;
for (int i = 0; i < Events.Events.Count; i++)
{
@@ -7,9 +7,24 @@ public sealed class VehiclesFile
{
[JsonPropertyName("$schema")] public string? Schema { get; init; }
public required int Version { get; init; }
/// <summary>Parametri dell'obsolescenza dei modelli superati (F6, ADR 0020).</summary>
public required ObsolescenceParams Obsolescence { get; init; }
public required List<VehicleDef> Vehicles { get; init; }
}
/// <summary>
/// Obsolescenza di un modello superato da un successore (ADR 0020): dal 1° gennaio dell'anno in cui il
/// successore entra in produzione il valore perde subito <see cref="ImmediateValueLoss"/> e poi si
/// ammortizza <see cref="DepreciationSpeed"/> volte più in fretta; gli interventi di manutenzione
/// costano <see cref="MaintenanceCostFactor"/> volte tanto.
/// </summary>
public sealed class ObsolescenceParams
{
public required double ImmediateValueLoss { get; init; }
public required double DepreciationSpeed { get; init; }
public required double MaintenanceCostFactor { get; init; }
}
/// <summary>Modello di veicolo: locomotiva, carro merci o carrozza.</summary>
public sealed class VehicleDef
{
@@ -17,8 +32,15 @@ public sealed class VehicleDef
public required VehicleKind Kind { get; init; }
[JsonPropertyName("name_it")] public required string NameIt { get; init; }
[JsonPropertyName("name_en")] public required string NameEn { get; init; }
/// <summary>Anno di introduzione: da quest'anno il modello si può comprare.</summary>
public required int EraFrom { get; init; }
/// <summary>Ultimo anno di produzione (assente: sempre in produzione); dall'anno dopo non si compra più.</summary>
public int? EraTo { get; init; }
/// <summary>
/// Modello che lo sostituisce (stessa categoria, introdotto dopo): dall'anno di introduzione del
/// successore questo modello è «superato» (ADR 0020).
/// </summary>
public string? Successor { get; init; }
public double PowerKw { get; init; }
public double TractiveEffortKn { get; init; }
public required double MaxSpeedKmh { get; init; }
@@ -39,6 +61,8 @@ public sealed class VehicleDef
public PaxClass? Class { get; init; }
[JsonIgnore] public int Index { get; internal set; }
/// <summary>Successore risolto (null se il modello non ne ha).</summary>
[JsonIgnore] public VehicleDef? SuccessorDef { get; internal set; }
/// <summary>Indici dei beni trasportabili (carri).</summary>
[JsonIgnore] public int[] GoodIndices { get; internal set; } = [];
}
@@ -0,0 +1,94 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Core.Economy;
/// <summary>
/// Stato di un veicolo per il rinnovo della flotta: età, condizione media, superato o no, successore
/// consigliato, valore di libro e di rivendita, moltiplicatore dei costi di manutenzione.
/// </summary>
public sealed record FleetVehicleLine(
VehicleId Id, VehicleDef Def, TrainId Train, DepotId Depot, double AgeYears, double Condition,
bool InProduction, bool Superseded, int? SupersededYear, VehicleDef? Successor,
Money BookValue, Money ResaleValue, double MaintenanceFactor);
/// <summary>Modello in produzione nell'anno, come lo mostra il catalogo d'acquisto: superato o no e successore consigliato.</summary>
public sealed record VehicleModelLine(VehicleDef Def, bool Superseded, int? SupersededYear, VehicleDef? Successor, int? LastYear);
/// <summary>
/// Treno con veicoli da rinnovare: quanti, spesa netta del rinnovo (successori − rivendite + lavoro), se la
/// cassa basta al netto degli altri rinnovi prenotati e se il rinnovo è già prenotato (in viaggio o in coda all'officina).
/// </summary>
public sealed record RenewalTrainLine(TrainId Train, int Vehicles, Money NetCost, bool Affordable, bool Booked);
/// <summary>
/// Quadro del rinnovo della flotta (F6, ADR 0020), in sola lettura: era in corso e prossima, veicoli
/// della compagnia con età, obsolescenza, successore e valori, catalogo dei modelli in produzione e
/// treni da rinnovare. Tutto viene da <see cref="Obsolescence"/>: lo stesso valore del patrimonio e
/// della rivendita. Il client lo mostra com'è.
/// </summary>
public sealed class FleetOutlook
{
public required long Day { get; init; }
public required int Year { get; init; }
public required CompanyId Company { get; init; }
public required EraDef Era { get; init; }
public required EraDef? NextEra { get; init; }
/// <summary>Veicoli non venduti della compagnia, in ordine di id.</summary>
public required List<FleetVehicleLine> Vehicles { get; init; }
/// <summary>Modelli in produzione nell'anno, nell'ordine di vehicles.json (i fuori produzione non ci sono).</summary>
public required List<VehicleModelLine> Models { get; init; }
/// <summary>Treni della compagnia con almeno un veicolo da rinnovare, in ordine di id.</summary>
public required List<RenewalTrainLine> Trains { get; init; }
/// <summary>Somma dei valori di libro: coincide con la voce «veicoli» dello stato patrimoniale calcolata oggi.</summary>
public Money BookValueTotal => new(Vehicles.Sum(v => v.BookValue.Cents));
public static FleetOutlook Build(World w, CompanyId company)
{
var d = w.Data;
int year = w.Clock.Year;
double daysPerYear = w.Calendar.DaysPerYear;
var vehicles = new List<FleetVehicleLine>();
foreach (var v in w.Vehicles)
{
if (v.Sold || v.Owner != company) continue;
bool superseded = Obsolescence.IsSuperseded(v.Def, year);
vehicles.Add(new FleetVehicleLine(
v.Id, v.Def, v.Train, v.Depot, (w.Clock.Day - v.BoughtDay) / daysPerYear, Obsolescence.AverageCondition(v),
Obsolescence.InProduction(v.Def, year), superseded, Obsolescence.SupersededYear(v.Def),
superseded ? Obsolescence.Recommended(v.Def, year) : null,
new Money(Obsolescence.BookValueCents(w, v)), Obsolescence.ResaleValue(w, v),
Obsolescence.MaintenanceCostFactor(d, v.Def, year)));
}
var models = new List<VehicleModelLine>();
foreach (var def in d.Vehicles)
{
if (!Obsolescence.InProduction(def, year)) continue;
bool superseded = Obsolescence.IsSuperseded(def, year);
models.Add(new VehicleModelLine(def, superseded, Obsolescence.SupersededYear(def),
superseded ? Obsolescence.Recommended(def, year) : null, def.EraTo));
}
var trains = new List<RenewalTrainLine>();
var c = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
// la cassa disponibile per un rinnovo esclude la spesa impegnata dagli altri già prenotati
var committed = Obsolescence.Committed(w, company);
foreach (var t in w.Trains)
{
if (t.Removed || t.Owner != company) continue;
var plan = Obsolescence.RenewalPlan(w, t);
if (plan.Count == 0) continue;
var net = Obsolescence.RenewalCost(w, t, plan);
var available = c is null ? Money.Zero : c.Cash - (committed - Obsolescence.Commitment(w, t));
trains.Add(new RenewalTrainLine(t.Id, plan.Count, net, c is not null && (!net.IsPositive || available >= net),
Obsolescence.RenewalBooked(w, t)));
}
return new FleetOutlook
{
Day = w.Clock.Day, Year = year, Company = company,
Era = EraSystem.CurrentEra(d, year), NextEra = EraSystem.NextEra(d, year),
Vehicles = vehicles, Models = models, Trains = trains,
};
}
}
@@ -192,10 +192,11 @@ internal sealed class AiAgent
/// <summary>Compra locomotiva e carri nel deposito del progetto, compone il treno e lo assegna alla linea.</summary>
private bool BuyTrain(AiProject project)
{
UpdateModels(project);
var loco = _w.Data.Vehicle(project.Loco);
var car = _w.Data.Vehicle(project.Car);
long price = Estimators.TrainPrice(loco, car, project.CarsPerTrain);
if (_c.Cash.Cents < price + Reserve() / 2 && !Borrow(price + Reserve() / 2 - _c.Cash.Cents, completing: project.Trains.Count == 0)) return false;
if (FreeCash() < price + Reserve() / 2 && !Borrow(price + Reserve() / 2 - FreeCash(), completing: project.Trains.Count == 0)) return false;
var ids = new List<VehicleId>();
var rl = Do(new BuyVehicleCommand(project.Loco, project.Depot, 1));
if (!rl.Ok) return false;
@@ -211,6 +212,31 @@ internal sealed class AiAgent
return true;
}
/// <summary>
/// Modelli superati o fuori produzione (ADR 0020): la linea passa al successore consigliato appena il
/// modello è superato, se il successore non ha trazione, potenza o velocità inferiori (comprarlo nuovo
/// vorrebbe dire perdere subito valore, pagare di più la manutenzione e rinnovarlo dopo pochi anni)
/// o, se è fuori produzione e la catena non offre un tale successore, al modello che l'IA sceglierebbe
/// oggi per un progetto nuovo. Così i treni aggiuntivi non nascono superati.
/// </summary>
private void UpdateModels(AiProject project)
{
int year = _ctx.Year;
var loco = _w.Data.Vehicle(project.Loco);
var newLoco = Obsolescence.IsSuperseded(loco, year) && Obsolescence.Recommended(loco, year) is { } rec && Obsolescence.NoWorseThan(rec, loco) ? rec : null;
if (newLoco is null && !Obsolescence.InProduction(loco, year)) newLoco = Estimators.BestLocomotive(_w, year);
if (newLoco is not null) project.Loco = newLoco.Id;
var car = _w.Data.Vehicle(project.Car);
var newCar = Obsolescence.IsSuperseded(car, year) && Obsolescence.Recommended(car, year) is { } recCar && Obsolescence.NoWorseThan(recCar, car) ? recCar : null;
if (newCar is null && !Obsolescence.InProduction(car, year))
{
newCar = car.Kind == VehicleKind.Coach
? Estimators.CoachFor(_w, car.Class ?? PaxClass.Worker, year)
: project.Good >= 0 ? Estimators.WagonFor(_w, project.Good, year) : null;
}
if (newCar is not null) project.Car = newCar.Id;
}
// ================================================================== mensile
public void Monthly()
@@ -240,6 +266,7 @@ internal sealed class AiAgent
}
Finance();
GrowLines();
RenewFleet();
StockMarket();
BuyIndustries();
if (!EnsurePartsSupply()) NewProject();
@@ -287,7 +314,7 @@ internal sealed class AiAgent
sources.Sort((a, b) => a.Km != b.Km ? a.Km.CompareTo(b.Km) : a.Key.CompareTo(b.Key));
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
if (loco is null) return false;
long budget = _c.Cash.Cents - Reserve() / 2 + LoanRoom();
long budget = FreeCash() - Reserve() / 2 + LoanRoom();
int tried = 0;
foreach (var (pos, key, km) in sources)
{
@@ -315,6 +342,12 @@ internal sealed class AiAgent
return false;
}
/// <summary>
/// Cassa libera: la cassa meno la spesa impegnata dai rinnovi prenotati e non ancora avviati, che si
/// paga giorni dopo a officina avviata (ADR 0020). Gli investimenti guardano questa, non la cassa intera.
/// </summary>
private long FreeCash() => _c.Cash.Cents - Obsolescence.Committed(_w, _c.Id).Cents;
/// <summary>Riserva di cassa: mesi di costi d'esercizio stimati dalla flotta e dalla rete.</summary>
private long Reserve()
{
@@ -401,6 +434,48 @@ internal sealed class AiAgent
}
}
// ================================================================== rinnovo della flotta (ADR 0020)
/// <summary>
/// Manda in officina per il rinnovo (intervento «renew», lo stesso comando ScheduleService del
/// giocatore) al più renewal.maxTrainsPerMonth treni in servizio, in ordine di id, che hanno un
/// veicolo superato da almeno renewal.minSupersededYears anni o con almeno renewal.minAgeShareOfLife
/// della vita utile, se il rinnovo non peggiora le prestazioni del treno
/// (<see cref="Obsolescence.KeepsPerformance"/>) e se dopo la spesa (successori − rivendite + lavoro)
/// la cassa libera resta sopra renewal.cashReserveMultiple volte la riserva. La spesa resta impegnata
/// (<see cref="FreeCash"/>) fino all'avvio dei lavori, così gli investimenti dello stesso mese non la riusano.
/// </summary>
private void RenewFleet()
{
var r = _w.Data.Ai.Renewal;
if (r.MaxTrainsPerMonth <= 0) return;
string renewal = _w.Data.Maintenance.Interventions[Obsolescence.RenewalIntervention(_w.Data)].Id;
double daysPerYear = _w.Calendar.DaysPerYear;
int scheduled = 0;
foreach (var t in _w.Trains)
{
if (scheduled >= r.MaxTrainsPerMonth) break;
if (t.Removed || t.Owner != _c.Id || !t.Line.IsValid || t.Reserve || t.InWorkshop || t.MaintenanceDepot.IsValid
|| t.Failure != FailureKind.None || t.State == TrainState.Broken) continue;
var plan = Obsolescence.RenewalPlan(_w, t);
if (plan.Count == 0) continue;
bool due = false;
foreach (var item in plan)
{
double age = (_ctx.Day - item.Old.BoughtDay) / daysPerYear;
if (Obsolescence.YearsSuperseded(_w, item.Old) >= r.MinSupersededYears || age >= r.MinAgeShareOfLife * item.Old.Def.LifeYears)
{
due = true;
break;
}
}
if (!due || !Obsolescence.KeepsPerformance(_w, t, plan)) continue;
long net = Obsolescence.RenewalCost(_w, t, plan).Cents;
if (FreeCash() - net < (long)(Reserve() * r.CashReserveMultiple)) continue;
if (Do(new ScheduleServiceCommand(t.Id, renewal)).Ok) scheduled++;
}
}
// ================================================================== borsa (12.2)
private void StockMarket()
@@ -412,13 +487,13 @@ internal sealed class AiAgent
if (other.Defunct || other.ControlledBy != _c.Id || other.IsPlayer) continue;
if (_ctx.Day - other.ControlSinceDay < sm.MergeAfterDays) continue;
double minority = (other.Shares.Outstanding - other.Shares.Of(_c.Id)) * other.SharePrice;
if (_c.Cash.Cents > minority + Reserve()) Do(new MergeCompanyCommand(other.Id));
if (FreeCash() > minority + Reserve()) Do(new MergeCompanyCommand(other.Id));
}
if (!_p.BuysShares) return;
// la Predatoria accumula quote dei concorrenti quotati (prima il giocatore) e poi lancia l'offerta;
// solo con una rete che rende e cassa abbondante, e solo in compagnie in utile
if (!_s.Projects.Any(p => p.Stage == AiProjectStage.Running) || _c.AnnualProfit <= 0) return;
long budget = (long)(Math.Max(0, _c.Cash.Cents - 3 * Reserve()) * _mk.SharesCashShare);
long budget = (long)(Math.Max(0, FreeCash() - 3 * Reserve()) * _mk.SharesCashShare);
if (budget <= 0) return;
foreach (var target in _w.Companies.OrderByDescending(t => t.IsPlayer).ThenBy(t => t.Id.Value))
{
@@ -452,7 +527,7 @@ internal sealed class AiAgent
long needed = (long)Math.Ceiling(goal * target.Shares.Outstanding) - target.Shares.Of(_c.Id);
if (needed <= 0) return false;
double cost = (double)needed * price;
if (_c.Cash.Cents < cost * _mk.BidCashMultiple + Reserve()) return false;
if (FreeCash() < cost * _mk.BidCashMultiple + Reserve()) return false;
return Do(new LaunchBidCommand(target.Id, new Money(price), goal)).Ok;
}
@@ -505,7 +580,7 @@ internal sealed class AiAgent
private void BuyIndustries()
{
if (!Tiers.Unlocks(_w, _c).BuyIndustry || _s.LastIndustryYear == _ctx.Year) return;
long budget = (long)(Math.Max(0, _c.Cash.Cents - Reserve()) * _mk.IndustryMaxCashShare);
long budget = (long)(Math.Max(0, FreeCash() - Reserve()) * _mk.IndustryMaxCashShare);
if (budget <= 0) return;
var served = Tiers.ServedStations(_w, _c.Id);
Industry? best = null;
@@ -571,7 +646,7 @@ internal sealed class AiAgent
{
int open = _s.Projects.Count(p => p.Stage is AiProjectStage.Construction or AiProjectStage.Equip);
if (open >= _plan.MaxConcurrentProjects) return;
long budget = _c.Cash.Cents - Reserve() + LoanRoom();
long budget = FreeCash() - Reserve() + LoanRoom();
if (budget <= 0) return;
var loco = Estimators.BestLocomotive(_w, _ctx.Year);
if (loco is null) return;
@@ -1147,7 +1222,7 @@ internal sealed class AiAgent
/// <summary>Apre i cantieri del progetto: stazioni, deposito, binario e raccordo del deposito.</summary>
private void Execute(Proposal p, DepotId? supply = null)
{
long need = p.Capital + Reserve() - _c.Cash.Cents;
long need = p.Capital + Reserve() - FreeCash();
if (need > 0 && !Borrow(need)) return;
var cand = p.Candidate;
var stationA = p.ExistingA;
@@ -30,8 +30,9 @@ public sealed class AiProject
public long CapitalCents { get; init; }
public long RevenuePerYearCents { get; init; }
public int TrainsPlanned { get; set; }
public required string Loco { get; init; }
public required string Car { get; init; }
/// <summary>Modelli dei treni della linea; se escono di produzione si passa al successore (ADR 0020).</summary>
public required string Loco { get; set; }
public required string Car { get; set; }
public int CarsPerTrain { get; init; }
/// <summary>Giorno prima del quale non si aggiungono treni (dopo uno stallo risolto).</summary>
public long GrowAfterDay { get; set; }
@@ -1,6 +1,7 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Core.Simulation;
@@ -64,26 +65,33 @@ public static class Estimators
return best;
}
/// <summary>Carro più economico che trasporta il bene nell'anno.</summary>
/// <summary>
/// Vero se il modello è superato e il suo successore consigliato si compra e non è peggiore: chi sceglie
/// un modello nuovo (IA, stime) lo scarta per non comprare un veicolo che perde subito valore (ADR 0020).
/// </summary>
private static bool Outdated(VehicleDef v, int year) =>
Obsolescence.IsSuperseded(v, year) && Obsolescence.Recommended(v, year) is { } next && Obsolescence.NoWorseThan(next, v);
/// <summary>Carro più economico che trasporta il bene nell'anno, esclusi i superati con un successore in produzione.</summary>
public static VehicleDef? WagonFor(World w, int good, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Wagon || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (v.Kind != VehicleKind.Wagon || v.EraFrom > year || (v.EraTo is { } to && year > to) || Outdated(v, year)) continue;
if (Array.IndexOf(v.GoodIndices, good) < 0) continue;
if (best is null || v.Price < best.Price) best = v;
}
return best;
}
/// <summary>Carrozza della classe indicata disponibile nell'anno.</summary>
/// <summary>Carrozza più economica della classe indicata disponibile nell'anno, esclusi i superati con un successore in produzione.</summary>
public static VehicleDef? CoachFor(World w, PaxClass cls, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Coach || v.Class != cls || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (v.Kind != VehicleKind.Coach || v.Class != cls || v.EraFrom > year || (v.EraTo is { } to && year > to) || Outdated(v, year)) continue;
if (best is null || v.Price < best.Price) best = v;
}
return best;
@@ -20,6 +20,8 @@ public enum EventKind : byte
Company = 9,
/// <summary>Evento del mondo (events.json, ADR 0017): inizio e fine.</summary>
World = 10,
/// <summary>Passaggio d'era e novità tecnologiche dell'anno (ADR 0020).</summary>
Technology = 11,
}
/// <summary>Riferimento facoltativo all'entità coinvolta.</summary>
@@ -74,13 +74,26 @@ public static class MaintenanceCommandHandlers
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 (idx < 0 || m.Interventions[idx].Effect is not (InterventionEffect.Inspection or InterventionEffect.Service or InterventionEffect.Overhaul or InterventionEffect.Renew))
return reply(CommandError.InvalidArgument, $"Intervento: inspection, service, overhaul o {m.Interventions.First(i => i.Effect == InterventionEffect.Renew).Id}");
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];
if (def.Effect == InterventionEffect.Renew)
{
// rinnovo (ADR 0020): serve almeno un veicolo superato con un successore in produzione e la cassa
// per la spesa netta, al netto degli altri rinnovi già prenotati; all'avvio dei lavori si ricontrolla
var plan = Obsolescence.RenewalPlan(w, train);
if (plan.Count == 0) return reply(CommandError.NotAllowed, $"{train.Name}: nessun veicolo superato da rinnovare");
var net = Obsolescence.RenewalCost(w, train, plan);
var committed = Obsolescence.Committed(w, company.Id, train);
if (net.IsPositive && company.Cash - committed < net)
return reply(CommandError.InsufficientFunds, committed.IsPositive
? $"Il rinnovo di {train.Name} costa {net} al netto delle rivendite: cassa insufficiente (già impegnati {committed} in altri rinnovi)"
: $"Il rinnovo di {train.Name} costa {net} al netto delle rivendite: cassa insufficiente");
}
int parts = Fleet.PartsFor(w, train, def);
FleetMaintenanceSystem.CancelBooking(train);
if (!FleetMaintenanceSystem.Book(ctx, train, idx, parts, requireParts: true))
@@ -408,14 +408,11 @@ public static class RailCommandHandlers
return reply(CommandError.None, $"Venduto per {value}");
}
/// <summary>Valore di rivendita: prezzo × (1 − età/vita, minimo 10 %) × condizione media.</summary>
public static Money ResaleValue(World w, Vehicle v)
{
double ageYears = (w.Clock.Day - v.BoughtDay) / (double)w.Calendar.DaysPerYear;
double residual = Math.Max(w.Data.Balance.Finance.BookValueFloor, 1 - ageYears / v.Def.LifeYears);
double condition = v.Components.Length == 0 ? 1 : v.Components.Average() / 100;
return new Money(v.Def.Price) * (residual * condition);
}
/// <summary>
/// Valore di rivendita: prezzo × residuo (1 − età/vita, minimo 10 %, più rapido per i modelli
/// superati) × condizione media; la curva è in <see cref="Obsolescence"/> (ADR 0020).
/// </summary>
public static Money ResaleValue(World w, Vehicle v) => Obsolescence.ResaleValue(w, v);
public static CommandResult ComposeTrain(World w, Company company, ComposeTrainCommand c, Reply reply)
{
@@ -9,7 +9,7 @@ namespace RailEnterprise.Core.Simulation;
/// inseriscono nella loro posizione quando vengono implementati:
/// Clock → Commands → Construction → Trains → Signals → Stations (+ trasporto locale)
/// → Maintenance → Demand → Commuting → Industries → IndustryMaintenance → Towns → Market
/// → Finance → StockMarket → AiAgents → Events → Contracts → Hash.
/// → Finance → StockMarket → AiAgents → Events → Eras (F6, ADR 0020) → Contracts → Hash.
/// </summary>
public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
{
@@ -43,6 +43,7 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
new StockMarketSystem(),
new AiSystem(),
new EventSystem(),
new EraSystem(),
new HashSystem(),
]);
@@ -0,0 +1,157 @@
using System.Globalization;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>Tipo di novità tecnologica di un anno (ADR 0020).</summary>
public enum TechKind : byte
{
Traction = 0,
Vehicle = 1,
BridgeType = 2,
TunnelLimit = 3,
TrackClass = 4,
Signal = 5,
Electrification = 6,
Good = 7,
Industry = 8,
}
/// <summary>Novità che un anno sblocca: tipo, id nei dati (vuoto per gallerie ed elettrificazione) e testo italiano.</summary>
public readonly record struct TechUnlock(TechKind Kind, string Id, string TextIt);
/// <summary>
/// Passaggi d'era e novità tecnologiche (F6, ADR 0020). Il 1° gennaio di ogni anno (non il giorno della
/// fondazione) annuncia, se ce ne sono, le novità di quell'anno lette dai dati: inizio di un'era
/// (eras.json), trazioni, veicoli introdotti, tipi di ponte, limiti delle gallerie, classi di binario,
/// segnali, elettrificazione, merci e industrie; poi i modelli che escono di produzione e quelli che
/// diventano superati. Nessun elenco è scritto a mano. La notizia (<see cref="EventKind.Technology"/>)
/// va a tutte le compagnie e la Cronaca del giocatore la registra come fatto saliente.
///
/// Il sistema non ha stato: la notizia nasce nel tick del cambio d'anno, che un salvataggio non ripete
/// (il mondo si salva tra un tick e l'altro), quindi esce una volta sola anche passando da un
/// salvataggio. Le ere continue della F7 aggiungeranno modelli ai dati: questo sistema li annuncerà
/// senza cambiare.
/// </summary>
public sealed class EraSystem : ISimSystem
{
public string Name => "Eras";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewYear || ctx.Day == 0) return;
Announce(ctx.World, ctx.Year);
}
/// <summary>Emette la notizia delle novità dell'anno (se ce ne sono) e la annota nella Cronaca del giocatore.</summary>
public static GameEvent? Announce(World w, int year)
{
string? text = NewsText(w.Data, year);
if (text is null) return null;
var era = EraStarting(w.Data, year);
var e = new GameEvent(w.Clock.Day, EventKind.Technology, EventSeverity.Opportunity, text, Company: CompanyId.None);
w.Events.Add(e);
if (w.Companies.Count > 0)
Corporate.Milestone(w, w.Player, era is not null ? $"inizia l'{era.NameIt}" : $"novità del {year}: {string.Join("; ", NewsParts(w.Data, year))}");
return e;
}
/// <summary>Era in corso nell'anno: l'ultima iniziata (la prima se l'anno la precede).</summary>
public static EraDef CurrentEra(GameData d, int year)
{
var eras = d.Eras.Eras;
var current = eras[0];
foreach (var e in eras)
{
if (e.From <= year) current = e;
}
return current;
}
/// <summary>Prossima era dopo l'anno (null all'ultima).</summary>
public static EraDef? NextEra(GameData d, int year) => d.Eras.Eras.FirstOrDefault(e => e.From > year);
/// <summary>Era che inizia esattamente nell'anno (null se nessuna).</summary>
public static EraDef? EraStarting(GameData d, int year) => d.Eras.Eras.FirstOrDefault(e => e.From == year);
/// <summary>Novità introdotte nell'anno, nell'ordine dei file dati.</summary>
public static List<TechUnlock> Unlocks(GameData d, int year)
{
var list = new List<TechUnlock>();
var eras = d.Eras;
foreach (var t in eras.Tractions)
{
if (t.From == year) list.Add(new TechUnlock(TechKind.Traction, t.Id.ToString().ToLowerInvariant(), $"trazione {t.NameIt.ToLowerInvariant()}"));
}
foreach (var v in d.Vehicles)
{
if (v.EraFrom == year) list.Add(new TechUnlock(TechKind.Vehicle, v.Id, v.Kind == VehicleKind.Locomotive ? $"locomotiva {v.NameIt}" : v.NameIt.ToLowerInvariant()));
}
foreach (var b in eras.BridgeTypes)
{
if (b.From == year) list.Add(new TechUnlock(TechKind.BridgeType, b.Id, $"ponti in {b.NameIt.ToLowerInvariant()} con campate fino a {Number(b.MaxSpanM)} m"));
}
foreach (var t in eras.TunnelLimits)
{
if (t.From == year) list.Add(new TechUnlock(TechKind.TunnelLimit, "", $"gallerie fino a {Number(t.MaxLengthM / 1000)} km"));
}
foreach (var c in eras.TrackClasses)
{
if (c.From == year) list.Add(new TechUnlock(TechKind.TrackClass, c.Id, $"binario {c.NameIt}"));
}
foreach (var s in eras.Signals)
{
if (s.From == year) list.Add(new TechUnlock(TechKind.Signal, s.Id, s.NameIt.ToLowerInvariant()));
}
if (eras.ElectrificationFrom == year) list.Add(new TechUnlock(TechKind.Electrification, "", "elettrificazione delle linee"));
foreach (var g in d.Goods)
{
if (g.Era == year) list.Add(new TechUnlock(TechKind.Good, g.Id, $"merce {g.NameIt.ToLowerInvariant()}"));
}
foreach (var i in d.Industries)
{
if (i.Era == year) list.Add(new TechUnlock(TechKind.Industry, i.Id, $"industria {i.NameIt.ToLowerInvariant()}"));
}
return list;
}
/// <summary>Modelli fuori produzione dall'anno (ultimo anno di produzione l'anno prima).</summary>
public static List<VehicleDef> Retired(GameData d, int year) => d.Vehicles.Where(v => v.EraTo == year - 1).ToList();
/// <summary>Modelli che nell'anno diventano superati (il successore è introdotto quell'anno).</summary>
public static List<VehicleDef> NewlySuperseded(GameData d, int year) => d.Vehicles.Where(v => v.SuccessorDef?.EraFrom == year).ToList();
/// <summary>Testo della notizia dell'anno, o null se l'anno non porta nulla di nuovo.</summary>
public static string? NewsText(GameData d, int year)
{
var era = EraStarting(d, year);
var parts = NewsParts(d, year);
if (era is null && parts.Count == 0) return null;
string head = era is not null ? $"Inizia l'{era.NameIt} ({year})" : $"Novità del {year}";
return parts.Count == 0 ? head : $"{head}: {string.Join("; ", parts)}";
}
/// <summary>Parti della notizia dell'anno: sblocchi, modelli superati, fuori produzione (vuota se nessuna).</summary>
public static List<string> NewsParts(GameData d, int year)
{
var unlocks = Unlocks(d, year);
var retired = Retired(d, year);
var superseded = NewlySuperseded(d, year);
var parts = new List<string>();
if (unlocks.Count > 0) parts.Add($"sblocca {Join(unlocks.Select(u => u.TextIt))}");
if (superseded.Count > 0)
parts.Add($"{(superseded.Count == 1 ? "modello superato" : "modelli superati")}: {Join(superseded.Select(v => $"{v.NameIt} (successore {v.SuccessorDef!.NameIt})"))}");
if (retired.Count > 0) parts.Add($"fuori produzione: {Join(retired.Select(v => v.NameIt))}");
return parts;
}
private static string Join(IEnumerable<string> items)
{
var list = items.ToList();
return list.Count <= 1 ? string.Concat(list) : $"{string.Join(", ", list.Take(list.Count - 1))} e {list[^1]}";
}
private static string Number(double value) =>
value.ToString("0.#", CultureInfo.InvariantCulture).Replace('.', ',');
}
@@ -221,8 +221,8 @@ public sealed class FinanceSystem : ISimSystem
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
double age = (today - v.BoughtDay) / daysPerYear;
values[v.Owner.Value][vehicles] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
// stessa curva della rivendita, con l'obsolescenza dei modelli superati (ADR 0020)
values[v.Owner.Value][vehicles] += Obsolescence.BookValueCents(w, v);
}
foreach (var ind in w.Industries)
{
@@ -173,27 +173,35 @@ public static class Fleet
public static int PartsFor(World w, Train t, InterventionDef def) =>
def.Effect == InterventionEffect.Repair ? def.SpareParts : def.SpareParts * t.Vehicles.Count;
/// <summary>Costo dell'intervento: quota del prezzo dei veicoli interessati × fattore di costo della politica.</summary>
/// <summary>
/// Costo dell'intervento: quota del prezzo dei veicoli interessati × fattore di costo della politica;
/// il prezzo di un modello superato conta maintenanceCostFactor volte (ricambi fuori catalogo, ADR 0020).
/// </summary>
public static Money CostOf(World w, Train t, InterventionDef def, PolicyDef policy)
{
long price = 0;
double price = 0;
int year = w.Clock.Year;
if (def.Effect == InterventionEffect.Repair)
{
if (t.FailedVehicle.IsValid) price = w.Vehicles[t.FailedVehicle.Value].Def.Price;
if (t.FailedVehicle.IsValid) price = WeightedPrice(w.Data, w.Vehicles[t.FailedVehicle.Value].Def, year);
}
else
{
foreach (var id in t.Vehicles) price += w.Vehicles[id.Value].Def.Price;
foreach (var id in t.Vehicles) price += WeightedPrice(w.Data, w.Vehicles[id.Value].Def, year);
}
return Money.FromCentsRounded(price * def.CostShare * policy.CostFactor);
}
private static double WeightedPrice(GameData d, VehicleDef def, int year) => def.Price * Obsolescence.MaintenanceCostFactor(d, def, year);
/// <summary>Applica gli effetti dell'intervento ai veicoli del treno (10.2), scalati dalla politica.</summary>
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;
// rinnovo: i veicoli superati si sono già sostituiti all'avvio dei lavori, quando si è pagato (ADR 0020)
if (def.Effect == InterventionEffect.Renew) return;
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
@@ -227,11 +235,17 @@ public static class Fleet
Raise(v, t.FailedComponent, def.RestoreTo ?? 100, ef);
break;
case InterventionEffect.Replace:
// veicolo sostituito: nuovo di fabbrica
// veicolo ricostruito: componenti nuovi di fabbrica. L'età contabile riparte solo se il
// modello è ancora in produzione: un modello che non si compra più non torna nuovo nel
// patrimonio (ADR 0020), l'usura però riparte da capo
for (int j = 0; j < v.Components.Length; j++) v.Components[j] = 100;
v.BoughtDay = today;
if (Obsolescence.InProduction(v.Def, w.Clock.Year))
{
v.BoughtDay = today;
v.AgeFactorOffset = 0;
}
else v.AgeFactorOffset = Math.Max(0, RawAgeFactor(m.Wear, v, today, w.Calendar.DaysPerYear) - 1);
v.OdometerKm = 0;
v.AgeFactorOffset = 0;
Array.Clear(v.WearEma);
MarkInspection(v, today);
MarkService(v, today);
@@ -489,7 +489,13 @@ public sealed class FleetMaintenanceSystem : ISimSystem
waitingParts = true;
continue;
}
Start(ctx, d, job, t, rate);
if (!Start(ctx, d, job, t, rate))
{
// rinnovo annullato all'avvio: il treno esce dall'officina senza lavori
d.Jobs.RemoveAt(i--);
inStall--;
continue;
}
}
job.Progress += rate;
if (job.Progress + 1e-9 < job.Days) continue;
@@ -507,19 +513,50 @@ public sealed class FleetMaintenanceSystem : ISimSystem
else if (!waitingParts) d.PartsAlerted = false;
}
private static void Start(WorldContext ctx, Depot d, WorkshopJob job, Train t, double rate)
/// <summary>Avvia il lavoro: preleva i ricambi e paga l'intervento. Falso se un rinnovo si annulla.</summary>
private static bool 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];
var cost = Fleet.CostOf(w, t, def, Fleet.PolicyOf(w, t));
List<RenewalItem>? plan = null;
if (def.Effect == InterventionEffect.Renew)
{
// rinnovo (ADR 0020): piano, spesa e cassa si controllano qui, quando si paga, non solo alla
// prenotazione: tra le due l'anno può cambiare il piano e la cassa può essersi spesa altrove
plan = Obsolescence.RenewalPlan(w, t);
var total = Obsolescence.NetCost(plan) + cost;
var company = w.Companies[t.Owner.Value];
string? why = plan.Count == 0 ? "nessun veicolo superato con un successore in produzione"
: total.IsPositive && company.Cash < total ? $"cassa insufficiente per la spesa netta di {total}" : null;
if (why is not null)
{
t.InWorkshop = false;
t.MaintenanceDepot = DepotId.None;
t.PlannedIntervention = -1;
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Warning,
$"{t.Name}: rinnovo annullato a {d.Name}, {why}", EntityKind.Train, t.Id.Value, t.Owner));
return false;
}
}
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 (plan is not null)
{
// i veicoli si sostituiscono all'avvio, con il piano appena pagato; i giorni d'officina sono la messa in servizio
var net = Obsolescence.NetCost(plan);
int renewed = Obsolescence.Renew(w, t, plan);
string what = renewed == 1 ? "1 veicolo sostituito" : $"{renewed} veicoli sostituiti";
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
$"{t.Name}: rinnovo avviato a {d.Name}, {what} (spesa netta {net + cost})", EntityKind.Train, t.Id.Value, t.Owner));
}
if (job.Days / rate >= m.Planner.ReserveMinDays) Cover(ctx, t, d);
return true;
}
private static void Complete(WorldContext ctx, Depot d, WorkshopJob job, Train t)
@@ -549,6 +586,11 @@ public sealed class FleetMaintenanceSystem : ISimSystem
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));
}
else if (def.Effect == InterventionEffect.Renew)
{
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
$"{t.Name}: rinnovo completato a {d.Name}", EntityKind.Train, t.Id.Value, t.Owner));
}
}
// ------------------------------------------------------------------ riserve
@@ -0,0 +1,226 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Time;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>Veicolo superato da rinnovare: il successore consigliato, il suo prezzo e la rivendita del vecchio.</summary>
public readonly record struct RenewalItem(Vehicle Old, VehicleDef Successor, Money Price, Money Resale);
/// <summary>
/// Produzione, obsolescenza e valore dei veicoli (F6, ADR 0020), senza stato: tutto discende dai dati
/// (anno di introduzione, ultimo anno di produzione, successore di vehicles.json), dal calendario e dal
/// giorno d'acquisto del veicolo. È l'unica fonte del valore di un veicolo: il valore di libro del
/// patrimonio (<see cref="FinanceSystem.BookValues"/>), la rivendita di <c>SellVehicle</c>, il rinnovo e
/// i quadri del client leggono le stesse funzioni.
///
/// Curva del valore (residuo r, frazione del prezzo, con il minimo <c>finance.bookValueFloor</c>):
/// - modello non superato: r = 1 − età / vita;
/// - superato (dal 1° gennaio dell'anno d'introduzione del successore, o dall'acquisto se è successivo):
/// r = (1 − perdita) × (1 − (età + (velocità − 1) × anni da superato) / vita), cioè un gradino di
/// <c>immediateValueLoss</c> e poi un ammortamento <c>depreciationSpeed</c> volte più rapido.
/// Valore di libro = prezzo × r; rivendita = prezzo × r × condizione media dei componenti.
/// </summary>
public static class Obsolescence
{
/// <summary>Vero se il modello si può comprare nell'anno: introdotto e non ancora fuori produzione.</summary>
public static bool InProduction(VehicleDef def, int year) => def.EraFrom <= year && (def.EraTo is not { } to || year <= to);
/// <summary>Vero se il successore del modello è già stato introdotto nell'anno.</summary>
public static bool IsSuperseded(VehicleDef def, int year) => def.SuccessorDef is { } s && s.EraFrom <= year;
/// <summary>Anno da cui il modello è superato (null se non ha successore).</summary>
public static int? SupersededYear(VehicleDef def) => def.SuccessorDef?.EraFrom;
/// <summary>
/// Successore consigliato nell'anno: il più recente della catena dei successori già introdotto e
/// ancora in produzione (null se il modello non è superato o nessun successore si può comprare).
/// </summary>
public static VehicleDef? Recommended(VehicleDef def, int year)
{
VehicleDef? best = null;
for (var s = def.SuccessorDef; s is not null && s.EraFrom <= year; s = s.SuccessorDef)
{
if (InProduction(s, year)) best = s;
}
return best;
}
/// <summary>Primo giorno in cui il modello è superato (long.MaxValue se non ha successore).</summary>
public static long SupersededDay(Calendar calendar, VehicleDef def) =>
def.SuccessorDef is { } s ? (long)(s.EraFrom - calendar.StartYear) * calendar.DaysPerYear : long.MaxValue;
/// <summary>Anni da quando il veicolo è superato (dal giorno d'acquisto se è successivo); 0 se non lo è.</summary>
public static double YearsSuperseded(World w, Vehicle v)
{
long since = SupersededDay(w.Calendar, v.Def);
long today = w.Clock.Day;
if (today < since) return 0;
return (today - Math.Max(v.BoughtDay, since)) / (double)w.Calendar.DaysPerYear;
}
/// <summary>Residuo del valore del veicolo oggi (frazione del prezzo di listino).</summary>
public static double Residual(World w, Vehicle v) => Residual(w.Data, w.Calendar, v.Def, v.BoughtDay, w.Clock.Day);
/// <summary>Residuo del valore di un veicolo del modello comprato in <paramref name="boughtDay"/>, al giorno <paramref name="today"/>.</summary>
public static double Residual(GameData d, Calendar calendar, VehicleDef def, long boughtDay, long today)
{
double daysPerYear = calendar.DaysPerYear;
double floor = d.Balance.Finance.BookValueFloor;
double age = (today - boughtDay) / daysPerYear;
long since = SupersededDay(calendar, def);
if (today < since) return Math.Max(floor, 1 - age / def.LifeYears);
var o = d.Obsolescence;
double years = (today - Math.Max(boughtDay, since)) / daysPerYear;
double effectiveAge = age + (o.DepreciationSpeed - 1) * years;
return Math.Max(floor, (1 - o.ImmediateValueLoss) * (1 - effectiveAge / def.LifeYears));
}
/// <summary>Valore di libro del veicolo in centesimi: prezzo × residuo (voce «veicoli» del patrimonio).</summary>
public static long BookValueCents(World w, Vehicle v) => (long)(v.Def.Price * Residual(w, v));
/// <summary>Condizione media dei componenti come frazione (1 se il veicolo non ne ha).</summary>
public static double AverageCondition(Vehicle v) => v.Components.Length == 0 ? 1 : v.Components.Average() / 100;
/// <summary>Valore di rivendita (mercato dell'usato): prezzo × residuo × condizione media.</summary>
public static Money ResaleValue(World w, Vehicle v) => new Money(v.Def.Price) * (Residual(w, v) * AverageCondition(v));
/// <summary>Moltiplicatore dei costi di manutenzione del modello nell'anno: maintenanceCostFactor se superato, altrimenti 1.</summary>
public static double MaintenanceCostFactor(GameData d, VehicleDef def, int year) =>
IsSuperseded(def, year) ? d.Obsolescence.MaintenanceCostFactor : 1;
/// <summary>
/// Veicoli del treno da rinnovare oggi, in ordine di composizione: quelli superati con un successore
/// consigliato in produzione, con il prezzo del successore e la rivendita del vecchio.
/// </summary>
public static List<RenewalItem> RenewalPlan(World w, Train t)
{
var list = new List<RenewalItem>();
int year = w.Clock.Year;
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
if (!IsSuperseded(v.Def, year) || Recommended(v.Def, year) is not { } next) continue;
list.Add(new RenewalItem(v, next, new Money(next.Price), ResaleValue(w, v)));
}
return list;
}
/// <summary>Spesa netta di un rinnovo: prezzi dei successori meno le rivendite (può essere negativa).</summary>
public static Money NetCost(List<RenewalItem> plan)
{
long cents = 0;
foreach (var item in plan) cents += item.Price.Cents - item.Resale.Cents;
return new Money(cents);
}
/// <summary>Indice in maintenance.json dell'intervento con effetto «renew» (il validatore ne garantisce uno).</summary>
public static int RenewalIntervention(GameData d) => d.Maintenance.Interventions.FindIndex(i => i.Effect == InterventionEffect.Renew);
/// <summary>Spesa complessiva del rinnovo del treno oggi: successori − rivendite + lavoro dell'officina.</summary>
public static Money RenewalCost(World w, Train t, List<RenewalItem> plan) =>
NetCost(plan) + Fleet.CostOf(w, t, w.Data.Maintenance.Interventions[RenewalIntervention(w.Data)], Fleet.PolicyOf(w, t));
/// <summary>Vero se il treno ha un rinnovo prenotato o in officina.</summary>
public static bool RenewalBooked(World w, Train t) => t.PlannedIntervention >= 0 && t.PlannedIntervention == RenewalIntervention(w.Data);
/// <summary>
/// Spesa impegnata dal rinnovo prenotato del treno e non ancora pagata: la spesa di oggi (se positiva)
/// finché i lavori non partono. All'avvio i veicoli si sostituiscono e il piano si svuota, quindi un
/// rinnovo già pagato non impegna più nulla.
/// </summary>
public static Money Commitment(World w, Train t)
{
if (t.Removed || !RenewalBooked(w, t)) return Money.Zero;
var plan = RenewalPlan(w, t);
if (plan.Count == 0) return Money.Zero;
var cost = RenewalCost(w, t, plan);
return cost.IsPositive ? cost : Money.Zero;
}
/// <summary>
/// Spesa impegnata dai rinnovi prenotati della compagnia e non ancora avviati, escluso eventualmente
/// un treno: va tolta dalla cassa prima di prenotarne un altro o di investire (ADR 0020).
/// </summary>
public static Money Committed(World w, CompanyId company, Train? except = null)
{
long cents = 0;
foreach (var t in w.Trains)
{
if (t != except && t.Owner == company) cents += Commitment(w, t).Cents;
}
return new Money(cents);
}
/// <summary>Vero se il modello <paramref name="next"/> non ha sforzo di trazione, potenza o velocità massima inferiori a <paramref name="old"/>.</summary>
public static bool NoWorseThan(VehicleDef next, VehicleDef old) =>
next.TractiveEffortKn >= old.TractiveEffortKn && next.PowerKw >= old.PowerKw && next.MaxSpeedKmh >= old.MaxSpeedKmh;
/// <summary>
/// Vero se il rinnovo non peggiora le prestazioni del treno: sforzo di trazione, potenza, velocità
/// massima e rapporto potenza/massa restano almeno quelli di oggi. Le IA rinnovano solo così; il
/// giocatore vede il successore con le sue prestazioni e decide da sé.
/// </summary>
public static bool KeepsPerformance(World w, Train t, List<RenewalItem> plan)
{
double te = 0, power = 0, mass = 0, vmax = double.MaxValue;
double te2 = 0, power2 = 0, mass2 = 0, vmax2 = double.MaxValue;
foreach (var id in t.Vehicles)
{
var def = w.Vehicles[id.Value].Def;
var next = def;
foreach (var item in plan)
{
if (item.Old.Id == id) next = item.Successor;
}
te += def.TractiveEffortKn; power += def.PowerKw; mass += def.MassT; vmax = Math.Min(vmax, def.MaxSpeedKmh);
te2 += next.TractiveEffortKn; power2 += next.PowerKw; mass2 += next.MassT; vmax2 = Math.Min(vmax2, next.MaxSpeedKmh);
}
if (mass <= 0 || mass2 <= 0) return true;
const double eps = 1e-9;
return te2 + eps >= te && power2 + eps >= power && vmax2 + eps >= vmax && power2 / mass2 + eps >= power / mass;
}
/// <summary>
/// Rinnovo in officina (intervento con effetto «renew»), all'avvio dei lavori: ogni veicolo del piano
/// si vende al valore di rivendita (voce «vendita di treni») e al suo posto, nella stessa posizione
/// della composizione, entra un veicolo nuovo del successore consigliato (voce «acquisto di treni»).
/// I veicoli venduti restano nell'elenco con <c>Sold</c>, come quelli di <c>SellVehicle</c>.
/// Il controllo della cassa spetta a chi chiama. Restituisce quanti veicoli sono stati sostituiti.
/// </summary>
public static int Renew(World w, Train t) => Renew(w, t, RenewalPlan(w, t));
/// <summary>Rinnovo con un piano già calcolato oggi (vedi <see cref="Renew(World, Train)"/>).</summary>
public static int Renew(World w, Train t, List<RenewalItem> plan)
{
if (plan.Count == 0) return 0;
var owner = Account.Of(t.Owner);
foreach (var item in plan)
{
var old = item.Old;
int index = t.Vehicles.IndexOf(old.Id);
var fresh = new Vehicle
{
Id = new VehicleId(w.Vehicles.Count),
Def = item.Successor,
Owner = old.Owner,
BoughtDay = w.Clock.Day,
Train = t.Id,
};
Fleet.InitVehicle(w.Data, fresh, w.Clock.Day);
w.Vehicles.Add(fresh);
old.Sold = true;
old.Train = TrainId.None;
old.Depot = DepotId.None;
t.Vehicles[index] = fresh.Id;
if (item.Resale.IsPositive) w.Money.Transfer(Account.External, owner, item.Resale, LedgerEntry.VehicleSale);
w.Money.Transfer(owner, Account.External, item.Price, LedgerEntry.VehiclePurchase);
}
w.NextIds.Vehicle = w.Vehicles.Count;
RailCommandHandlers.RecomputeTrain(w, t);
w.LineGraphs.Touch();
return plan.Count;
}
}
@@ -56,6 +56,9 @@ public sealed class ClientWorld(GameData data)
/// <summary>Quadro delle finanze (F6), su richiesta: lo usa il pannello «Finanze».</summary>
public FinanceReport? Finance { get; private set; }
/// <summary>Quadro del rinnovo della flotta (F6, ADR 0020), su richiesta: lo usano i pannelli Treni e Officine.</summary>
public FleetReport? Fleet { get; private set; }
/// <summary>Stato del server dall'ultimo Welcome (F6, ADR 0021): versione, sistema, attività, tick, sessioni.</summary>
public ServerInfo? Server { get; private set; }
@@ -154,6 +157,10 @@ public sealed class ClientWorld(GameData data)
Finance = m;
DetailVersion++;
return true;
case FleetReport m:
Fleet = m;
DetailVersion++;
return true;
case SaveList m:
Saves = m;
DetailVersion++;
@@ -180,6 +187,7 @@ public sealed class ClientWorld(GameData data)
Market = null;
Climb = null;
Finance = null;
Fleet = null;
Alerts.Clear();
Summary = m.Summary;
Server = m.Server;
+2
View File
@@ -47,6 +47,8 @@ public enum MessageId : ushort
ClimbReport = 134,
/// <summary>Quadro delle finanze: conto economico per voce, rating spiegato, prestiti, bancarotta (F6).</summary>
FinanceReport = 135,
/// <summary>Quadro del rinnovo della flotta: ere, veicoli superati, successori, valori (F6).</summary>
FleetReport = 136,
}
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
@@ -243,6 +243,8 @@ public enum DetailKind : byte
Climb = 8,
/// <summary>Quadro delle finanze (risposta FinanceReport, F6; Id ignorato).</summary>
Finance = 9,
/// <summary>Quadro del rinnovo della flotta (risposta FleetReport, F6, ADR 0020; Id ignorato).</summary>
Fleet = 10,
}
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
@@ -0,0 +1,161 @@
using RailEnterprise.Core.Common;
namespace RailEnterprise.Protocol.Messages;
// Messaggi della fase F6: ere e obsolescenza dei veicoli (ADR 0020). Il quadro del rinnovo della flotta
// arriva su richiesta (RequestDetail con DetailKind.Fleet) ed è calcolato dal server con FleetOutlook: il
// client lo mostra com'è, senza calcolare età, valori, successori o modelli in produzione.
/// <summary>
/// Veicolo della compagnia per il rinnovo: modello, treno o deposito, età e vita utile, condizione media
/// (0–1), produzione, obsolescenza (anno da cui è superato, 0 se non ha successore), successore consigliato
/// ("" se non superato o senza successore in produzione), valore di libro e di rivendita, moltiplicatore dei
/// costi di manutenzione.
/// </summary>
public sealed class FleetVehicleInfo
{
public int Vehicle { get; init; }
public string Type { get; init; } = "";
public int Train { get; init; } = -1;
public int Depot { get; init; } = -1;
public float AgeYears { get; init; }
public int LifeYears { get; init; }
public float Condition { get; init; }
public bool InProduction { get; init; }
public bool Superseded { get; init; }
public int SupersededYear { get; init; }
public string Successor { get; init; } = "";
public Money BookValue { get; init; }
public Money Resale { get; init; }
public float MaintenanceFactor { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Vehicle); w.String(Type); w.I32(Train); w.I32(Depot); w.F32(AgeYears); w.I32(LifeYears); w.F32(Condition);
w.Bool(InProduction); w.Bool(Superseded); w.I32(SupersededYear); w.String(Successor);
w.Money(BookValue); w.Money(Resale); w.F32(MaintenanceFactor);
w.Flags(0);
}
public static FleetVehicleInfo Read(ref SpanReader r)
{
var m = new FleetVehicleInfo
{
Vehicle = r.I32(), Type = r.String(), Train = r.I32(), Depot = r.I32(), AgeYears = r.F32(), LifeYears = r.I32(), Condition = r.F32(),
InProduction = r.Bool(), Superseded = r.Bool(), SupersededYear = r.I32(), Successor = r.String(),
BookValue = r.Money(), Resale = r.Money(), MaintenanceFactor = r.F32(),
};
r.Flags();
return m;
}
}
/// <summary>
/// Modello in produzione per il catalogo d'acquisto: superato o no, anno da cui lo è (0 se non ha
/// successore), successore consigliato, ultimo anno di produzione (0 se non previsto).
/// </summary>
public sealed class VehicleModelInfo
{
public string Type { get; init; } = "";
public bool Superseded { get; init; }
public int SupersededYear { get; init; }
public string Successor { get; init; } = "";
public int LastYear { get; init; }
public void Write(ref SpanWriter w)
{
w.String(Type); w.Bool(Superseded); w.I32(SupersededYear); w.String(Successor); w.I32(LastYear);
w.Flags(0);
}
public static VehicleModelInfo Read(ref SpanReader r)
{
var m = new VehicleModelInfo { Type = r.String(), Superseded = r.Bool(), SupersededYear = r.I32(), Successor = r.String(), LastYear = r.I32() };
r.Flags();
return m;
}
}
/// <summary>
/// Treno con veicoli superati da rinnovare: quanti, spesa netta (successori − rivendite + lavoro), se la cassa
/// basta al netto degli altri rinnovi prenotati e se il rinnovo è già prenotato (in viaggio o in coda all'officina).
/// </summary>
public sealed class RenewalTrainInfo
{
public int Train { get; init; }
public int Vehicles { get; init; }
public Money NetCost { get; init; }
public bool Affordable { get; init; }
public bool Booked { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Train); w.I32(Vehicles); w.Money(NetCost); w.Bool(Affordable); w.Bool(Booked);
w.Flags(0);
}
public static RenewalTrainInfo Read(ref SpanReader r)
{
var m = new RenewalTrainInfo { Train = r.I32(), Vehicles = r.I32(), NetCost = r.Money(), Affordable = r.Bool(), Booked = r.Bool() };
r.Flags();
return m;
}
}
/// <summary>
/// Quadro del rinnovo della flotta della compagnia della sessione (F6, ADR 0020): era in corso e prossima
/// (con l'anno; "" e 0 all'ultima), veicoli con età, obsolescenza, successore e valori, catalogo dei
/// modelli in produzione, treni da rinnovare con l'intervento «renewal».
/// </summary>
public sealed class FleetReport : IMessage
{
public MessageId Id => MessageId.FleetReport;
public long Day { get; init; }
public int Company { get; init; }
public int Year { get; init; }
public string Era { get; init; } = "";
public string NextEra { get; init; } = "";
public int NextEraYear { get; init; }
/// <summary>Id dell'intervento di rinnovo in maintenance.json (per ScheduleService).</summary>
public string RenewalIntervention { get; init; } = "";
public Money BookValueTotal { get; init; }
public List<FleetVehicleInfo> Vehicles { get; init; } = [];
public List<VehicleModelInfo> Models { get; init; } = [];
public List<RenewalTrainInfo> Trains { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I64(Day); w.I32(Company); w.I32(Year); w.String(Era); w.String(NextEra); w.I32(NextEraYear); w.String(RenewalIntervention);
w.Money(BookValueTotal);
w.Count(Vehicles.Count);
foreach (var v in Vehicles) v.Write(ref w);
w.Count(Models.Count);
foreach (var m in Models) m.Write(ref w);
w.Count(Trains.Count);
foreach (var t in Trains) t.Write(ref w);
w.Flags(0);
}
public static FleetReport Read(ref SpanReader r)
{
long day = r.I64();
int company = r.I32(), year = r.I32();
string era = r.String(), next = r.String();
int nextYear = r.I32();
string renewal = r.String();
var book = r.Money();
var vehicles = new List<FleetVehicleInfo>();
for (int n = r.Count(), i = 0; i < n; i++) vehicles.Add(FleetVehicleInfo.Read(ref r));
var models = new List<VehicleModelInfo>();
for (int n = r.Count(), i = 0; i < n; i++) models.Add(VehicleModelInfo.Read(ref r));
var trains = new List<RenewalTrainInfo>();
for (int n = r.Count(), i = 0; i < n; i++) trains.Add(RenewalTrainInfo.Read(ref r));
var m = new FleetReport
{
Day = day, Company = company, Year = year, Era = era, NextEra = next, NextEraYear = nextYear, RenewalIntervention = renewal,
BookValueTotal = book, Vehicles = vehicles, Models = models, Trains = trains,
};
r.Flags();
return m;
}
}
@@ -34,6 +34,7 @@ public static class MessageCodec
MessageId.MarketReport => MarketReport.Read(ref r),
MessageId.ClimbReport => ClimbReport.Read(ref r),
MessageId.FinanceReport => FinanceReport.Read(ref r),
MessageId.FleetReport => FleetReport.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),
+3
View File
@@ -689,6 +689,9 @@ public sealed class GameHost : IDisposable
case DetailKind.Finance:
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Finance(w, s.Company));
break;
case DetailKind.Fleet:
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.FleetRenewal(w, s.Company));
break;
}
}
+26
View File
@@ -664,6 +664,32 @@ public static class Projection
};
}
/// <summary>Quadro del rinnovo della flotta per la compagnia della sessione (FleetOutlook, ADR 0020).</summary>
public static FleetReport FleetRenewal(World w, CompanyId company)
{
var report = FleetOutlook.Build(w, company);
var interventions = w.Data.Maintenance.Interventions;
return new FleetReport
{
Day = report.Day, Company = report.Company.Value, Year = report.Year, Era = report.Era.Id,
NextEra = report.NextEra?.Id ?? "", NextEraYear = report.NextEra?.From ?? 0,
RenewalIntervention = interventions.First(i => i.Effect == InterventionEffect.Renew).Id,
BookValueTotal = report.BookValueTotal,
Vehicles = report.Vehicles.Select(v => new FleetVehicleInfo
{
Vehicle = v.Id.Value, Type = v.Def.Id, Train = v.Train.Value, Depot = v.Depot.Value, AgeYears = (float)v.AgeYears,
LifeYears = v.Def.LifeYears, Condition = (float)v.Condition, InProduction = v.InProduction, Superseded = v.Superseded,
SupersededYear = v.SupersededYear ?? 0, Successor = v.Successor?.Id ?? "", BookValue = v.BookValue, Resale = v.ResaleValue,
MaintenanceFactor = (float)v.MaintenanceFactor,
}).ToList(),
Models = report.Models.Select(m => new VehicleModelInfo
{
Type = m.Def.Id, Superseded = m.Superseded, SupersededYear = m.SupersededYear ?? 0, Successor = m.Successor?.Id ?? "", LastYear = m.LastYear ?? 0,
}).ToList(),
Trains = report.Trains.Select(t => new RenewalTrainInfo { Train = t.Train.Value, Vehicles = t.Vehicles, NetCost = t.NetCost, Affordable = t.Affordable, Booked = t.Booked }).ToList(),
};
}
/// <summary>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
{