Cut 9b: Godot Main Menu, Public Yggdrasil Server Browser, Pre-Match Lobby, and Pause Overlay

This commit is contained in:
Meta Vens 2026-12-05 17:49:15 +01:00
commit 1673ce5c69
6 changed files with 2426 additions and 54 deletions

View file

@ -175,8 +175,31 @@ public partial class Hud : CanvasLayer
_schematic.QueueRedraw();
}
public void SetMatchHudActive(bool active)
{
Visible = active;
if (!active)
{
if (_netPanel.Visible)
{
_netPanel.Visible = false;
_callsignEdit.ReleaseFocus();
_endpointEdit.ReleaseFocus();
}
if (_garageExpanded)
{
ToggleGarage();
}
ResetFeedback();
}
}
public override void _Process(double delta)
{
if (!Visible)
{
return;
}
float dt = (float)delta;
_crosshair?.Advance(dt);

213
client/ImperialChrome.cs Normal file
View file

@ -0,0 +1,213 @@
using Godot;
namespace RustToDust.Client;
/// <summary>
/// Shared Industrial Imperial palette and beveled <c>panel_chrome.gdshader</c> panel/control
/// helpers for pre-match UI layers (<see cref="MainMenu"/>, <see cref="ServerBrowser"/>,
/// <see cref="LobbyScreen"/>). Kept separate from <see cref="Hud"/> so <c>Hud.GetChromeMaterials()</c>
/// preserves its exact 6-panel contract.
/// </summary>
public static class ImperialChrome
{
public static readonly Color BgDark = Color.FromHtml("#131613");
public static readonly Color BgInner = Color.FromHtml("#1b1f1b");
public static readonly Color BgHover = Color.FromHtml("#242b23");
public static readonly Color BgPressed = Color.FromHtml("#2e372c");
public static readonly Color BorderCol = Color.FromHtml("#3e4638");
public static readonly Color OliveCol = Color.FromHtml("#9bb06a");
public static readonly Color OrangeCol = Color.FromHtml("#e08a4a");
public static readonly Color TextLight = Color.FromHtml("#e4dfd2");
public static readonly Color TextMuted = Color.FromHtml("#989487");
public static readonly Color CyanCol = Color.FromHtml("#44d9e8");
public static readonly Color GoldCol = Color.FromHtml("#e6b838");
public static readonly Color RedCol = Color.FromHtml("#d93829");
public static readonly Color ScrimCol = new(0.03f, 0.04f, 0.03f, 0.56f);
private static Shader? _sharedChromeShader;
private static ImageTexture? _sharedWhiteTex;
internal static Shader? ChromeShader => _sharedChromeShader ??= GD.Load<Shader>("res://panel_chrome.gdshader");
internal static ImageTexture WhiteTexture
{
get
{
if (_sharedWhiteTex is null)
{
var img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8);
img.SetPixel(0, 0, Colors.White);
_sharedWhiteTex = ImageTexture.CreateFromImage(img);
}
return _sharedWhiteTex;
}
}
public static ImperialChromePanel CreatePanel(
Color accentColor,
float cornerLen = 14f,
float borderPx = 1.5f,
float bgAlpha = 0.90f,
int padH = 14,
int padV = 12)
{
return new ImperialChromePanel(accentColor, cornerLen, borderPx, bgAlpha, padH, padV);
}
public static Label CreateLabel(string text, int fontSize, Color color, HorizontalAlignment align = HorizontalAlignment.Left)
{
var lbl = new Label
{
Text = text,
HorizontalAlignment = align
};
lbl.AddThemeFontSizeOverride("font_size", fontSize);
lbl.AddThemeColorOverride("font_color", color);
return lbl;
}
public static Button CreateButton(string text, Color accentColor, int fontSize = 13, float minHeight = 32f)
{
var btn = new Button
{
Text = text,
FocusMode = Control.FocusModeEnum.None,
CustomMinimumSize = new Vector2(0f, minHeight)
};
StyleButton(btn, accentColor, fontSize);
return btn;
}
public static void StyleButton(Button btn, Color accentColor, int fontSize = 13)
{
btn.AddThemeFontSizeOverride("font_size", fontSize);
btn.AddThemeColorOverride("font_color", TextLight);
btn.AddThemeColorOverride("font_hover_color", Colors.White);
btn.AddThemeColorOverride("font_pressed_color", accentColor);
btn.AddThemeColorOverride("font_disabled_color", new Color(TextMuted.R, TextMuted.G, TextMuted.B, 0.45f));
var normal = MakeBox(BgInner, new Color(accentColor.R, accentColor.G, accentColor.B, 0.55f), 1);
var hover = MakeBox(BgHover, accentColor, 1);
var pressed = MakeBox(BgPressed, accentColor, 2);
var disabled = MakeBox(new Color(BgDark.R, BgDark.G, BgDark.B, 0.65f), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.4f), 1);
btn.AddThemeStyleboxOverride("normal", normal);
btn.AddThemeStyleboxOverride("hover", hover);
btn.AddThemeStyleboxOverride("pressed", pressed);
btn.AddThemeStyleboxOverride("disabled", disabled);
btn.AddThemeStyleboxOverride("focus", hover);
}
public static void StyleLineEdit(LineEdit edit, Color accentColor, int fontSize = 13)
{
edit.AddThemeFontSizeOverride("font_size", fontSize);
edit.AddThemeColorOverride("font_color", TextLight);
edit.AddThemeColorOverride("font_placeholder_color", new Color(TextMuted.R, TextMuted.G, TextMuted.B, 0.65f));
edit.AddThemeColorOverride("font_uneditable_color", TextMuted);
edit.AddThemeColorOverride("caret_color", accentColor);
var normal = MakeBox(BgInner, BorderCol, 1, padH: 8, padV: 4);
var focus = MakeBox(BgHover, accentColor, 1, padH: 8, padV: 4);
var readOnly = MakeBox(new Color(BgDark.R, BgDark.G, BgDark.B, 0.72f), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.45f), 1, padH: 8, padV: 4);
edit.AddThemeStyleboxOverride("normal", normal);
edit.AddThemeStyleboxOverride("focus", focus);
edit.AddThemeStyleboxOverride("read_only", readOnly);
}
public static void StyleOptionButton(OptionButton opt, Color accentColor, int fontSize = 13)
{
StyleButton(opt, accentColor, fontSize);
}
public static void StyleCheckBox(CheckBox chk, Color accentColor, int fontSize = 12)
{
chk.FocusMode = Control.FocusModeEnum.None;
chk.AddThemeFontSizeOverride("font_size", fontSize);
chk.AddThemeColorOverride("font_color", TextLight);
chk.AddThemeColorOverride("font_hover_color", Colors.White);
chk.AddThemeColorOverride("font_pressed_color", accentColor);
chk.AddThemeColorOverride("font_disabled_color", TextMuted);
}
public static HSeparator MakeRule(Color? color = null)
{
var sep = new HSeparator();
var line = new StyleBoxLine
{
Color = color ?? new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.75f),
Thickness = 1
};
sep.AddThemeStyleboxOverride("separator", line);
return sep;
}
private static StyleBoxFlat MakeBox(Color bg, Color border, int borderW, int padH = 10, int padV = 6)
{
var box = new StyleBoxFlat
{
BgColor = bg,
BorderColor = border,
ContentMarginLeft = padH,
ContentMarginRight = padH,
ContentMarginTop = padV,
ContentMarginBottom = padV
};
box.SetBorderWidthAll(borderW);
return box;
}
}
public sealed partial class ImperialChromePanel : PanelContainer
{
private readonly ShaderMaterial _material;
public ImperialChromePanel(
Color accentColor,
float cornerLen = 14f,
float borderPx = 1.5f,
float bgAlpha = 0.90f,
int padH = 14,
int padV = 12)
{
_material = new ShaderMaterial { Shader = ImperialChrome.ChromeShader };
_material.SetShaderParameter("bg_color", new Color(ImperialChrome.BgDark.R, ImperialChrome.BgDark.G, ImperialChrome.BgDark.B, bgAlpha));
_material.SetShaderParameter("border_color", ImperialChrome.BorderCol);
_material.SetShaderParameter("accent_color", accentColor);
_material.SetShaderParameter("corner_len", cornerLen);
_material.SetShaderParameter("border_px", borderPx);
Material = _material;
var empty = new StyleBoxEmpty
{
ContentMarginLeft = padH,
ContentMarginRight = padH,
ContentMarginTop = padV,
ContentMarginBottom = padV
};
AddThemeStyleboxOverride("panel", empty);
}
public ShaderMaterial ChromeMaterial => _material;
public void SetAccentColor(Color accentColor)
{
_material.SetShaderParameter("accent_color", accentColor);
}
public override void _Notification(int what)
{
if (what == NotificationResized)
{
_material.SetShaderParameter("rect_size", Size);
QueueRedraw();
}
}
public override void _Draw()
{
if (Size.X < 2f || Size.Y < 2f) return;
_material.SetShaderParameter("rect_size", Size);
DrawTextureRect(ImperialChrome.WhiteTexture, new Rect2(Vector2.Zero, Size), false, Colors.White);
}
}

