namespace RailEnterprise.Core.Data;
///
/// Validazione semantica dei dati, dopo lo schema: id univoci, riferimenti risolti,
/// coerenza tra file e limiti che lo schema non può esprimere.
///
public static class DataValidator
{
private static readonly string[] SizeKeys = ["small", "medium", "large"];
private static readonly string[] ResourceKeys = ["coal", "iron", "stone", "oil"];
private static readonly string[] WorkKeys = ["natural", "embankment", "cutting", "bridge", "tunnel"];
private static readonly string[] CellTypeKeys = ["plain", "hill", "mountain", "forest", "field", "water", "sea", "town", "industry", "rock", "marsh"];
public static void Validate(GameData d, List errors)
{
void Err(string file, string message) => errors.Add($"{file}: {message}");
// --- beni
Unique("goods.json", d.Goods.Select(g => g.Id), errors);
if (d.Goods.Count > Rail.LineGraph.MaxGoods) Err("goods.json", $"al massimo {Rail.LineGraph.MaxGoods} beni (maschera dei carichi delle linee)");
var goodIds = d.Goods.Select(g => g.Id).ToHashSet(StringComparer.Ordinal);
foreach (string required in new[] { "spare_parts", "machinery" })
{
if (!goodIds.Contains(required)) Err("goods.json", $"manca il bene di servizio obbligatorio «{required}»");
}
foreach (var g in d.Goods)
{
if (g.Town is { UntilYear: { } until } && until <= g.Era) Err("goods.json", $"{g.Id}: town.untilYear precedente all'era del bene");
}
// --- industrie
Unique("industries.json", d.Industries.Select(i => i.Id), errors);
foreach (var ind in d.Industries)
{
string p = $"{ind.Id}:";
foreach (var item in ind.Recipe.Inputs.Concat(ind.Recipe.Outputs))
{
if (!goodIds.Contains(item.Good)) Err("industries.json", $"{p} bene sconosciuto «{item.Good}»");
}
Unique("industries.json", ind.Recipe.Inputs.Select(x => x.Good), errors, $"{p} input");
Unique("industries.json", ind.Recipe.Outputs.Select(x => x.Good), errors, $"{p} output");
if (ind.Kind == IndustryKind.Primary && ind.Recipe.Inputs.Count > 0) Err("industries.json", $"{p} un'industria primaria non ha input");
if (ind.Kind != IndustryKind.Primary && ind.Recipe.Inputs.Count == 0) Err("industries.json", $"{p} un'industria di trasformazione richiede input");
NonDecreasing("industries.json", $"{p} capacityPerLevel", ind.CapacityPerLevel, errors);
NonDecreasing("industries.json", $"{p} workersPerLevel", ind.WorkersPerLevel, errors);
NonDecreasing("industries.json", $"{p} staffPerLevel", ind.StaffPerLevel, errors);
if (ind.CapacityPerLevel[0] <= 0) Err("industries.json", $"{p} capacità di livello 1 nulla");
if (ind.Placement.Needs == PlacementNeed.Deposit && ind.Placement.Resource is null)
Err("industries.json", $"{p} needs=deposit richiede «resource»");
if (ind.Depletable && ind.Placement.Needs != PlacementNeed.Deposit)
Err("industries.json", $"{p} solo le industrie su giacimento possono esaurirsi");
if (ind.Placement is { MinTownDistanceKm: { } mn, MaxTownDistanceKm: { } mx } && mx < mn)
Err("industries.json", $"{p} maxTownDistanceKm < minTownDistanceKm");
if (d.Balance.Industry.FootprintCells is { } fc && !fc.ContainsKey(ind.Footprint.ToString().ToLowerInvariant()))
Err("balance.json", $"industry.footprintCells non definisce «{ind.Footprint}»");
}
foreach (var g in d.Goods)
{
bool produced = d.Industries.Any(i => i.Recipe.Outputs.Any(o => o.Good == g.Id));
if (!produced) Err("industries.json", $"nessuna industria produce «{g.Id}»");
}
// --- veicoli
Unique("vehicles.json", d.Vehicles.Select(v => v.Id), errors);
var locoComponents = d.Maintenance.Components.Locomotive.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
var carComponents = d.Maintenance.Components.Car.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
foreach (var v in d.Vehicles)
{
string p = $"{v.Id}:";
if (v.EraTo is { } to && to < v.EraFrom) Err("vehicles.json", $"{p} eraTo precedente a eraFrom");
switch (v.Kind)
{
case VehicleKind.Locomotive:
if (v.Traction is null) Err("vehicles.json", $"{p} una locomotiva richiede «traction»");
if (v.PowerKw <= 0 || v.TractiveEffortKn <= 0) Err("vehicles.json", $"{p} potenza e sforzo di trazione devono essere positivi");
foreach (string comp in v.Components.Keys)
{
if (!locoComponents.Contains(comp)) Err("vehicles.json", $"{p} componente sconosciuto «{comp}»");
}
foreach (string comp in locoComponents)
{
if (!v.Components.ContainsKey(comp)) Err("vehicles.json", $"{p} manca il componente «{comp}»");
}
break;
case VehicleKind.Wagon:
if (v.Capacity is null || v.WagonType is null || v.Goods is null)
Err("vehicles.json", $"{p} un carro richiede capacity, wagonType e goods");
foreach (string g in v.Goods ?? [])
{
if (!goodIds.Contains(g)) Err("vehicles.json", $"{p} bene sconosciuto «{g}»");
}
CheckCarComponents(v, carComponents, errors);
break;
case VehicleKind.Coach:
if (v.PaxCapacity is null || v.Class is null) Err("vehicles.json", $"{p} una carrozza richiede paxCapacity e class");
CheckCarComponents(v, carComponents, errors);
break;
}
}
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));
if (!carried) Err("vehicles.json", $"nessun carro di tipo «{g.Wagon}» trasporta «{g.Id}»");
}
foreach (PaxClass cls in Enum.GetValues())
{
if (!d.Vehicles.Any(v => v.Kind == VehicleKind.Coach && v.Class == cls))
Err("vehicles.json", $"nessuna carrozza per la classe «{cls}»");
}
if (!d.Vehicles.Any(v => v.Kind == VehicleKind.Locomotive && v.EraFrom <= d.Balance.Time.DefaultStartYear))
Err("vehicles.json", "nessuna locomotiva disponibile all'anno di inizio predefinito");
// --- ere
Unique("eras.json", d.Eras.Eras.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.TrackClasses.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.BridgeTypes.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.Signals.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.Tractions.Select(e => e.Id.ToString()), errors);
foreach (Traction t in Enum.GetValues())
{
if (!d.Eras.Tractions.Any(x => x.Id == t)) Err("eras.json", $"manca la trazione «{t}»");
}
Increasing("eras.json", "eras.from", d.Eras.Eras.Select(e => (double)e.From), errors);
Increasing("eras.json", "bridgeTypes.from", d.Eras.BridgeTypes.Select(e => (double)e.From), errors);
Increasing("eras.json", "bridgeTypes.maxSpanM", d.Eras.BridgeTypes.Select(e => e.MaxSpanM), errors);
Increasing("eras.json", "tunnelLimits.from", d.Eras.TunnelLimits.Select(e => (double)e.From), errors);
Increasing("eras.json", "tunnelLimits.maxLengthM", d.Eras.TunnelLimits.Select(e => e.MaxLengthM), errors);
Increasing("eras.json", "trackClasses.speedKmh", d.Eras.TrackClasses.Select(e => e.SpeedKmh), errors);
int start = d.Balance.Time.DefaultStartYear;
if (d.Eras.BridgeTypes[0].From > start) Err("eras.json", "nessun tipo di ponte all'anno di inizio");
if (d.Eras.TunnelLimits[0].From > start) Err("eras.json", "nessun limite di galleria all'anno di inizio");
if (d.Eras.TrackClasses[0].From > start) Err("eras.json", "nessuna classe di binario all'anno di inizio");
// --- livelli
var levels = d.Tiers.Tiers.Select(t => t.Level).ToList();
if (!levels.SequenceEqual(Enumerable.Range(1, levels.Count))) Err("tiers.json", "i livelli devono essere 1, 2, 3, 4, 5 in ordine");
Increasing("tiers.json", "requirements.netWorth", d.Tiers.Tiers.Select(t => (double)t.Requirements.NetWorth), errors, strictFromSecond: true);
if (!d.Tiers.RatingScale.SequenceEqual(Enum.GetValues())) Err("tiers.json", "ratingScale deve elencare i rating da AAA a D");
// --- difficoltà
Unique("difficulty.json", d.Difficulty.Presets.Select(p => p.Id), errors);
if (!d.Difficulty.Presets.Any(p => p.Id == d.Difficulty.Default)) Err("difficulty.json", $"preset predefinito «{d.Difficulty.Default}» inesistente");
// --- bilanciamento
var b = d.Balance;
if (!b.Time.Speeds.Contains(0) || !b.Time.Speeds.Contains(1)) Err("balance.json", "time.speeds deve contenere 0 e 1");
if (b.Market.MinPriceFactor >= 1 || b.Market.MaxPriceFactor <= 1) Err("balance.json", "market: i fattori di prezzo devono racchiudere 1");
if (b.Market.Outlook.HistoryMonths * b.Time.DaysPerMonth > b.Market.HistoryDays)
Err("balance.json", "market.outlook.historyMonths: lo storico mensile richiede più giorni di market.historyDays");
if (b.Market.Outlook.ChangeDays >= b.Market.HistoryDays) Err("balance.json", "market.outlook.changeDays deve essere minore di market.historyDays");
foreach (int size in b.Map.SizesKm)
{
string key = size.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (!b.Map.Towns.CountBySize.ContainsKey(key)) Err("balance.json", $"map.towns.countBySize non definisce {key}");
if (!b.Map.Industries.CountBySize.ContainsKey(key)) Err("balance.json", $"map.industries.countBySize non definisce {key}");
}
RequireKeys("balance.json", "map.deposits.perThousandKm2", b.Map.Deposits.PerThousandKm2.Keys, ResourceKeys, errors);
RequireKeys("balance.json", "map.deposits.reserveTonnes", b.Map.Deposits.ReserveTonnes.Keys, ResourceKeys, errors);
RequireKeys("balance.json", "map.deposits.preferredMinPercentile", b.Map.Deposits.PreferredMinPercentile.Keys, ResourceKeys, errors);
RequireKeys("balance.json", "map.deposits.preferredMaxPercentile", b.Map.Deposits.PreferredMaxPercentile.Keys, ResourceKeys, errors);
foreach (var (k, range) in b.Map.Deposits.ReserveTonnes)
{
if (range.Length != 2 || range[0] > range[1] || range[0] <= 0) Err("balance.json", $"map.deposits.reserveTonnes.{k} deve essere [min, max] positivo");
}
if (b.Map.Deposits.RadiusCells.Length != 2) Err("balance.json", "map.deposits.radiusCells deve essere [min, max]");
if (b.Map.Towns.LargestPopulation.Length != 2) Err("balance.json", "map.towns.largestPopulation deve essere [min, max]");
if (b.Map.Hydrology.RiverWidthSteps.Length != 4) Err("balance.json", "map.hydrology.riverWidthSteps deve avere 4 soglie (larghezze 1–4)");
RequireKeys("balance.json", "map.industries.shares", b.Map.Industries.Shares.Keys, ["farm", "logging", "processing", "manufacturing"], errors);
if (Math.Abs(b.Map.Industries.Shares.Values.Sum() - 1.0) > 1e-6) Err("balance.json", "map.industries.shares deve sommare a 1");
if (b.Map.Industries.InitialLevels.Length != 2 || b.Map.Industries.InitialLevels[0] > b.Map.Industries.InitialLevels[1])
Err("balance.json", "map.industries.initialLevels deve essere [min, max]");
RequireKeys("balance.json", "industry.footprintCells", b.Industry.FootprintCells.Keys, SizeKeys, errors);
RequireKeys("balance.json", "tariffs.classMultipliers", b.Tariffs.ClassMultipliers.Keys, ["worker", "staff"], errors);
RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames(), errors);
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
Increasing("balance.json", "finance.ratingByScore (decrescente)", Enumerable.Reverse(b.Finance.RatingByScore), errors);
RequireKeys("balance.json", "industryMaintenance.budgets", b.IndustryMaintenance.Budgets.Keys, ["none", "base", "high"], errors);
if (b.IndustryMaintenance.BreakdownDays.Length != 2) Err("balance.json", "industryMaintenance.breakdownDays deve essere [min, max]");
if (b.Growth.MaxLevel > 5 || b.Growth.MaxLevel < 1) Err("balance.json", "growth.maxLevel deve stare tra 1 e 5");
// --- costruzione
var c = d.Construction;
var classIds = d.Eras.TrackClasses.Select(t => t.Id).ToHashSet(StringComparer.Ordinal);
foreach (var sc in c.SpeedClasses)
{
if (!classIds.Contains(sc.TrackClass)) Err("construction.json", $"speedClasses: classe «{sc.TrackClass}» inesistente in eras.json");
}
foreach (string id in classIds)
{
if (!c.SpeedClasses.Any(s => s.TrackClass == id)) Err("construction.json", $"speedClasses non definisce la classe «{id}»");
}
RequireKeys("construction.json", "crews.metersPerDay", c.Crews.MetersPerDay.Keys, WorkKeys, errors);
if (c.Crews.CrewsByTier.Length != 5) Err("construction.json", "crews.crewsByTier deve avere 5 valori");
RequireKeys("construction.json", "costs.depotBySize", c.Costs.DepotBySize.Keys, SizeKeys, errors);
foreach (string k in c.Costs.TerrainModifiers.Keys)
{
if (!CellTypeKeys.Contains(k)) Err("construction.json", $"costs.terrainModifiers: tipo di cella sconosciuto «{k}»");
}
RequireKeys("construction.json", "physics.cxByKind", c.Physics.CxByKind.Keys, ["locomotive", "wagon", "coach"], errors);
RequireKeys("construction.json", "stations.depotUpkeepPerYear", c.Stations.DepotUpkeepPerYear.Keys, SizeKeys, errors);
if (c.Profile.SmoothingWindow % 2 == 0) Err("construction.json", "profile.smoothingWindow deve essere dispari");
if (c.Profile.RiverWidthMByClass.Length != 4) Err("construction.json", "profile.riverWidthMByClass deve avere 4 valori (classi 1–4)");
// --- manutenzione
var m = d.Maintenance;
Unique("maintenance.json", m.Interventions.Select(i => i.Id), errors);
Unique("maintenance.json", m.Components.Locomotive.Select(i => i.Id), errors);
Unique("maintenance.json", m.Components.Car.Select(i => i.Id), errors);
Near1("maintenance.json", "components.locomotive.failureWeight", m.Components.Locomotive.Sum(x => x.FailureWeight), errors);
Near1("maintenance.json", "components.car.failureWeight", m.Components.Car.Sum(x => x.FailureWeight), errors);
Near1("maintenance.json", "failure.*Share", m.Failure.MinorShare + m.Failure.MajorShare + m.Failure.CatastrophicShare, errors);
foreach (string id in new[] { "inspection", "service", "overhaul", "repair_minor", "repair_major", "repair_catastrophic" })
{
if (!m.Interventions.Any(i => i.Id == id)) Err("maintenance.json", $"manca l'intervento «{id}»");
}
foreach (var i in m.Interventions)
{
if (i.Effect == InterventionEffect.Repair && i.RestoreTo is null) Err("maintenance.json", $"{i.Id}: una riparazione richiede restoreTo");
}
RequireKeys("maintenance.json", "depots.stallsBySize", m.Depots.StallsBySize.Keys, SizeKeys, errors);
// --- IA, contratti, regioni
Unique("ai.json", d.Ai.Personalities.Select(p => p.Id), errors);
Unique("contracts.json", d.Contracts.Templates.Select(t => t.Id), errors);
foreach (var t in d.Contracts.Templates)
{
if (t.DurationYears[0] > t.DurationYears[1]) Err("contracts.json", $"{t.Id}: durationYears [min, max] invertito");
if (t.Kind == ContractKind.Connect && t.MaxMinutes is null) Err("contracts.json", $"{t.Id}: un collegamento richiede maxMinutes");
if (t.Kind is ContractKind.Deliver or ContractKind.Service && t.Quantity is null) Err("contracts.json", $"{t.Id}: richiede quantity");
if (t.Kind == ContractKind.GreatWork && t.LengthKm is null) Err("contracts.json", $"{t.Id}: una grande opera richiede lengthKm");
}
ValidateEvents(d, goodIds, errors);
Unique("regions.json", d.Regions.Regions.Select(r => r.Id), errors);
Unique("regions.json", d.Regions.NamePools.Select(r => r.Id), errors);
var pools = d.Regions.NamePools.Select(p => p.Id).ToHashSet(StringComparer.Ordinal);
foreach (var r in d.Regions.Regions)
{
if (!pools.Contains(r.NamePool)) Err("regions.json", $"{r.Id}: serbatoio di nomi «{r.NamePool}» inesistente");
}
}
/// Effetti ammessi per ogni bersaglio (ADR 0017).
public static bool EffectFits(EventTarget target, EventEffectKind effect) => effect switch
{
EventEffectKind.IndustryCapacity => target == EventTarget.Industry,
EventEffectKind.TownDemand => target == EventTarget.Town,
EventEffectKind.GoodDemand => target == EventTarget.TownGood,
EventEffectKind.Attendance => target is EventTarget.Town or EventTarget.Depot,
EventEffectKind.TrainSpeed or EventEffectKind.TrackWear => target == EventTarget.Area,
_ => false,
};
private static void ValidateEvents(GameData d, HashSet goodIds, List errors)
{
const string file = "events.json";
Unique(file, d.Events.Events.Select(e => e.Id), errors);
foreach (var e in d.Events.Events)
{
string p = $"{e.Id}:";
if (e.DurationDays[0] > e.DurationDays[1]) errors.Add($"{file}: {p} durationDays [min, max] invertito");
bool zone = e.Target is EventTarget.Area or EventTarget.TownGood;
if (zone && e.RadiusKm is null) errors.Add($"{file}: {p} il bersaglio «{e.Target}» richiede radiusKm");
if (!zone && e.RadiusKm is not null) errors.Add($"{file}: {p} radiusKm vale solo per area e townGood");
if (e.Goods is not null && e.Target != EventTarget.TownGood) errors.Add($"{file}: {p} goods vale solo per townGood");
if (e.IndustryKinds is not null && e.Target != EventTarget.Industry) errors.Add($"{file}: {p} industryKinds vale solo per industry");
foreach (string g in e.Goods ?? [])
{
if (!goodIds.Contains(g)) errors.Add($"{file}: {p} bene sconosciuto «{g}»");
else if (d.Goods.First(x => x.Id == g).Town is null) errors.Add($"{file}: {p} «{g}» non è un bene di consumo delle città");
}
Unique(file, e.Effects.Select(x => x.Kind.ToString()), errors, $"{p} effetti");
foreach (var x in e.Effects)
{
if (x.Min > x.Max) errors.Add($"{file}: {p} effetto {x.Kind} con min > max");
if (!EffectFits(e.Target, x.Kind)) errors.Add($"{file}: {p} l'effetto {x.Kind} non si applica al bersaglio {e.Target}");
}
}
}
private static void CheckCarComponents(VehicleDef v, HashSet carComponents, List errors)
{
foreach (string c in v.Components.Keys)
{
if (!carComponents.Contains(c)) errors.Add($"vehicles.json: {v.Id}: componente sconosciuto «{c}»");
}
foreach (string c in carComponents)
{
if (!v.Components.ContainsKey(c)) errors.Add($"vehicles.json: {v.Id}: manca il componente «{c}»");
}
}
private static void Unique(string file, IEnumerable ids, List errors, string context = "id")
{
var seen = new HashSet(StringComparer.Ordinal);
foreach (string id in ids)
{
if (!seen.Add(id)) errors.Add($"{file}: {context} duplicato «{id}»");
}
}
private static void RequireKeys(string file, string what, IEnumerable keys, IEnumerable required, List errors)
{
var set = keys.ToHashSet(StringComparer.Ordinal);
foreach (string k in required)
{
if (!set.Contains(k)) errors.Add($"{file}: {what} non definisce «{k}»");
}
}
private static void NonDecreasing(string file, string what, IReadOnlyList values, List errors)
{
for (int i = 1; i < values.Count; i++)
{
if (values[i] < values[i - 1]) errors.Add($"{file}: {what} non deve decrescere");
}
}
private static void Increasing(string file, string what, IEnumerable values, List errors, bool strictFromSecond = false)
{
double? prev = null;
int i = 0;
foreach (double v in values)
{
if (prev is { } p && (strictFromSecond && i == 1 ? v < p : v <= p))
errors.Add($"{file}: {what} deve essere crescente");
prev = v;
i++;
}
}
private static void Near1(string file, string what, double sum, List errors)
{
if (Math.Abs(sum - 1.0) > 1e-6) errors.Add($"{file}: la somma di {what} deve essere 1 (è {sum})");
}
}