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:
Claude committed 2026-10-02 00:47:42 +00:00
1 parent 5a318e6528
commit 9a4ada6d9d
97 files changed
+5151 -96

No files matched your search

@@ -0,0 +1,166 @@
using Godot;
using ViaFerrea.Client.Hud;
using ViaFerrea.Client.Map;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Screens;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.App;
/// <summary>
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
/// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno,
/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo.
/// </summary>
public partial class AutoPilot : Node
{
private readonly GameScreen _game;
private readonly string _out;
public AutoPilot(GameScreen game, string outDir)
{
_game = game;
_out = outDir;
}
private GameSession Session => _game.Session;
private ClientWorld World => _game.Session.World;
public override async void _Ready()
{
int code = 0;
try
{
await Run();
GD.Print("autopilot: ok");
}
catch (Exception e)
{
GD.PrintErr($"autopilot: FALLITO {e.Message}\n{e.StackTrace}");
code = 1;
}
GetTree().Quit(code);
}
private async Task Frame() => await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
private async Task Until(Func<bool> condition, string what, double timeoutS = 120)
{
ulong start = Time.GetTicksMsec();
while (!condition())
{
if (Time.GetTicksMsec() - start > timeoutS * 1000) throw new TimeoutException(what);
await Frame();
}
}
private Task<CommandResultMessage> Do(GameCommand command)
{
var tcs = new TaskCompletionSource<CommandResultMessage>();
Session.Command(command, r => tcs.TrySetResult(r));
return tcs.Task;
}
private async Task<int> Ok(GameCommand command)
{
var r = await Do(command);
if (!r.Ok) throw new InvalidOperationException($"{command.Type}: {r.Message}");
GD.Print($"autopilot: {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
private async Task Shot(string name, int settleFrames = 30)
{
for (int i = 0; i < settleFrames; i++) await Frame();
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
var image = GetViewport().GetTexture().GetImage();
string path = Path.Combine(_out, name + ".jpg");
image.SaveJpg(path, 0.88f);
GD.Print($"autopilot: schermata {path}");
}
private async Task Run()
{
Directory.CreateDirectory(_out);
var summary = World.Summary!;
Session.Send(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 });
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
await Until(() => World.Chunks.Count == chunks && World.Towns.Count > 0, "terreno");
await Shot("01_avvio", 90);
await Ok(new TakeLoanCommand(Money.FromLire(200_000)));
var site = BridgeSiteFinder.Find(World) ?? throw new InvalidOperationException("nessun sito con ponte");
int a = await Ok(new BuildStationCommand(site.A, 2));
int b = await Ok(new BuildStationCommand(site.B, 2));
int depot = await Ok(new BuildDepotCommand(site.Depot, "small"));
await Until(() => World.Stations.ContainsKey(b) && World.Depots.ContainsKey(depot), "stazioni");
var main = new BuildTrackCommand([site.A, site.B]);
var plan = World.PreviewTrack(main);
await Ok(main with { ExpectedCostCents = plan.TotalCost.Cents });
await Until(() => World.Edges.Count > 0, "binario");
var spur = new BuildTrackCommand([site.Depot, site.A]);
await Ok(spur with { ExpectedCostCents = World.PreviewTrack(spur).TotalCost.Cents });
// vista d'insieme del cantiere
var center = MapScale.V((site.A + site.B) / 2);
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("02_cantiere");
Session.SetSpeed(8);
await Until(() => World.Edges.Count >= 2 && World.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri", 240);
var loco = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var wagons = await Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3));
int train = await Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
var loco2 = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var coaches = await Do(new BuyVehicleCommand("coach_worker", new DepotId(depot), 2));
int train2 = await Ok(new ComposeTrainCommand(new DepotId(depot), loco2.Created.Concat(coaches.Created).Select(i => new VehicleId(i)).ToList(), "Treno 2"));
int line = await Ok(new CreateLineCommand("Linea 1, collaudo", "#e0a526", [new LineStop(new StationId(a)), new LineStop(new StationId(b))]));
await Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
Session.SetSpeed(1);
await Until(() => World.Motions.TryGetValue(train, out var m) && m.Speed > 3, "treno in moto", 120);
await Ok(new AssignTrainCommand(new TrainId(train2), new LineId(line)));
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("03_linea");
// ponte da vicino (immagine 02)
_game.Map.CenterOn(MapScale.V(site.River));
_game.Map.SetZoom(0.9f);
await Shot("04_ponte");
// treno da vicino (immagine 03): la camera lo segue per qualche fotogramma
for (int i = 0; i < 40; i++)
{
if (World.TrainHead(train) is { } head) _game.Map.CenterOn(MapScale.V(head));
_game.Map.SetZoom(1.4f);
await Frame();
}
_game.SelectTrain(train);
await Shot("05_treno", 5);
// scheda del treno con la mappa d'insieme
_game.Map.SetZoom(0.3f);
await Shot("06_scheda_treno", 20);
// strumento binari con il profilo di un tracciato in collina
_game.UseTool(Tool.Track);
var dir = (site.B - site.A).Normalized();
var normal = new Vec2(-dir.Y, dir.X);
var p0 = MapScale.V(site.B);
var p1 = MapScale.V(site.B + normal * 2500);
var p2 = MapScale.V(site.B + normal * 4000 + dir * 1500);
_game.SetTrackPoints([p0, p1], p2);
_game.Map.CenterOn(MapScale.V(site.B + normal * 2000 + dir * 500));
_game.Map.SetZoom(0.2f);
await Shot("07_profilo", 40);
_game.UseTool(Tool.None);
_game.Map.SetZoom(0.06f);
await Shot("08_panoramica", 60);
}
}
@@ -0,0 +1 @@
uid://bdw1fy2qphri5
@@ -0,0 +1,26 @@
using Godot;
using ViaFerrea.Core.Data;
namespace ViaFerrea.Client.App;
/// <summary>File dati del gioco dentro il progetto Godot (res://data, copiati dalla build del client).</summary>
public sealed class GodotDataSource(string root = "res://data") : IDataSource
{
public string Description => root;
public bool Exists(string relativePath) => Godot.FileAccess.FileExists($"{root}/{relativePath}");
public string ReadText(string relativePath)
{
using var f = Godot.FileAccess.Open($"{root}/{relativePath}", Godot.FileAccess.ModeFlags.Read)
?? throw new FileNotFoundException(relativePath);
return f.GetAsText();
}
/// <summary>Dati del gioco: res://data se presenti, altrimenti la cartella data del repository.</summary>
public static GameData LoadGameData()
{
var source = new GodotDataSource();
return source.Exists("goods.json") ? GameData.Load(source) : GameData.LoadDefault();
}
}
@@ -0,0 +1 @@
uid://bn1h4nbl2f1rc
@@ -0,0 +1,43 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>
/// Testi dell'interfaccia: la lingua sorgente è l'italiano (le chiavi sono i testi italiani),
/// le traduzioni stanno in <c>assets/i18n/strings.csv</c> (colonne keys, it, en) e si caricano
/// all'avvio senza passare dall'importazione dell'editor.
/// </summary>
public static class Localization
{
public static void Load(string locale)
{
const string path = "res://assets/i18n/strings.csv";
using var file = Godot.FileAccess.Open(path, Godot.FileAccess.ModeFlags.Read);
if (file is null)
{
GD.PushWarning("Traduzioni non trovate");
return;
}
string[] header = file.GetCsvLine();
var translations = new List<Translation>();
for (int c = 1; c < header.Length; c++)
{
var t = new Translation { Locale = header[c] };
translations.Add(t);
}
while (!file.EofReached())
{
string[] row = file.GetCsvLine();
if (row.Length < 2 || row[0].Length == 0) continue;
for (int c = 1; c < row.Length && c - 1 < translations.Count; c++)
{
if (row[c].Length > 0) translations[c - 1].AddMessage(row[0], row[c]);
}
}
foreach (var t in translations) TranslationServer.AddTranslation(t);
TranslationServer.SetLocale(locale);
}
/// <summary>Traduce un testo dell'interfaccia (chiave = testo italiano).</summary>
public static string T(string italian) => TranslationServer.Translate(italian);
}
@@ -0,0 +1 @@
uid://bxob5yr4t8lu8
@@ -0,0 +1,43 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>Palette dell'immagine di riferimento 05: interfaccia blu-ardesia con accento ambra, mappa cartografica chiara.</summary>
public static class Palette
{
// interfaccia
public static readonly Color AppBackground = new("11181c");
public static readonly Color Panel = new("172127");
public static readonly Color Inner = new("1f2a30");
public static readonly Color Border = new("2c3a42");
public static readonly Color Text = new("dde3e6");
public static readonly Color TextSecondary = new("9fb0b8");
public static readonly Color Amber = new("e0a526");
public static readonly Color AmberLight = new("f0bd52");
public static readonly Color AmberDark = new("3a2c12");
public static readonly Color Workers = new("3f86d1");
public static readonly Color Staff = new("9cc9f2");
public static readonly Color Ok = new("5fc39b");
public static readonly Color Danger = new("b3573e");
// mappa
public static readonly Color Plain = new("cfd7bd");
public static readonly Color Hill = new("c0c8a6");
public static readonly Color Highland = new("aeb690");
public static readonly Color Undergrowth = new("9db38a");
public static readonly Color Canopy = new("5f8f4a");
public static readonly Color Water = new("8fb4c6");
public static readonly Color Banks = new("b9bf9c");
public static readonly Color Grain = new("d9c26a");
public static readonly Color TileRoof = new("b3573e");
public static readonly Color IndustrialRoof = new("7c8590");
public static readonly Color Ballast = new("bfb79f");
public static readonly Color Sleepers = new("5b4a39");
public static readonly Color Rails = new("3b3f42");
public static readonly Color Construction = new("8a7a52");
public static readonly Color Rock = new("9a9a8c");
public static readonly Color Marsh = new("a9bba0");
public static readonly Color Sea = new("86adc0");
public static Color WithAlpha(Color c, float a) => new(c.R, c.G, c.B, a);
}
@@ -0,0 +1 @@
uid://blsg133y5mi21
@@ -0,0 +1,144 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>
/// Tema dell'interfaccia costruito in codice dalla palette (immagine 05): titoli in Big Shoulders
/// Display 800, testo e numeri in IBM Plex Sans; raggio 8–12 px, bordi 1 px #2c3a42, nessuna ombra.
/// </summary>
public static class UiTheme
{
public static Font Body { get; private set; } = ThemeDB.FallbackFont;
public static Font BodyBold { get; private set; } = ThemeDB.FallbackFont;
public static Font Title { get; private set; } = ThemeDB.FallbackFont;
public static Theme Build()
{
Body = LoadFont("res://assets/fonts/IBMPlexSans-Regular.ttf");
BodyBold = LoadFont("res://assets/fonts/IBMPlexSans-SemiBold.ttf");
Title = LoadFont("res://assets/fonts/BigShouldersDisplay-ExtraBold.ttf");
var t = new Theme { DefaultFont = Body, DefaultFontSize = 14 };
foreach (string type in new[] { "Label", "Button", "LineEdit", "CheckBox", "OptionButton", "SpinBox", "ItemList", "PopupMenu", "TooltipLabel" })
{
t.SetColor("font_color", type, Palette.Text);
}
t.SetColor("font_color", "TooltipLabel", Palette.Text);
t.SetStylebox("panel", "TooltipPanel", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("panel", "PanelContainer", Box(Palette.Panel, Palette.Border, 10, 12));
t.SetStylebox("panel", "Panel", Box(Palette.Panel, Palette.Border, 0, 0));
var normal = Box(Palette.Panel, Palette.Border, 8, 10);
t.SetStylebox("normal", "Button", normal);
t.SetStylebox("hover", "Button", Box(Palette.Inner, Palette.TextSecondary, 8, 10));
t.SetStylebox("pressed", "Button", Box(Palette.Amber, Palette.Amber, 8, 10));
t.SetStylebox("disabled", "Button", Box(Palette.AppBackground, Palette.Border, 8, 10));
t.SetStylebox("focus", "Button", Box(new Color(0, 0, 0, 0), Palette.AmberLight, 8, 10));
t.SetColor("font_pressed_color", "Button", Palette.AppBackground);
t.SetColor("font_hover_color", "Button", Palette.Text);
t.SetColor("font_disabled_color", "Button", Palette.TextSecondary);
t.SetColor("font_hover_pressed_color", "Button", Palette.AppBackground);
t.SetStylebox("normal", "LineEdit", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("focus", "LineEdit", Box(Palette.Inner, Palette.Amber, 8, 8));
t.SetColor("caret_color", "LineEdit", Palette.Amber);
t.SetStylebox("panel", "ItemList", Box(Palette.Inner, Palette.Border, 8, 6));
t.SetColor("font_selected_color", "ItemList", Palette.AppBackground);
t.SetStylebox("selected", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
t.SetStylebox("selected_focus", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
t.SetStylebox("background", "ProgressBar", Box(Palette.Border, Palette.Border, 4, 0));
t.SetStylebox("fill", "ProgressBar", Box(Palette.Workers, Palette.Workers, 4, 0));
t.SetColor("font_color", "ProgressBar", Palette.Text);
return t;
}
/// <summary>Riquadro piatto con bordo di 1 px.</summary>
public static StyleBoxFlat Box(Color bg, Color border, int radius, int margin)
{
var s = new StyleBoxFlat { BgColor = bg, BorderColor = border };
s.SetBorderWidthAll(1);
s.SetCornerRadiusAll(radius);
s.ContentMarginLeft = margin;
s.ContentMarginRight = margin;
s.ContentMarginTop = margin * 0.6f;
s.ContentMarginBottom = margin * 0.6f;
return s;
}
/// <summary>Carica un font importato dall'editor oppure, in mancanza, direttamente dal file.</summary>
private static Font LoadFont(string path)
{
if (ResourceLoader.Exists(path))
{
var imported = ResourceLoader.Load<FontFile>(path);
if (imported is not null) return imported;
}
var font = new FontFile();
if (font.LoadDynamicFont(path) == Error.Ok) return font;
GD.PushWarning($"Font non trovato: {path}");
return ThemeDB.FallbackFont;
}
/// <summary>Etichetta con il font dei titoli.</summary>
public static Label TitleLabel(string text, int size, Color? color = null)
{
var l = new Label { Text = text };
l.AddThemeFontOverride("font", Title);
l.AddThemeFontSizeOverride("font_size", size);
l.AddThemeColorOverride("font_color", color ?? Palette.Text);
return l;
}
public static Label Text(string text, int size = 14, Color? color = null, bool bold = false)
{
var l = new Label { Text = text };
l.AddThemeFontOverride("font", bold ? BodyBold : Body);
l.AddThemeFontSizeOverride("font_size", size);
l.AddThemeColorOverride("font_color", color ?? Palette.Text);
return l;
}
/// <summary>Pulsante d'azione primaria (ambra).</summary>
public static Button Primary(string text)
{
var b = new Button { Text = text };
b.AddThemeStyleboxOverride("normal", Box(Palette.Amber, Palette.Amber, 8, 12));
b.AddThemeStyleboxOverride("hover", Box(Palette.AmberLight, Palette.AmberLight, 8, 12));
b.AddThemeColorOverride("font_color", Palette.AppBackground);
b.AddThemeColorOverride("font_hover_color", Palette.AppBackground);
b.AddThemeFontOverride("font", BodyBold);
return b;
}
/// <summary>Distintivo ambra (livello della compagnia, linea).</summary>
public static PanelContainer Badge(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.Amber, Palette.Amber, 4, 6));
var l = Text(text, 12, Palette.AppBackground, bold: true);
p.AddChild(l);
return p;
}
/// <summary>Etichetta di linea: ambra su fondo ambra scuro, su una riga (immagine 01).</summary>
public static PanelContainer LineBadge(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.AmberDark, Palette.AmberDark, 6, 10));
p.AddChild(Text(text, 13, Palette.AmberLight, bold: true));
return p;
}
/// <summary>Riquadro d'avviso ambra scuro (colli di bottiglia e opportunità).</summary>
public static PanelContainer Notice(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.AmberDark, Palette.AmberDark, 8, 12));
var l = Text(text, 13, Palette.AmberLight);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
p.AddChild(l);
return p;
}
}
@@ -0,0 +1 @@
uid://fvsnf1rxxhbh