474
client/LobbyScreen.cs Normal file
View file

@ -0,0 +1,474 @@
using System;
using System.Globalization;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Authoritative pre-match orbital lobby overlay (<see cref="MatchPhase.Lobby"/>).
/// Displays the 12 contender slots, ready states, host-only map/seed controls,
/// live 5-second orbital insertion countdown banner, and launch/leave actions.
/// </summary>
public sealed partial class LobbyScreen : CanvasLayer
{
private sealed class SlotRowView
{
public required PanelContainer Frame;
public required Label IndexLabel;
public required Label NameLabel;
public required Label RoleBadge;
public required Label ReadyBadge;
}
private readonly SlotRowView[] _slotViews = new SlotRowView[MatchState.ContenderCount];
private Control _root = null!;
private ImperialChromePanel _panel = null!;
private Label _modeBadge = null!;
private PanelContainer _countdownBanner = null!;
private Label _countdownLabel = null!;
private Label _rosterSummaryLabel = null!;
private OptionButton _mapOption = null!;
private LineEdit _seedEdit = null!;
private Button _applyConfigBtn = null!;
private Button _randomSeedBtn = null!;
private Label _authorityNoteLabel = null!;
private Label _netStatusLabel = null!;
private Button _readyBtn = null!;
private Button _launchBtn = null!;
private Button _leaveBtn = null!;
private IClientArenaSession? _activeSession;
private int? _lastSyncedSeed;
private byte? _lastSyncedMap;
public LobbyScreen()
{
Layer = 20;
}
public event Action? LeaveRequested;
public bool IsTextInputFocused => Visible && _seedEdit is not null && _seedEdit.HasFocus();
public override void _Ready()
{
BuildUi();
SetLobbyVisible(false);
}
public void SetLobbyVisible(bool visible)
{
Visible = visible;
if (_root is not null)
{
_root.Visible = visible;
}
if (!visible)
{
_activeSession = null;
_lastSyncedSeed = null;
_lastSyncedMap = null;
_seedEdit?.ReleaseFocus();
}
}
public void Sync(IClientArenaSession session)
{
_activeSession = session;
var net = session.ConnectionStatus;
var lobby = session.LobbyState;
_modeBadge.Text = net.Mode switch
{
NetworkMode.ListenHost => net.StateLabel,
NetworkMode.RemoteClient => net.Connected
? $"CONNECTED • PING {net.PingMs} ms"
: (net.LastError is not null ? $"DISCONNECTED: {net.LastError}" : "CONNECTING TO LOBBY..."),
_ => "SOLO"
};
_modeBadge.AddThemeColorOverride("font_color",
net.LastError is not null ? ImperialChrome.RedCol : (net.Connected ? ImperialChrome.CyanCol : ImperialChrome.OrangeCol));
if (lobby is null)
{
_countdownLabel.Text = net.LastError is not null
? $"CONNECTION LOST — {net.LastError}"
: "ESTABLISHING RUDP UPLINK TO SERVER LOBBY...";
_countdownLabel.AddThemeColorOverride("font_color", net.LastError is not null ? ImperialChrome.RedCol : ImperialChrome.OrangeCol);
_rosterSummaryLabel.Text = "Awaiting authoritative lobby roster...";
_readyBtn.Disabled = true;
_launchBtn.Visible = false;
_mapOption.Disabled = true;
_seedEdit.Editable = false;
_applyConfigBtn.Disabled = true;
_randomSeedBtn.Disabled = true;
_authorityNoteLabel.Text = "Waiting for server snapshot...";
_netStatusLabel.Text = net.StateLabel;
return;
}
int localId = session.LocalContenderId;
bool isHost = lobby.HostSlotId.HasValue && lobby.HostSlotId.Value == localId;
bool localReady = false;
int humanCount = 0;
int readyCount = 0;
int aiCount = 0;
for (int i = 0; i < _slotViews.Length; i++)
{
var view = _slotViews[i];
if (i < lobby.Slots.Count)
{
var slot = lobby.Slots[i];
bool isLocalSlot = slot.SlotId == localId;
bool isHostSlot = lobby.HostSlotId.HasValue && slot.SlotId == lobby.HostSlotId.Value;
view.IndexLabel.Text = $"SLOT {slot.SlotId + 1:00}";
if (slot.IsHuman)
{
humanCount++;
if (slot.IsReady) readyCount++;
if (isLocalSlot) localReady = slot.IsReady;
view.NameLabel.Text = string.IsNullOrWhiteSpace(slot.Callsign) ? $"Pilot {slot.SlotId + 1}" : slot.Callsign;
view.NameLabel.AddThemeColorOverride("font_color", isLocalSlot ? ImperialChrome.TextLight : Colors.White);
view.RoleBadge.Text = isHostSlot
? (isLocalSlot ? "[HOST / YOU]" : "[HOST]")
: (isLocalSlot ? "[YOU]" : "[PILOT]");
view.RoleBadge.AddThemeColorOverride("font_color", isHostSlot ? ImperialChrome.GoldCol : ImperialChrome.CyanCol);
view.ReadyBadge.Text = slot.IsReady ? "[READY]" : "[WAIT]";
view.ReadyBadge.AddThemeColorOverride("font_color", slot.IsReady ? ImperialChrome.OliveCol : ImperialChrome.OrangeCol);
ApplyRowFrame(view.Frame, isLocalSlot ? ImperialChrome.CyanCol : ImperialChrome.BorderCol, highlighted: isLocalSlot);
}
else
{
aiCount++;
view.NameLabel.Text = "AI BACKFILL";
view.NameLabel.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
view.RoleBadge.Text = "[BOT]";
view.RoleBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
view.ReadyBadge.Text = "[ARMED]";
view.ReadyBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
ApplyRowFrame(view.Frame, new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.45f), highlighted: false);
}
}
}
_rosterSummaryLabel.Text = $"HUMANS: {humanCount}/{MatchState.ContenderCount} • READY: {readyCount}/{Math.Max(1, humanCount)} • AI BACKFILL: {aiCount}";
// Countdown banner
if (lobby.CountdownSeconds is float cd)
{
int ceilSec = Math.Max(1, (int)MathF.Ceiling(cd));
_countdownLabel.Text = $"ORBITAL INSERTION IN {ceilSec}...";
_countdownLabel.AddThemeColorOverride("font_color", ceilSec <= 2 ? ImperialChrome.OrangeCol : ImperialChrome.GoldCol);
_panel.SetAccentColor(ImperialChrome.GoldCol);
}
else
{
string readyHint = humanCount < lobby.MinHumansToAutoStart
? $"NEED {lobby.MinHumansToAutoStart} HUMANS FOR AUTO-LAUNCH"
: "ALL PILOTS READY UP TO BEGIN DROP";
_countdownLabel.Text = isHost
? $"PRE-MATCH STANDBY • {readyHint} (OR LAUNCH DROP)"
: $"PRE-MATCH STANDBY • {readyHint}";
_countdownLabel.AddThemeColorOverride("font_color", ImperialChrome.CyanCol);
_panel.SetAccentColor(ImperialChrome.CyanCol);
}
// Sync Map & Seed without clobbering active typing by host
if (_lastSyncedMap != lobby.SelectedMap)
{
_lastSyncedMap = lobby.SelectedMap;
_mapOption.Select((ArenaMapKind)lobby.SelectedMap == ArenaMapKind.Desert ? 1 : 0);
}
if (_lastSyncedSeed != lobby.SelectedSeed && (!_seedEdit.HasFocus() || !isHost))
{
_lastSyncedSeed = lobby.SelectedSeed;
_seedEdit.Text = lobby.SelectedSeed.ToString(CultureInfo.InvariantCulture);
}
// Strict host authority gating
_mapOption.Disabled = !isHost;
_seedEdit.Editable = isHost;
_applyConfigBtn.Disabled = !isHost;
_randomSeedBtn.Disabled = !isHost;
_authorityNoteLabel.Text = isHost
? "HOST AUTHORITY: You control drop zone, seed, and forced launch."
: "READ-ONLY: Only the match host can edit map, seed, or force launch.";
_authorityNoteLabel.AddThemeColorOverride("font_color", isHost ? ImperialChrome.GoldCol : ImperialChrome.TextMuted);
_readyBtn.Disabled = false;
_readyBtn.Text = localReady ? "READY [ON] — CLICK TO UNREADY" : "READY UP";
ImperialChrome.StyleButton(_readyBtn, localReady ? ImperialChrome.OliveCol : ImperialChrome.CyanCol, 14);
_launchBtn.Visible = isHost;
_launchBtn.Disabled = !isHost;
_launchBtn.Text = lobby.ForceLaunched ? "LAUNCHING NOW..." : "LAUNCH DROP";
_netStatusLabel.Text = $"{net.StateLabel} • MAP: {((ArenaMapKind)lobby.SelectedMap == ArenaMapKind.Sion ? "SION 3KM" : "DESERT RING")} • SEED {lobby.SelectedSeed}";
}
private void BuildUi()
{
_root = new Control
{
Name = "LobbyScreenRoot",
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.36f),
MouseFilter = Control.MouseFilterEnum.Stop
};
scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_root.AddChild(scrim);
_panel = ImperialChrome.CreatePanel(ImperialChrome.CyanCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.92f, padH: 18, padV: 16);
_panel.Name = "LobbyScreenPanel";
_panel.AnchorLeft = 0.5f;
_panel.AnchorRight = 0.5f;
_panel.AnchorTop = 0.5f;
_panel.AnchorBottom = 0.5f;
_panel.OffsetLeft = -500f;
_panel.OffsetRight = 500f;
_panel.OffsetTop = -305f;
_panel.OffsetBottom = 305f;
_root.AddChild(_panel);
var vbox = new VBoxContainer();
vbox.AddThemeConstantOverride("separation", 10);
_panel.AddChild(vbox);
// Header row
var headerRow = new HBoxContainer();
headerRow.AddThemeConstantOverride("separation", 12);
vbox.AddChild(headerRow);
var titleLbl = ImperialChrome.CreateLabel("PRE-MATCH ORBITAL LOBBY", 20, ImperialChrome.TextLight);
titleLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
headerRow.AddChild(titleLbl);
_modeBadge = ImperialChrome.CreateLabel("HOST :3076", 12, ImperialChrome.CyanCol, HorizontalAlignment.Right);
headerRow.AddChild(_modeBadge);
// Countdown Banner
_countdownBanner = new PanelContainer();
var cdStyle = new StyleBoxFlat
{
BgColor = ImperialChrome.BgInner,
BorderColor = ImperialChrome.GoldCol,
ContentMarginLeft = 12,
ContentMarginRight = 12,
ContentMarginTop = 8,
ContentMarginBottom = 8
};
cdStyle.SetBorderWidthAll(1);
_countdownBanner.AddThemeStyleboxOverride("panel", cdStyle);
vbox.AddChild(_countdownBanner);
_countdownLabel = ImperialChrome.CreateLabel("PRE-MATCH STANDBY", 15, ImperialChrome.CyanCol, HorizontalAlignment.Center);
_countdownBanner.AddChild(_countdownLabel);
// Body: Two columns (Left Roster | Right Config & Actions)
var bodyRow = new HBoxContainer
{
SizeFlagsVertical = Control.SizeFlags.ExpandFill
};
bodyRow.AddThemeConstantOverride("separation", 16);
vbox.AddChild(bodyRow);
// Left Column: Roster (Slot 01..12)
var leftCol = new VBoxContainer
{
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill,
SizeFlagsStretchRatio = 1.35f
};
leftCol.AddThemeConstantOverride("separation", 4);
bodyRow.AddChild(leftCol);
leftCol.AddChild(ImperialChrome.CreateLabel("CONTENDER ROSTER (SLOTS 01 – 12)", 12, ImperialChrome.OrangeCol));
for (int i = 0; i < _slotViews.Length; i++)
{
var frame = new PanelContainer();
ApplyRowFrame(frame, ImperialChrome.BorderCol, highlighted: false);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 8);
frame.AddChild(row);
var idxLbl = ImperialChrome.CreateLabel($"SLOT {i + 1:00}", 11, ImperialChrome.TextMuted);
idxLbl.CustomMinimumSize = new Vector2(64f, 0f);
row.AddChild(idxLbl);
var nameLbl = ImperialChrome.CreateLabel("AI BACKFILL", 12, ImperialChrome.TextMuted);
nameLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
nameLbl.ClipText = true;
row.AddChild(nameLbl);
var roleLbl = ImperialChrome.CreateLabel("[BOT]", 11, ImperialChrome.TextMuted);
roleLbl.CustomMinimumSize = new Vector2(92f, 0f);
roleLbl.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(roleLbl);
var readyLbl = ImperialChrome.CreateLabel("[ARMED]", 11, ImperialChrome.TextMuted);
readyLbl.CustomMinimumSize = new Vector2(72f, 0f);
readyLbl.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(readyLbl);
leftCol.AddChild(frame);
_slotViews[i] = new SlotRowView
{
Frame = frame,
IndexLabel = idxLbl,
NameLabel = nameLbl,
RoleBadge = roleLbl,
ReadyBadge = readyLbl
};
}
_rosterSummaryLabel = ImperialChrome.CreateLabel("HUMANS: 1/12 • READY: 0/1 • AI BACKFILL: 11", 11, ImperialChrome.OliveCol);
leftCol.AddChild(_rosterSummaryLabel);
// Right Column: Drop Zone Config & Launch Actions
var rightCol = new VBoxContainer
{
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill,
SizeFlagsStretchRatio = 1.0f
};
rightCol.AddThemeConstantOverride("separation", 10);
bodyRow.AddChild(rightCol);
rightCol.AddChild(ImperialChrome.CreateLabel("DROP ZONE CONFIGURATION", 12, ImperialChrome.GoldCol));
rightCol.AddChild(ImperialChrome.MakeRule());
var mapRow = new HBoxContainer();
mapRow.AddThemeConstantOverride("separation", 8);
rightCol.AddChild(mapRow);
var mapLbl = ImperialChrome.CreateLabel("MAP", 12, ImperialChrome.TextMuted);
mapLbl.CustomMinimumSize = new Vector2(68f, 0f);
mapRow.AddChild(mapLbl);
_mapOption = new OptionButton { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
_mapOption.AddItem("SION (3KM ALPINE)", 0);
_mapOption.AddItem("DESERT RING", 1);
ImperialChrome.StyleOptionButton(_mapOption, ImperialChrome.OliveCol, 13);
_mapOption.ItemSelected += _ => ApplyConfigFromUi();
mapRow.AddChild(_mapOption);
var seedRow = new HBoxContainer();
seedRow.AddThemeConstantOverride("separation", 8);
rightCol.AddChild(seedRow);
var seedLbl = ImperialChrome.CreateLabel("SEED", 12, ImperialChrome.TextMuted);
seedLbl.CustomMinimumSize = new Vector2(68f, 0f);
seedRow.AddChild(seedLbl);
_seedEdit = new LineEdit
{
Text = "42",
MaxLength = 12,
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
ImperialChrome.StyleLineEdit(_seedEdit, ImperialChrome.GoldCol, 13);
_seedEdit.TextSubmitted += _ => ApplyConfigFromUi();
seedRow.AddChild(_seedEdit);
_randomSeedBtn = ImperialChrome.CreateButton("RND", ImperialChrome.BorderCol, 12, 30f);
_randomSeedBtn.CustomMinimumSize = new Vector2(54f, 30f);
_randomSeedBtn.Pressed += () =>
{
int nextSeed = Random.Shared.Next(1, 999999);
_seedEdit.Text = nextSeed.ToString(CultureInfo.InvariantCulture);
ApplyConfigFromUi();
};
seedRow.AddChild(_randomSeedBtn);
_applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP & SEED", ImperialChrome.GoldCol, 12, 32f);
_applyConfigBtn.Pressed += ApplyConfigFromUi;
rightCol.AddChild(_applyConfigBtn);
_authorityNoteLabel = ImperialChrome.CreateLabel("HOST AUTHORITY", 11, ImperialChrome.TextMuted);
_authorityNoteLabel.AutowrapMode = TextServer.AutowrapMode.Word;
rightCol.AddChild(_authorityNoteLabel);
rightCol.AddChild(ImperialChrome.MakeRule());
var spacer = new Control { SizeFlagsVertical = Control.SizeFlags.ExpandFill };
rightCol.AddChild(spacer);
_readyBtn = ImperialChrome.CreateButton("READY UP", ImperialChrome.CyanCol, 14, 42f);
_readyBtn.Pressed += OnReadyPressed;
rightCol.AddChild(_readyBtn);
_launchBtn = ImperialChrome.CreateButton("LAUNCH DROP", ImperialChrome.OliveCol, 14, 42f);
_launchBtn.Pressed += OnLaunchPressed;
rightCol.AddChild(_launchBtn);
_leaveBtn = ImperialChrome.CreateButton("LEAVE TO MENU", ImperialChrome.RedCol, 13, 36f);
_leaveBtn.Pressed += () => LeaveRequested?.Invoke();
rightCol.AddChild(_leaveBtn);
_netStatusLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.TextMuted);
_netStatusLabel.AutowrapMode = TextServer.AutowrapMode.Word;
vbox.AddChild(_netStatusLabel);
}
private void OnReadyPressed()
{
if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return;
int localId = _activeSession.LocalContenderId;
bool currentReady = false;
for (int i = 0; i < lobby.Slots.Count; i++)
{
if (lobby.Slots[i].SlotId == localId)
{
currentReady = lobby.Slots[i].IsReady;
break;
}
}
_activeSession.SetLobbyReady(!currentReady);
}
private void OnLaunchPressed()
{
_activeSession?.RequestLobbyStart();
}
private void ApplyConfigFromUi()
{
if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return;
if (!lobby.HostSlotId.HasValue || lobby.HostSlotId.Value != _activeSession.LocalContenderId) return;
var mapKind = _mapOption.Selected == 1 ? ArenaMapKind.Desert : ArenaMapKind.Sion;
int seed = int.TryParse(_seedEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed)
? parsed
: lobby.SelectedSeed;
_seedEdit.ReleaseFocus();
_activeSession.RequestLobbyConfig(seed, mapKind);
}
private static void ApplyRowFrame(PanelContainer frame, Color borderColor, bool highlighted)
{
var style = new StyleBoxFlat
{
BgColor = highlighted ? ImperialChrome.BgHover : ImperialChrome.BgInner,
BorderColor = borderColor,
ContentMarginLeft = 8,
ContentMarginRight = 8,
ContentMarginTop = 4,
ContentMarginBottom = 4
};
style.SetBorderWidthAll(1);
frame.AddThemeStyleboxOverride("panel", style);
}
}

