using Godot; using ViaFerrea.Client.App; using ViaFerrea.Client.Hud; using ViaFerrea.Client.Map; using ViaFerrea.Client.Net; using ViaFerrea.Client.Panels; using ViaFerrea.Core.Commands; using ViaFerrea.Core.Common; using ViaFerrea.Core.Rail; using ViaFerrea.Protocol; using ViaFerrea.Protocol.Messages; using static ViaFerrea.Client.App.Localization; namespace ViaFerrea.Client.Screens; /// /// 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. /// 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 readonly List _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; /// Seleziona uno strumento come dalla barra (anche per il pilota automatico). public void UseTool(Tool tool) => _toolbar.Select(tool); /// Imposta i punti del tracciato in corso e aggiorna l'anteprima. public void SetTrackPoints(IEnumerable points, Vector2? mouse) { _trackPoints.Clear(); _trackPoints.AddRange(points); _mouse = mouse; _previewDirty = true; } /// Mostra la scheda di un treno e lo evidenzia. 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 }; 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); _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); var sideCol = new VBoxContainer(); sideCol.AddThemeConstantOverride("separation", 12); side.AddChild(sideCol); sideCol.AddChild(_scroll); _scroll.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); _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); } public override void _ExitTree() => _session.MessageApplied -= OnMessage; private void BuildDisconnectedOverlay(CanvasLayer hud) { _disconnected.SetAnchorsPreset(Control.LayoutPreset.FullRect); _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); SendViewport(force: true); 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; SendViewport(force: false); _sincePreview += delta; if (_previewDirty && _sincePreview > 0.12) { _previewDirty = false; _sincePreview = 0; UpdateTrackPreview(); } } /// Sottoscrive l'area visibile quando la camera si sposta di almeno un quarto di schermo. 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; 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.Market: panel = new MarketPanel(_session); break; case Tool.Finance: panel = new FinancePanel(_session); break; default: panel = _info = new InfoPanel(_session); break; } panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; _content.AddChild(panel); } 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; default: SelectAt(world); break; } } /// Scatto a 45° rispetto al punto precedente (Maiusc per disattivarlo). 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(_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 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; foreach (var ind in w.Industries.Values) { if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6)) { _info.Select(InfoPanel.Kind.Industry, ind.Id); 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); } /// Messaggio temporaneo in alto sulla mappa. 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(); } }