F6: ere e obsolescenza, correzioni della revisione

Due revisori hanno trovato 12 rilievi. I principali:
- Il rinnovo si ricontrolla all'avvio dei lavori: piano, spesa e cassa
  possono cambiare tra prenotazione e avvio. Se la cassa non basta il
  rinnovo si annulla senza pagare e con un avviso, così non va mai in
  scoperto.
- La cassa impegnata dai rinnovi prenotati e non ancora avviati
  (Obsolescence.Committed) conta per il giocatore e per le IA, così la
  stessa cassa non si spende due volte nello stesso mese.
- Le IA comprano il successore solo se non peggiora il treno, e rinnovano
  solo se le prestazioni restano almeno quelle di oggi.
- Dopo un deragliamento la ricostruzione non ringiovanisce nel patrimonio
  un modello fuori produzione.
- Quadro della flotta e pannelli mostrano un rinnovo già prenotato e la
  spesa netta al netto degli altri rinnovi.

Suite completa 210 su 210, client senza avvisi.

Refs #41.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 14:22:49 +01:00
1 parent f7c286bf1d
commit b7737455c6
18 files changed
+447 -96

No files matched your search

@@ -17,8 +17,11 @@ public sealed record FleetVehicleLine(
/// <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) e se la cassa basta.</summary>
public sealed record RenewalTrainLine(TrainId Train, int Vehicles, Money NetCost, bool Affordable);
/// <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
@@ -69,14 +72,17 @@ public sealed class FleetOutlook
}
var trains = new List<RenewalTrainLine>();
var c = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
int renew = d.Maintenance.Interventions.FindIndex(i => i.Effect == InterventionEffect.Renew);
// 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.NetCost(plan) + Fleet.CostOf(w, t, d.Maintenance.Interventions[renew], Fleet.PolicyOf(w, t));
trains.Add(new RenewalTrainLine(t.Id, plan.Count, net, c is not null && (!net.IsPositive || c.Cash >= net)));
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
{
@@ -196,7 +196,7 @@ internal sealed class AiAgent
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;
@@ -213,21 +213,27 @@ internal sealed class AiAgent
}
/// <summary>
/// Modelli fuori produzione (ADR 0020): la linea passa al successore consigliato o, se la catena non
/// ne offre, al modello che l'IA sceglierebbe oggi per un progetto nuovo. Così i treni aggiuntivi non
/// chiedono veicoli che non si possono più comprare.
/// 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);
if (!Obsolescence.InProduction(loco, year) && (Obsolescence.Recommended(loco, year) ?? Estimators.BestLocomotive(_w, year)) is { } newLoco)
project.Loco = newLoco.Id;
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);
if (Obsolescence.InProduction(car, year)) return;
var newCar = Obsolescence.Recommended(car, year) ?? (car.Kind == VehicleKind.Coach
? Estimators.CoachFor(_w, car.Class ?? PaxClass.Worker, year)
: project.Good >= 0 ? Estimators.WagonFor(_w, project.Good, year) : null);
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;
}
@@ -308,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)
{
@@ -336,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()
{
@@ -428,15 +440,16 @@ internal sealed class AiAgent
/// 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 dopo la spesa netta (successori − rivendite) la cassa resta sopra
/// renewal.cashReserveMultiple volte la riserva.
/// 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;
var interventions = _w.Data.Maintenance.Interventions;
string renewal = interventions[interventions.FindIndex(i => i.Effect == InterventionEffect.Renew)].Id;
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)
@@ -456,9 +469,9 @@ internal sealed class AiAgent
break;
}
}
if (!due) continue;
long net = Obsolescence.NetCost(plan).Cents;
if (_c.Cash.Cents - net < (long)(Reserve() * r.CashReserveMultiple)) continue;
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++;
}
}
@@ -474,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))
{
@@ -514,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;
}
@@ -567,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;
@@ -633,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;
@@ -1209,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;
@@ -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;
@@ -83,11 +83,16 @@ public static class MaintenanceCommandHandlers
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
// 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.NetCost(plan) + Fleet.CostOf(w, train, def, Fleet.PolicyOf(w, train));
if (net.IsPositive && company.Cash < net) return reply(CommandError.InsufficientFunds, $"Il rinnovo di {train.Name} costa {net} al netto delle rivendite: cassa insufficiente");
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);
@@ -53,7 +53,7 @@ public sealed class EraSystem : ISimSystem
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}: {Join(Unlocks(w.Data, year).Select(u => u.TextIt))}");
Corporate.Milestone(w, w.Player, era is not null ? $"inizia l'{era.NameIt}" : $"novità del {year}: {string.Join("; ", NewsParts(w.Data, year))}");
return e;
}
@@ -126,17 +126,24 @@ public sealed class EraSystem : ISimSystem
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);
if (era is null && unlocks.Count == 0 && retired.Count == 0 && superseded.Count == 0) return null;
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))}");
string head = era is not null ? $"Inizia l'{era.NameIt} ({year})" : $"Novità del {year}";
return parts.Count == 0 ? head : $"{head}: {string.Join("; ", parts)}";
return parts;
}
private static string Join(IEnumerable<string> items)
@@ -200,12 +200,8 @@ public static class Fleet
var m = w.Data.Maintenance;
long today = w.Clock.Day;
double ef = policy.EffectFactor;
if (def.Effect == InterventionEffect.Renew)
{
// rinnovo: i veicoli superati si vendono e al loro posto entrano i successori nuovi (ADR 0020)
Obsolescence.Renew(w, t);
return;
}
// 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];
@@ -239,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)
@@ -527,7 +564,6 @@ public sealed class FleetMaintenanceSystem : ISimSystem
var w = ctx.World;
var m = w.Data.Maintenance;
var def = m.Interventions[job.Intervention];
int renewed = def.Effect == InterventionEffect.Renew ? Obsolescence.RenewalPlan(w, t).Count : 0;
Fleet.Apply(w, t, def, Fleet.PolicyOf(w, t));
bool repair = def.Effect is InterventionEffect.Repair or InterventionEffect.Replace;
if (def.Effect != InterventionEffect.Inspection)
@@ -552,9 +588,8 @@ public sealed class FleetMaintenanceSystem : ISimSystem
}
else if (def.Effect == InterventionEffect.Renew)
{
string what = renewed == 1 ? "1 veicolo sostituito" : $"{renewed} veicoli sostituiti";
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Info,
$"{t.Name}: rinnovo completato a {d.Name}, {what}", EntityKind.Train, t.Id.Value, t.Owner));
$"{t.Name}: rinnovo completato a {d.Name}", EntityKind.Train, t.Id.Value, t.Owner));
}
}
@@ -116,16 +116,85 @@ public static class Obsolescence
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>
/// Rinnovo in officina (intervento con effetto «renew»): ogni veicolo superato del treno 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>.
/// Restituisce quanti veicoli sono stati sostituiti.
/// 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 int Renew(World w, Train t)
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)
@@ -76,23 +76,27 @@ public sealed class VehicleModelInfo
}
}
/// <summary>Treno con veicoli superati da rinnovare: quanti, spesa netta (successori − rivendite + lavoro) e se la cassa basta.</summary>
/// <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.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() };
var m = new RenewalTrainInfo { Train = r.I32(), Vehicles = r.I32(), NetCost = r.Money(), Affordable = r.Bool(), Booked = r.Bool() };
r.Flags();
return m;
}
+1 -1
View File
@@ -647,7 +647,7 @@ public static class Projection
{
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 }).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(),
};
}