using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Audio;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Screens;
using RailEnterprise.Client.Tutorial;
using RailEnterprise.Core.Data;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client;
///
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra schermata di connessione e partita;
/// alla chiusura termina la sessione e l'eventuale server locale.
///
public partial class Main : Node
{
private const string SettingsPath = "user://settings.cfg";
// cartelle del server locale: la partita del giocatore (la apre la schermata di connessione), la
// partita di prova del tutorial e quella del collaudo (queste due ripartono sempre da una partita nuova)
private const string LocalDataDir = "user://server";
private const string TutorialDataDir = "user://tutorial-server";
private const string AutopilotDataDir = "user://autopilot-server";
private GameData? _data;
private Node? _screen;
private GameSession? _session;
private string? _autopilot;
// tutorial della partita che si apre: casella «Mostra il tutorial» e pulsante «Tutorial» (dal primo passo)
private bool _tutorialRequested, _tutorialRestart;
public override void _Ready()
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
string locale = (string)cfg.GetValue("ui", "locale", "it");
Localization.Load(locale);
GetWindow().Theme = UiTheme.Build();
GetWindow().Title = "Rail Enterprise";
var args = OS.GetCmdlineUserArgs();
int i = Array.IndexOf(args, "--autopilot");
// audio: niente nel pilota automatico e senza schermo (non rallenta il collaudo)
var audio = new AudioManager(enabled: i < 0 && DisplayServer.GetName() != "headless");
AddChild(audio);
try
{
_data = GodotDataSource.LoadGameData();
audio.SetEras(_data.Eras.Eras);
}
catch (Exception e)
{
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
}
if (i >= 0 && _data is not null)
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
// nel collaudo la schermata di connessione non avvia un suo server: lo avvia StartLocal qui sotto
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "", autoStart: _autopilot is null);
if (_autopilot is not null)
{
// collaudo: mappa piccola e seme fisso per il server locale
System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64");
System.Environment.SetEnvironmentVariable("RE_SEED", "3");
System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0");
StartLocal();
}
}
private void Swap(Node screen)
{
_screen?.QueueFree();
_screen = screen;
AddChild(screen);
}
/// Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.
/// Avvia subito la strada scelta l'ultima volta (server locale o in rete).
/// Sessione di prova della schermata precedente, ripresa così com'è (cambio di lingua).
private void ShowMenu(string status = "", bool autoStart = true, GameSession? handover = null)
{
if (_data is null)
{
// senza dati non si può aprire nessuna sessione: resta solo il messaggio
var label = UiTheme.Text(status, 16, Palette.Danger);
label.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.Center);
Swap(label);
return;
}
// chi aggiorna con una partita locale già salvata non è alla prima partita: casella spenta
if (!TutorialSettings.Played && HasLocalSaves()) TutorialSettings.Played = true;
var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover);
screen.PlayRequested += session =>
{
SetTutorial(screen.ShowTutorial, restart: false);
ShowGame(session, screen.GameScope);
};
screen.TutorialRequested += async () =>
{
// la partita di prova ha un suo server: quello della sessione di prova della schermata si chiude
var trial = screen.TakeSession();
if (trial is not null) await trial.DisposeAsync();
SetTutorial(true, restart: true);
StartLocal(tutorial: true);
};
screen.AudioRequested += () => AudioManager.Instance?.ShowSettings();
screen.LanguageChanged += code =>
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("ui", "locale", code);
cfg.Save(SettingsPath);
TranslationServer.SetLocale(code);
// la schermata si ricrea con i testi nuovi: la sessione di prova (e il server locale) passa a lei
ShowMenu(handover: screen.TakeSession());
};
Swap(screen);
if (status.Length > 0) screen.SetStatus(status, error: true);
}
private void SetTutorial(bool requested, bool restart)
{
_tutorialRequested = requested;
_tutorialRestart = restart;
}
/// Vero se la partita locale del giocatore ha già dei salvataggi (file .vfsave del server).
private static bool HasLocalSaves()
{
try
{
string saves = System.IO.Path.Combine(ProjectSettings.GlobalizePath(LocalDataDir), "saves");
return Directory.Exists(saves) && Directory.EnumerateFiles(saves, "*.vfsave").Any();
}
catch (IOException)
{
return false;
}
}
///
/// Server locale da zero e subito in partita, senza la schermata di connessione: il collaudo e la partita
/// di prova del tutorial, ciascuno nella sua cartella; la partita del giocatore non si tocca.
///
/// pulsante «Tutorial»: partita di prova nuova, con il tutorial dal primo passo
private async void StartLocal(bool tutorial = false)
{
if (_data is null) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), autoStart: false);
return;
}
if (tutorial && _screen is ConnectScreen connect) connect.SetStatus(T("Avvio della partita di prova del tutorial…"));
var launcher = new LocalServerLauncher();
try
{
string dataDir = ProjectSettings.GlobalizePath(tutorial ? TutorialDataDir : AutopilotDataDir);
if (Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
int port = await launcher.StartAsync(server, dataDir, 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;
ShowGame(session, tutorial ? "tutorial" : "autopilot");
}
catch (Exception e)
{
launcher.Dispose();
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}", autoStart: false);
}
}
/// origine della partita (locale, tutorial, server in rete) per la voce del tutorial
private void ShowGame(GameSession session, string scope)
{
_session = session;
var game = new GameScreen(session);
game.Exit += async () =>
{
// prima si chiude la partita (e il server locale), poi la schermata di connessione ne
// avvia uno nuovo: due server sulla stessa cartella dei salvataggi non convivono
var s = _session;
_session = null;
if (s is not null) await s.DisposeAsync();
ShowMenu();
};
Swap(game);
// il pilota automatico non mostra il tutorial: le sue schermate di partita restano quelle di sempre
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
else
{
game.AddChild(new TutorialController(game, scope, _tutorialRequested, _tutorialRestart));
TutorialSettings.Played = true;
_tutorialRestart = false;
}
}
public override void _Notification(int what)
{
if (what != NotificationWMCloseRequest) return;
// anche la sessione di prova della schermata di connessione chiude il suo server locale
var session = _session ?? (_screen as ConnectScreen)?.TakeSession();
_session = null;
session?.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
}
}