Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s

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:
Alby96andClaude Opus 5.5 committed 2026-11-07 11:14:54 +01:00
1 parent f6c2a17b4d
commit c1a0049bcf
300 files changed
+1602 -1045

No files matched your search

@@ -0,0 +1,220 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Panels;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Cronaca finale (12.3), a tutto schermo sopra la partita: storia della compagnia anno per anno
/// (patrimonio netto), primati, fatti salienti e prestigio, con «Continua come osservatore» e
/// «Nuova partita+». A partita in corso la stessa schermata è la Cronaca provvisoria.
/// Mostra solo ciò che manda il server (messaggio Chronicle).
/// </summary>
public partial class ChronicleScreen : Control
{
private readonly ClientWorld _world;
private readonly Chronicle _chronicle;
private readonly string _nextDifficulty;
/// <summary>Chiusura: continua come osservatore (o torna alla partita, se provvisoria).</summary>
public event Action? Closed;
/// <summary>Nuova partita+ con la difficoltà successiva.</summary>
public event Action? NewGamePlus;
public ChronicleScreen(ClientWorld world, Chronicle chronicle, string nextDifficulty)
{
_world = world;
_chronicle = chronicle;
_nextDifficulty = nextDifficulty;
}
public bool Final => _chronicle.GameOver;
public override void _Ready()
{
// già nell'albero: ancore e margini insieme, altrimenti resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
MouseFilter = MouseFilterEnum.Stop;
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var margin = new MarginContainer();
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (string side in new[] { "left", "right" }) margin.AddThemeConstantOverride("margin_" + side, 48);
foreach (string side in new[] { "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 28);
AddChild(margin);
var root = PanelKit.Column(16);
margin.AddChild(root);
var c = _chronicle;
var header = PanelKit.Row(24);
var titles = PanelKit.Column(2);
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
titles.AddChild(UiTheme.TitleLabel(c.GameOver ? T("Cronaca finale") : T("Cronaca provvisoria"), 60));
int lastYear = c.History.Count > 0 ? c.History[^1].Year : c.FoundedYear;
titles.AddChild(UiTheme.Text($"{c.Company} · {c.FoundedYear}–{lastYear} · {Fmt.Date(_world, c.Day)}", 20, Palette.TextSecondary, bold: true));
header.AddChild(titles);
var prestige = new PanelContainer { SizeFlagsVertical = SizeFlags.ShrinkCenter };
prestige.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 18));
var prestigeCol = PanelKit.Column(0);
prestigeCol.AddChild(UiTheme.Text(T("Prestigio"), 14, Palette.AmberLight));
prestigeCol.AddChild(UiTheme.TitleLabel(Fmt.Number(c.Prestige, 0), 48, Palette.AmberLight));
prestige.AddChild(prestigeCol);
header.AddChild(prestige);
root.AddChild(header);
if (c.GameOver)
{
var reason = new PanelContainer();
reason.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 16));
var col = PanelKit.Column(2);
col.AddChild(UiTheme.Text(ReasonTitle(c.Reason) + (c.Winner >= 0 ? $" · {T("vincitore")}: {Fmt.Company(_world, c.Winner)}" : ""), 17, Palette.AmberLight, bold: true));
if (c.Text.Length > 0) col.AddChild(Wrapped(c.Text, 14, Palette.Text));
col.AddChild(Wrapped(T("Il mondo continua: le compagnie IA giocano e puoi guardarle come osservatore, ma il server non accetta più i tuoi comandi."), 13, Palette.TextSecondary));
reason.AddChild(col);
root.AddChild(reason);
}
else
{
root.AddChild(UiTheme.Notice(T("La partita è in corso: questa è la storia finora. La Cronaca finale arriva quando la tua compagnia esce di scena.")));
}
var body = PanelKit.Row(20);
body.SizeFlagsVertical = SizeFlags.ExpandFill;
root.AddChild(body);
// sinistra: grafico e tabella anno per anno
var left = Frame(body, 1.7f);
left.AddChild(UiTheme.Text(T("Patrimonio netto anno per anno"), 16, bold: true));
var chart = new SeriesChart(240);
chart.Show(c.History.Select(y => (double)y.NetWorth.Cents).ToList(), c.History.Select(y => $"{y.Year}").ToList(),
v => Core.Common.Money.FromCentsRounded(v).ToString("short"), SeriesChart.Style.Bars, Palette.Amber, T("Nessun anno registrato"));
left.AddChild(chart);
left.AddChild(YearTable(c.History));
// destra: primati e fatti salienti
var right = Frame(body, 1f);
right.AddChild(UiTheme.Text(T("Primati"), 16, bold: true));
var records = new GridContainer { Columns = 2, SizeFlagsHorizontal = SizeFlags.ExpandFill };
records.AddThemeConstantOverride("h_separation", 8);
records.AddThemeConstantOverride("v_separation", 8);
foreach (var r in c.Records)
{
var value = PanelKit.Value(r.Value);
value.ClipText = true;
value.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
var stat = PanelKit.Stat($"{r.Title} ({r.Year})", value);
stat.TooltipText = $"{r.Title}: {r.Value} ({r.Year})";
records.AddChild(stat);
}
right.AddChild(records);
right.AddChild(PanelKit.Separator());
right.AddChild(UiTheme.Text(T("Fatti salienti"), 16, bold: true));
if (c.Highlights.Count == 0) right.AddChild(UiTheme.Text(T("Ancora nessun fatto da raccontare."), 13, Palette.TextSecondary));
foreach (string h in c.Highlights) right.AddChild(Wrapped("• " + h, 13, Palette.Text));
// pulsanti
var buttons = PanelKit.Row(12);
buttons.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
if (c.GameOver)
{
var hint = UiTheme.Text($"{T("Nuova mappa con la difficoltà")} «{_nextDifficulty}»", 14, Palette.TextSecondary);
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
buttons.AddChild(hint);
var observe = new Button { Text = T("Continua come osservatore"), CustomMinimumSize = new Vector2(0, 48) };
observe.Pressed += () => Closed?.Invoke();
buttons.AddChild(observe);
var again = UiTheme.Primary(T("Nuova partita+"));
again.CustomMinimumSize = new Vector2(200, 48);
again.Pressed += () => NewGamePlus?.Invoke();
buttons.AddChild(again);
}
else
{
var back = UiTheme.Primary(T("Torna alla partita"));
back.CustomMinimumSize = new Vector2(200, 48);
back.Pressed += () => Closed?.Invoke();
buttons.AddChild(back);
}
root.AddChild(buttons);
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (e is InputEventKey { Pressed: true, Keycode: Key.Escape })
{
Closed?.Invoke();
GetViewport().SetInputAsHandled();
}
}
private static VBoxContainer Frame(HBoxContainer body, float ratio)
{
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 18));
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
frame.AddChild(scroll);
// margine destro: la barra di scorrimento non tocca i numeri allineati a destra
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 12);
scroll.AddChild(margin);
var col = PanelKit.Column(10);
margin.AddChild(col);
body.AddChild(frame);
return col;
}
private static Control YearTable(List<CompanyYearInfo> history)
{
var grid = new GridContainer { Columns = 7, SizeFlagsHorizontal = SizeFlags.ExpandFill };
grid.AddThemeConstantOverride("h_separation", 18);
grid.AddThemeConstantOverride("v_separation", 4);
string[] heads = [T("Anno"), T("Patrimonio"), T("Cassa"), T("Ricavi"), T("Utile"), T("Treni"), T("Km di binari")];
for (int i = 0; i < heads.Length; i++)
{
var l = UiTheme.Text(heads[i], 12, Palette.TextSecondary);
l.HorizontalAlignment = i == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
l.SizeFlagsHorizontal = i == 0 ? SizeFlags.Fill : SizeFlags.ExpandFill;
grid.AddChild(l);
}
foreach (var y in Enumerable.Reverse(history).Take(12))
{
grid.AddChild(UiTheme.Text($"{y.Year}", 13, bold: true));
foreach (var (text, color) in new[]
{
(y.NetWorth.ToString("short"), Palette.Text),
(y.Cash.ToString("short"), Palette.Text),
(y.Revenue.ToString("short"), Palette.Text),
(y.Profit.ToString("short"), y.Profit.IsNegative ? Palette.Danger : Palette.Ok),
($"{y.Trains}", Palette.Text),
(Fmt.Number(y.TrackKm, 1), Palette.Text),
})
{
var l = UiTheme.Text(text, 13, color);
l.HorizontalAlignment = HorizontalAlignment.Right;
grid.AddChild(l);
}
}
return grid;
}
private static string ReasonTitle(byte reason) => reason switch
{
1 => T("Fallimento"),
2 => T("La compagnia è stata scalata"),
3 => T("Riscatto non riuscito in tempo"),
_ => T("Partita conclusa"),
};
private static Label Wrapped(string text, int size, Color color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://ck3hivvfy7bdr
@@ -0,0 +1,93 @@
using Godot;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Collegamento a un server (immagine 09 non fornita: palette e componenti dell'immagine 05).
/// Ricorda indirizzo e token in user://settings.cfg.
/// </summary>
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400" };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server") };
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Button _connect = UiTheme.Primary(T("Collegati"));
public event Action<Uri, string, string>? ConnectRequested;
public event Action? Back;
public override void _Ready()
{
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var panel = new PanelContainer { CustomMinimumSize = new Vector2(480, 0) };
center.AddChild(panel);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
panel.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Collegati a un server"), 40));
col.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
col.AddChild(_address);
col.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
col.AddChild(_token);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 10);
_connect.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_connect.Pressed += Submit;
row.AddChild(_connect);
var back = new Button { Text = T("Indietro") };
back.Pressed += () => Back?.Invoke();
row.AddChild(back);
col.AddChild(row);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
col.AddChild(UiTheme.Notice(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).")));
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
}
_token.TextSubmitted += _ => Submit();
}
public void SetStatus(string text, bool busy)
{
_status.Text = text;
_connect.Disabled = busy;
}
private void Submit()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
SetStatus(T("Indica l'indirizzo del server"), false);
return;
}
string url = address.Contains("://") ? address : $"ws://{address}";
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
SetStatus(T("Indirizzo non valido"), false);
return;
}
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", address);
cfg.SetValue("server", "token", _token.Text);
cfg.Save(SettingsPath);
ConnectRequested?.Invoke(uri, _token.Text, uri.Host);
}
}
@@ -0,0 +1 @@
uid://3yfity6oaer
@@ -0,0 +1,773 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Hud;
using RailEnterprise.Client.Map;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Panels;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Partita: mappa con i livelli, HUD (barra superiore, strumenti, pannello destro con minimappa,
/// notiziario) e logica degli strumenti. Ogni modifica è un comando al server; il client calcola
/// solo l'anteprima del tracciato con le classi di Core.
/// </summary>
public partial class GameScreen : Node
{
private readonly GameSession _session;
private readonly MapView _map = new();
private readonly LabelLayer _labels = new();
private readonly TopBar _top = new();
private readonly Toolbar _toolbar = new();
private readonly Ticker _ticker = new();
private readonly Minimap _minimap = new();
private readonly ScrollContainer _scroll = new() { SizeFlagsVertical = Control.SizeFlags.ExpandFill, HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
private readonly VBoxContainer _content = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
private readonly VBoxContainer _toasts = new();
private readonly Control _disconnected = new();
private Tool _tool = Tool.None;
private TrackPanel? _trackPanel;
private StationPanel? _stationPanel;
private DepotPanel? _depotPanel;
private LinesPanel? _linesPanel;
private InfoPanel? _info;
private MaintenancePanel? _maintenance;
private IndustryPanel? _industryPanel;
private CompaniesPanel? _companies;
// pannelli a tutto schermo (Compagnie e borsa): coprono mappa e pannello destro, la barra resta
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
private Control? _mapArea;
private Control? _side;
// Cronaca finale (o provvisoria) sopra tutta la partita e avviso dell'osservatore
private readonly CanvasLayer _overlay = new() { Layer = 3 };
private readonly PanelContainer _observer = new() { Visible = false };
private ChronicleScreen? _chronicleScreen;
private Protocol.Messages.Chronicle? _seenChronicle;
private bool _wantChronicle, _finalShown;
private bool _heatMap;
private readonly List<Vector2> _trackPoints = [];
private Vector2? _mouse;
private bool _previewDirty;
private double _sincePreview;
private TrackPlan? _plan;
private Vector2 _lastViewportCenter;
private float _lastViewportZoom;
public event Action? Exit;
public GameScreen(GameSession session) => _session = session;
public GameSession Session => _session;
public MapView Map => _map;
/// <summary>Seleziona uno strumento come dalla barra (anche per il pilota automatico).</summary>
public void UseTool(Tool tool) => _toolbar.Select(tool);
/// <summary>Imposta i punti del tracciato in corso e aggiorna l'anteprima.</summary>
public void SetTrackPoints(IEnumerable<Vector2> points, Vector2? mouse)
{
_trackPoints.Clear();
_trackPoints.AddRange(points);
_mouse = mouse;
_previewDirty = true;
}
/// <summary>Mostra la scheda di un treno e lo evidenzia.</summary>
/// <summary>Apre la cartella di manutenzione del treno nel pannello Officine.</summary>
public void OpenMaintenance(int train)
{
_toolbar.Select(Tool.Maintenance);
_maintenance?.SelectTrain(train);
}
/// <summary>Apre il Registro officina del deposito nel pannello Officine.</summary>
public void OpenWorkshop(int depot)
{
if (_tool != Tool.Maintenance) _toolbar.Select(Tool.Maintenance);
_maintenance?.SelectDepot(depot);
}
/// <summary>Apre il pannello Industrie sull'industria indicata (scheda del proprietario).</summary>
public void OpenIndustry(int industry)
{
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
_industryPanel?.Select(industry);
}
/// <summary>Apre «Compagnie e borsa» a tutto schermo sulla compagnia indicata.</summary>
public void OpenCompanies(int company)
{
if (_tool != Tool.Companies) _toolbar.Select(Tool.Companies);
_companies?.Select(company);
}
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
public void OpenChronicle()
{
_wantChronicle = true;
_session.Send(new RequestDetail { Kind = DetailKind.Chronicle, Target = 0 });
}
public bool ChronicleVisible => _chronicleScreen is not null;
/// <summary>Mappa di calore della condizione dei treni.</summary>
public void SetHeatMap(bool on)
{
_map.Trains.HeatMap = _heatMap = on;
_maintenance?.SetHeatMap(on);
}
/// <summary>Scorre il pannello laterale (0 = in cima, 1 = in fondo).</summary>
public void ScrollPanel(double fraction)
{
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
public void SelectTrain(int id)
{
_map.Trains.SelectedTrain = id;
_info?.Select(InfoPanel.Kind.Train, id);
}
public override void _Ready()
{
AddChild(_map);
var labelLayer = new CanvasLayer { Layer = 1 };
AddChild(labelLayer);
labelLayer.AddChild(_labels);
_labels.Bind(_session.World, _map.Camera);
var hud = new CanvasLayer { Layer = 2 };
AddChild(hud);
var root = new VBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
UiTheme.Apply(root);
root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
root.AddThemeConstantOverride("separation", 0);
hud.AddChild(root);
root.AddChild(_top);
var middle = new HBoxContainer { SizeFlagsVertical = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddThemeConstantOverride("separation", 0);
root.AddChild(middle);
middle.AddChild(_toolbar);
var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddChild(mapArea);
_mapArea = mapArea;
_toasts.SetAnchorsPreset(Control.LayoutPreset.TopWide);
_toasts.OffsetLeft = 16;
_toasts.OffsetRight = -16;
_toasts.OffsetTop = 12;
_toasts.MouseFilter = Control.MouseFilterEnum.Ignore;
mapArea.AddChild(_toasts);
var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18));
middle.AddChild(side);
_side = side;
_full.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AppBackground, Palette.Border, 0, 20));
middle.AddChild(_full);
BuildObserverBanner(mapArea);
var sideCol = new VBoxContainer();
sideCol.AddThemeConstantOverride("separation", 12);
side.AddChild(sideCol);
sideCol.AddChild(_scroll);
// margine destro: la barra di scorrimento non copre i valori allineati a destra
var contentMargin = new MarginContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
contentMargin.AddThemeConstantOverride("margin_right", 12);
_scroll.AddChild(contentMargin);
contentMargin.AddChild(_content);
var miniHeader = new HBoxContainer();
var miniTitle = UiTheme.Text(T("Minimappa"), 13, Palette.TextSecondary);
miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
miniHeader.AddChild(miniTitle);
miniHeader.AddChild(UiTheme.Text(_session.World.Summary?.RegionId is { Length: > 0 } r ? $"{T("Regione di")} {char.ToUpperInvariant(r[0])}{r[1..]}" : "", 13, Palette.TextSecondary));
sideCol.AddChild(miniHeader);
sideCol.AddChild(_minimap);
root.AddChild(_ticker);
BuildDisconnectedOverlay(hud);
AddChild(_overlay);
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
_top.Bind(_session);
_toolbar.Selected += SelectTool;
_map.Clicked += OnMapClicked;
_map.Hovered += OnMapHovered;
_map.Cancelled += () => _toolbar.Select(Tool.None);
_session.MessageApplied += OnMessage;
_session.Notified += e => _ticker.Add(e);
_session.CommandFailed += r => Toast(r.Message, error: true);
SelectTool(Tool.None);
SendViewport(force: true);
// il Registro degli impieghi alimenta anche le schede di industrie e città
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
}
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
/// <summary>Avviso permanente dopo la fine della partita: si guarda il mondo, la Cronaca resta a portata.</summary>
private void BuildObserverBanner(Control mapArea)
{
_observer.SetAnchorsPreset(Control.LayoutPreset.BottomWide);
_observer.OffsetLeft = 16;
_observer.OffsetRight = -16;
_observer.OffsetTop = -70;
_observer.OffsetBottom = -16;
_observer.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AmberDark, Palette.Amber, 8, 14));
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 14);
var text = UiTheme.Text(T("Partita conclusa: sei un osservatore. Il mondo va avanti e le compagnie IA continuano a giocare."), 14, Palette.AmberLight, bold: true);
text.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
text.SizeFlagsVertical = Control.SizeFlags.ShrinkCenter;
text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
row.AddChild(text);
var open = UiTheme.Primary(T("Cronaca finale"));
open.Pressed += () =>
{
if (_session.World.Chronicle is { } c) ShowChronicle(c);
else OpenChronicle();
};
row.AddChild(open);
_observer.AddChild(row);
mapArea.AddChild(_observer);
}
private void BuildDisconnectedOverlay(CanvasLayer hud)
{
_disconnected.SetAnchorsPreset(Control.LayoutPreset.FullRect);
UiTheme.Apply(_disconnected);
_disconnected.Visible = false;
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.55f) };
shade.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.AddChild(shade);
var center = new CenterContainer();
center.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.AddChild(center);
var panel = new PanelContainer();
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
col.AddChild(UiTheme.TitleLabel(T("Connessione persa"), 36));
col.AddChild(UiTheme.Text(T("Il server non risponde più. La partita continua sul server."), 14, Palette.TextSecondary));
var back = UiTheme.Primary(T("Torna al menu"));
back.Pressed += () => Exit?.Invoke();
col.AddChild(back);
panel.AddChild(col);
center.AddChild(panel);
hud.AddChild(_disconnected);
}
// ------------------------------------------------------------------ messaggi e ciclo
private void OnMessage(IMessage m)
{
switch (m)
{
case MapChunk c:
_map.Terrain.MarkDirty(c.Cx, c.Cy);
_map.Entities.ForestChunk(c.Cx, c.Cy);
break;
case Welcome:
// nuova partita o caricamento: si ricomincia dalla copia locale vuota
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
CloseChronicle();
_seenChronicle = null;
_wantChronicle = _finalShown = false;
_toolbar.Select(Tool.None);
SendViewport(force: true);
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
break;
case DailyDigest d:
foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e);
break;
}
}
public override void _Process(double delta)
{
_session.Poll();
_disconnected.Visible = !_session.IsOpen;
UpdateChronicle();
SendViewport(force: false);
_sincePreview += delta;
if (_previewDirty && _sincePreview > 0.12)
{
_previewDirty = false;
_sincePreview = 0;
UpdateTrackPreview();
}
}
/// <summary>Sottoscrive l'area visibile quando la camera si sposta di almeno un quarto di schermo.</summary>
private void SendViewport(bool force)
{
var w = _session.World;
if (w.Summary is null) return;
var view = _map.VisibleRect();
var center = view.GetCenter();
if (!force && center.DistanceTo(_lastViewportCenter) < view.Size.X / 4 && Math.Abs(_map.Zoom - _lastViewportZoom) < _lastViewportZoom * 0.3f) return;
_lastViewportCenter = center;
_lastViewportZoom = _map.Zoom;
double cs = w.Summary.CellSizeM;
_session.Send(new Subscribe
{
X0 = Math.Max(0, (int)(view.Position.X / cs)),
Y0 = Math.Max(0, (int)(view.Position.Y / cs)),
X1 = Math.Min(w.Summary.WidthCells - 1, (int)(view.End.X / cs)),
Y1 = Math.Min(w.Summary.HeightCells - 1, (int)(view.End.Y / cs)),
Lod = (byte)(_map.Zoom >= MapScale.DetailZoom ? 0 : _map.Zoom >= MapScale.OverviewZoom ? 1 : 2),
});
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (e is not InputEventKey { Pressed: true } key) return;
switch (key.Keycode)
{
case Key.Escape:
_toolbar.Select(Tool.None);
break;
case Key.Enter or Key.KpEnter when _tool == Tool.Track:
BuildTrack();
break;
case Key.Backspace when _tool == Tool.Track && _trackPoints.Count > 0:
_trackPoints.RemoveAt(_trackPoints.Count - 1);
_previewDirty = true;
break;
case Key.Space:
_session.SetSpeed(_session.World.Speed == 0 ? (byte)1 : (byte)0);
break;
}
}
// ------------------------------------------------------------------ strumenti
private void SelectTool(Tool tool)
{
_tool = tool;
_trackPoints.Clear();
_plan = null;
_map.Tools.Clear();
_map.Entities.SelectedStation = -1;
foreach (var c in _content.GetChildren()) c.QueueFree();
_trackPanel = null;
_stationPanel = null;
_depotPanel = null;
_linesPanel = null;
_info = null;
_maintenance = null;
_industryPanel = null;
_companies = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
bool full = tool == Tool.Companies;
_full.Visible = full;
if (_mapArea is not null) _mapArea.Visible = !full;
if (_side is not null) _side.Visible = !full;
Control panel;
switch (tool)
{
case Tool.Track:
_trackPanel = new TrackPanel(_session.World);
_trackPanel.OptionsChanged += () => _previewDirty = true;
_trackPanel.Build.Pressed += BuildTrack;
_trackPanel.Cancel.Pressed += () => _toolbar.Select(Tool.None);
panel = _trackPanel;
break;
case Tool.Station:
panel = _stationPanel = new StationPanel(_session);
break;
case Tool.Depot:
panel = _depotPanel = new DepotPanel(_session);
break;
case Tool.Signal:
panel = new HelpPanel(T("Segnali"), T("Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea."));
break;
case Tool.Demolish:
panel = new HelpPanel(T("Demolisci"), T("Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo."));
break;
case Tool.Trains:
var trains = new TrainsPanel(_session);
trains.TrainSelected += id =>
{
_map.Trains.SelectedTrain = id;
if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p);
};
panel = trains;
break;
case Tool.Lines:
_linesPanel = new LinesPanel(_session);
_linesPanel.StopsChanged += UpdateStopsOverlay;
panel = _linesPanel;
break;
case Tool.Maintenance:
_maintenance = new MaintenancePanel(_session, _heatMap);
_maintenance.HeatMapToggled += on => _map.Trains.HeatMap = _heatMap = on;
_maintenance.TrainSelected += id =>
{
_map.Trains.SelectedTrain = id;
if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p);
};
panel = _maintenance;
break;
case Tool.Employment:
panel = new EmploymentPanel(_session);
break;
case Tool.Industries:
panel = _industryPanel = new IndustryPanel(_session);
break;
case Tool.Companies:
_companies = new CompaniesPanel(_session);
_companies.CloseRequested += () => _toolbar.Select(Tool.None);
_companies.ChronicleRequested += OpenChronicle;
_full.AddChild(_companies);
panel = NewInfoPanel();
break;
case Tool.Market:
panel = new MarketPanel(_session);
break;
case Tool.Finance:
panel = new FinancePanel(_session);
break;
default:
panel = NewInfoPanel();
break;
}
panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
_content.AddChild(panel);
}
private InfoPanel NewInfoPanel()
{
_info = new InfoPanel(_session);
_info.MaintenanceRequested += OpenMaintenance;
_info.IndustryRequested += OpenIndustry;
return _info;
}
private void OnMapHovered(Vector2 world)
{
_mouse = world;
switch (_tool)
{
case Tool.Track:
if (_trackPoints.Count > 0) _previewDirty = true;
_map.Tools.SetTrack(_trackPoints, Snap(world), _plan);
break;
case Tool.Station:
_map.Tools.SetGhost(ToolOverlay.Ghost.Station, world);
break;
case Tool.Depot:
_map.Tools.SetGhost(ToolOverlay.Ghost.Depot, world);
break;
case Tool.Demolish:
_map.Tools.SetGhost(ToolOverlay.Ghost.Demolish, world);
break;
}
}
private void OnMapClicked(Vector2 world)
{
var w = _session.World;
var p = MapScale.W(world);
switch (_tool)
{
case Tool.Track:
_trackPoints.Add(Snap(world));
_previewDirty = true;
break;
case Tool.Station when _stationPanel is not null:
string? name = string.IsNullOrWhiteSpace(_stationPanel.StationName.Text) ? null : _stationPanel.StationName.Text.Trim();
_session.Command(new BuildStationCommand(p, (int)_stationPanel.Platforms.Value, name), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Depot when _depotPanel is not null:
_session.Command(new BuildDepotCommand(p, _depotPanel.SelectedSize), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Signal:
if (NearestEdge(world) is { } hit)
_session.Command(new PlaceSignalCommand(new EdgeId(hit.Edge), hit.S), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Demolish:
Demolish(world);
break;
case Tool.Lines when _linesPanel is not null:
if (NearestStation(world) is { } station) _linesPanel.AddStop(station);
break;
case Tool.Industries when _industryPanel is not null:
if (IndustryAt(world) is { } industry) _industryPanel.Select(industry);
break;
default:
SelectAt(world);
break;
}
}
/// <summary>Scatto a 45° rispetto al punto precedente (Maiusc per disattivarlo).</summary>
private Vector2 Snap(Vector2 world)
{
if (_trackPoints.Count == 0 || Input.IsKeyPressed(Key.Shift)) return world;
var prev = _trackPoints[^1];
var d = world - prev;
if (d.LengthSquared() < 1) return world;
float step = MathF.PI / 4;
float angle = MathF.Round(d.Angle() / step) * step;
return prev + Vector2.FromAngle(angle) * d.Length();
}
private void UpdateTrackPreview()
{
if (_tool != Tool.Track || _trackPanel is null) return;
var pts = new List<Vector2>(_trackPoints);
if (_mouse is { } m && pts.Count >= 1) pts.Add(Snap(m));
if (pts.Count < 2)
{
_plan = null;
_trackPanel.Show(null);
_map.Tools.SetTrack(_trackPoints, _mouse, null);
return;
}
try
{
_plan = _session.World.PreviewTrack(TrackCommand(pts, 0));
_trackPanel.Show(_plan);
_trackPanel.SetStatus("");
}
catch (Exception e)
{
_plan = null;
_trackPanel.Show(null);
_trackPanel.SetStatus(T("Anteprima non disponibile: ") + e.Message, error: true);
}
_map.Tools.SetTrack(_trackPoints, _mouse is { } mm ? Snap(mm) : null, _plan);
}
private BuildTrackCommand TrackCommand(List<Vector2> pts, long expectedCost)
{
var p = _trackPanel!;
return new BuildTrackCommand(pts.Select(MapScale.W).ToList(), p.HeightOffset, p.AllowBridges, p.AllowTunnels, p.TrackClass, p.DoubleTrack, p.Electrified, expectedCost);
}
private void BuildTrack()
{
if (_trackPanel is null || _trackPoints.Count < 2) return;
// si costruisce il tracciato dei punti fissati (senza il punto sotto il mouse)
var plan = _session.World.PreviewTrack(TrackCommand(_trackPoints, 0));
if (!plan.Valid)
{
_trackPanel.SetStatus(plan.Errors[0].Message, error: true);
return;
}
_session.Command(TrackCommand(_trackPoints, plan.TotalCost.Cents), r =>
{
if (!r.Ok)
{
_trackPanel?.SetStatus(r.Message, error: true);
return;
}
Toast(r.Message);
// il prossimo tratto parte dall'ultimo punto
var last = _trackPoints[^1];
_trackPoints.Clear();
_trackPoints.Add(last);
_plan = null;
_trackPanel?.Show(null);
_map.Tools.SetTrack(_trackPoints, _mouse, null);
});
}
private void UpdateStopsOverlay()
{
if (_linesPanel is null) return;
var pts = _linesPanel.Stops.Where(_session.World.Stations.ContainsKey).Select(s => MapScale.V(_session.World.Stations[s].Position)).ToList();
_map.Tools.SetStops(pts);
}
private float PickRadius => 24f / _map.Zoom;
private int? NearestStation(Vector2 world)
{
int? best = null;
float bestD = Math.Max(PickRadius, 150);
foreach (var s in _session.World.Stations.Values)
{
float d = MapScale.V(s.Position).DistanceTo(world);
if (d < bestD)
{
bestD = d;
best = s.Id;
}
}
return best;
}
private int? NearestDepot(Vector2 world)
{
int? best = null;
float bestD = Math.Max(PickRadius, 120);
foreach (var d in _session.World.Depots.Values)
{
float dist = MapScale.V(d.Position).DistanceTo(world);
if (dist < bestD)
{
bestD = dist;
best = d.Id;
}
}
return best;
}
private (int Edge, double S)? NearestEdge(Vector2 world)
{
(int, double)? best = null;
double bestD = Math.Max(PickRadius, 25);
var p = MapScale.W(world);
foreach (var e in _session.World.Edges.Values)
{
for (int i = 0; i < e.S.Length - 1; i++)
{
var a = new Vec2(e.X[i], e.Y[i]);
var b = new Vec2(e.X[i + 1], e.Y[i + 1]);
double d = RailNetwork.DistanceToSegment(p, a, b, out double t);
if (d >= bestD) continue;
bestD = d;
best = (e.Id, e.S[i] + (e.S[i + 1] - e.S[i]) * t);
}
}
return best;
}
private void Demolish(Vector2 world)
{
if (NearestStation(world) is { } st)
_session.Command(new DemolishCommand(DemolishTarget.Station, st), r => { if (r.Ok) Toast(r.Message); });
else if (NearestDepot(world) is { } dp)
_session.Command(new DemolishCommand(DemolishTarget.Depot, dp), r => { if (r.Ok) Toast(r.Message); });
else if (NearestEdge(world) is { } hit)
_session.Command(new DemolishCommand(DemolishTarget.Edge, hit.Edge), r => { if (r.Ok) Toast(r.Message); });
}
private void SelectAt(Vector2 world)
{
if (_info is null) return;
var w = _session.World;
foreach (var (id, head) in _map.Trains.Heads)
{
if (head.DistanceTo(world) < PickRadius * 1.5f)
{
_map.Trains.SelectedTrain = id;
_info.Select(InfoPanel.Kind.Train, id);
return;
}
}
_map.Trains.SelectedTrain = -1;
if (NearestStation(world) is { } st)
{
_map.Entities.SelectedStation = st;
_map.Entities.QueueRedraw();
_info.Select(InfoPanel.Kind.Station, st);
return;
}
_map.Entities.SelectedStation = -1;
_map.Entities.QueueRedraw();
double cs = w.Summary?.CellSizeM ?? 100;
if (IndustryAt(world) is { } industry)
{
_info.Select(InfoPanel.Kind.Industry, industry);
return;
}
foreach (var town in w.Towns.Values)
{
if (MapScale.V(town.Position).DistanceTo(world) < Math.Max(PickRadius, (town.RadiusCells + 0.5) * cs))
{
_info.Select(InfoPanel.Kind.Town, town.Id);
return;
}
}
_info.Select(InfoPanel.Kind.None, -1);
}
private int? IndustryAt(Vector2 world)
{
double cs = _session.World.Summary?.CellSizeM ?? 100;
foreach (var ind in _session.World.Industries.Values)
{
if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6)) return ind.Id;
}
return null;
}
// ------------------------------------------------------------------ Cronaca finale e osservatore
/// <summary>Mostra la Cronaca quando arriva: subito se la partita è finita, oppure se l'ha chiesta il giocatore.</summary>
private void UpdateChronicle()
{
var chronicle = _session.World.Chronicle;
if (!ReferenceEquals(chronicle, _seenChronicle))
{
_seenChronicle = chronicle;
if (chronicle is not null && ((chronicle.GameOver && !_finalShown) || _wantChronicle))
{
_wantChronicle = false;
if (chronicle.GameOver) _finalShown = true;
ShowChronicle(chronicle);
}
}
_observer.Visible = chronicle?.GameOver == true && _chronicleScreen is null;
}
private void ShowChronicle(Protocol.Messages.Chronicle chronicle)
{
CloseChronicle();
var next = NextDifficulty();
string name = TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt;
var screen = new ChronicleScreen(_session.World, chronicle, name);
screen.Closed += CloseChronicle;
screen.NewGamePlus += StartNewGamePlus;
_overlay.AddChild(screen);
_chronicleScreen = screen;
}
private void CloseChronicle()
{
_chronicleScreen?.QueueFree();
_chronicleScreen = null;
}
/// <summary>Difficoltà successiva a quella della partita (l'ultima resta l'ultima).</summary>
private DifficultyDef NextDifficulty()
{
var file = _session.World.Data.Difficulty;
int i = file.Presets.FindIndex(p => p.Id == _session.Difficulty);
if (i < 0) i = file.Presets.FindIndex(p => p.Id == file.Default);
return file.Presets[Math.Clamp(i + 1, 0, file.Presets.Count - 1)];
}
/// <summary>Nuova partita+: mappa nuova (seme successivo, stessa dimensione) con la difficoltà superiore.</summary>
private void StartNewGamePlus()
{
var summary = _session.World.Summary;
var next = NextDifficulty();
_session.Send(new NewGame { Seed = (summary?.Seed ?? 0) + 1, SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = next.Id });
CloseChronicle();
Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}");
}
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
private void Toast(string text, bool error = false)
{
var notice = UiTheme.Notice(text);
if (error) notice.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 12));
_toasts.AddChild(notice);
GetTree().CreateTimer(4.5).Timeout += () =>
{
if (IsInstanceValid(notice)) notice.QueueFree();
};
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
}
}
@@ -0,0 +1 @@
uid://ddktpojqhxvg6
@@ -0,0 +1,56 @@
using Godot;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>Menu iniziale: partita locale (server figlio), collegamento a un server, lingua, uscita.</summary>
public partial class MenuScreen : Control
{
public event Action? LocalGame;
public event Action? ConnectToServer;
public event Action<string>? LanguageChanged;
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
public override void _Ready()
{
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var col = new VBoxContainer { CustomMinimumSize = new Vector2(440, 0) };
col.AddThemeConstantOverride("separation", 14);
center.AddChild(col);
col.AddChild(UiTheme.TitleLabel("Rail Enterprise", 96));
col.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 18, Palette.TextSecondary));
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 20) });
var local = UiTheme.Primary(T("Partita locale"));
local.CustomMinimumSize = new Vector2(0, 48);
local.Pressed += () => LocalGame?.Invoke();
col.AddChild(local);
var remote = new Button { Text = T("Collegati a un server"), CustomMinimumSize = new Vector2(0, 48) };
remote.Pressed += () => ConnectToServer?.Invoke();
col.AddChild(remote);
var lang = new HBoxContainer();
lang.AddThemeConstantOverride("separation", 8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
lang.AddChild(b);
}
col.AddChild(lang);
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(0, 40) };
quit.Pressed += () => GetTree().Quit();
col.AddChild(quit);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
}
public void SetStatus(string text) => _status.Text = text;
}
@@ -0,0 +1 @@
uid://b5eyw35w2vo7l