Files
Rail_Enterprise/client/RailEnterprise.Client/scripts/Screens/ConnectScreen.cs
T
Alby96andClaude Opus 5.5 45462bf9ec F6: scheda industria e schermata di connessione definitive
La scheda dell'industria e la schermata di connessione si allineano alle
immagini di riferimento 07 e 09. I dati che mancavano li calcola il Core
con una funzione pura, e viaggiano in blocchi compatibili del protocollo.
Il formato dei salvataggi non cambia (ADR 0021).

- IndustryOutlook calcola la scheda in sola lettura:
  - fattori dell'efficienza e quello che la limita;
  - ingressi e uscite al mese, con giorni di scorta o di magazzino;
  - fornitori e clienti con prezzo, distanza e linea che li collega;
  - forza lavoro dai contratti dei pendolari;
  - punteggio di crescita del trimestre con le soglie;
  - prezzo medio, utile annuo, stazioni che la servono, sblocco
    dell'acquisto.
  IndustryMath.GrowthScore è ora l'unica formula del punteggio e la usa
  anche IndustrySystem: gli hash non cambiano. Nuovi parametri in
  balance.json, industry.outlook.
- Protocollo:
  - IndustryCard: blocco 1 IndustrySheetInfo;
  - Welcome: blocco 1 ServerInfo (versione, sistema, Docker, tempo di
    attività, passo del ciclo, client collegati);
  - ClientWorld conserva lo stato del server e l'elenco dei salvataggi.
- Client:
  - IndustryPanel a tutto schermo, con tre schede, il grafo della
    catena, impianti e crescita, e i comandi del proprietario;
  - ConnectScreen sostituisce MenuScreen: server locale o in rete,
    stato del server, partite salvate, «Connetti e riprendi» e «Nuova
    partita sul server» su una sessione di prova;
  - testi in strings.csv;
  - pilota automatico: schermate 19_scheda_industria e 20_connessione.
- Test:
  - IndustryOutlookTests;
  - scheda e stato del server via WebSocket;
  - campioni del protocollo con i blocchi nuovi.
  200 test, 181 senza i lenti.

Refs #42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 14:04:28 +01:00

609 lines
27 KiB
C#

