Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
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>
This commit is contained in:
1 parent
f6c2a17b4d
commit
c1a0049bcf
300 files changed
+1602
-1045
No files matched your search
@@ -0,0 +1,42 @@
|
||||
namespace RailEnterprise.Tools;
|
||||
|
||||
/// <summary>Scrittura di bitmap BMP a 24 bit senza dipendenze.</summary>
|
||||
public static class BmpWriter
|
||||
{
|
||||
/// <summary>Scrive un'immagine RGB (pixel riga per riga dall'alto, 3 byte per pixel).</summary>
|
||||
public static void Write(string path, int width, int height, byte[] rgb)
|
||||
{
|
||||
int rowSize = (width * 3 + 3) & ~3;
|
||||
int imageSize = rowSize * height;
|
||||
using var fs = File.Create(path);
|
||||
using var w = new BinaryWriter(fs);
|
||||
w.Write((byte)'B');
|
||||
w.Write((byte)'M');
|
||||
w.Write(54 + imageSize);
|
||||
w.Write(0);
|
||||
w.Write(54);
|
||||
w.Write(40);
|
||||
w.Write(width);
|
||||
w.Write(height);
|
||||
w.Write((short)1);
|
||||
w.Write((short)24);
|
||||
w.Write(0);
|
||||
w.Write(imageSize);
|
||||
w.Write(2835);
|
||||
w.Write(2835);
|
||||
w.Write(0);
|
||||
w.Write(0);
|
||||
var row = new byte[rowSize];
|
||||
for (int y = height - 1; y >= 0; y--)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
int s = (y * width + x) * 3;
|
||||
row[x * 3] = rgb[s + 2];
|
||||
row[x * 3 + 1] = rgb[s + 1];
|
||||
row[x * 3 + 2] = rgb[s];
|
||||
}
|
||||
w.Write(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace RailEnterprise.Tools;
|
||||
|
||||
/// <summary>Analisi minima degli argomenti: «--chiave valore» e opzioni booleane «--flag».</summary>
|
||||
public sealed class CommandLine
|
||||
{
|
||||
private readonly Dictionary<string, string?> _options = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _used = new(StringComparer.Ordinal);
|
||||
|
||||
public CommandLine(IReadOnlyList<string> args)
|
||||
{
|
||||
for (int i = 0; i < args.Count; i++)
|
||||
{
|
||||
string a = args[i];
|
||||
if (!a.StartsWith("--", StringComparison.Ordinal))
|
||||
throw new ArgumentException($"Argomento inatteso: {a}");
|
||||
string key = a[2..];
|
||||
string? value = null;
|
||||
int eq = key.IndexOf('=');
|
||||
if (eq >= 0)
|
||||
{
|
||||
value = key[(eq + 1)..];
|
||||
key = key[..eq];
|
||||
}
|
||||
else if (i + 1 < args.Count && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
value = args[++i];
|
||||
}
|
||||
_options[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Flag(string name)
|
||||
{
|
||||
_used.Add(name);
|
||||
return _options.ContainsKey(name);
|
||||
}
|
||||
|
||||
public string? String(string name)
|
||||
{
|
||||
_used.Add(name);
|
||||
return _options.TryGetValue(name, out var v) ? v : null;
|
||||
}
|
||||
|
||||
public string String(string name, string fallback) => String(name) ?? fallback;
|
||||
|
||||
public string Required(string name) => String(name) ?? throw new ArgumentException($"Opzione obbligatoria mancante: --{name}");
|
||||
|
||||
public int Int(string name, int fallback)
|
||||
{
|
||||
string? v = String(name);
|
||||
return v is null ? fallback : int.Parse(v, NumberStyles.Integer, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
public ulong ULong(string name, ulong fallback)
|
||||
{
|
||||
string? v = String(name);
|
||||
return v is null ? fallback : ulong.Parse(v, NumberStyles.Integer, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
public double Double(string name, double fallback)
|
||||
{
|
||||
string? v = String(name);
|
||||
return v is null ? fallback : double.Parse(v, NumberStyles.Float, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>Segnala le opzioni passate ma mai lette (probabili refusi).</summary>
|
||||
public void EnsureAllUsed()
|
||||
{
|
||||
var unknown = _options.Keys.Where(k => !_used.Contains(k)).ToList();
|
||||
if (unknown.Count > 0) throw new ArgumentException($"Opzioni sconosciute: {string.Join(", ", unknown.Select(u => "--" + u))}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Un comando di railenterprise-tools.</summary>
|
||||
public interface IToolCommand
|
||||
{
|
||||
string Name { get; }
|
||||
string Usage { get; }
|
||||
int Run(CommandLine args);
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
using System.Diagnostics;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// bench: costruisce con i comandi del protocollo una rete di linee a doppio binario con segnali,
|
||||
/// stazioni a quattro binari e un deposito per linea, vi mette N treni merci e misura il tempo
|
||||
/// di tick (media, percentili, massimo) e la ripartizione per sistema. Obiettivo della guida
|
||||
/// (sezione 15): tick medio ≤ 10 ms con 2.000 treni.
|
||||
/// </summary>
|
||||
public sealed class BenchCommand : IToolCommand
|
||||
{
|
||||
public string Name => "bench";
|
||||
|
||||
public string Usage => "bench --trains 2000 [--size 256] [--seed 1] [--stations 600] [--days 5] [--warmup 3] [--budget-ms 10]";
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
int trainCount = args.Int("trains", 2000);
|
||||
int size = args.Int("size", 256);
|
||||
ulong seed = args.ULong("seed", 1);
|
||||
int stationCount = args.Int("stations", 600);
|
||||
int days = args.Int("days", 5);
|
||||
int warmupDays = args.Int("warmup", 3);
|
||||
double budgetMs = args.Double("budget-ms", 10);
|
||||
args.EnsureAllUsed();
|
||||
|
||||
var data = GameData.LoadDefault();
|
||||
var total = Stopwatch.StartNew();
|
||||
var w = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size });
|
||||
long createMs = total.ElapsedMilliseconds;
|
||||
Console.WriteLine($"bench: mappa {size} km (seme {seed}) in {createMs} ms; {w.Industries.Count} industrie, {w.Towns.Count} città");
|
||||
|
||||
var me = w.Player.Id;
|
||||
// cassa illimitata per il banco di prova (registrata come movimento esterno: gli invarianti reggono)
|
||||
w.Money.Transfer(Account.External, Account.Of(me), new Money(1_000_000_000_000_00), LedgerEntry.Other);
|
||||
|
||||
var build = Stopwatch.StartNew();
|
||||
var lines = BuildNetwork(w, me, stationCount / 2, seed);
|
||||
ConstructionSystem.CompleteAllNow(w);
|
||||
int signals = PlaceSignals(w, me);
|
||||
int trains = BuyTrains(w, me, lines, trainCount);
|
||||
var net = w.Network;
|
||||
var edges = net.Edges.Where(e => e.State != EdgeState.Demolished).ToList();
|
||||
int stations = net.Stations.Count(s => net.Nodes[s.Node.Value].Station == s.Id);
|
||||
Console.WriteLine($" rete: {lines.Count} linee, {stations} stazioni, {edges.Count} archi ({edges.Sum(e => e.Length) / 1000:F0} km), " +
|
||||
$"{signals} segnali, {trains} treni in {build.ElapsedMilliseconds} ms");
|
||||
|
||||
w.RunDays(warmupDays);
|
||||
int ticks = days * w.Calendar.TicksPerDay;
|
||||
var samples = new double[ticks];
|
||||
w.Pipeline.Profile = true;
|
||||
Array.Clear(w.Pipeline.ElapsedTicks);
|
||||
Array.Clear(w.Pipeline.AllocatedBytes);
|
||||
long gc0 = GC.CollectionCount(0);
|
||||
long allocDay = 0, allocOther = 0;
|
||||
var dayElapsed = new long[w.Pipeline.Systems.Count];
|
||||
var snapshot = new long[w.Pipeline.Systems.Count];
|
||||
for (int i = 0; i < ticks; i++)
|
||||
{
|
||||
bool dayTick = w.Clock.IsNewDay;
|
||||
if (dayTick) Array.Copy(w.Pipeline.ElapsedTicks, snapshot, snapshot.Length);
|
||||
long before = GC.GetAllocatedBytesForCurrentThread();
|
||||
long start = Stopwatch.GetTimestamp();
|
||||
w.Tick();
|
||||
samples[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
|
||||
if (dayTick)
|
||||
{
|
||||
for (int k = 0; k < snapshot.Length; k++) dayElapsed[k] += w.Pipeline.ElapsedTicks[k] - snapshot[k];
|
||||
}
|
||||
long bytes = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
if (dayTick) allocDay += bytes;
|
||||
else allocOther += bytes;
|
||||
}
|
||||
w.Pipeline.Profile = false;
|
||||
|
||||
var sorted = (double[])samples.Clone();
|
||||
Array.Sort(sorted);
|
||||
double avg = samples.Average();
|
||||
int moving = w.Trains.Count(t => !t.Removed && t.State == TrainState.Moving);
|
||||
int loading = w.Trains.Count(t => !t.Removed && t.State == TrainState.Loading);
|
||||
int packets = w.Network.Stations.Sum(s => s.Waiting.Count) + w.Trains.Sum(t => t.Cargo.Count);
|
||||
Console.WriteLine($" misura: {ticks} tick ({days} giorni dopo {warmupDays} di avvio); treni in moto {moving}, in stazione {loading}, pacchetti {packets}");
|
||||
Console.WriteLine($" tick: media {avg:F2} ms, mediana {Pct(sorted, 0.5):F2}, p95 {Pct(sorted, 0.95):F2}, p99 {Pct(sorted, 0.99):F2}, max {sorted[^1]:F2} ms");
|
||||
Console.WriteLine($" allocazioni: {allocOther / (double)(ticks - days) / 1024:F2} KB per tick ordinario, {allocDay / (double)days / 1024:F0} KB per cambio di giorno, GC gen0 {GC.CollectionCount(0) - gc0}");
|
||||
for (int i = 0; i < w.Pipeline.Systems.Count; i++)
|
||||
{
|
||||
double ms = w.Pipeline.ElapsedTicks[i] * 1000.0 / Stopwatch.Frequency / ticks;
|
||||
double kb = w.Pipeline.AllocatedBytes[i] / 1024.0 / ticks;
|
||||
double dayMs = dayElapsed[i] * 1000.0 / Stopwatch.Frequency / days;
|
||||
if (ms >= 0.005 || kb >= 0.01 || dayMs >= 0.5)
|
||||
Console.WriteLine($" {w.Pipeline.Systems[i].Name,-16} {ms,8:F3} ms/tick {kb,8:F2} KB/tick {dayMs,8:F2} ms al cambio di giorno");
|
||||
}
|
||||
bool stalls = w.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal));
|
||||
Console.WriteLine($" invarianti: denaro {(w.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}; avvisi di stallo: {(stalls ? "sì" : "no")}");
|
||||
bool ok = avg <= budgetMs;
|
||||
Console.WriteLine(ok ? $" esito: entro il budget di {budgetMs} ms" : $" esito: OLTRE il budget di {budgetMs} ms");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
private static double Pct(double[] sorted, double p) => sorted[Math.Min(sorted.Length - 1, (int)(p * sorted.Length))];
|
||||
|
||||
private sealed record BenchLine(int StationA, int StationB, int Depot);
|
||||
|
||||
private static CommandResult Do(World w, GameCommand c, CompanyId me)
|
||||
{
|
||||
w.Enqueue(c with { Issuer = me });
|
||||
w.RunTicks(1);
|
||||
return w.DrainResults().Last();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Linee rettilinee di 6–10 km ancorate alle industrie, lontane tra loro, con stazioni a quattro
|
||||
/// binari alle estremità e un deposito su una diramazione vicino alla prima stazione.
|
||||
/// </summary>
|
||||
private static List<BenchLine> BuildNetwork(World w, CompanyId me, int count, ulong seed)
|
||||
{
|
||||
var rng = new Rng(seed).Fork("bench");
|
||||
var placed = new List<(Vec2 A, Vec2 B)>();
|
||||
var result = new List<BenchLine>();
|
||||
double margin = 3000, spacing = 1500;
|
||||
double maxX = w.Terrain.WidthM - margin, maxY = w.Terrain.HeightM - margin;
|
||||
for (int attempt = 0; result.Count < count && attempt < count * 30; attempt++)
|
||||
{
|
||||
var anchor = w.Industries[rng.NextInt(w.Industries.Count)].Position;
|
||||
double angle = rng.NextDouble(0, 2 * Math.PI);
|
||||
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
|
||||
var a = anchor + dir.Perpendicular * rng.NextDouble(400, 1200);
|
||||
var b = a + dir * rng.NextDouble(6000, 10000);
|
||||
if (!Inside(a, margin, maxX, maxY) || !Inside(b, margin, maxX, maxY)) continue;
|
||||
if (placed.Any(s => SegmentDistance(a, b, s.A, s.B) < spacing)) continue;
|
||||
var junction = a + dir * 800;
|
||||
var depotAt = junction + dir.Perpendicular * 350;
|
||||
if (Water(w, a) || Water(w, b) || Water(w, depotAt)) continue;
|
||||
|
||||
var sa = Do(w, new BuildStationCommand(a, 4), me);
|
||||
if (!sa.Ok) continue;
|
||||
var sb = Do(w, new BuildStationCommand(b, 4), me);
|
||||
if (!sb.Ok) { Do(w, new DemolishCommand(DemolishTarget.Station, sa.Created[0]), me); continue; }
|
||||
var track = Do(w, new BuildTrackCommand([a, b], DoubleTrack: true), me);
|
||||
if (!track.Ok)
|
||||
{
|
||||
Do(w, new DemolishCommand(DemolishTarget.Station, sb.Created[0]), me);
|
||||
Do(w, new DemolishCommand(DemolishTarget.Station, sa.Created[0]), me);
|
||||
continue;
|
||||
}
|
||||
var depot = Do(w, new BuildDepotCommand(depotAt, "small"), me);
|
||||
var spur = depot.Ok ? Do(w, new BuildTrackCommand([depotAt, junction]), me) : depot;
|
||||
if (!spur.Ok)
|
||||
{
|
||||
// linea senza deposito: i suoi treni nasceranno nel deposito di un'altra linea, non serve
|
||||
if (depot.Ok) Do(w, new DemolishCommand(DemolishTarget.Depot, depot.Created[0]), me);
|
||||
foreach (var e in track.Created) Do(w, new DemolishCommand(DemolishTarget.Edge, e), me);
|
||||
Do(w, new DemolishCommand(DemolishTarget.Station, sb.Created[0]), me);
|
||||
Do(w, new DemolishCommand(DemolishTarget.Station, sa.Created[0]), me);
|
||||
continue;
|
||||
}
|
||||
placed.Add((a, b));
|
||||
result.Add(new BenchLine(sa.Created[0], sb.Created[0], depot.Created[0]));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Segnali ogni 800 m sugli archi principali (non sulle diramazioni dei depositi).</summary>
|
||||
private static int PlaceSignals(World w, CompanyId me)
|
||||
{
|
||||
const double every = 800;
|
||||
int placed = 0;
|
||||
foreach (var e in w.Network.Edges.ToList())
|
||||
{
|
||||
if (e.State != EdgeState.Active || e.Owner != me) continue;
|
||||
if (w.Network.Nodes[e.A.Value].Depot.IsValid || w.Network.Nodes[e.B.Value].Depot.IsValid) continue;
|
||||
for (double s = every; s < e.Length - every / 2; s += every)
|
||||
{
|
||||
w.Enqueue(new PlaceSignalCommand(e.Id, s) with { Issuer = me });
|
||||
placed++;
|
||||
}
|
||||
}
|
||||
w.RunTicks(1);
|
||||
placed -= w.DrainResults().Count(r => !r.Ok);
|
||||
return placed;
|
||||
}
|
||||
|
||||
/// <summary>Compra locomotive e tramogge, compone i treni, crea una linea per tratta e li assegna.</summary>
|
||||
private static int BuyTrains(World w, CompanyId me, List<BenchLine> lines, int count)
|
||||
{
|
||||
if (lines.Count == 0) return 0;
|
||||
var perLine = new int[lines.Count];
|
||||
for (int i = 0; i < count; i++) perLine[i % lines.Count]++;
|
||||
for (int l = 0; l < lines.Count; l++)
|
||||
{
|
||||
for (int k = 0; k < perLine[l]; k++)
|
||||
{
|
||||
w.Enqueue(new BuyVehicleCommand("loco_steam_1850", new DepotId(lines[l].Depot), 1) with { Issuer = me });
|
||||
w.Enqueue(new BuyVehicleCommand("wagon_hopper", new DepotId(lines[l].Depot), 4) with { Issuer = me });
|
||||
}
|
||||
}
|
||||
w.RunTicks(1);
|
||||
var bought = w.DrainResults();
|
||||
int r = 0;
|
||||
for (int l = 0; l < lines.Count; l++)
|
||||
{
|
||||
for (int k = 0; k < perLine[l]; k++)
|
||||
{
|
||||
var ids = bought[r].Created.Concat(bought[r + 1].Created).Select(i => new VehicleId(i)).ToList();
|
||||
r += 2;
|
||||
w.Enqueue(new ComposeTrainCommand(new DepotId(lines[l].Depot), ids) with { Issuer = me });
|
||||
}
|
||||
w.Enqueue(new CreateLineCommand($"Linea {l + 1}", "#e0a526",
|
||||
[new LineStop(new StationId(lines[l].StationA)), new LineStop(new StationId(lines[l].StationB))]) with { Issuer = me });
|
||||
}
|
||||
w.RunTicks(1);
|
||||
var composed = w.DrainResults();
|
||||
int c = 0, trains = 0;
|
||||
for (int l = 0; l < lines.Count; l++)
|
||||
{
|
||||
var trainIds = new List<int>();
|
||||
for (int k = 0; k < perLine[l]; k++)
|
||||
{
|
||||
if (composed[c].Ok) trainIds.Add(composed[c].Created[0]);
|
||||
c++;
|
||||
}
|
||||
var line = composed[c++];
|
||||
if (!line.Ok) continue;
|
||||
foreach (int t in trainIds)
|
||||
{
|
||||
w.Enqueue(new AssignTrainCommand(new TrainId(t), new LineId(line.Created[0])) with { Issuer = me });
|
||||
trains++;
|
||||
}
|
||||
}
|
||||
w.RunTicks(1);
|
||||
trains -= w.DrainResults().Count(x => !x.Ok);
|
||||
return trains;
|
||||
}
|
||||
|
||||
private static bool Inside(Vec2 p, double margin, double maxX, double maxY) => p.X >= margin && p.Y >= margin && p.X <= maxX && p.Y <= maxY;
|
||||
|
||||
private static bool Water(World w, Vec2 p)
|
||||
{
|
||||
var (x, y) = w.Terrain.CellAt(p);
|
||||
return w.Terrain.IsWater(x, y);
|
||||
}
|
||||
|
||||
private static double SegmentDistance(Vec2 a, Vec2 b, Vec2 c, Vec2 d)
|
||||
{
|
||||
if (Intersects(a, b, c, d)) return 0;
|
||||
return Math.Min(Math.Min(PointSegment(a, c, d), PointSegment(b, c, d)), Math.Min(PointSegment(c, a, b), PointSegment(d, a, b)));
|
||||
}
|
||||
|
||||
private static bool Intersects(Vec2 a, Vec2 b, Vec2 c, Vec2 d)
|
||||
{
|
||||
double d1 = Vec2.Cross(b - a, c - a), d2 = Vec2.Cross(b - a, d - a);
|
||||
double d3 = Vec2.Cross(d - c, a - c), d4 = Vec2.Cross(d - c, b - c);
|
||||
return d1 * d2 < 0 && d3 * d4 < 0;
|
||||
}
|
||||
|
||||
private static double PointSegment(Vec2 p, Vec2 a, Vec2 b)
|
||||
{
|
||||
var ab = b - a;
|
||||
double len2 = Vec2.Dot(ab, ab);
|
||||
double t = len2 <= 0 ? 0 : Math.Clamp(Vec2.Dot(p - a, ab) / len2, 0, 1);
|
||||
return Vec2.Distance(p, a + ab * t);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Diagnostics;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Map;
|
||||
|
||||
namespace RailEnterprise.Tools.Commands;
|
||||
|
||||
/// <summary>genmap --seed --size --out mappa.bmp: genera una mappa e ne scrive un'immagine di controllo.</summary>
|
||||
public sealed class GenMapCommand : IToolCommand
|
||||
{
|
||||
public string Name => "genmap";
|
||||
|
||||
public string Usage => "genmap --seed <n> --size <64|128|256> --out <mappa.bmp> [--scale <n>] [--year <anno>] [--region <id>]";
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
ulong seed = args.ULong("seed", 1);
|
||||
int size = args.Int("size", 128);
|
||||
string output = args.String("out", "mappa.bmp");
|
||||
int scale = args.Int("scale", 1);
|
||||
var data = GameData.LoadDefault();
|
||||
int year = args.Int("year", data.Balance.Time.DefaultStartYear);
|
||||
string region = args.String("region", "valdoria");
|
||||
args.EnsureAllUsed();
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var map = MapGenerator.Generate(data, new MapSpec(seed, size, year, region));
|
||||
long genMs = sw.ElapsedMilliseconds;
|
||||
|
||||
var rgb = MapRenderer.Render(map, Math.Max(1, scale), out int w, out int h);
|
||||
BmpWriter.Write(output, w, h, rgb);
|
||||
|
||||
var t = map.Terrain;
|
||||
var counts = new int[11];
|
||||
foreach (byte b in t.Types) counts[b]++;
|
||||
Console.WriteLine($"genmap: seme {seed}, {size} km ({t.Width}×{t.Height} celle), mare a {map.SeaSide}, generata in {genMs} ms");
|
||||
Console.WriteLine($" fasi: {string.Join(", ", map.PhaseMillis.Select(kv => $"{kv.Key} {kv.Value} ms"))}");
|
||||
Console.WriteLine($" città {map.Towns.Count}, industrie {map.Industries.Count}, giacimenti {map.Sites.Count}, hub {map.Hubs.Count}");
|
||||
Console.WriteLine(" celle: " + string.Join(", ", Enum.GetValues<CellType>().Select(c => $"{c} {100.0 * counts[(int)c] / t.Types.Length:F1}%")));
|
||||
foreach (var town in map.Towns.Take(8)) Console.WriteLine($" città {town.Name}: {town.Population} abitanti");
|
||||
Console.WriteLine($" hash del terreno {t.ComputeHash():x16}");
|
||||
Console.WriteLine($" immagine {output} ({w}×{h})");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Map;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Scenarios;
|
||||
|
||||
namespace RailEnterprise.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// profile: pianifica un tracciato e scrive il profilo campionato ogni 25 m in CSV (separatore «;»),
|
||||
/// con il riepilogo delle opere, dei costi e dei giorni.
|
||||
/// </summary>
|
||||
public sealed class ProfileCommand : IToolCommand
|
||||
{
|
||||
public string Name => "profile";
|
||||
|
||||
public string Usage => "profile (--seed <n> [--size 128] | --scenario <file> [--route <nome>]) [--polyline \"x1,y1;x2,y2;…\" (km)] [--offset <m>] [--class c60] [--no-tunnels] [--no-bridges] [--year <anno>] [--out profilo.csv]";
|
||||
|
||||
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
ulong seed = args.ULong("seed", 1);
|
||||
int size = args.Int("size", 64);
|
||||
string? scenarioPath = args.String("scenario");
|
||||
string? routeName = args.String("route");
|
||||
string? polyline = args.String("polyline");
|
||||
double offset = args.Double("offset", 0);
|
||||
string trackClass = args.String("class", "c60");
|
||||
bool noTunnels = args.Flag("no-tunnels");
|
||||
bool noBridges = args.Flag("no-bridges");
|
||||
int? year = args.String("year") is { } y ? int.Parse(y, Inv) : null;
|
||||
string output = args.String("out", "profilo.csv");
|
||||
args.EnsureAllUsed();
|
||||
|
||||
var data = GameData.LoadDefault();
|
||||
World world;
|
||||
TrackPlanRequest request;
|
||||
if (scenarioPath is not null)
|
||||
{
|
||||
var scenario = ScenarioLoader.LoadFile(data, scenarioPath);
|
||||
world = scenario.World;
|
||||
request = routeName is not null
|
||||
? scenario.Route(routeName, world.Player.Id)
|
||||
: new TrackPlanRequest { Polyline = ParsePolyline(polyline ?? throw new ArgumentException("serve --route o --polyline")) };
|
||||
}
|
||||
else
|
||||
{
|
||||
world = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size });
|
||||
request = new TrackPlanRequest { Polyline = ParsePolyline(polyline ?? throw new ArgumentException("serve --polyline")) };
|
||||
}
|
||||
if (polyline is not null || routeName is null)
|
||||
{
|
||||
request = request with
|
||||
{
|
||||
HeightOffsetM = offset,
|
||||
TrackClass = trackClass,
|
||||
AllowTunnels = !noTunnels,
|
||||
AllowBridges = !noBridges,
|
||||
};
|
||||
}
|
||||
|
||||
var ctx = new TrackPlanContext
|
||||
{
|
||||
Data = data,
|
||||
Sampler = world.Sampler,
|
||||
Year = year ?? world.Clock.Year,
|
||||
CostMultiplier = world.Difficulty.ConstructionCostMultiplier,
|
||||
NearestTownEdgeKm = p => world.Towns.Count == 0 ? double.MaxValue : world.Towns.Min(t => world.TownEdgeDistanceKm(t, p)),
|
||||
};
|
||||
var plan = TrackPlanner.Plan(ctx, request);
|
||||
|
||||
var csv = new StringBuilder();
|
||||
csv.AppendLine("s_m;x_m;y_m;terreno_m;binario_m;differenza_m;opera;cella;velocita_kmh");
|
||||
foreach (var s in plan.Samples)
|
||||
{
|
||||
csv.AppendLine(string.Join(';', F(s.S), F(s.Point.X), F(s.Point.Y), F(s.TerrainM), F(s.TrackM), F(s.TrackM - s.TerrainM),
|
||||
s.Kind.ToString(), s.Cell.ToString(), F(s.SpeedLimitKmh)));
|
||||
}
|
||||
File.WriteAllText(output, csv.ToString(), new UTF8Encoding(true));
|
||||
|
||||
Console.WriteLine($"profile: {(plan.Valid ? "VALIDO" : "RIFIUTATO")} — {plan.LengthM / 1000:F2} km, pendenza max {plan.MaxGradient * 100:F2}% (limite {plan.GradientLimit * 100:F1}%), raggio min {(double.IsInfinity(plan.MinRadiusM) ? "∞" : plan.MinRadiusM.ToString("F0", Inv))} m");
|
||||
foreach (var e in plan.Errors) Console.WriteLine($" errore al km {e.AtM / 1000:F2}: {e.Message}");
|
||||
foreach (var w in plan.Warnings) Console.WriteLine($" avviso: {w.Message}");
|
||||
foreach (var w in plan.Works)
|
||||
Console.WriteLine($" {w.Kind,-10} {w.StartM / 1000,6:F2}–{w.EndM / 1000,6:F2} km h max {w.MaxHeightM,5:F1} m {new Money(w.CostCents),14} {w.Days,4} gg{(w.BridgeType is { } b ? " ponte " + b : "")}");
|
||||
double natural = plan.LengthM * data.Construction.Costs.BasePerMeter * ctx.CostMultiplier;
|
||||
Console.WriteLine($" opere {plan.WorksCost}, terreni {plan.LandCost}, totale {plan.TotalCost} ({plan.TotalCost.Cents / Math.Max(1, natural + plan.LandCost.Cents):F2}× la sede naturale), {plan.Days} giorni");
|
||||
Console.WriteLine($" profilo in {output}");
|
||||
return plan.Valid ? 0 : 3;
|
||||
}
|
||||
|
||||
private static string F(double v) => double.IsInfinity(v) ? "" : v.ToString("0.##", Inv).Replace('.', ',');
|
||||
|
||||
private static List<Vec2> ParsePolyline(string text) =>
|
||||
text.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(p => p.Split(','))
|
||||
.Select(p => new Vec2(double.Parse(p[0], Inv) * 1000, double.Parse(p[1], Inv) * 1000))
|
||||
.ToList();
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Diagnostics;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Protocol;
|
||||
|
||||
namespace RailEnterprise.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// replay: carica un salvataggio, riapplica i comandi registrati dal server (<c>--record</c>) ai
|
||||
/// loro tick e stampa l'hash di stato finale; con <c>--expect</c> lo confronta (determinismo).
|
||||
/// </summary>
|
||||
public sealed class ReplayCommand : IToolCommand
|
||||
{
|
||||
public string Name => "replay";
|
||||
|
||||
public string Usage => "replay --save <file.vfsave> --commands <file.vfcmd> [--until <tick>] [--expect <hash esadecimale>]";
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
string savePath = args.Required("save");
|
||||
string commandsPath = args.Required("commands");
|
||||
long until = args.Int("until", -1);
|
||||
string? expect = args.String("expect");
|
||||
args.EnsureAllUsed();
|
||||
|
||||
var data = GameData.LoadDefault();
|
||||
var world = SaveFile.LoadFromFile(data, savePath);
|
||||
var commands = CommandLogFile.ReadAll(File.ReadAllBytes(commandsPath));
|
||||
long start = world.Clock.Tick;
|
||||
long last = commands.Count > 0 ? commands[^1].Tick : start;
|
||||
long end = until >= 0 ? until : last + 1;
|
||||
var clock = Stopwatch.StartNew();
|
||||
int next = 0;
|
||||
while (next < commands.Count && commands[next].Tick < start) next++;
|
||||
int skipped = next;
|
||||
while (world.Clock.Tick < end)
|
||||
{
|
||||
while (next < commands.Count && commands[next].Tick == world.Clock.Tick) world.Enqueue(commands[next++].Command);
|
||||
world.Tick();
|
||||
world.DrainResults();
|
||||
world.Events.Drain();
|
||||
}
|
||||
ulong hash = StateHasher.Compute(world);
|
||||
Console.WriteLine($"replay: {next - skipped} comandi su {commands.Count} (saltati {skipped} precedenti al salvataggio), tick {start} → {world.Clock.Tick} in {clock.ElapsedMilliseconds} ms");
|
||||
Console.WriteLine($" data {world.Clock.Date}, hash di stato {hash:x16}");
|
||||
if (expect is null) return 0;
|
||||
bool ok = string.Equals(expect.Trim(), hash.ToString("x16"), StringComparison.OrdinalIgnoreCase);
|
||||
Console.WriteLine(ok ? " hash atteso: coincide" : $" hash atteso {expect}: DIVERSO");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// simulate: fa girare il mondo per N anni senza client e scrive i KPI annuali in CSV
|
||||
/// (separatore «;», decimali con la virgola) con le colonne della guida (14.5).
|
||||
/// </summary>
|
||||
public sealed class SimulateCommand : IToolCommand
|
||||
{
|
||||
public string Name => "simulate";
|
||||
|
||||
public string Usage => "simulate --seed <n> --years <n> [--size 128] [--difficulty imprenditore] [--scenario <file>] [--out kpi.csv] [--save <file>] [--trace-ai]";
|
||||
|
||||
private static readonly CultureInfo It = CultureInfo.InvariantCulture;
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
ulong seed = args.ULong("seed", 1);
|
||||
int years = args.Int("years", 20);
|
||||
int size = args.Int("size", 128);
|
||||
string difficulty = args.String("difficulty", "imprenditore");
|
||||
string? scenario = args.String("scenario");
|
||||
string output = args.String("out", "kpi.csv");
|
||||
string? savePath = args.String("save");
|
||||
bool trace = args.Flag("trace-ai");
|
||||
args.EnsureAllUsed();
|
||||
if (trace) Core.Simulation.Ai.AiSystem.Trace = Console.WriteLine;
|
||||
|
||||
var data = GameData.LoadDefault();
|
||||
var total = Stopwatch.StartNew();
|
||||
World world;
|
||||
if (scenario is not null)
|
||||
world = Scenarios.ScenarioLoader.Load(data, scenario).World;
|
||||
else
|
||||
world = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size, DifficultyId = difficulty });
|
||||
long createMs = total.ElapsedMilliseconds;
|
||||
|
||||
var csv = new StringBuilder();
|
||||
csv.AppendLine("anno;compagnia;bene;prezzo medio;produzione;consumo;popolazione;efficienza media;condizione media flotta;condizione media impianti;cassa;patrimonio;quota di mercato;nota");
|
||||
var lastProduced = (long[])world.Goods.Produced.Clone();
|
||||
var lastConsumed = (long[])world.Goods.Consumed.Clone();
|
||||
|
||||
var sim = Stopwatch.StartNew();
|
||||
for (int y = 0; y < years; y++)
|
||||
{
|
||||
int year = world.Clock.Year;
|
||||
world.RunYears(1);
|
||||
WriteYear(world, year, csv, lastProduced, lastConsumed);
|
||||
Array.Copy(world.Goods.Produced, lastProduced, lastProduced.Length);
|
||||
Array.Copy(world.Goods.Consumed, lastConsumed, lastConsumed.Length);
|
||||
world.Events.Drain();
|
||||
}
|
||||
long simMs = sim.ElapsedMilliseconds;
|
||||
|
||||
File.WriteAllText(output, csv.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
|
||||
if (savePath is not null) SaveFile.SaveToFile(world, savePath, typeof(SimulateCommand).Assembly.GetName().Version?.ToString() ?? "?");
|
||||
|
||||
Console.WriteLine($"simulate: {years} anni su {world.Settings.SizeKm} km in {simMs / 1000.0:F1} s (creazione {createMs} ms)");
|
||||
Console.WriteLine($" data finale {world.Clock.Date}, hash {world.LastStateHash:x16}");
|
||||
Console.WriteLine($" popolazione {Core.Common.Money.GroupThousands((ulong)world.Towns.Sum(t => (long)t.Population))}, industrie aperte {world.Industries.Count(i => !i.Closed)} su {world.Industries.Count}");
|
||||
Console.WriteLine($" invarianti: denaro {(world.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}, merci {(Enumerable.Range(0, data.GoodCount).All(g => world.TotalStock(g) == world.Goods.ExpectedStock(g)) ? "ok" : "ROTTO")}");
|
||||
foreach (var c in world.Companies)
|
||||
Console.WriteLine($" {c.Name}: patrimonio {c.NetWorth}, cassa {c.Cash}, livello {c.Tier}, rating {c.Rating}, azione {c.SharePrice / 100:0.00} lire{AiNote(world, c)}{(c.Defunct ? " (fuori gioco)" : "")}");
|
||||
Console.WriteLine($" KPI in {output}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void WriteYear(World w, int year, StringBuilder csv, long[] lastProduced, long[] lastConsumed)
|
||||
{
|
||||
var data = w.Data;
|
||||
long population = w.Towns.Sum(t => (long)t.Population);
|
||||
var open = w.Industries.Where(i => !i.Closed).ToList();
|
||||
double efficiency = open.Count == 0 ? 0 : open.Average(i => i.Efficiency);
|
||||
double plant = open.Count == 0 ? 0 : open.Average(i => i.Condition);
|
||||
for (int g = 0; g < data.GoodCount; g++)
|
||||
{
|
||||
var def = data.Goods[g];
|
||||
double price = w.Market.PriceHistory[g].Average / 100.0;
|
||||
long produced = w.Goods.Produced[g] - lastProduced[g];
|
||||
long consumed = w.Goods.Consumed[g] - lastConsumed[g];
|
||||
string note = def.Era > year ? "non ancora disponibile" : "";
|
||||
csv.AppendLine(string.Join(';', year.ToString(It), "", def.Id, Dec(price), produced.ToString(It), consumed.ToString(It),
|
||||
population.ToString(It), Dec(efficiency), "", Dec(plant), "", "", "", note));
|
||||
}
|
||||
long totalCarrier = w.Companies.Sum(c => Company.Revenue(c.LastYearEntries));
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
long revenue = Company.Revenue(c.LastYearEntries);
|
||||
double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0;
|
||||
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}{(c.Merged ? ", fusa" : "")}{AiNote(w, c)}";
|
||||
bool fleet = w.Trains.Any(t => !t.Removed && t.Owner == c.Id && t.Vehicles.Count > 0);
|
||||
csv.AppendLine(string.Join(';', year.ToString(It), c.Name, "", "", "", "", population.ToString(It), "",
|
||||
fleet ? Dec(Fleet.FleetCondition(w, c.Id)) : "", "", Dec(c.Cash.Lire), Dec(c.NetWorth.Lire), Dec(share), note));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Diagnostica dell'agente IA: progetti, treni, comandi rifiutati.</summary>
|
||||
private static string AiNote(World w, Company c)
|
||||
{
|
||||
var s = w.AiStates.FirstOrDefault(a => a.Company == c.Id);
|
||||
if (s is null) return "";
|
||||
int running = s.Projects.Count(p => p.Stage == Core.Simulation.Ai.AiProjectStage.Running);
|
||||
int trains = w.Trains.Count(t => !t.Removed && t.Owner == c.Id);
|
||||
return $", progetti {running}/{s.Projects.Count}, treni {trains}, città collegate {Tiers.ConnectedTowns(w, c.Id, 1000)} (≥1000) {Tiers.ConnectedTowns(w, c.Id, 2000)} (≥2000), comandi {s.Issued} (rifiutati {s.RejectedShare * 100:0.0} %)";
|
||||
}
|
||||
|
||||
private static string Dec(double v) => v.ToString("0.###", It).Replace('.', ',');
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Diagnostics;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Map;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
|
||||
namespace RailEnterprise.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// smoke: collaudo di un server in esecuzione (locale o in Docker) con un client vero. Trova un
|
||||
/// fiume, costruisce due stazioni, un deposito e un binario con ponte usando l'anteprima del
|
||||
/// client come costo atteso (il server rifiuta se differisce), compra un treno, lo mette in linea
|
||||
/// e verifica che la posizione interpolata dal client coincida con quella inviata dal server
|
||||
/// (scarto < 1 cella sui tratti a velocità costante).
|
||||
/// </summary>
|
||||
public sealed class SmokeCommand : IToolCommand
|
||||
{
|
||||
public string Name => "smoke";
|
||||
|
||||
public string Usage => "smoke --url ws://127.0.0.1:7400/ws [--token <t>] [--timeout 600]";
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
string url = args.String("url", "ws://127.0.0.1:7400/ws");
|
||||
string token = args.String("token", "");
|
||||
int timeout = args.Int("timeout", 600);
|
||||
args.EnsureAllUsed();
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeout));
|
||||
try
|
||||
{
|
||||
return RunAsync(new Uri(url), token, cts.Token).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Console.Error.WriteLine("smoke: tempo scaduto");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Session(ProtocolClient connection, ClientWorld world)
|
||||
{
|
||||
public ProtocolClient Connection { get; } = connection;
|
||||
public ClientWorld World { get; } = world;
|
||||
public Dictionary<uint, CommandResultMessage> Results { get; } = [];
|
||||
public List<TrainMotion> Motions { get; } = [];
|
||||
|
||||
public async Task Until(Func<bool> condition, CancellationToken ct)
|
||||
{
|
||||
while (!condition())
|
||||
{
|
||||
var m = await Connection.ReceiveAsync(ct);
|
||||
if (m is CommandResultMessage r) Results[r.Seq] = r;
|
||||
if (m is TrainMotion tm) Motions.Add(tm);
|
||||
World.Apply(m);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<CommandResultMessage> Do(GameCommand c, CancellationToken ct)
|
||||
{
|
||||
uint seq = await Connection.SendCommandAsync(c, ct);
|
||||
await Until(() => Results.ContainsKey(seq), ct);
|
||||
return Results[seq];
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<int> RunAsync(Uri url, string token, CancellationToken ct)
|
||||
{
|
||||
var data = GameData.LoadDefault();
|
||||
var clock = Stopwatch.StartNew();
|
||||
await using var connection = await ProtocolClient.ConnectAsync(url, ct);
|
||||
var welcome = await connection.HandshakeAsync(new Hello { ClientVersion = "smoke", Token = token, DataHash = data.Hash }, ct);
|
||||
var s = new Session(connection, new ClientWorld(data));
|
||||
var w = s.World;
|
||||
w.Apply(welcome);
|
||||
var summary = welcome.Summary;
|
||||
Console.WriteLine($"smoke: sessione {welcome.SessionId:x}, mappa {summary.SizeKm} km, {summary.Date}");
|
||||
await connection.SendAsync(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 }, ct);
|
||||
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
|
||||
await s.Until(() => w.Chunks.Count == chunks && w.Companies.Count > 0, ct);
|
||||
Console.WriteLine($" terreno ricevuto: {chunks} chunk, hash {w.Terrain!.ComputeHash():x16} (server {summary.TerrainHash:x16})");
|
||||
if (w.Terrain.ComputeHash() != summary.TerrainHash) return Fail("terreno diverso da quello del server");
|
||||
|
||||
// capitale: un prestito per stazioni, deposito, binario e treno (il più grande concesso)
|
||||
for (long lire = 400_000; lire >= 25_000; lire /= 2)
|
||||
{
|
||||
var loan = await s.Do(new TakeLoanCommand(Money.FromLire(lire)), ct);
|
||||
if (!loan.Ok) continue;
|
||||
Console.WriteLine($" prestito di {Money.FromLire(lire)}");
|
||||
break;
|
||||
}
|
||||
await s.Until(() => w.Companies.TryGetValue(summary.CompanyId, out var c) && c.Cash.Cents > 0, ct);
|
||||
var site = BridgeSiteFinder.Find(w);
|
||||
if (site is null) return Fail("nessun attraversamento di fiume adatto trovato");
|
||||
var (a, b, depotAt, _) = site.Value;
|
||||
Console.WriteLine($" sito: da ({a.X / 1000:F2}, {a.Y / 1000:F2}) a ({b.X / 1000:F2}, {b.Y / 1000:F2}) km");
|
||||
|
||||
var sa = await s.Do(new BuildStationCommand(a, 2, "Smoke Ovest"), ct);
|
||||
var sb = await s.Do(new BuildStationCommand(b, 2, "Smoke Est"), ct);
|
||||
var sd = await s.Do(new BuildDepotCommand(depotAt, "small", "Smoke Deposito"), ct);
|
||||
if (!sa.Ok || !sb.Ok || !sd.Ok) return Fail($"stazioni: {sa.Message} / {sb.Message} / {sd.Message}");
|
||||
await s.Until(() => w.Stations.ContainsKey(sb.Created[0]) && w.Depots.ContainsKey(sd.Created[0]), ct);
|
||||
|
||||
var main = new BuildTrackCommand([a, b]);
|
||||
var preview = w.PreviewTrack(main);
|
||||
if (!preview.Valid) return Fail("anteprima non valida: " + string.Join("; ", preview.Errors.Select(e => e.Message)));
|
||||
var built = await s.Do(main with { ExpectedCostCents = preview.TotalCost.Cents }, ct);
|
||||
if (!built.Ok) return Fail($"binario: {built.Message}");
|
||||
Console.WriteLine($" binario: {preview.LengthM / 1000:F2} km, ponte {preview.LengthOf(WorkKind.Bridge):F0} m, {preview.TotalCost}, {preview.Days} giorni (anteprima = server)");
|
||||
int edge = built.Created[0];
|
||||
await s.Until(() => w.Edges.ContainsKey(edge), ct);
|
||||
var info = w.Edges[edge];
|
||||
for (int i = 0; i < info.S.Length; i++)
|
||||
{
|
||||
if (info.S.Length != preview.Samples.Count || info.H[i] != preview.Samples[i].TrackM) return Fail($"profilo diverso al campione {i}");
|
||||
}
|
||||
var spur = new BuildTrackCommand([depotAt, a]);
|
||||
var spurPreview = w.PreviewTrack(spur);
|
||||
var spurBuilt = await s.Do(spur with { ExpectedCostCents = spurPreview.Valid ? spurPreview.TotalCost.Cents : 0 }, ct);
|
||||
if (!spurBuilt.Ok) return Fail($"raccordo del deposito: {spurBuilt.Message}");
|
||||
|
||||
await connection.SendAsync(new SetSpeed { Speed = 8 }, ct);
|
||||
await s.Until(() => w.Edges.Values.All(e => e.State == (byte)EdgeState.Active), ct);
|
||||
Console.WriteLine($" cantieri completati: {w.LastDigest?.Date} ({clock.Elapsed.TotalSeconds:F0} s)");
|
||||
|
||||
int depot = sd.Created[0];
|
||||
var loco = await s.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1), ct);
|
||||
var cars = await s.Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3), ct);
|
||||
if (!loco.Ok || !cars.Ok) return Fail($"acquisto: {loco.Message} / {cars.Message}");
|
||||
var train = await s.Do(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(cars.Created).Select(i => new VehicleId(i)).ToList(), "Treno di collaudo"), ct);
|
||||
var line = await s.Do(new CreateLineCommand("Linea di collaudo", "#e0a526", [new LineStop(new StationId(sa.Created[0])), new LineStop(new StationId(sb.Created[0]))]), ct);
|
||||
if (!train.Ok || !line.Ok) return Fail($"treno o linea: {train.Message} / {line.Message}");
|
||||
int trainId = train.Created[0];
|
||||
var assign = await s.Do(new AssignTrainCommand(new TrainId(trainId), new LineId(line.Created[0])), ct);
|
||||
if (!assign.Ok) return Fail(assign.Message);
|
||||
|
||||
// a velocità 1 si confronta la posizione estrapolata dal client con quella del moto successivo
|
||||
await connection.SendAsync(new SetSpeed { Speed = 1 }, ct);
|
||||
var calendar = w.Calendar!;
|
||||
int pairs = 0;
|
||||
double worst = 0;
|
||||
s.Motions.Clear();
|
||||
await s.Until(() =>
|
||||
{
|
||||
var list = s.Motions.Where(m => m.TrainId == trainId).ToList();
|
||||
pairs = 0;
|
||||
worst = 0;
|
||||
for (int i = 1; i < list.Count; i++)
|
||||
{
|
||||
var p = list[i - 1];
|
||||
var q = list[i];
|
||||
if (p.Speed < 1 || Math.Abs(p.Speed - q.Speed) > 0.05 || q.Tick <= p.Tick || q.Tick - p.Tick > 20) continue;
|
||||
var predicted = w.TrainHead(p, (q.Tick - p.Tick) * calendar.TrainSecondsPerTick);
|
||||
var actual = w.PointAlong(q, q.HeadDistance);
|
||||
if (predicted is null || actual is null) continue;
|
||||
worst = Math.Max(worst, Vec2.Distance(predicted.Value, actual.Value));
|
||||
pairs++;
|
||||
}
|
||||
return pairs >= 5;
|
||||
}, ct);
|
||||
Console.WriteLine($" treno {trainId} in moto: {pairs} confronti, scarto massimo {worst:F2} m (limite {summary.CellSizeM:F0} m)");
|
||||
await connection.SendAsync(new SetSpeed { Speed = 1 }, ct);
|
||||
if (worst >= summary.CellSizeM) return Fail("posizione del treno incoerente");
|
||||
Console.WriteLine($"smoke: ok in {clock.Elapsed.TotalSeconds:F0} s");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Fail(string why)
|
||||
{
|
||||
Console.Error.WriteLine($"smoke: FALLITO — {why}");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using RailEnterprise.Core.Data;
|
||||
|
||||
namespace RailEnterprise.Tools.Commands;
|
||||
|
||||
/// <summary>validate-data [--data cartella]: valida schema e semantica di tutti i file dati.</summary>
|
||||
public sealed class ValidateDataCommand : IToolCommand
|
||||
{
|
||||
public string Name => "validate-data";
|
||||
|
||||
public string Usage => "validate-data [--data <cartella>] valida data/*.json con schema e regole semantiche";
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
string? dir = args.String("data");
|
||||
args.EnsureAllUsed();
|
||||
var source = dir is null ? DirectoryDataSource.FindDefault() : new DirectoryDataSource(dir);
|
||||
try
|
||||
{
|
||||
var data = GameData.Load(source);
|
||||
Console.WriteLine($"validate-data: ok ({source.Description})");
|
||||
Console.WriteLine($" beni {data.Goods.Count}, industrie {data.Industries.Count}, veicoli {data.Vehicles.Count}, " +
|
||||
$"ere {data.Eras.Eras.Count}, livelli {data.Tiers.Tiers.Count}, difficoltà {data.Difficulty.Presets.Count}");
|
||||
Console.WriteLine($" hash dei dati {data.Hash:x16}");
|
||||
return 0;
|
||||
}
|
||||
catch (DataValidationException ex)
|
||||
{
|
||||
Console.Error.WriteLine(ex.Message);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using RailEnterprise.Core.Map;
|
||||
|
||||
namespace RailEnterprise.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// Rendering di controllo della mappa con la palette dell'immagine di riferimento 05:
|
||||
/// colore per tipo di cella, fasce altimetriche, ombreggiatura da nord-ovest, città e industrie.
|
||||
/// </summary>
|
||||
public static class MapRenderer
|
||||
{
|
||||
private static (byte R, byte G, byte B) Hex(int rgb) => ((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
|
||||
|
||||
private static readonly (byte R, byte G, byte B) Plain = Hex(0xcfd7bd);
|
||||
private static readonly (byte R, byte G, byte B) Hill = Hex(0xc0c8a6);
|
||||
private static readonly (byte R, byte G, byte B) Mountain = Hex(0xaeb690);
|
||||
private static readonly (byte R, byte G, byte B) Forest = Hex(0x5f8f4a);
|
||||
private static readonly (byte R, byte G, byte B) Field = Hex(0xd9c26a);
|
||||
private static readonly (byte R, byte G, byte B) Water = Hex(0x8fb4c6);
|
||||
private static readonly (byte R, byte G, byte B) Sea = Hex(0x8fb4c6);
|
||||
private static readonly (byte R, byte G, byte B) Town = Hex(0xb3573e);
|
||||
private static readonly (byte R, byte G, byte B) Industry = Hex(0x7c8590);
|
||||
private static readonly (byte R, byte G, byte B) Rock = Hex(0x9a9a8a);
|
||||
private static readonly (byte R, byte G, byte B) Marsh = Hex(0x9db38a);
|
||||
|
||||
public static byte[] Render(GeneratedMap map, int scale, out int width, out int height)
|
||||
{
|
||||
var t = map.Terrain;
|
||||
width = t.Width / scale;
|
||||
height = t.Height / scale;
|
||||
var rgb = new byte[width * height * 3];
|
||||
var sampler = new TerrainSampler(t);
|
||||
for (int py = 0; py < height; py++)
|
||||
{
|
||||
for (int px = 0; px < width; px++)
|
||||
{
|
||||
int x = px * scale + scale / 2, y = py * scale + scale / 2;
|
||||
var type = t.TypeAt(x, y);
|
||||
var c = type switch
|
||||
{
|
||||
CellType.Plain => Plain,
|
||||
CellType.Hill => Hill,
|
||||
CellType.Mountain => Mountain,
|
||||
CellType.Forest => Forest,
|
||||
CellType.Field => Field,
|
||||
CellType.Water => Water,
|
||||
CellType.Sea => Sea,
|
||||
CellType.Town => Town,
|
||||
CellType.Industry => Industry,
|
||||
CellType.Rock => Rock,
|
||||
_ => Marsh,
|
||||
};
|
||||
double shade = 1.0;
|
||||
if (type is not (CellType.Sea or CellType.Water))
|
||||
{
|
||||
// ombreggiatura: luce da nord-ovest, ombre verso sud-est
|
||||
var g = sampler.Gradient((x + 0.5) * t.CellSizeM, (y + 0.5) * t.CellSizeM);
|
||||
double light = (-g.X * -0.7071 + -g.Y * -0.7071) * 6.0;
|
||||
shade = Math.Clamp(1.0 + light, 0.6, 1.25);
|
||||
// fasce altimetriche leggere
|
||||
double h = t.CellHeightM(x, y);
|
||||
shade *= 1.0 - Math.Min(0.18, h / 2200.0 * 0.18);
|
||||
if (Math.Abs(h % 100) < 4 && h > 50) shade *= 0.93;
|
||||
}
|
||||
int o = (py * width + px) * 3;
|
||||
rgb[o] = (byte)Math.Clamp(c.R * shade, 0, 255);
|
||||
rgb[o + 1] = (byte)Math.Clamp(c.G * shade, 0, 255);
|
||||
rgb[o + 2] = (byte)Math.Clamp(c.B * shade, 0, 255);
|
||||
}
|
||||
}
|
||||
return rgb;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using RailEnterprise.Tools.Commands;
|
||||
|
||||
namespace RailEnterprise.Tools;
|
||||
|
||||
/// <summary>Strumenti da riga di comando di Rail Enterprise.</summary>
|
||||
public static class ToolsProgram
|
||||
{
|
||||
private static readonly IToolCommand[] Commands =
|
||||
[
|
||||
new ValidateDataCommand(),
|
||||
new GenMapCommand(),
|
||||
new SimulateCommand(),
|
||||
new ProfileCommand(),
|
||||
new BenchCommand(),
|
||||
new SmokeCommand(),
|
||||
new ReplayCommand(),
|
||||
];
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
|
||||
{
|
||||
PrintHelp();
|
||||
return args.Length == 0 ? 1 : 0;
|
||||
}
|
||||
var command = Commands.FirstOrDefault(c => c.Name == args[0]);
|
||||
if (command is null)
|
||||
{
|
||||
Console.Error.WriteLine($"Comando sconosciuto: {args[0]}");
|
||||
PrintHelp();
|
||||
return 1;
|
||||
}
|
||||
try
|
||||
{
|
||||
return command.Run(new CommandLine(args[1..]));
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
Console.Error.WriteLine($"{command.Name}: {ex.Message}");
|
||||
Console.Error.WriteLine($"uso: railenterprise-tools {command.Usage}");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
private static void PrintHelp()
|
||||
{
|
||||
Console.WriteLine("railenterprise-tools <comando> [opzioni]");
|
||||
foreach (var c in Commands) Console.WriteLine($" {c.Usage}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Strumenti da riga di comando: validate-data, genmap, profile, simulate, bench, replay. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<AssemblyName>railenterprise-tools</AssemblyName>
|
||||
<RootNamespace>RailEnterprise.Tools</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\RailEnterprise.Core\RailEnterprise.Core.csproj" />
|
||||
<ProjectReference Include="..\RailEnterprise.Protocol\RailEnterprise.Protocol.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\..\data\**\*.json" LinkBase="data" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace RailEnterprise.Tools.Scenarios;
|
||||
|
||||
/// <summary>Accesso agli scenari di Core dagli strumenti.</summary>
|
||||
public static class ScenarioLoader
|
||||
{
|
||||
public static Core.Simulation.Scenarios.LoadedScenario Load(Core.Data.GameData data, string path) =>
|
||||
Core.Simulation.Scenarios.ScenarioLoader.LoadFile(data, path);
|
||||
}
|
||||
Reference in new issue
Block a user