using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Godot; using RustToDust.Net; namespace RustToDust.Client; /// /// Public Yggdrasil directory server browser with live non-blocking UDP RTDP /// ping probes, optional 127.0.0.1:3076 localhost probe, and direct IP:Port join. /// public sealed partial class ServerBrowser : CanvasLayer { public const string DefaultDirectoryUrl = "https://eureka.gamecult.org/rtd-directory"; private sealed class ServerRowModel { public required string Key; public required string Host; public required int Port; public required string Name; public required string Map; public required int Humans; public required int MaxHumans; public required string Phase; public required bool IsLocalProbe; public int? PingMs; public bool TimedOut; public bool Probing = true; public bool Disposed; public Button? RowButton; public Label? NameLabel; public Label? MapLabel; public Label? PlayersLabel; public Label? PhaseLabel; public Label? PingLabel; public Label? AddressLabel; } private readonly ConcurrentQueue _mainThreadQueue = new(); private readonly List _rows = new(); private Control _root = null!; private Label _dirStatusLabel = null!; private Label _dirUrlLabel = null!; private VBoxContainer _rowsContainer = null!; private CheckBox _probeLocalhostCheck = null!; private LineEdit _directEndpointEdit = null!; private Button _refreshBtn = null!; private Button _joinBtn = null!; private Label _footerErrorLabel = null!; private CancellationTokenSource? _refreshCts; private int _refreshSeq; private string _directoryUrl = DefaultDirectoryUrl; private string _callsign = "Pilot"; private string? _selectedKey; public ServerBrowser() { Layer = 20; } public event Action? JoinRequested; public event Action? HostRequested; public event Action? BackRequested; public bool IsTextInputFocused => Visible && _directEndpointEdit is not null && _directEndpointEdit.HasFocus(); public int RowCount => _rows.Count; public override void _Ready() { BuildUi(); SetBrowserVisible(false); } public override void _ExitTree() { CancelPendingRefresh(); } public override void _Process(double delta) { while (_mainThreadQueue.TryDequeue(out var action)) { action(); } } public void Configure(string directoryUrl, string callsign, string? defaultDirectEndpoint = null) { _directoryUrl = directoryUrl ?? string.Empty; _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim(); if (_dirUrlLabel is not null) { _dirUrlLabel.Text = string.IsNullOrWhiteSpace(_directoryUrl) ? "DIRECTORY: DISABLED" : $"DIRECTORY: {_directoryUrl}"; } if (_directEndpointEdit is not null && !string.IsNullOrWhiteSpace(defaultDirectEndpoint)) { _directEndpointEdit.Text = defaultDirectEndpoint.Trim(); } } public void SetBrowserVisible(bool visible, bool autoRefresh = true) { Visible = visible; if (_root is not null) { _root.Visible = visible; } if (visible) { SetError(null); if (autoRefresh) { Refresh(); } } else { CancelPendingRefresh(); _directEndpointEdit?.ReleaseFocus(); } } public void SetError(string? message) { if (_footerErrorLabel is null) return; if (string.IsNullOrWhiteSpace(message)) { _footerErrorLabel.Visible = false; _footerErrorLabel.Text = string.Empty; return; } _footerErrorLabel.Text = message.Trim(); _footerErrorLabel.Visible = true; } public void Refresh() { CancelPendingRefresh(); int seq = ++_refreshSeq; _refreshCts = new CancellationTokenSource(); CancellationToken ct = _refreshCts.Token; ClearRows(); _selectedKey = null; UpdateJoinButtonState(); SetError(null); bool probeLocal = _probeLocalhostCheck is null || _probeLocalhostCheck.ButtonPressed; if (probeLocal) { var localRow = new ServerRowModel { Key = "local:127.0.0.1:3076", Host = "127.0.0.1", Port = 3076, Name = "LOCALHOST (127.0.0.1:3076)", Map = "-", Humans = 0, MaxHumans = 12, Phase = "PROBING", IsLocalProbe = true, Probing = true }; AddRowWidget(localRow); _ = ProbeRowAsync(localRow, seq, ct); } string dirUrl = DirectoryBrowserClient.NormalizeBaseUrl(_directoryUrl); if (string.IsNullOrEmpty(dirUrl)) { SetDirectoryStatus("Directory URL not configured — local/direct connect ready.", isWarning: true); return; } SetDirectoryStatus("Querying public Yggdrasil directory...", isWarning: false); _ = Task.Run(async () => { try { var servers = await DirectoryBrowserClient.FetchServersAsync(dirUrl, ct).ConfigureAwait(false); _mainThreadQueue.Enqueue(() => { if (!IsInsideTree() || seq != _refreshSeq) return; OnDirectoryFetched(servers, seq, ct); }); } catch (OperationCanceledException) { } catch (Exception ex) { _mainThreadQueue.Enqueue(() => { if (!IsInsideTree() || seq != _refreshSeq) return; SetDirectoryStatus($"Directory offline ({ShortError(ex.Message)}) — direct IP:Port connect available.", isWarning: true); }); } }, ct); } private void OnDirectoryFetched(IReadOnlyList servers, int seq, CancellationToken ct) { if (servers.Count == 0) { SetDirectoryStatus("Directory online — 0 public servers listed.", isWarning: false); return; } SetDirectoryStatus($"Directory online — {servers.Count} {(servers.Count == 1 ? "server" : "servers")} listed. Pinging...", isWarning: false); for (int i = 0; i < servers.Count; i++) { var s = servers[i]; if (string.IsNullOrWhiteSpace(s.PublicHost) || s.UdpPort is < 1 or > 65535) { continue; } // Avoid duplicating localhost row if directory explicitly lists 127.0.0.1:3076 bool isLoopbackDefault = string.Equals(s.PublicHost, "127.0.0.1", StringComparison.Ordinal) && s.UdpPort == 3076; if (isLoopbackDefault) { RemoveLocalProbeRowIfPresent(); } var row = new ServerRowModel { Key = $"dir:{s.ServerId:N}:{s.PublicHost}:{s.UdpPort}", Host = s.PublicHost, Port = s.UdpPort, Name = string.IsNullOrWhiteSpace(s.Name) ? $"{s.PublicHost}:{s.UdpPort}" : s.Name.Trim(), Map = FormatMap(s.Map), Humans = s.Humans, MaxHumans = s.MaxHumans > 0 ? s.MaxHumans : 12, Phase = FormatPhase(s.Phase), IsLocalProbe = false, Probing = true }; AddRowWidget(row); _ = ProbeRowAsync(row, seq, ct); } } private async Task ProbeRowAsync(ServerRowModel row, int seq, CancellationToken ct) { try { var result = await ServerPingProbe.ProbeAsync(row.Host, row.Port, TimeSpan.FromMilliseconds(1400), ct).ConfigureAwait(false); _mainThreadQueue.Enqueue(() => { if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; row.Probing = false; if (result.Success && result.Summary is { } summary) { row.PingMs = result.RttMs; row.TimedOut = false; if (!string.IsNullOrWhiteSpace(summary.ServerName)) { row.Name = row.IsLocalProbe ? $"[LOCAL] {summary.ServerName.Trim()}" : summary.ServerName.Trim(); } row.Map = summary.MapKind == RustToDust.Core.ArenaMapKind.Sion ? "SION" : "DESERT"; row.Humans = summary.Humans; row.MaxHumans = summary.MaxHumans > 0 ? summary.MaxHumans : 12; row.Phase = summary.Phase switch { RustToDust.Core.MatchPhase.Lobby => "LOBBY", RustToDust.Core.MatchPhase.Completed => "COMPLETE", _ => "IN-MATCH" }; } else { row.PingMs = null; row.TimedOut = true; if (row.IsLocalProbe) { row.Phase = "OFFLINE"; } } SyncRowVisual(row); }); } catch (OperationCanceledException) { } catch { _mainThreadQueue.Enqueue(() => { if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; row.Probing = false; row.PingMs = null; row.TimedOut = true; SyncRowVisual(row); }); } } private void CancelPendingRefresh() { _refreshSeq++; if (_refreshCts is not null) { try { _refreshCts.Cancel(); } catch { } _refreshCts.Dispose(); _refreshCts = null; } while (_mainThreadQueue.TryDequeue(out _)) { } } private void BuildUi() { _root = new Control { Name = "ServerBrowserRoot", MouseFilter = Control.MouseFilterEnum.Stop }; _root.SetAnchorsPreset(Control.LayoutPreset.FullRect); AddChild(_root); var scrim = new ColorRect { Color = new Color(0.03f, 0.04f, 0.03f, 0.42f), MouseFilter = Control.MouseFilterEnum.Stop }; scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect); _root.AddChild(scrim); var panel = ImperialChrome.CreatePanel(ImperialChrome.CyanCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.93f, padH: 18, padV: 16); panel.Name = "ServerBrowserPanel"; panel.AnchorLeft = 0.5f; panel.AnchorRight = 0.5f; panel.AnchorTop = 0.5f; panel.AnchorBottom = 0.5f; panel.OffsetLeft = -530f; panel.OffsetRight = 530f; panel.OffsetTop = -290f; panel.OffsetBottom = 290f; _root.AddChild(panel); var vbox = new VBoxContainer(); vbox.AddThemeConstantOverride("separation", 10); panel.AddChild(vbox); // Header bar var headerRow = new HBoxContainer(); headerRow.AddThemeConstantOverride("separation", 10); vbox.AddChild(headerRow); var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; titleCol.AddThemeConstantOverride("separation", 2); headerRow.AddChild(titleCol); titleCol.AddChild(ImperialChrome.CreateLabel("PUBLIC YGGDRASIL SERVER BROWSER", 20, ImperialChrome.CyanCol)); _dirUrlLabel = ImperialChrome.CreateLabel($"DIRECTORY: {_directoryUrl}", 11, ImperialChrome.TextMuted); titleCol.AddChild(_dirUrlLabel); _refreshBtn = ImperialChrome.CreateButton("REFRESH", ImperialChrome.CyanCol, 13, 34f); _refreshBtn.CustomMinimumSize = new Vector2(108f, 34f); _refreshBtn.Pressed += Refresh; headerRow.AddChild(_refreshBtn); var hostBtn = ImperialChrome.CreateButton("HOST", ImperialChrome.GoldCol, 13, 34f); hostBtn.CustomMinimumSize = new Vector2(92f, 34f); hostBtn.Pressed += () => HostRequested?.Invoke(); headerRow.AddChild(hostBtn); var backBtn = ImperialChrome.CreateButton("BACK", ImperialChrome.OrangeCol, 13, 34f); backBtn.CustomMinimumSize = new Vector2(92f, 34f); backBtn.Pressed += () => BackRequested?.Invoke(); headerRow.AddChild(backBtn); // Status + Localhost toggle row var subRow = new HBoxContainer(); subRow.AddThemeConstantOverride("separation", 12); vbox.AddChild(subRow); _dirStatusLabel = ImperialChrome.CreateLabel("Ready.", 12, ImperialChrome.TextMuted); _dirStatusLabel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; _dirStatusLabel.ClipText = true; subRow.AddChild(_dirStatusLabel); _probeLocalhostCheck = new CheckBox { Text = "Probe Localhost (127.0.0.1:3076)", ButtonPressed = true }; ImperialChrome.StyleCheckBox(_probeLocalhostCheck, ImperialChrome.OliveCol, 12); _probeLocalhostCheck.Toggled += _ => Refresh(); subRow.AddChild(_probeLocalhostCheck); vbox.AddChild(ImperialChrome.MakeRule()); // Column headers var colHeader = new HBoxContainer(); colHeader.AddThemeConstantOverride("separation", 8); vbox.AddChild(colHeader); AddHeaderCell(colHeader, "SERVER NAME", expand: true, width: 0f); AddHeaderCell(colHeader, "MAP", expand: false, width: 96f); AddHeaderCell(colHeader, "PLAYERS", expand: false, width: 90f); AddHeaderCell(colHeader, "PHASE", expand: false, width: 112f); AddHeaderCell(colHeader, "PING", expand: false, width: 100f); AddHeaderCell(colHeader, "ENDPOINT", expand: false, width: 175f); // Scrollable rows var listFrame = new PanelContainer { SizeFlagsVertical = Control.SizeFlags.ExpandFill }; var frameStyle = new StyleBoxFlat { BgColor = new Color(ImperialChrome.BgDark.R, ImperialChrome.BgDark.G, ImperialChrome.BgDark.B, 0.72f), BorderColor = ImperialChrome.BorderCol, ContentMarginLeft = 6, ContentMarginRight = 6, ContentMarginTop = 6, ContentMarginBottom = 6 }; frameStyle.SetBorderWidthAll(1); listFrame.AddThemeStyleboxOverride("panel", frameStyle); vbox.AddChild(listFrame); var scroll = new ScrollContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, SizeFlagsVertical = Control.SizeFlags.ExpandFill, HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled }; listFrame.AddChild(scroll); _rowsContainer = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; _rowsContainer.AddThemeConstantOverride("separation", 4); scroll.AddChild(_rowsContainer); vbox.AddChild(ImperialChrome.MakeRule()); // Footer: direct IP:Port + Join Selected var footerRow = new HBoxContainer(); footerRow.AddThemeConstantOverride("separation", 10); vbox.AddChild(footerRow); footerRow.AddChild(ImperialChrome.CreateLabel("DIRECT IP:PORT", 12, ImperialChrome.TextMuted)); _directEndpointEdit = new LineEdit { Text = "127.0.0.1:3076", PlaceholderText = "127.0.0.1:3076", MaxLength = 96, CustomMinimumSize = new Vector2(240f, 34f) }; ImperialChrome.StyleLineEdit(_directEndpointEdit, ImperialChrome.CyanCol, 13); _directEndpointEdit.TextSubmitted += _ => JoinDirect(); footerRow.AddChild(_directEndpointEdit); var directBtn = ImperialChrome.CreateButton("DIRECT CONNECT", ImperialChrome.OrangeCol, 13, 34f); directBtn.CustomMinimumSize = new Vector2(150f, 34f); directBtn.Pressed += JoinDirect; footerRow.AddChild(directBtn); var spacer = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; footerRow.AddChild(spacer); _joinBtn = ImperialChrome.CreateButton("JOIN SELECTED", ImperialChrome.OliveCol, 14, 34f); _joinBtn.CustomMinimumSize = new Vector2(170f, 34f); _joinBtn.Disabled = true; _joinBtn.Pressed += JoinSelected; footerRow.AddChild(_joinBtn); _footerErrorLabel = ImperialChrome.CreateLabel(string.Empty, 12, ImperialChrome.RedCol); _footerErrorLabel.AutowrapMode = TextServer.AutowrapMode.Word; _footerErrorLabel.Visible = false; vbox.AddChild(_footerErrorLabel); } private static void AddHeaderCell(HBoxContainer parent, string text, bool expand, float width) { var lbl = ImperialChrome.CreateLabel(text, 11, ImperialChrome.TextMuted); if (expand) { lbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; } else { lbl.CustomMinimumSize = new Vector2(width, 0f); } parent.AddChild(lbl); } private void ClearRows() { for (int i = 0; i < _rows.Count; i++) { _rows[i].Disposed = true; } _rows.Clear(); if (_rowsContainer is null) return; for (int i = _rowsContainer.GetChildCount() - 1; i >= 0; i--) { var c = _rowsContainer.GetChild(i); _rowsContainer.RemoveChild(c); c.QueueFree(); } } private void RemoveLocalProbeRowIfPresent() { for (int i = _rows.Count - 1; i >= 0; i--) { if (!_rows[i].IsLocalProbe) continue; var row = _rows[i]; row.Disposed = true; var btn = row.RowButton; _rows.RemoveAt(i); if (btn is not null && IsInstanceValid(btn)) { _rowsContainer.RemoveChild(btn); btn.QueueFree(); } } } private void AddRowWidget(ServerRowModel row) { _rows.Add(row); var btn = new Button { FocusMode = Control.FocusModeEnum.None, CustomMinimumSize = new Vector2(0f, 34f), SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; row.RowButton = btn; var hbox = new HBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore }; hbox.SetAnchorsPreset(Control.LayoutPreset.FullRect); hbox.OffsetLeft = 10f; hbox.OffsetRight = -10f; hbox.AddThemeConstantOverride("separation", 8); btn.AddChild(hbox); row.NameLabel = MakeRowCell(row.Name, 13, ImperialChrome.TextLight, expand: true, width: 0f); row.MapLabel = MakeRowCell(row.Map, 12, ImperialChrome.OliveCol, expand: false, width: 96f); row.PlayersLabel = MakeRowCell($"{row.Humans}/{row.MaxHumans}", 12, ImperialChrome.TextLight, expand: false, width: 90f); row.PhaseLabel = MakeRowCell(row.Phase, 12, ImperialChrome.CyanCol, expand: false, width: 112f); row.PingLabel = MakeRowCell("...", 12, ImperialChrome.TextMuted, expand: false, width: 100f); row.AddressLabel = MakeRowCell($"{row.Host}:{row.Port}", 11, ImperialChrome.TextMuted, expand: false, width: 175f); hbox.AddChild(row.NameLabel); hbox.AddChild(row.MapLabel); hbox.AddChild(row.PlayersLabel); hbox.AddChild(row.PhaseLabel); hbox.AddChild(row.PingLabel); hbox.AddChild(row.AddressLabel); btn.Pressed += () => SelectRow(row); btn.GuiInput += ev => { if (ev is InputEventMouseButton mb && mb.Pressed && mb.DoubleClick && mb.ButtonIndex == MouseButton.Left) { SelectRow(row); JoinSelected(); } }; _rowsContainer.AddChild(btn); SyncRowVisual(row); } private static Label MakeRowCell(string text, int fontSize, Color color, bool expand, float width) { var lbl = new Label { Text = text, VerticalAlignment = VerticalAlignment.Center, ClipText = true, MouseFilter = Control.MouseFilterEnum.Ignore }; lbl.AddThemeFontSizeOverride("font_size", fontSize); lbl.AddThemeColorOverride("font_color", color); if (expand) { lbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; } else { lbl.CustomMinimumSize = new Vector2(width, 0f); } return lbl; } private void SelectRow(ServerRowModel row) { _selectedKey = row.Key; if (_directEndpointEdit is not null && !_directEndpointEdit.HasFocus()) { _directEndpointEdit.Text = $"{row.Host}:{row.Port}"; } for (int i = 0; i < _rows.Count; i++) { SyncRowVisual(_rows[i]); } UpdateJoinButtonState(); } private void SyncRowVisual(ServerRowModel row) { if (row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; bool selected = string.Equals(_selectedKey, row.Key, StringComparison.Ordinal); Color accent = selected ? ImperialChrome.OliveCol : (row.TimedOut ? ImperialChrome.BorderCol : ImperialChrome.CyanCol); var normal = new StyleBoxFlat { BgColor = selected ? ImperialChrome.BgPressed : ImperialChrome.BgInner, BorderColor = selected ? ImperialChrome.OliveCol : new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.7f) }; normal.SetBorderWidthAll(selected ? 2 : 1); var hover = new StyleBoxFlat { BgColor = ImperialChrome.BgHover, BorderColor = accent }; hover.SetBorderWidthAll(1); row.RowButton.AddThemeStyleboxOverride("normal", normal); row.RowButton.AddThemeStyleboxOverride("hover", hover); row.RowButton.AddThemeStyleboxOverride("pressed", hover); row.RowButton.AddThemeStyleboxOverride("focus", hover); row.NameLabel!.Text = row.Name; row.NameLabel.AddThemeColorOverride("font_color", row.TimedOut && row.IsLocalProbe ? ImperialChrome.TextMuted : ImperialChrome.TextLight); row.MapLabel!.Text = row.Map; row.PlayersLabel!.Text = $"{row.Humans}/{row.MaxHumans}"; row.PhaseLabel!.Text = row.Phase; Color phaseCol = row.Phase switch { "LOBBY" => ImperialChrome.OliveCol, "IN-MATCH" => ImperialChrome.GoldCol, "OFFLINE" => ImperialChrome.TextMuted, _ => ImperialChrome.CyanCol }; row.PhaseLabel.AddThemeColorOverride("font_color", phaseCol); if (row.Probing) { row.PingLabel!.Text = "..."; row.PingLabel.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); } else if (row.PingMs is int ms) { row.PingLabel!.Text = $"{ms} ms"; Color pingCol = ms < 70 ? ImperialChrome.OliveCol : (ms < 150 ? ImperialChrome.GoldCol : ImperialChrome.OrangeCol); row.PingLabel.AddThemeColorOverride("font_color", pingCol); } else { row.PingLabel!.Text = "TIMEOUT"; row.PingLabel.AddThemeColorOverride("font_color", ImperialChrome.RedCol); } row.AddressLabel!.Text = $"{row.Host}:{row.Port}"; } private void UpdateJoinButtonState() { if (_joinBtn is null) return; _joinBtn.Disabled = string.IsNullOrEmpty(_selectedKey); } private void JoinSelected() { for (int i = 0; i < _rows.Count; i++) { if (string.Equals(_rows[i].Key, _selectedKey, StringComparison.Ordinal)) { string ep = $"{_rows[i].Host}:{_rows[i].Port}"; JoinRequested?.Invoke(ep, _callsign); return; } } } private void JoinDirect() { string ep = (_directEndpointEdit?.Text ?? string.Empty).Trim(); if (string.IsNullOrEmpty(ep)) { SetError("Enter host:port to connect directly."); return; } SetError(null); JoinRequested?.Invoke(ep, _callsign); } private void SetDirectoryStatus(string message, bool isWarning) { if (_dirStatusLabel is null) return; _dirStatusLabel.Text = message; _dirStatusLabel.AddThemeColorOverride("font_color", isWarning ? ImperialChrome.OrangeCol : ImperialChrome.OliveCol); } private static string FormatMap(string? map) => string.Equals(map, "sion", StringComparison.OrdinalIgnoreCase) ? "SION" : "DESERT"; private static string FormatPhase(string? phase) { if (string.Equals(phase, "Lobby", StringComparison.OrdinalIgnoreCase)) return "LOBBY"; if (string.Equals(phase, "Completed", StringComparison.OrdinalIgnoreCase)) return "COMPLETE"; return "IN-MATCH"; } private static string ShortError(string msg) { if (string.IsNullOrWhiteSpace(msg)) return "unreachable"; string oneLine = msg.Replace('\r', ' ').Replace('\n', ' ').Trim(); return oneLine.Length > 64 ? oneLine[..64] + "..." : oneLine; } }