View file

@ -11,6 +11,15 @@ using RustToDust.Ymir;
namespace RustToDust.Client;
public enum ClientScreenMode
{
MainMenu,
ServerBrowser,
Lobby,
InMatch,
PauseOverlay
}
/// <summary>
/// Root Godot node for Rust to Dust.
/// Godot physics is Dummy; <see cref="IClientArenaSession"/> drives Solo (<see cref="LocalArenaSession"/>),
@ -27,12 +36,31 @@ public partial class Main : Node3D
private ArenaAudioSystem _audio = null!;
private Camera3D _camera = null!;
private Hud _hud = null!;
private MainMenu _mainMenu = null!;
private ServerBrowser _serverBrowser = null!;
private LobbyScreen _lobbyScreen = null!;
private DirectionalLight3D _sun = null!;
private ProceduralSkyMaterial _skyMat = null!;
private Godot.Environment _env = null!;
private IClientArenaSession? _session;
private MatchState? _boundViewState;
private bool _wasNetConnected;
private ClientScreenMode _screenMode = ClientScreenMode.MainMenu;
private DirectoryReporter? _directoryReporter;
private string _directoryUrl = ServerBrowser.DefaultDirectoryUrl;
private string _publicHostOverride = "auto";
private string _serverName = "Rust to Dust";
private DirectoryHeartbeatSnapshot _cachedDirectorySnapshot;
private readonly object _dirSnapGate = new();
private int _lastDirHumans = -1;
private MatchPhase _lastDirPhase = (MatchPhase)(-1);
private ArenaMapKind _lastDirMap = (ArenaMapKind)(-1);
private int _lastDirSeed;
private SionMapData? _menuSionData;
private TerrainField? _menuSionTerrain;
private int _menuPreviewTargetFrames;
private int _menuPreviewFrames;
private string? _menuPreviewOut;
private readonly WalkerFootstepTracker _footsteps = new();
private readonly CameraJuiceState _camJuice = new();
private readonly List<ISimEvent> _frameEvents = new(128);
@ -82,6 +110,8 @@ public partial class Main : Node3D
private double _perfCamMsSum;
public IClientArenaSession Session => _session ?? throw new InvalidOperationException($"No active IClientArenaSession ({Failure ?? "uninitialized"})");
public bool HasActiveSession => _session is not null;
public ClientScreenMode ScreenMode => _screenMode;
public TerrainRenderer Terrain => _terrain;
public SionMapRenderer SionMap => _sionMap;
public ArenaRenderer Arena => _arena;
@ -90,9 +120,13 @@ public partial class Main : Node3D
public CameraJuiceState CameraJuice => _camJuice;
public Camera3D Camera => _camera;
public Hud Hud => _hud;
public MainMenu MainMenuOverlay => _mainMenu;
public ServerBrowser ServerBrowserOverlay => _serverBrowser;
public LobbyScreen LobbyOverlay => _lobbyScreen;
public ArenaMapKind MapKind => _mapKind;
public ArenaMapKind? InitialMapKindOverride { get; set; }
public bool InitialSkipDropOverride { get; set; }
public bool InitialSkipMenuOverride { get; set; }
public string? Failure { get; private set; }
public int Seed => _seed;
public float CameraYaw => _cameraYaw;
@ -133,6 +167,40 @@ public partial class Main : Node3D
_hud.NetworkPanelToggled += _ => SyncMouseMode();
AddChild(_hud);
_mainMenu = new MainMenu { Name = "MainMenu" };
_mainMenu.PlaySoloRequested += OnMainMenuPlaySolo;
_mainMenu.ServerBrowserRequested += OnMainMenuServerBrowser;
_mainMenu.HostLobbyRequested += OnMainMenuHostLobby;
_mainMenu.CallsignChanged += cs =>
{
_callsign = cs;
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
};
_mainMenu.QuitRequested += () => GetTree().Quit(0);
_mainMenu.ResumeRequested += () =>
{
if (_screenMode == ClientScreenMode.PauseOverlay)
{
SetScreenMode(ClientScreenMode.InMatch);
}
};
_mainMenu.ReturnToMainMenuRequested += ReturnToMainMenu;
AddChild(_mainMenu);
_serverBrowser = new ServerBrowser { Name = "ServerBrowser" };
_serverBrowser.JoinRequested += OnBrowserJoinRequested;
_serverBrowser.HostRequested += () =>
{
SetScreenMode(ClientScreenMode.MainMenu);
_mainMenu.SetHostPanelOpen(true);
};
_serverBrowser.BackRequested += () => SetScreenMode(ClientScreenMode.MainMenu);
AddChild(_serverBrowser);
_lobbyScreen = new LobbyScreen { Name = "LobbyScreen" };
_lobbyScreen.LeaveRequested += ReturnToMainMenu;
AddChild(_lobbyScreen);
var reticleMat = new StandardMaterial3D
{
ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded,
@ -156,6 +224,25 @@ public partial class Main : Node3D
string? cliName = GetCliArg("--name");
string? cliMap = GetCliArg("--map");
string? cliSeed = GetCliArg("--seed");
bool cliSolo = GetCliArg("--solo", allowBareFlag: true) is not null
|| System.Environment.GetEnvironmentVariable("RTD_SOLO") == "1";
bool cliLobby = GetCliArg("--lobby", allowBareFlag: true) is not null
|| System.Environment.GetEnvironmentVariable("RTD_LOBBY") == "1";
string? cliDirUrl = GetCliArg("--directory-url");
string? envDirUrl = System.Environment.GetEnvironmentVariable("RTD_DIRECTORY_URL");
_directoryUrl = cliDirUrl ?? envDirUrl ?? ServerBrowser.DefaultDirectoryUrl;
string? cliPublicHost = GetCliArg("--public-host");
string? envPublicHost = System.Environment.GetEnvironmentVariable("RTD_PUBLIC_HOST");
if ((cliPublicHost ?? envPublicHost) is { Length: > 0 } ph)
{
_publicHostOverride = ph.Trim();
}
string? cliServerName = GetCliArg("--server-name");
string? envServerName = System.Environment.GetEnvironmentVariable("RTD_SERVER_NAME");
if ((cliServerName ?? envServerName) is { Length: > 0 } sn)
{
_serverName = sn.Trim();
}
if (!string.IsNullOrWhiteSpace(cliName))
{
@ -202,6 +289,8 @@ public partial class Main : Node3D
: $"127.0.0.1:{hostTarget.Trim()}";
}
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
{
@ -213,20 +302,44 @@ public partial class Main : Node3D
_perfTargetFrames = autoExitFrames;
}
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_MENU_EXIT_FRAMES"), out int menuExitFrames) && menuExitFrames > 0)
{
_menuPreviewTargetFrames = menuExitFrames;
}
_menuPreviewOut = System.Environment.GetEnvironmentVariable("RTD_MENU_PREVIEW_OUT");
bool perfCombat = _perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1";
bool skipInitialDrop = InitialSkipDropOverride || perfCombat;
bool autoBypassMenu = InitialMapKindOverride.HasValue
|| InitialSkipDropOverride
|| InitialSkipMenuOverride
|| _perfTargetFrames > 0
|| !string.IsNullOrWhiteSpace(connectTarget)
|| hostTarget is not null
|| cliSolo;
if (!string.IsNullOrWhiteSpace(connectTarget))
{
StartRemoteSession(connectTarget, _callsign);
StartRemoteSession(connectTarget, _callsign, fromBrowser: false);
}
else if (hostTarget is not null)
{
StartListenHostSession(hostTarget, _callsign);
StartListenHostSession(
hostTarget,
_callsign,
_mapKind,
_serverName,
startInLobby: cliLobby,
listOnPublicDirectory: false,
fallbackToLocalOnFailure: true);
}
else if (autoBypassMenu)
{
Reset(_seed, _mapKind, skipInitialDrop);
}
else
{
Reset(_seed, _mapKind, skipInitialDrop);
EnterMainMenuBackdrop();
}
if (perfCombat && _session is not null)
@ -301,9 +414,7 @@ public partial class Main : Node3D
public override void _ExitTree()
{
_session?.Dispose();
_session = null;
_boundViewState = null;
DisposeSessionAndDirectory();
}
public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false)
@ -314,16 +425,14 @@ public partial class Main : Node3D
_mapKind = mapKind.Value;
}
_session?.Dispose();
_session = null;
_boundViewState = null;
_wasNetConnected = false;
DisposeSessionAndDirectory();
Failure = null;
_hud.SetNetworkError(null);
try
{
_session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
catch (Exception ex)
@ -333,46 +442,219 @@ public partial class Main : Node3D
}
}
private void StartListenHostSession(string hostArg, string callsign)
private void EnterMainMenuBackdrop()
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim();
DisposeSessionAndDirectory();
Failure = null;
_hud.SetNetworkError(null);
EnsureMenuSionBackdrop();
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_mainMenu.SetHostPanelOpen(false);
SetScreenMode(ClientScreenMode.MainMenu);
}
private void ReturnToMainMenu()
{
_mainMenu.SetStatus(null);
EnterMainMenuBackdrop();
}
private void DisposeSessionAndDirectory()
{
_directoryReporter?.Dispose();
_directoryReporter = null;
_lastDirHumans = -1;
_lastDirPhase = (MatchPhase)(-1);
_lastDirMap = (ArenaMapKind)(-1);
_lastDirSeed = 0;
if (_session is RemoteArenaSession remote)
{
remote.DisconnectGracefully("Leave");
}
_session?.Dispose();
_session = null;
_boundViewState = null;
_wasNetConnected = false;
}
private void EnsureMenuSionBackdrop()
{
_menuSionData ??= SionMapLoader.Load();
_menuSionTerrain ??= TerrainField.LoadHeightmap(
_menuSionData.Metadata.SizeMeters,
_menuSionData.Metadata.GridRes,
_menuSionData.Heights,
_menuSionData.Metadata.MinY,
_menuSionData.Metadata.MaxY,
42UL);
_terrain.Visible = false;
_sionMap.Visible = true;
_arena.Visible = false;
_dropReticleMesh.Visible = false;
_camera.Far = 4200f;
ApplyEnvironmentForMap(ArenaMapKind.Sion);
_sionMap.EnsureBuilt(_menuSionData, _menuSionTerrain);
UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain);
_sionMap.UpdateLod(_camera.GlobalPosition);
}
private void UpdateLobbyOrMenuOrbitCamera(ArenaMapKind mapKind, TerrainField terrain)
{
float orbitRadius = mapKind == ArenaMapKind.Sion ? 460f : 210f;
float speed = mapKind == ArenaMapKind.Sion ? 0.055f : 0.08f;
float angle = _elapsedSeconds * speed + 0.65f;
float ox = MathF.Cos(angle) * orbitRadius;
float oz = MathF.Sin(angle) * orbitRadius;
float groundY = terrain.SampleHeight(ox, oz);
float targetY = terrain.SampleHeight(0f, 0f) + (mapKind == ArenaMapKind.Sion ? 42f : 14f);
float camY = mapKind == ArenaMapKind.Sion
? MathF.Max(groundY + 115f, targetY + 135f)
: MathF.Max(groundY + 55f, 85f);
_camera.Fov = 58f;
_camera.GlobalPosition = new Vector3(ox, camY, oz);
_camera.LookAt(new Vector3(0f, targetY, 0f), Vector3.Up);
}
private void SetScreenMode(ClientScreenMode mode)
{
_screenMode = mode;
switch (mode)
{
case ClientScreenMode.MainMenu:
_hud.SetMatchHudActive(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.ServerBrowser:
_hud.SetMatchHudActive(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_lobbyScreen.SetLobbyVisible(false);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
_serverBrowser.SetBrowserVisible(true, autoRefresh: true);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.Lobby:
_hud.SetMatchHudActive(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(true);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.InMatch:
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
break;
case ClientScreenMode.PauseOverlay:
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
_mainMenu.SetPauseContext(BuildPauseContextLine());
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.PauseOverlay);
break;
}
SyncMouseMode();
}
private string BuildPauseContextLine()
{
string mapLabel = _mapKind == ArenaMapKind.Sion ? "SION 3KM" : "DESERT RING";
if (_session is null) return mapLabel;
var net = _session.ConnectionStatus;
return net.Mode switch
{
NetworkMode.ListenHost => $"{mapLabel} • {net.StateLabel}",
NetworkMode.RemoteClient => $"{mapLabel} • {net.StateLabel}",
_ => $"SOLO • {mapLabel} • SEED {_seed}"
};
}
private void StartListenHostSession(
string hostArg,
string callsign,
ArenaMapKind mapKind,
string serverName,
bool startInLobby,
bool listOnPublicDirectory,
bool fallbackToLocalOnFailure)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim();
string cleanServerName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim();
Failure = null;
_hud.SetNetworkError(null);
_mainMenu.SetHostError(null);
try
{
ParseBindAndPort(hostArg, IPAddress.Loopback, DefaultNetPort, out IPAddress bindIp, out int port);
var hostSession = new ListenHostArenaSession(bindIp, port, _seed, _mapKind);
IPAddress defaultBind = listOnPublicDirectory || !fallbackToLocalOnFailure ? IPAddress.Any : IPAddress.Loopback;
ParseBindAndPort(hostArg, defaultBind, DefaultNetPort, out IPAddress bindIp, out int port);
var hostSession = new ListenHostArenaSession(
bindIp,
port,
_seed,
mapKind,
startInLobby: startInLobby,
serverName: cleanServerName,
minHumansToStart: 1);
hostSession.Host.Session.SetHumanSlot(0, true, nextCallsign);
var oldSession = _session;
DisposeSessionAndDirectory();
_session = hostSession;
_callsign = nextCallsign;
_boundViewState = null;
_wasNetConnected = false;
_lastEndpoint = $"{bindIp}:{hostSession.Host.BoundPort}";
_mapKind = mapKind;
_serverName = cleanServerName;
_lastEndpoint = $"{(bindIp.Equals(IPAddress.Any) ? IPAddress.Loopback : bindIp)}:{hostSession.Host.BoundPort}";
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
if (listOnPublicDirectory)
{
string normDir = DirectoryBrowserClient.NormalizeBaseUrl(_directoryUrl);
if (!string.IsNullOrEmpty(normDir))
{
UpdateCachedDirectorySnapshot(hostSession);
_directoryReporter = new DirectoryReporter(normDir, ReadCachedDirectorySnapshot);
}
}
SetScreenMode(startInLobby ? ClientScreenMode.Lobby : ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
oldSession?.Dispose();
}
catch (Exception ex)
{
Failure = ex.Message;
if (_session is null)
if (fallbackToLocalOnFailure && _session is null)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
_hud.SetNetworkError(ex.Message);
_mainMenu.SetHostError(ex.Message);
GD.PushError("ListenHostArenaSession startup failed: " + ex);
}
}
private void StartRemoteSession(string endpointText, string callsign)
private void StartRemoteSession(string endpointText, string callsign, bool fromBrowser)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
Failure = null;
_hud.SetNetworkError(null);
_serverBrowser.SetError(null);
try
{
@ -380,29 +662,112 @@ public partial class Main : Node3D
var remote = new RemoteArenaSession(ep, nextCallsign);
remote.PumpNetwork();
var oldSession = _session;
DisposeSessionAndDirectory();
_session = remote;
_callsign = nextCallsign;
_boundViewState = null;
_wasNetConnected = false;
_lastEndpoint = endpointText.Trim();
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
SetScreenMode(fromBrowser ? ClientScreenMode.Lobby : ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
oldSession?.Dispose();
}
catch (Exception ex)
{
Failure = ex.Message;
if (_session is null)
if (!fromBrowser && _session is null && _screenMode == ClientScreenMode.InMatch)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
_hud.SetNetworkError(ex.Message);
_serverBrowser.SetError(ex.Message);
GD.PushError("RemoteArenaSession startup failed: " + ex);
}
}
private DirectoryHeartbeatSnapshot ReadCachedDirectorySnapshot()
{
lock (_dirSnapGate)
{
return _cachedDirectorySnapshot;
}
}
private void UpdateCachedDirectorySnapshot(ListenHostArenaSession hostSession)
{
var state = hostSession.ViewState;
int humans = hostSession.Host.ConnectedHumanCount;
string phaseStr = state.Phase switch
{
MatchPhase.Lobby => "Lobby",
MatchPhase.Completed => "Completed",
_ => "Active"
};
string mapStr = state.MapKind == ArenaMapKind.Sion ? "sion" : "desert";
int wave = hostSession.DropWaveState.CurrentWaveIndex;
bool changed = humans != _lastDirHumans
|| state.Phase != _lastDirPhase
|| state.MapKind != _lastDirMap
|| state.Seed != _lastDirSeed;
lock (_dirSnapGate)
{
_cachedDirectorySnapshot = new DirectoryHeartbeatSnapshot(
Name: _serverName,
PublicHost: _publicHostOverride,
UdpPort: hostSession.Host.BoundPort,
Map: mapStr,
Seed: state.Seed,
Humans: humans,
MaxHumans: MatchState.ContenderCount,
Phase: phaseStr,
Wave: wave);
}
if (changed)
{
_lastDirHumans = humans;
_lastDirPhase = state.Phase;
_lastDirMap = state.MapKind;
_lastDirSeed = state.Seed;
_directoryReporter?.NotifyChanged();
}
}
private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign)
{
_callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
Reset(_seed, mapKind, skipInitialDrop: false);
}
private void OnMainMenuServerBrowser(string callsign)
{
_callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
SetScreenMode(ClientScreenMode.ServerBrowser);
}
private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign)
{
string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND");
string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture);
StartListenHostSession(
hostArg,
callsign,
mapKind,
serverName,
startInLobby: true,
listOnPublicDirectory: listOnPublicDirectory,
fallbackToLocalOnFailure: false);
}
private void OnBrowserJoinRequested(string endpointText, string callsign)
{
StartRemoteSession(endpointText, callsign, fromBrowser: true);
}
private void OnSoloRequested()
{
Reset(_seed, _mapKind);
@ -412,12 +777,19 @@ public partial class Main : Node3D
{
string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND");
string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture);
StartListenHostSession(hostArg, callsign);
StartListenHostSession(
hostArg,
callsign,
_mapKind,
_serverName,
startInLobby: false,
listOnPublicDirectory: false,
fallbackToLocalOnFailure: true);
}
private void OnJoinRequested(string endpointText, string callsign)
{
StartRemoteSession(endpointText, callsign);
StartRemoteSession(endpointText, callsign, fromBrowser: false);
}
private void BindSessionPresentation(bool resetCamera)
@ -462,13 +834,22 @@ public partial class Main : Node3D
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f;
ApplyEnvironmentForMap(_mapKind);
bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby;
if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null)
{
_terrain.Visible = false;
_sionMap.Visible = true;
_sionMap.EnsureBuilt(state.SionMap, state.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
}
else
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
@ -477,18 +858,31 @@ public partial class Main : Node3D
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(state.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
}
else
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
var localStart = _session.LocalContender;
Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z);
Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw));
_arena.Particles.PrewarmFlashLights(startVec, startFwd);
_arena.PomDecals.PrewarmShader(startVec);
_hud.Sync(_session);
if (!inLobby)
{
var localStart = _session.LocalContender;
Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z);
Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw));
_arena.Particles.PrewarmFlashLights(startVec, startFwd);
_arena.PomDecals.PrewarmShader(startVec);
_hud.Sync(_session);
}
else
{
_lobbyScreen.Sync(_session);
}
SyncMouseMode();
}
@ -498,6 +892,11 @@ public partial class Main : Node3D
{
return;
}
if (_screenMode != ClientScreenMode.InMatch)
{
Input.MouseMode = Input.MouseModeEnum.Visible;
return;
}
bool uiOpen = _hud.GarageExpanded || _hud.NetworkPanelOpen;
Input.MouseMode = uiOpen ? Input.MouseModeEnum.Visible : Input.MouseModeEnum.Captured;
}
@ -614,18 +1013,37 @@ public partial class Main : Node3D
public override void _UnhandledInput(InputEvent @event)
{
if (@event is InputEventMouseMotion mm && Input.MouseMode == Input.MouseModeEnum.Captured)
{
_cameraYaw -= mm.Relative.X * 0.0028f;
_cameraPitch = Math.Clamp(
_cameraPitch + mm.Relative.Y * 0.0024f,
Mathf.DegToRad(-78f),
Mathf.DegToRad(62f));
return;
}
if (@event is InputEventKey key && key.Pressed && !key.Echo)
{
if (_screenMode == ClientScreenMode.MainMenu)
{
if (key.Keycode == Key.Escape && _mainMenu.IsHostPanelOpen)
{
_mainMenu.SetHostPanelOpen(false);
}
return;
}
if (_screenMode == ClientScreenMode.ServerBrowser)
{
if (key.Keycode == Key.Escape)
{
SetScreenMode(ClientScreenMode.MainMenu);
}
return;
}
if (_screenMode == ClientScreenMode.Lobby)
{
return;
}
if (_screenMode == ClientScreenMode.PauseOverlay)
{
if (key.Keycode == Key.Escape)
{
SetScreenMode(ClientScreenMode.InMatch);
}
return;
}
if (key.Keycode == Key.F9)
{
_hud.ToggleNetworkPanel();
@ -645,11 +1063,9 @@ public partial class Main : Node3D
_hud.ToggleGarage();
SyncMouseMode();
}
else if (DisplayServer.GetName() != "headless")
else
{
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Captured
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
SetScreenMode(ClientScreenMode.PauseOverlay);
}
return;
}
@ -675,8 +1091,25 @@ public partial class Main : Node3D
_session?.RequestNewMatch(_seed, _mapKind == ArenaMapKind.Sion ? ArenaMapKind.Desert : ArenaMapKind.Sion);
break;
}
return;
}
else if (@event is InputEventMouseButton mb && mb.Pressed)
if (_screenMode != ClientScreenMode.InMatch)
{
return;
}
if (@event is InputEventMouseMotion mm && Input.MouseMode == Input.MouseModeEnum.Captured)
{
_cameraYaw -= mm.Relative.X * 0.0028f;
_cameraPitch = Math.Clamp(
_cameraPitch + mm.Relative.Y * 0.0024f,
Mathf.DegToRad(-78f),
Mathf.DegToRad(62f));
return;
}
if (@event is InputEventMouseButton mb && mb.Pressed)
{
if (mb.ButtonIndex == MouseButton.WheelUp)
{
@ -706,7 +1139,15 @@ public partial class Main : Node3D
}
_elapsedSeconds += (float)delta;
var input = _scriptedInput ?? GatherPlayerInput();
PlayerInput input;
if (_screenMode == ClientScreenMode.InMatch)
{
input = _scriptedInput ?? GatherPlayerInput();
}
else
{
input = new PlayerInput(0f, 0f, 0f, 0f, false, false, false);
}
_interactQueued = false;
if (_perfTargetFrames > 0)
@ -728,13 +1169,43 @@ public partial class Main : Node3D
{
if (_session is null)
{
_elapsedSeconds += (float)delta;
EnsureMenuSionBackdrop();
if (_menuPreviewTargetFrames > 0)
{
_menuPreviewFrames++;
if (_menuPreviewFrames >= _menuPreviewTargetFrames)
{
SaveMenuPreviewAndQuit();
}
}
return;
}
float alpha = Math.Clamp((float)Engine.GetPhysicsInterpolationFraction(), 0f, 1f);
_session.BeginRenderFrame(delta, alpha);
if (_session is ListenHostArenaSession liveHost && _directoryReporter is not null)
{
UpdateCachedDirectorySnapshot(liveHost);
}
bool nowConnected = _session.ConnectionStatus.Connected;
bool sessionReadyForPhaseRouting = _session is not RemoteArenaSession || nowConnected;
if (sessionReadyForPhaseRouting)
{
if (_session.ViewState.Phase == MatchPhase.Lobby && _screenMode != ClientScreenMode.Lobby)
{
SetScreenMode(ClientScreenMode.Lobby);
BindSessionPresentation(resetCamera: true);
}
else if (_session.ViewState.Phase != MatchPhase.Lobby && _screenMode == ClientScreenMode.Lobby)
{
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
}
if (!ReferenceEquals(_boundViewState, _session.ViewState) || (!_wasNetConnected && nowConnected))
{
BindSessionPresentation(resetCamera: true);
@ -760,6 +1231,27 @@ public partial class Main : Node3D
}
_wasNetConnected = nowConnected;
if (_screenMode == ClientScreenMode.Lobby)
{
_frameEvents.Clear();
_session.DrainSimEvents(_frameEvents);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_lobbyScreen.Sync(_session);
return;
}
if (_perfTargetFrames > 0)
{
if (_session.ConnectionStatus.Mode == NetworkMode.RemoteClient && !nowConnected && _perfWaitConnectFrames < 300)
@ -856,6 +1348,20 @@ public partial class Main : Node3D
}
}
private void SaveMenuPreviewAndQuit()
{
if (!string.IsNullOrWhiteSpace(_menuPreviewOut) && DisplayServer.GetName() != "headless")
{
var img = GetViewport().GetTexture()?.GetImage();
if (img is not null)
{
var err = img.SavePng(_menuPreviewOut);
GD.Print($"MENU PREVIEW SAVED: {_menuPreviewOut} ({img.GetWidth()}x{img.GetHeight()}, err={err})");
}
}
GetTree().Quit(0);
}
private void DrainAndFanSimEvents(float dt, float alpha)
{
if (_session is null)

425
client/MainMenu.cs Normal file
View file

@ -0,0 +1,425 @@
using System;
using System.Globalization;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Industrial Imperial main menu overlay over the live Sion 3D orbit backdrop,
/// plus the in-match <c>[ESC]</c> pause overlay.
/// </summary>
public sealed partial class MainMenu : CanvasLayer
{
public enum OverlayKind
{
Hidden,
MainMenu,
PauseOverlay
}
private Control _mainRoot = null!;
private ImperialChromePanel _menuPanel = null!;
private ImperialChromePanel _hostPanel = null!;
private LineEdit _callsignEdit = null!;
private Label _statusLabel = null!;
private LineEdit _serverNameEdit = null!;
private LineEdit _portEdit = null!;
private OptionButton _hostMapOption = null!;
private CheckBox _listPublicCheck = null!;
private Label _directoryHintLabel = null!;
private Label _hostErrorLabel = null!;
private Control _pauseRoot = null!;
private Label _pauseContextLabel = null!;
private OverlayKind _overlayKind = OverlayKind.Hidden;
private string _directoryUrl = string.Empty;
public MainMenu()
{
Layer = 20;
}
public event Action<ArenaMapKind, string>? PlaySoloRequested;
public event Action<string>? ServerBrowserRequested;
public event Action<int, string, ArenaMapKind, bool, string>? HostLobbyRequested;
public event Action<string>? CallsignChanged;
public event Action? QuitRequested;
public event Action? ResumeRequested;
public event Action? ReturnToMainMenuRequested;
public bool IsHostPanelOpen => _hostPanel is not null && _hostPanel.Visible;
public bool IsTextInputFocused =>
Visible && _overlayKind == OverlayKind.MainMenu &&
(_callsignEdit.HasFocus() || _serverNameEdit.HasFocus() || _portEdit.HasFocus());
public string Callsign => SanitizeCallsign(_callsignEdit?.Text);
public override void _Ready()
{
BuildMainRoot();
BuildPauseRoot();
SetOverlayKind(OverlayKind.Hidden);
}
public void SetOverlayKind(OverlayKind kind)
{
_overlayKind = kind;
Visible = kind != OverlayKind.Hidden;
if (_mainRoot is not null)
{
_mainRoot.Visible = kind == OverlayKind.MainMenu;
}
if (_pauseRoot is not null)
{
_pauseRoot.Visible = kind == OverlayKind.PauseOverlay;
}
if (kind != OverlayKind.MainMenu)
{
ReleaseTextFocus();
}
}
public void SetHostPanelOpen(bool open)
{
if (_hostPanel is null) return;
_hostPanel.Visible = open;
if (open)
{
_hostErrorLabel.Text = string.Empty;
_hostErrorLabel.Visible = false;
}
else
{
_serverNameEdit.ReleaseFocus();
_portEdit.ReleaseFocus();
}
}
public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076)
{
_directoryUrl = directoryUrl ?? string.Empty;
if (_callsignEdit is not null)
{
_callsignEdit.Text = SanitizeCallsign(callsign);
}
if (_portEdit is not null)
{
_portEdit.Text = defaultPort.ToString(CultureInfo.InvariantCulture);
}
if (_hostMapOption is not null)
{
_hostMapOption.Select(defaultMap == ArenaMapKind.Desert ? 1 : 0);
}
if (_directoryHintLabel is not null)
{
_directoryHintLabel.Text = string.IsNullOrWhiteSpace(_directoryUrl)
? "Public directory disabled (empty URL)"
: $"Directory: {_directoryUrl}";
}
}
public void SetStatus(string? message, bool isError = false)
{
if (_statusLabel is null) return;
if (string.IsNullOrWhiteSpace(message))
{
_statusLabel.Visible = false;
_statusLabel.Text = string.Empty;
return;
}
_statusLabel.Text = message.Trim();
_statusLabel.AddThemeColorOverride("font_color", isError ? ImperialChrome.RedCol : ImperialChrome.CyanCol);
_statusLabel.Visible = true;
}
public void SetHostError(string? message)
{
if (_hostErrorLabel is null) return;
if (string.IsNullOrWhiteSpace(message))
{
_hostErrorLabel.Visible = false;
_hostErrorLabel.Text = string.Empty;
return;
}
_hostErrorLabel.Text = message.Trim();
_hostErrorLabel.Visible = true;
}
public void SetPauseContext(string contextLine)
{
if (_pauseContextLabel is not null)
{
_pauseContextLabel.Text = contextLine;
}
}
private void ReleaseTextFocus()
{
_callsignEdit?.ReleaseFocus();
_serverNameEdit?.ReleaseFocus();
_portEdit?.ReleaseFocus();
}
private void BuildMainRoot()
{
_mainRoot = new Control
{
Name = "MainMenuRoot",
MouseFilter = Control.MouseFilterEnum.Ignore
};
_mainRoot.SetAnchorsPreset(Control.LayoutPreset.FullRect);
AddChild(_mainRoot);
_menuPanel = ImperialChrome.CreatePanel(ImperialChrome.OrangeCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.91f, padH: 20, padV: 18);
_menuPanel.Name = "MainMenuPanel";
_menuPanel.AnchorLeft = 0f;
_menuPanel.AnchorTop = 0f;
_menuPanel.OffsetLeft = 48f;
_menuPanel.OffsetTop = 52f;
_menuPanel.OffsetRight = 458f;
_mainRoot.AddChild(_menuPanel);
var vbox = new VBoxContainer();
vbox.AddThemeConstantOverride("separation", 10);
_menuPanel.AddChild(vbox);
vbox.AddChild(ImperialChrome.CreateLabel("IMPERIAL ORBITAL INSERTION • SECTOR 01", 11, ImperialChrome.GoldCol));
var title = ImperialChrome.CreateLabel("RUST TO DUST", 32, ImperialChrome.TextLight);
vbox.AddChild(title);
vbox.AddChild(ImperialChrome.CreateLabel("SION 3KM ALPINE ARENA • BROKKR COMBAT CHASSIS", 11, ImperialChrome.TextMuted));
vbox.AddChild(ImperialChrome.MakeRule());
// Callsign row
var callRow = new HBoxContainer();
callRow.AddThemeConstantOverride("separation", 10);
vbox.AddChild(callRow);
var callLbl = ImperialChrome.CreateLabel("CALLSIGN", 12, ImperialChrome.TextMuted);
callLbl.CustomMinimumSize = new Vector2(82f, 0f);
callRow.AddChild(callLbl);
_callsignEdit = new LineEdit
{
Text = "Pilot",
MaxLength = 24,
PlaceholderText = "Pilot",
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
ImperialChrome.StyleLineEdit(_callsignEdit, ImperialChrome.CyanCol, 13);
_callsignEdit.TextChanged += txt => CallsignChanged?.Invoke(SanitizeCallsign(txt));
callRow.AddChild(_callsignEdit);
vbox.AddChild(ImperialChrome.MakeRule());
var playSionBtn = ImperialChrome.CreateButton("PLAY SOLO — SION", ImperialChrome.OliveCol, 14, 38f);
playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign);
vbox.AddChild(playSionBtn);
var playDesertBtn = ImperialChrome.CreateButton("PLAY SOLO — DESERT", ImperialChrome.OrangeCol, 14, 38f);
playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign);
vbox.AddChild(playDesertBtn);
var browserBtn = ImperialChrome.CreateButton("SERVER BROWSER", ImperialChrome.CyanCol, 14, 38f);
browserBtn.Pressed += () => ServerBrowserRequested?.Invoke(Callsign);
vbox.AddChild(browserBtn);
var hostBtn = ImperialChrome.CreateButton("HOST MATCH", ImperialChrome.GoldCol, 14, 38f);
hostBtn.Pressed += () => SetHostPanelOpen(!IsHostPanelOpen);
vbox.AddChild(hostBtn);
vbox.AddChild(ImperialChrome.MakeRule());
var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f);
quitBtn.Pressed += () => QuitRequested?.Invoke();
vbox.AddChild(quitBtn);
_statusLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.CyanCol);
_statusLabel.AutowrapMode = TextServer.AutowrapMode.Word;
_statusLabel.Visible = false;
vbox.AddChild(_statusLabel);
vbox.AddChild(ImperialChrome.CreateLabel("Data: swisstopo 3km Sion | CultNet UDP 3076", 10, ImperialChrome.TextMuted));
BuildHostPanel();
}
private void BuildHostPanel()
{
_hostPanel = ImperialChrome.CreatePanel(ImperialChrome.GoldCol, cornerLen: 16f, borderPx: 1.5f, bgAlpha: 0.93f, padH: 18, padV: 16);
_hostPanel.Name = "HostConfigPanel";
_hostPanel.AnchorLeft = 0f;
_hostPanel.AnchorTop = 0f;
_hostPanel.OffsetLeft = 480f;
_hostPanel.OffsetTop = 132f;
_hostPanel.OffsetRight = 900f;
_hostPanel.Visible = false;
_mainRoot.AddChild(_hostPanel);
var vbox = new VBoxContainer();
vbox.AddThemeConstantOverride("separation", 10);
_hostPanel.AddChild(vbox);
vbox.AddChild(ImperialChrome.CreateLabel("HOST PRE-MATCH LOBBY", 14, ImperialChrome.GoldCol));
vbox.AddChild(ImperialChrome.MakeRule());
var nameRow = new HBoxContainer();
nameRow.AddThemeConstantOverride("separation", 8);
vbox.AddChild(nameRow);
var srvLbl = ImperialChrome.CreateLabel("SERVER NAME", 11, ImperialChrome.TextMuted);
srvLbl.CustomMinimumSize = new Vector2(106f, 0f);
nameRow.AddChild(srvLbl);
_serverNameEdit = new LineEdit
{
Text = "Rust to Dust",
MaxLength = 48,
PlaceholderText = "Server Name",
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
ImperialChrome.StyleLineEdit(_serverNameEdit, ImperialChrome.GoldCol, 13);
nameRow.AddChild(_serverNameEdit);
var portRow = new HBoxContainer();
portRow.AddThemeConstantOverride("separation", 8);
vbox.AddChild(portRow);
var portLbl = ImperialChrome.CreateLabel("UDP PORT", 11, ImperialChrome.TextMuted);
portLbl.CustomMinimumSize = new Vector2(106f, 0f);
portRow.AddChild(portLbl);
_portEdit = new LineEdit
{
Text = "3076",
MaxLength = 5,
PlaceholderText = "3076",
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
ImperialChrome.StyleLineEdit(_portEdit, ImperialChrome.GoldCol, 13);
portRow.AddChild(_portEdit);
var mapRow = new HBoxContainer();
mapRow.AddThemeConstantOverride("separation", 8);
vbox.AddChild(mapRow);
var mapLbl = ImperialChrome.CreateLabel("DROP ZONE", 11, ImperialChrome.TextMuted);
mapLbl.CustomMinimumSize = new Vector2(106f, 0f);
mapRow.AddChild(mapLbl);
_hostMapOption = new OptionButton
{
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
_hostMapOption.AddItem("SION (3KM ALPINE)", 0);
_hostMapOption.AddItem("DESERT RING", 1);
_hostMapOption.Select(0);
ImperialChrome.StyleOptionButton(_hostMapOption, ImperialChrome.OliveCol, 13);
mapRow.AddChild(_hostMapOption);
_listPublicCheck = new CheckBox
{
Text = "List on Public Directory",
ButtonPressed = false
};
ImperialChrome.StyleCheckBox(_listPublicCheck, ImperialChrome.CyanCol, 12);
vbox.AddChild(_listPublicCheck);
_directoryHintLabel = ImperialChrome.CreateLabel("Directory: https://eureka.gamecult.org/rtd-directory", 10, ImperialChrome.TextMuted);
_directoryHintLabel.AutowrapMode = TextServer.AutowrapMode.Word;
vbox.AddChild(_directoryHintLabel);
_hostErrorLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.RedCol);
_hostErrorLabel.AutowrapMode = TextServer.AutowrapMode.Word;
_hostErrorLabel.Visible = false;
vbox.AddChild(_hostErrorLabel);
var btnRow = new HBoxContainer();
btnRow.AddThemeConstantOverride("separation", 8);
vbox.AddChild(btnRow);
var launchBtn = ImperialChrome.CreateButton("LAUNCH LOBBY", ImperialChrome.OliveCol, 13, 34f);
launchBtn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
launchBtn.Pressed += OnHostLaunchPressed;
btnRow.AddChild(launchBtn);
var cancelBtn = ImperialChrome.CreateButton("CANCEL", ImperialChrome.BorderCol, 13, 34f);
cancelBtn.Pressed += () => SetHostPanelOpen(false);
btnRow.AddChild(cancelBtn);
}
private void OnHostLaunchPressed()
{
if (!int.TryParse(_portEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int port) ||
port is < 1 or > 65535)
{
SetHostError("UDP port must be between 1 and 65535.");
return;
}
string serverName = string.IsNullOrWhiteSpace(_serverNameEdit.Text)
? "Rust to Dust"
: _serverNameEdit.Text.Trim();
var mapKind = _hostMapOption.Selected == 1 ? ArenaMapKind.Desert : ArenaMapKind.Sion;
bool listPublic = _listPublicCheck.ButtonPressed;
SetHostError(null);
HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign);
}
private void BuildPauseRoot()
{
_pauseRoot = new Control
{
Name = "PauseOverlayRoot",
MouseFilter = Control.MouseFilterEnum.Stop
};
_pauseRoot.SetAnchorsPreset(Control.LayoutPreset.FullRect);
AddChild(_pauseRoot);
var scrim = new ColorRect
{
Color = ImperialChrome.ScrimCol,
MouseFilter = Control.MouseFilterEnum.Stop
};
scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_pauseRoot.AddChild(scrim);
var panel = ImperialChrome.CreatePanel(ImperialChrome.OrangeCol, cornerLen: 16f, borderPx: 2f, bgAlpha: 0.94f, padH: 20, padV: 18);
panel.Name = "PauseOverlayPanel";
panel.AnchorLeft = 0.5f;
panel.AnchorRight = 0.5f;
panel.AnchorTop = 0.5f;
panel.AnchorBottom = 0.5f;
panel.OffsetLeft = -190f;
panel.OffsetRight = 190f;
panel.OffsetTop = -132f;
panel.OffsetBottom = 132f;
_pauseRoot.AddChild(panel);
var vbox = new VBoxContainer();
vbox.AddThemeConstantOverride("separation", 10);
panel.AddChild(vbox);
vbox.AddChild(ImperialChrome.CreateLabel("TACTICAL PAUSE • [ESC]", 16, ImperialChrome.OrangeCol, HorizontalAlignment.Center));
_pauseContextLabel = ImperialChrome.CreateLabel("COMBAT ACTIVE", 11, ImperialChrome.TextMuted, HorizontalAlignment.Center);
vbox.AddChild(_pauseContextLabel);
vbox.AddChild(ImperialChrome.MakeRule());
var resumeBtn = ImperialChrome.CreateButton("RESUME", ImperialChrome.OliveCol, 14, 36f);
resumeBtn.Pressed += () => ResumeRequested?.Invoke();
vbox.AddChild(resumeBtn);
var menuBtn = ImperialChrome.CreateButton("RETURN TO MAIN MENU", ImperialChrome.OrangeCol, 14, 36f);
menuBtn.Pressed += () => ReturnToMainMenuRequested?.Invoke();
vbox.AddChild(menuBtn);
var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f);
quitBtn.Pressed += () => QuitRequested?.Invoke();
vbox.AddChild(quitBtn);
}
private static string SanitizeCallsign(string? raw)
{
string trimmed = (raw ?? string.Empty).Trim();
return string.IsNullOrEmpty(trimmed) ? "Pilot" : trimmed;
}
}

731
client/ServerBrowser.cs Normal file
View file

@ -0,0 +1,731 @@
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;
/// <summary>
/// Public Yggdrasil directory server browser with live non-blocking UDP <c>RTDP</c>
/// ping probes, optional <c>127.0.0.1:3076</c> localhost probe, and direct <c>IP:Port</c> join.
/// </summary>
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 Button? RowButton;
public Label? NameLabel;
public Label? MapLabel;
public Label? PlayersLabel;
public Label? PhaseLabel;
public Label? PingLabel;
public Label? AddressLabel;
}
private readonly ConcurrentQueue<Action> _mainThreadQueue = new();
private readonly List<ServerRowModel> _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<string, string>? 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<DirectoryServerInfo> 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) 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) 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()
{
_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 btn = _rows[i].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.RowButton is null) 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;
}
}