using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Panels;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Schermata iniziale e di connessione (immagine di riferimento 09): a sinistra la mappa decorativa
/// con il titolo, a destra «Dove gira il motore di gioco?» con le due strade (server locale figlio
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione, sistema, tempo di
/// attività, tick al secondo, latenza, client collegati), le partite salvate sul server e i
/// pulsanti per riprendere o iniziare. La schermata apre una sessione di prova per leggere lo stato
/// e l'elenco dei salvataggi; «Connetti e riprendi» la passa alla partita. Nessuna logica di gioco:
/// carica, nuova partita ed elenco sono richieste al server (Load, NewGame, ListSaves).
/// </summary>
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private const double SavesRefreshS = 5;
private const double WelcomeTimeoutS = 30;
private readonly GameData _data;
private readonly bool _remember;
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400", SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly CheckBox _rememberBox = new() { Text = T("Ricorda questo server"), ButtonPressed = true };
private readonly Button _probe = new() { Text = T("Verifica connessione"), CustomMinimumSize = new Vector2(0, 40) };
private readonly VBoxContainer _remoteFields = new();
private readonly Button _localCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Button _remoteCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly ColorRect _dot = new() { CustomMinimumSize = new Vector2(12, 12), SizeFlagsVertical = SizeFlags.ShrinkCenter };
private readonly Label _stateTitle = UiTheme.Text("", 16, bold: true);
private readonly GridContainer _stateRows = new() { Columns = 2 };
private readonly ItemList _saves = new() { CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill };
private readonly List<string> _saveIds = [];
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private GameSession? _session;
private bool _busy, _local;
private double _sinceSaves = double.MaxValue;
private SaveList? _shownSaves;
private Action<IMessage>? _awaitingWelcome;
private double _waiting;
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
public event Action<GameSession>? PlayRequested;
public event Action<string>? LanguageChanged;
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
public ConnectScreen(GameData data, bool remember = true)
{
_data = data;
_remember = remember;
}
/// <summary>Stato e salvataggi sono arrivati dal server (serve al collaudo).</summary>
public bool Loaded => _session?.World.Server is not null && _shownSaves is not null;
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 split = new HBoxContainer();
split.SetAnchorsPreset(LayoutPreset.FullRect);
split.AddThemeConstantOverride("separation", 0);
AddChild(split);
// sinistra: mappa decorativa con il titolo
var left = new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 1.1f, ClipContents = true };
var backdrop = new ConnectBackdrop();
backdrop.SetAnchorsPreset(LayoutPreset.FullRect);
left.AddChild(backdrop);
// titolo in basso a sinistra, sopra il velo della mappa
var brand = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
brand.AnchorLeft = 0;
brand.AnchorRight = 1;
brand.AnchorTop = 1;
brand.AnchorBottom = 1;
brand.OffsetLeft = 56;
brand.OffsetRight = -56;
brand.OffsetTop = -280;
brand.OffsetBottom = -56;
brand.AddThemeConstantOverride("separation", 6);
brand.AddChild(UiTheme.TitleLabel("RAIL ENTERPRISE", 76, Palette.AmberLight));
brand.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 20, Palette.Text));
brand.AddChild(UiTheme.Text($"{T("Versione del gioco")} {ClientVersion}", 13, Palette.TextSecondary));
left.AddChild(brand);
split.AddChild(left);
// destra: dove gira il motore
var right = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 0.9f };
right.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 40));
split.AddChild(right);
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
right.AddChild(scroll);
var col = PanelKit.Column(14);
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
col.SizeFlagsVertical = SizeFlags.ExpandFill;
scroll.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Dove gira il motore di gioco?"), 38));
var lead = UiTheme.Text(T("Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso."), 14, Palette.TextSecondary);
lead.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(lead);
var modes = PanelKit.Row(12);
var group = new ButtonGroup();
ModeCard(_localCard, group, T("Gioca in locale"), T("Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui."));
ModeCard(_remoteCard, group, T("Connetti a un server"), T("Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa."));
_localCard.Pressed += () => SetMode(local: true, start: true);
_remoteCard.Pressed += () => SetMode(local: false, start: false);
modes.AddChild(_localCard);
modes.AddChild(_remoteCard);
col.AddChild(modes);
// indirizzo e token del server in rete
_remoteFields.AddThemeConstantOverride("separation", 8);
var fields = PanelKit.Row(10);
var addressCol = PanelKit.Column(4);
addressCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
addressCol.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
addressCol.AddChild(_address);
var tokenCol = PanelKit.Column(4);
tokenCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
tokenCol.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
tokenCol.AddChild(_token);
fields.AddChild(addressCol);
fields.AddChild(tokenCol);
_remoteFields.AddChild(fields);
var probeRow = PanelKit.Row(10);
_rememberBox.SizeFlagsHorizontal = SizeFlags.ExpandFill;
probeRow.AddChild(_rememberBox);
_probe.Pressed += SubmitRemote;
probeRow.AddChild(_probe);
_remoteFields.AddChild(probeRow);
_token.TextSubmitted += _ => SubmitRemote();
col.AddChild(_remoteFields);
// stato del server
var state = new PanelContainer();
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
var stateCol = PanelKit.Column(10);
var stateHead = PanelKit.Row(10);
stateHead.AddChild(_dot);
stateHead.AddChild(_stateTitle);
stateCol.AddChild(stateHead);
_stateRows.AddThemeConstantOverride("h_separation", 24);
_stateRows.AddThemeConstantOverride("v_separation", 6);
stateCol.AddChild(_stateRows);
state.AddChild(stateCol);
col.AddChild(state);
// partite salvate sul server
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
_saves.ItemActivated += _ => Resume();
col.AddChild(_saves);
var actions = PanelKit.Row(10);
_resume.CustomMinimumSize = new Vector2(0, 48);
_resume.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_resume.Pressed += Resume;
actions.AddChild(_resume);
_newGame.CustomMinimumSize = new Vector2(0, 48);
_newGame.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_newGame.Pressed += NewGameOnServer;
actions.AddChild(_newGame);
col.AddChild(actions);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
// piede: lingua, uscita, avviso sulla cifratura
var foot = PanelKit.Row(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);
foot.AddChild(b);
}
foot.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(100, 0) };
quit.Pressed += () => GetTree().Quit();
foot.AddChild(quit);
col.AddChild(foot);
var notice = UiTheme.Text(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://)."), 12, Palette.TextSecondary);
notice.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(notice);
bool remote = false;
if (_remember)
{
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
}
}
SetMode(local: !remote, start: false);
ShowState();
}
private static void ModeCard(Button card, ButtonGroup group, string title, string text)
{
card.ButtonGroup = group;
card.AddThemeStyleboxOverride("normal", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
card.AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.AmberDark, 10, 0));
card.AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("hover_pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
var margin = new MarginContainer { MouseFilter = MouseFilterEnum.Ignore };
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (var side in new[] { "left", "right", "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 16);
var col = PanelKit.Column(6);
col.MouseFilter = MouseFilterEnum.Ignore;
var t = UiTheme.Text(title, 17, Palette.AmberLight, bold: true);
var d = UiTheme.Text(text, 12, Palette.TextSecondary);
d.AutowrapMode = TextServer.AutowrapMode.WordSmart;
t.MouseFilter = d.MouseFilter = MouseFilterEnum.Ignore;
col.AddChild(t);
col.AddChild(d);
margin.AddChild(col);
card.AddChild(margin);
}
private static string ClientVersion =>
typeof(ConnectScreen).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
// ------------------------------------------------------------------ modalità e sessione di prova
private void SetMode(bool local, bool start)
{
_local = local;
_localCard.SetPressedNoSignal(local);
_remoteCard.SetPressedNoSignal(!local);
_remoteFields.Visible = !local;
if (start && local && (_session is null || _session.LocalServer is null)) _ = StartLocal();
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "mode", local ? "local" : "remote");
cfg.Save(SettingsPath);
}
ShowState();
}
/// <summary>Avvia il server locale figlio del gioco e apre la sessione di prova.</summary>
private async Task StartLocal()
{
if (_busy) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
SetStatus(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), error: true);
return;
}
await Release();
_busy = true;
SetStatus(T("Avvio del server locale…"));
ShowState();
var launcher = new LocalServerLauncher();
try
{
int port = await launcher.StartAsync(server, ProjectSettings.GlobalizePath("user://server"), TimeSpan.FromSeconds(60));
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
session.LocalServer = launcher;
Attach(session);
}
catch (Exception e)
{
launcher.Dispose();
SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
}
private void SubmitRemote()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
SetStatus(T("Indica l'indirizzo del server"), error: true);
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"), error: true);
return;
}
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", _rememberBox.ButtonPressed ? address : "");
cfg.SetValue("server", "token", _rememberBox.ButtonPressed ? _token.Text : "");
cfg.Save(SettingsPath);
}
_ = ProbeRemote(uri, _token.Text);
}
/// <summary>Collega la sessione di prova a un server in rete (dal pulsante o dal collaudo).</summary>
public async Task ProbeRemote(Uri uri, string token)
{
if (_busy) return;
SetMode(local: false, start: false);
await Release();
_busy = true;
SetStatus(T("Collegamento in corso…"));
ShowState();
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
Attach(await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token));
SetStatus("");
}
catch (Exception e)
{
SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
}
private void Attach(GameSession session)
{
_session = session;
_shownSaves = null;
_sinceSaves = double.MaxValue;
_session.MessageApplied += OnMessage;
}
/// <summary>Chiude la sessione di prova (e il server locale, se è suo).</summary>
private async Task Release()
{
var s = _session;
_session = null;
_shownSaves = null;
_awaitingWelcome = null;
if (s is null) return;
s.MessageApplied -= OnMessage;
await s.DisposeAsync();
}
/// <summary>Consegna la sessione di prova a chi la chiede (Main, alla chiusura del gioco).</summary>
public GameSession? TakeSession()
{
var s = _session;
if (s is not null) s.MessageApplied -= OnMessage;
_session = null;
return s;
}
public override void _ExitTree()
{
if (_session is not null) _ = Release();
}
private void OnMessage(IMessage m) => _awaitingWelcome?.Invoke(m);
public override void _Process(double delta)
{
if (_session is null) return;
_session.Poll();
if (!_session.IsOpen)
{
SetStatus(T("Il server ha chiuso la connessione"), error: true);
_ = Release();
ShowState();
return;
}
_sinceSaves += delta;
if (_awaitingWelcome is not null && (_waiting += delta) > WelcomeTimeoutS)
{
_awaitingWelcome = null;
SetStatus(T("Il server non ha risposto"), error: true);
}
if (_sinceSaves >= SavesRefreshS && _awaitingWelcome is null)
{
_sinceSaves = 0;
_session.Send(new ListSaves());
}
if (!ReferenceEquals(_session.World.Saves, _shownSaves)) ShowSaves();
ShowState();
}
// ------------------------------------------------------------------ azioni
private void Resume()
{
if (_session is null || _awaitingWelcome is not null) return;
int index = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
if (index <= 0 || index > _saveIds.Count)
{
Play();
return;
}
string id = _saveIds[index - 1];
SetStatus($"{T("Caricamento di")} {_saves.GetItemText(index)}…");
AwaitWelcome();
_session.Send(new Load { SaveId = id });
}
private void NewGameOnServer()
{
if (_session is null || _awaitingWelcome is not null) return;
var summary = _session.World.Summary;
SetStatus(T("Creazione della nuova partita sul server…"));
AwaitWelcome();
// il seme lo sceglie il client: la generazione resta deterministica sul server
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
}
/// <summary>Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.</summary>
private void AwaitWelcome()
{
_awaitingWelcome = m =>
{
if (m is Welcome)
{
_awaitingWelcome = null;
Play();
}
else if (m is Notification { Event.Severity: >= (byte)EventSeverity.Warning } note)
{
// caricamento o creazione rifiutati: il server risponde con un avviso
_awaitingWelcome = null;
SetStatus(note.Event.Text, error: true);
}
};
_waiting = 0;
}
private void Play()
{
var s = TakeSession();
if (s is not null) PlayRequested?.Invoke(s);
}
// ------------------------------------------------------------------ stato
public void SetStatus(string text, bool error = false)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", error ? Palette.Danger : Palette.TextSecondary);
}
private void ShowState()
{
var info = _session?.World.Server;
var summary = _session?.World.Summary;
string title;
Color dot;
if (_busy)
{
title = _local ? T("Avvio del server locale…") : T("Collegamento in corso…");
dot = Palette.Amber;
}
else if (_session is not null)
{
title = $"{T("Collegato a")} {_session.ServerLabel}";
dot = Palette.Ok;
}
else
{
title = _local ? T("Server locale spento: scegli «Gioca in locale» per avviarlo") : T("Non collegato");
dot = Palette.TextSecondary;
}
_stateTitle.Text = title;
_dot.Color = dot;
var rows = new List<(string, string)>
{
(T("Versione"), info is null ? "—" : $"{info.Version} · {T("dati compatibili")}"),
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds)),
(T("Simulazione"), info is null || info.TickMs <= 0 ? "—" : $"{Fmt.Number(1000 / info.TickMs, 0)} {T("tick al secondo")}" + (summary is null ? "" : $" · {summary.Date}")),
(T("Latenza"), _session is null || _session.LatencyMs <= 0 ? "—" : $"{Fmt.Number(_session.LatencyMs, 0)} ms"),
(T("Client collegati"), info is null ? "—" : $"{info.Sessions} / {info.MaxSessions}"),
};
if (_stateRows.GetChildCount() != rows.Count * 2)
{
foreach (var c in _stateRows.GetChildren()) c.QueueFree();
foreach (var (caption, _) in rows)
{
_stateRows.AddChild(UiTheme.Text(caption, 13, Palette.TextSecondary));
_stateRows.AddChild(UiTheme.Text("", 13, bold: true));
}
}
for (int i = 0; i < rows.Count; i++)
{
((Label)_stateRows.GetChild(i * 2)).Text = rows[i].Item1;
((Label)_stateRows.GetChild(i * 2 + 1)).Text = rows[i].Item2;
}
bool ready = _session is not null && !_busy && _awaitingWelcome is null;
_resume.Disabled = !ready;
_newGame.Disabled = !ready;
_probe.Disabled = _busy;
}
private void ShowSaves()
{
var w = _session!.World;
_shownSaves = w.Saves;
int selected = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
_saves.Clear();
_saveIds.Clear();
string company = w.Summary?.CompanyName ?? "";
_saves.AddItem($"{T("Partita in corso")} · {company} · {w.Summary?.Date ?? ""}");
double now = Time.GetUnixTimeFromSystem();
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs))
{
_saveIds.Add(s.SaveId);
string kind = s.Autosave ? $" ({T("automatico")})" : "";
_saves.AddItem($"{s.Name}{kind} · {s.GameDate} · {Ago(now - s.SavedUnixMs / 1000.0)}");
}
_saves.Select(Math.Clamp(selected, 0, _saves.ItemCount - 1));
}
private static string Uptime(long seconds)
{
if (seconds < 3600) return $"{Math.Max(1, seconds / 60)} min";
if (seconds < 86_400) return $"{seconds / 3600} h {seconds % 3600 / 60} min";
return $"{seconds / 86_400} {T("giorni")} {seconds % 86_400 / 3600} h";
}
private static string Ago(double seconds)
{
if (seconds < 90) return T("adesso");
if (seconds < 3600) return $"{(int)(seconds / 60)} {T("minuti fa")}";
if (seconds < 86_400) return $"{(int)(seconds / 3600)} {T("ore fa")}";
return $"{(int)(seconds / 86_400)} {T("giorni fa")}";
}
}
/// <summary>
/// Mappa decorativa della schermata iniziale: pianura, un fiume, una linea a doppio binario con
/// stazioni e i tetti dei paesi, disegnati in codice con la palette della mappa (immagine 05) e
/// velati verso il basso per il titolo. Solo grafica: nessun dato di gioco.
/// </summary>
public partial class ConnectBackdrop : Control
{
public override void _Draw()
{
var size = Size;
DrawRect(new Rect2(Vector2.Zero, size), Palette.Plain);
// colline e boschi a macchie, posizioni fisse in frazioni della superficie
foreach (var (x, y, r, c) in new[] { (0.15f, 0.2f, 0.16f, Palette.Hill), (0.7f, 0.15f, 0.2f, Palette.Highland), (0.85f, 0.55f, 0.14f, Palette.Undergrowth),
(0.3f, 0.6f, 0.12f, Palette.Undergrowth), (0.55f, 0.35f, 0.07f, Palette.Canopy), (0.1f, 0.45f, 0.06f, Palette.Canopy), (0.62f, 0.72f, 0.05f, Palette.Canopy) })
DrawCircle(new Vector2(x * size.X, y * size.Y), r * Math.Max(size.X, size.Y), c);
// fiume
var river = new Vector2[] { new(0.62f, 0f), new(0.58f, 0.18f), new(0.66f, 0.36f), new(0.6f, 0.55f), new(0.7f, 0.78f), new(0.66f, 1f) };
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Banks, 30, true);
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Water, 20, true);
// linea ferroviaria: massicciata, traversine, rotaie
var rail = new Vector2[] { new(-0.05f, 0.42f), new(0.25f, 0.38f), new(0.48f, 0.44f), new(0.75f, 0.4f), new(1.05f, 0.3f) };
var pts = rail.Select(p => p * size).ToArray();
DrawPolyline(pts, Palette.Ballast, 16, true);
for (int i = 0; i < pts.Length - 1; i++)
{
var a = pts[i];
var b = pts[i + 1];
var dir = (b - a).Normalized();
var n = new Vector2(-dir.Y, dir.X) * 7;
for (float t = 0; t < a.DistanceTo(b); t += 9)
{
var p = a + dir * t;
DrawLine(p - n, p + n, Palette.Sleepers, 3);
}
}
foreach (float off in new[] { -3.5f, 3.5f })
DrawPolyline(pts.Select((p, i) => p + Normal(pts, i) * off).ToArray(), Palette.Rails, 1.5f, true);
// stazioni e paesi
foreach (var (x, y) in new[] { (0.25f, 0.38f), (0.75f, 0.4f) })
{
var c = new Vector2(x * size.X, y * size.Y);
DrawRect(new Rect2(c - new Vector2(22, 26), new Vector2(44, 14)), Palette.Panel);
for (int k = 0; k < 9; k++)
{
var roof = c + new Vector2((k % 3 - 1) * 26 + (k * 7 % 5), 28 + k / 3 * 20);
DrawRect(new Rect2(roof, new Vector2(16, 12)), k % 4 == 0 ? Palette.IndustrialRoof : Palette.TileRoof);
}
}
// velo verso il basso per leggere il titolo
var veil = new Color[] { Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.92f), Palette.WithAlpha(Palette.AppBackground, 0.92f) };
DrawPolygon([new Vector2(0, size.Y * 0.35f), new Vector2(size.X, size.Y * 0.35f), new Vector2(size.X, size.Y), new Vector2(0, size.Y)], veil);
}
private static Vector2 Normal(Vector2[] pts, int i)
{
var dir = (pts[Math.Min(i + 1, pts.Length - 1)] - pts[Math.Max(i - 1, 0)]).Normalized();
return new Vector2(-dir.Y, dir.X);
}
public override void _Notification(int what)
{
if (what == NotificationResized) QueueRedraw();
}
}