F3: client Godot minimo, replay dei comandi e collaudi automatici
- Client Godot 4.7 .NET (Godot.NET.Sdk 4.7.2): menu, collegamento, partita locale con server figlio; mappa con terreno (fasce, ombreggiatura, rive curve con shader, curve di livello), opere, entità, alberi, treni interpolati con fumo; strumenti binari con profilo, stazione, deposito, segnali, demolizione; pannelli treni, linee, mercato, finanze, schede; barra superiore, minimappa, notiziario; italiano e inglese. - Pilota automatico del client e scripts/client-autopilot.sh: partita locale, linea con ponte, treni in moto e schermate (docs/screenshots). - Registro dei comandi del server (--record) e viaferrea-tools replay. - PROTOCOL.md normativo, ADR 0009, ARCHITECTURE, STATE e README aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
97 files changed
+5151
-96
No files matched your search
@@ -0,0 +1,49 @@
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Map;
|
||||
using ViaFerrea.Core.Rail;
|
||||
|
||||
namespace ViaFerrea.Protocol.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Collaudi (viaferrea-tools smoke, pilota automatico del client): cerca sulla copia locale del
|
||||
/// terreno un attraversamento di fiume rettilineo di 1,5–2,5 km con estremità e deposito su
|
||||
/// terreno libero e un'anteprima valida con ponte.
|
||||
/// </summary>
|
||||
public static class BridgeSiteFinder
|
||||
{
|
||||
public readonly record struct Site(Vec2 A, Vec2 B, Vec2 Depot, Vec2 River);
|
||||
|
||||
public static Site? Find(ClientWorld w, ulong seed = 7, int attempts = 400, int maxDays = 120)
|
||||
{
|
||||
var t = w.Terrain ?? throw new InvalidOperationException("Terreno non ricevuto");
|
||||
var rng = new Rng(seed);
|
||||
bool Free(Vec2 p)
|
||||
{
|
||||
if (p.X < 2000 || p.Y < 2000 || p.X > t.WidthM - 2000 || p.Y > t.HeightM - 2000) return false;
|
||||
var (x, y) = t.CellAt(p);
|
||||
return (CellType)t.Types[y * t.Width + x] is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill;
|
||||
}
|
||||
var rivers = new List<int>();
|
||||
for (int i = 0; i < t.RiverWidth.Length; i++)
|
||||
{
|
||||
if (t.RiverWidth[i] > 0) rivers.Add(i);
|
||||
}
|
||||
if (rivers.Count == 0) return null;
|
||||
for (int attempt = 0; attempt < attempts; attempt++)
|
||||
{
|
||||
int cell = rivers[rng.NextInt(rivers.Count)];
|
||||
var center = t.CellCenter(cell % t.Width, cell / t.Width);
|
||||
double angle = rng.NextDouble(0, Math.PI);
|
||||
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
|
||||
double half = rng.NextDouble(750, 1250);
|
||||
var a = center - dir * half;
|
||||
var b = center + dir * half;
|
||||
var depot = a - dir * 600;
|
||||
if (!Free(a) || !Free(b) || !Free(depot)) continue;
|
||||
var plan = w.PreviewTrack(new BuildTrackCommand([a, b]));
|
||||
if (plan.Valid && plan.LengthOf(WorkKind.Bridge) > 0 && plan.Days <= maxDays) return new Site(a, b, depot, center);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,9 @@ public sealed class ProtocolClient : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Riserva un numero di sequenza (per registrare l'attesa dell'esito prima dell'invio).</summary>
|
||||
public uint ReserveSeq() => Interlocked.Increment(ref _seq);
|
||||
|
||||
/// <summary>Invia un comando con un nuovo numero di sequenza e lo restituisce.</summary>
|
||||
public async Task<uint> SendCommandAsync(GameCommand command, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Buffers.Binary;
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
|
||||
namespace ViaFerrea.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// Registro dei comandi per il replay: intestazione «VFCL» + versione, poi record
|
||||
/// <c>[u32 lunghezza][i64 tick][i32 emittente][u32 seq][u16 tipo][payload]</c> con il payload
|
||||
/// del protocollo. Il server lo scrive con <c>--record</c>, <c>viaferrea-tools replay</c> lo rilegge.
|
||||
/// </summary>
|
||||
public static class CommandLogFile
|
||||
{
|
||||
private static ReadOnlySpan<byte> Magic => "VFCL"u8;
|
||||
public const ushort Version = 1;
|
||||
|
||||
public static void WriteHeader(Stream s)
|
||||
{
|
||||
s.Write(Magic);
|
||||
Span<byte> v = stackalloc byte[2];
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(v, Version);
|
||||
s.Write(v);
|
||||
}
|
||||
|
||||
public static void Append(Stream s, long tick, GameCommand command)
|
||||
{
|
||||
var w = new SpanWriter(128);
|
||||
w.U32(0);
|
||||
w.I64(tick);
|
||||
w.I32(command.Issuer.Value);
|
||||
w.U32(command.Seq);
|
||||
w.U16((ushort)command.Type);
|
||||
CommandCodec.Write(ref w, command);
|
||||
w.PatchU32(0, (uint)(w.Length - 4));
|
||||
s.Write(w.Written);
|
||||
}
|
||||
|
||||
public static List<(long Tick, GameCommand Command)> ReadAll(byte[] file)
|
||||
{
|
||||
if (file.Length < 6 || !file.AsSpan(0, 4).SequenceEqual(Magic)) throw new ProtocolException("non è un registro di comandi di Via Ferrea");
|
||||
ushort version = BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(4));
|
||||
if (version > Version) throw new ProtocolException($"registro di versione più recente ({version})");
|
||||
var list = new List<(long, GameCommand)>();
|
||||
int pos = 6;
|
||||
while (pos + 4 <= file.Length)
|
||||
{
|
||||
int length = (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos));
|
||||
if (length < 18 || pos + 4 + length > file.Length) throw new ProtocolException("registro troncato");
|
||||
var r = new SpanReader(file.AsSpan(pos + 4, length));
|
||||
long tick = r.I64();
|
||||
var issuer = new CompanyId(r.I32());
|
||||
uint seq = r.U32();
|
||||
var type = (CommandType)r.U16();
|
||||
var command = CommandCodec.Read(type, ref r) with { Issuer = issuer, Seq = seq };
|
||||
list.Add((tick, command));
|
||||
pos += 4 + length;
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,7 @@ public sealed class GameHost : IDisposable
|
||||
private bool _dailyDue;
|
||||
private bool _monthlyDue;
|
||||
private ulong _lastTerrainHash;
|
||||
private FileStream? _record;
|
||||
|
||||
// istantanee per /metrics (lette da altri thread)
|
||||
private volatile int _sessionCount;
|
||||
@@ -67,6 +68,15 @@ public sealed class GameHost : IDisposable
|
||||
_saves = new SaveStore(config.SavesDir, GameVersion);
|
||||
_world = world ?? InitialWorld();
|
||||
_lastTerrainHash = _world.Terrain.ComputeHash();
|
||||
if (config.RecordPath is { Length: > 0 } path)
|
||||
{
|
||||
// registro dei comandi: si apre con un salvataggio di partenza accanto
|
||||
_record = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
|
||||
Protocol.CommandLogFile.WriteHeader(_record);
|
||||
Core.Persistence.SaveFile.SaveToFile(_world, path + ".start.vfsave", GameVersion);
|
||||
_world.CommandLog = [];
|
||||
_log.LogInformation("Registro dei comandi in {Path}", path);
|
||||
}
|
||||
}
|
||||
|
||||
public SaveStore Saves => _saves;
|
||||
@@ -109,6 +119,7 @@ public sealed class GameHost : IDisposable
|
||||
{
|
||||
_stop = true;
|
||||
_thread?.Join(5000);
|
||||
_record?.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Esegue un'azione sul thread del ciclo di gioco.</summary>
|
||||
@@ -337,6 +348,12 @@ public sealed class GameHost : IDisposable
|
||||
Interlocked.Exchange(ref _tickMsBits, BitConverter.DoubleToInt64Bits(_tickMsEma));
|
||||
Interlocked.Increment(ref _ticks);
|
||||
|
||||
if (_record is not null && w.CommandLog is { Count: > 0 } log)
|
||||
{
|
||||
foreach (var (tick, command) in log) Protocol.CommandLogFile.Append(_record, tick, command);
|
||||
log.Clear();
|
||||
_record.Flush();
|
||||
}
|
||||
foreach (var r in w.DrainResults())
|
||||
{
|
||||
if (r.Ok) _publishDirty = true;
|
||||
|
||||
@@ -20,6 +20,8 @@ public sealed class ServerConfig
|
||||
/// <summary>Processo locale figlio del client: porta casuale su 127.0.0.1, stampa «LISTENING porta».</summary>
|
||||
public bool Local { get; init; }
|
||||
public bool HealthCheck { get; init; }
|
||||
/// <summary>File in cui registrare i comandi eseguiti (per <c>viaferrea-tools replay</c>).</summary>
|
||||
public string? RecordPath { get; init; }
|
||||
/// <summary>Numero massimo di sessioni contemporanee.</summary>
|
||||
public int MaxSessions { get; init; } = 16;
|
||||
|
||||
@@ -43,6 +45,7 @@ public sealed class ServerConfig
|
||||
{
|
||||
Local = local,
|
||||
HealthCheck = args.Contains("--healthcheck"),
|
||||
RecordPath = Arg("--record") ?? Env("VF_RECORD"),
|
||||
Port = int.TryParse(Arg("--port") ?? Env("VF_PORT"), out int port) ? port : 7400,
|
||||
Token = Arg("--token") ?? Env("VF_TOKEN") ?? "",
|
||||
DataDir = dataDir,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Diagnostics;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Persistence;
|
||||
using ViaFerrea.Protocol;
|
||||
|
||||
namespace ViaFerrea.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;
|
||||
}
|
||||
}
|
||||
@@ -93,9 +93,9 @@ public sealed class SmokeCommand : IToolCommand
|
||||
break;
|
||||
}
|
||||
await s.Until(() => w.Companies.TryGetValue(summary.CompanyId, out var c) && c.Cash.Cents > 0, ct);
|
||||
var site = FindBridgeSite(w);
|
||||
var site = BridgeSiteFinder.Find(w);
|
||||
if (site is null) return Fail("nessun attraversamento di fiume adatto trovato");
|
||||
var (a, b, depotAt) = site.Value;
|
||||
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);
|
||||
@@ -173,41 +173,4 @@ public sealed class SmokeCommand : IToolCommand
|
||||
Console.Error.WriteLine($"smoke: FALLITO — {why}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cerca un attraversamento di fiume rettilineo di 1,5–2,5 km con estremità e deposito su
|
||||
/// terreno libero e un'anteprima valida con ponte.
|
||||
/// </summary>
|
||||
private static (Vec2 A, Vec2 B, Vec2 Depot)? FindBridgeSite(ClientWorld w)
|
||||
{
|
||||
var t = w.Terrain!;
|
||||
var rng = new Rng(7);
|
||||
bool Free(Vec2 p)
|
||||
{
|
||||
if (p.X < 2000 || p.Y < 2000 || p.X > t.WidthM - 2000 || p.Y > t.HeightM - 2000) return false;
|
||||
var (x, y) = t.CellAt(p);
|
||||
return (CellType)t.Types[y * t.Width + x] is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill;
|
||||
}
|
||||
var rivers = new List<int>();
|
||||
for (int i = 0; i < t.RiverWidth.Length; i++)
|
||||
{
|
||||
if (t.RiverWidth[i] > 0) rivers.Add(i);
|
||||
}
|
||||
if (rivers.Count == 0) return null;
|
||||
for (int attempt = 0; attempt < 400; attempt++)
|
||||
{
|
||||
int cell = rivers[rng.NextInt(rivers.Count)];
|
||||
var center = t.CellCenter(cell % t.Width, cell / t.Width);
|
||||
double angle = rng.NextDouble(0, Math.PI);
|
||||
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
|
||||
double half = rng.NextDouble(750, 1250);
|
||||
var a = center - dir * half;
|
||||
var b = center + dir * half;
|
||||
var depot = a - dir * 600;
|
||||
if (!Free(a) || !Free(b) || !Free(depot)) continue;
|
||||
var plan = w.PreviewTrack(new BuildTrackCommand([a, b]));
|
||||
if (plan.Valid && plan.LengthOf(WorkKind.Bridge) > 0 && plan.Days <= 120) return (a, b, depot);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ public static class ToolsProgram
|
||||
new ProfileCommand(),
|
||||
new BenchCommand(),
|
||||
new SmokeCommand(),
|
||||
new ReplayCommand(),
|
||||
];
|
||||
|
||||
public static int Main(string[] args)
|
||||
|
||||
Reference in new issue
Block a user