Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*, variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos: CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly. Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
198 lines
8.8 KiB
C#
198 lines
8.8 KiB
C#
using System.Buffers;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization.Metadata;
|
|
using RailEnterprise.Core.Common;
|
|
|
|
namespace RailEnterprise.Core.Data;
|
|
|
|
/// <summary>
|
|
/// Tutte le definizioni immutabili del gioco, caricate e validate da data/*.json.
|
|
/// Un'istanza è condivisa in sola lettura da mondo, server, strumenti e client.
|
|
/// </summary>
|
|
public sealed class GameData
|
|
{
|
|
/// <summary>File dati nell'ordine canonico usato anche per l'hash.</summary>
|
|
public static readonly string[] FileNames =
|
|
[
|
|
"goods.json", "industries.json", "vehicles.json", "eras.json", "tiers.json", "balance.json",
|
|
"difficulty.json", "construction.json", "maintenance.json", "ai.json", "contracts.json", "regions.json",
|
|
];
|
|
|
|
public required IReadOnlyList<GoodDef> Goods { get; init; }
|
|
public required IReadOnlyList<IndustryDef> Industries { get; init; }
|
|
public required IReadOnlyList<VehicleDef> Vehicles { get; init; }
|
|
public required ErasFile Eras { get; init; }
|
|
public required TiersFile Tiers { get; init; }
|
|
public required BalanceFile Balance { get; init; }
|
|
public required DifficultyFile Difficulty { get; init; }
|
|
public required ConstructionFile Construction { get; init; }
|
|
public required MaintenanceFile Maintenance { get; init; }
|
|
public required AiFile Ai { get; init; }
|
|
public required ContractsFile Contracts { get; init; }
|
|
public required RegionsFile Regions { get; init; }
|
|
|
|
/// <summary>XxHash64 del contenuto canonico (minificato) di tutti i file: client e server devono coincidere.</summary>
|
|
public ulong Hash { get; private init; }
|
|
|
|
/// <summary>Indice del bene «ricambi».</summary>
|
|
public int SparePartsGood { get; private set; }
|
|
|
|
/// <summary>Indice del bene «macchinari».</summary>
|
|
public int MachineryGood { get; private set; }
|
|
|
|
private Dictionary<string, int> _goodIndex = new(StringComparer.Ordinal);
|
|
private Dictionary<string, int> _industryIndex = new(StringComparer.Ordinal);
|
|
private Dictionary<string, int> _vehicleIndex = new(StringComparer.Ordinal);
|
|
|
|
public int GoodCount => Goods.Count;
|
|
|
|
public GoodDef Good(string id) => Goods[GoodIndex(id)];
|
|
|
|
public int GoodIndex(string id) =>
|
|
_goodIndex.TryGetValue(id, out int i) ? i : throw new KeyNotFoundException($"Bene sconosciuto: {id}");
|
|
|
|
public bool TryGoodIndex(string id, out int index) => _goodIndex.TryGetValue(id, out index);
|
|
|
|
public IndustryDef Industry(string id) =>
|
|
_industryIndex.TryGetValue(id, out int i) ? Industries[i] : throw new KeyNotFoundException($"Industria sconosciuta: {id}");
|
|
|
|
public bool TryIndustry(string id, out IndustryDef? def)
|
|
{
|
|
def = _industryIndex.TryGetValue(id, out int i) ? Industries[i] : null;
|
|
return def is not null;
|
|
}
|
|
|
|
public VehicleDef Vehicle(string id) =>
|
|
_vehicleIndex.TryGetValue(id, out int i) ? Vehicles[i] : throw new KeyNotFoundException($"Veicolo sconosciuto: {id}");
|
|
|
|
public bool TryVehicle(string id, out VehicleDef? def)
|
|
{
|
|
def = _vehicleIndex.TryGetValue(id, out int i) ? Vehicles[i] : null;
|
|
return def is not null;
|
|
}
|
|
|
|
/// <summary>Preset di difficoltà per id.</summary>
|
|
public DifficultyDef DifficultyPreset(string id) =>
|
|
Difficulty.Presets.FirstOrDefault(p => p.Id == id) ?? throw new KeyNotFoundException($"Difficoltà sconosciuta: {id}");
|
|
|
|
/// <summary>Carica i dati dalla cartella predefinita.</summary>
|
|
public static GameData LoadDefault() => Load(DirectoryDataSource.FindDefault());
|
|
|
|
/// <summary>
|
|
/// Carica, valida (schema e semantica) e indicizza tutti i file dati. In caso di errori
|
|
/// lancia <see cref="DataValidationException"/> con l'elenco completo.
|
|
/// </summary>
|
|
public static GameData Load(IDataSource source)
|
|
{
|
|
var errors = new List<string>();
|
|
var canonical = new ArrayBufferWriter<byte>();
|
|
|
|
GoodsFile? goods = Read(source, "goods.json", DataJsonContext.Default.GoodsFile, errors, canonical);
|
|
IndustriesFile? industries = Read(source, "industries.json", DataJsonContext.Default.IndustriesFile, errors, canonical);
|
|
VehiclesFile? vehicles = Read(source, "vehicles.json", DataJsonContext.Default.VehiclesFile, errors, canonical);
|
|
ErasFile? eras = Read(source, "eras.json", DataJsonContext.Default.ErasFile, errors, canonical);
|
|
TiersFile? tiers = Read(source, "tiers.json", DataJsonContext.Default.TiersFile, errors, canonical);
|
|
BalanceFile? balance = Read(source, "balance.json", DataJsonContext.Default.BalanceFile, errors, canonical);
|
|
DifficultyFile? difficulty = Read(source, "difficulty.json", DataJsonContext.Default.DifficultyFile, errors, canonical);
|
|
ConstructionFile? construction = Read(source, "construction.json", DataJsonContext.Default.ConstructionFile, errors, canonical);
|
|
MaintenanceFile? maintenance = Read(source, "maintenance.json", DataJsonContext.Default.MaintenanceFile, errors, canonical);
|
|
AiFile? ai = Read(source, "ai.json", DataJsonContext.Default.AiFile, errors, canonical);
|
|
ContractsFile? contracts = Read(source, "contracts.json", DataJsonContext.Default.ContractsFile, errors, canonical);
|
|
RegionsFile? regions = Read(source, "regions.json", DataJsonContext.Default.RegionsFile, errors, canonical);
|
|
|
|
if (errors.Count > 0) throw new DataValidationException(errors);
|
|
|
|
var data = new GameData
|
|
{
|
|
Goods = goods!.Goods,
|
|
Industries = industries!.Industries,
|
|
Vehicles = vehicles!.Vehicles,
|
|
Eras = eras!,
|
|
Tiers = tiers!,
|
|
Balance = balance!,
|
|
Difficulty = difficulty!,
|
|
Construction = construction!,
|
|
Maintenance = maintenance!,
|
|
Ai = ai!,
|
|
Contracts = contracts!,
|
|
Regions = regions!,
|
|
Hash = XxHash64.Hash(canonical.WrittenSpan),
|
|
};
|
|
|
|
DataValidator.Validate(data, errors);
|
|
if (errors.Count > 0) throw new DataValidationException(errors);
|
|
data.Index();
|
|
return data;
|
|
}
|
|
|
|
private static T? Read<T>(IDataSource source, string file, JsonTypeInfo<T> typeInfo, List<string> errors, ArrayBufferWriter<byte> canonical)
|
|
where T : class
|
|
{
|
|
if (!source.Exists(file))
|
|
{
|
|
errors.Add($"{file}: file mancante in {source.Description}");
|
|
return null;
|
|
}
|
|
string schemaFile = "schema/" + file.Replace(".json", ".schema.json", StringComparison.Ordinal);
|
|
if (!source.Exists(schemaFile))
|
|
{
|
|
errors.Add($"{file}: schema mancante ({schemaFile})");
|
|
return null;
|
|
}
|
|
try
|
|
{
|
|
using var doc = JsonDocument.Parse(source.ReadText(file));
|
|
using var schemaDoc = JsonDocument.Parse(source.ReadText(schemaFile));
|
|
var schemaErrors = JsonSchemaValidator.Validate(doc.RootElement, schemaDoc.RootElement);
|
|
foreach (string e in schemaErrors) errors.Add($"{file}: {e}");
|
|
if (schemaErrors.Count > 0) return null;
|
|
|
|
// forma canonica per l'hash: nome del file + JSON minificato
|
|
canonical.Write(Encoding.UTF8.GetBytes(file));
|
|
canonical.Write("\n"u8);
|
|
using (var writer = new Utf8JsonWriter(canonical, new JsonWriterOptions { Indented = false }))
|
|
doc.RootElement.WriteTo(writer);
|
|
canonical.Write("\n"u8);
|
|
|
|
return doc.RootElement.Deserialize(typeInfo);
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
errors.Add($"{file}: {ex.Message}");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// Assegna indici e risolve i riferimenti per id dopo la validazione.
|
|
private void Index()
|
|
{
|
|
_goodIndex = new Dictionary<string, int>(StringComparer.Ordinal);
|
|
for (int i = 0; i < Goods.Count; i++)
|
|
{
|
|
Goods[i].Index = i;
|
|
_goodIndex[Goods[i].Id] = i;
|
|
}
|
|
_industryIndex = new Dictionary<string, int>(StringComparer.Ordinal);
|
|
for (int i = 0; i < Industries.Count; i++)
|
|
{
|
|
var def = Industries[i];
|
|
def.Index = i;
|
|
_industryIndex[def.Id] = i;
|
|
foreach (var item in def.Recipe.Inputs) item.GoodIndex = _goodIndex[item.Good];
|
|
foreach (var item in def.Recipe.Outputs) item.GoodIndex = _goodIndex[item.Good];
|
|
}
|
|
_vehicleIndex = new Dictionary<string, int>(StringComparer.Ordinal);
|
|
for (int i = 0; i < Vehicles.Count; i++)
|
|
{
|
|
var def = Vehicles[i];
|
|
def.Index = i;
|
|
_vehicleIndex[def.Id] = i;
|
|
def.GoodIndices = def.Goods?.Select(g => _goodIndex[g]).ToArray() ?? [];
|
|
}
|
|
for (int i = 0; i < Eras.TrackClasses.Count; i++) Eras.TrackClasses[i].Index = i;
|
|
SparePartsGood = _goodIndex["spare_parts"];
|
|
MachineryGood = _goodIndex["machinery"];
|
|
}
|
|
}
|