diff --git a/RustToDust.slnx b/RustToDust.slnx index 28d4f8b..cf1fca2 100644 --- a/RustToDust.slnx +++ b/RustToDust.slnx @@ -4,6 +4,7 @@ + diff --git a/client/Hud.cs b/client/Hud.cs index 6c2c789..40d4312 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -180,8 +180,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); diff --git a/client/ImperialChrome.cs b/client/ImperialChrome.cs new file mode 100644 index 0000000..39896a0 --- /dev/null +++ b/client/ImperialChrome.cs @@ -0,0 +1,213 @@ +using Godot; + +namespace RustToDust.Client; + +/// +/// Shared Industrial Imperial palette and beveled panel_chrome.gdshader panel/control +/// helpers for pre-match UI layers (, , +/// ). Kept separate from so Hud.GetChromeMaterials() +/// preserves its exact 6-panel contract. +/// +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("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); + } +} diff --git a/client/LobbyScreen.cs b/client/LobbyScreen.cs new file mode 100644 index 0000000..7a64842 --- /dev/null +++ b/client/LobbyScreen.cs @@ -0,0 +1,474 @@ +using System; +using System.Globalization; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Authoritative pre-match orbital lobby overlay (). +/// Displays the 12 contender slots, ready states, host-only map/seed controls, +/// live 5-second orbital insertion countdown banner, and launch/leave actions. +/// +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); + } +} diff --git a/client/Main.cs b/client/Main.cs index 2beeea3..9d76e57 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -11,6 +11,15 @@ using RustToDust.Ymir; namespace RustToDust.Client; +public enum ClientScreenMode +{ + MainMenu, + ServerBrowser, + Lobby, + InMatch, + PauseOverlay +} + /// /// Root Godot node for Rust to Dust. /// Godot physics is Dummy; drives Solo (), @@ -28,9 +37,28 @@ public partial class Main : Node3D private Camera3D _camera = null!; private Hud _hud = null!; private AtmosphereSystem _atmosphere = null!; + private MainMenu _mainMenu = null!; + private ServerBrowser _serverBrowser = null!; + private LobbyScreen _lobbyScreen = 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 _frameEvents = new(128); @@ -80,6 +108,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; @@ -89,9 +119,13 @@ public partial class Main : Node3D public Camera3D Camera => _camera; public Hud Hud => _hud; public AtmosphereSystem Atmosphere => _atmosphere; + 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; @@ -135,6 +169,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, @@ -158,6 +226,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)) { @@ -204,6 +291,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) { @@ -215,20 +304,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) @@ -303,9 +416,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) @@ -316,16 +427,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) @@ -335,46 +444,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; + _atmosphere.ApplyMap(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 { @@ -382,29 +664,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); @@ -414,12 +779,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) @@ -464,13 +836,22 @@ public partial class Main : Node3D _camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f; _atmosphere.ApplyMap(_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 @@ -479,18 +860,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(); } @@ -500,6 +894,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; } @@ -616,18 +1015,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(); @@ -647,11 +1065,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; } @@ -677,8 +1093,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) { @@ -708,7 +1141,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) @@ -730,13 +1171,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); @@ -762,6 +1233,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) @@ -858,6 +1350,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) diff --git a/client/MainMenu.cs b/client/MainMenu.cs new file mode 100644 index 0000000..15c8da9 --- /dev/null +++ b/client/MainMenu.cs @@ -0,0 +1,425 @@ +using System; +using System.Globalization; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Industrial Imperial main menu overlay over the live Sion 3D orbit backdrop, +/// plus the in-match [ESC] pause overlay. +/// +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? PlaySoloRequested; + public event Action? ServerBrowserRequested; + public event Action? HostLobbyRequested; + public event Action? 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; + } +} diff --git a/client/ServerBrowser.cs b/client/ServerBrowser.cs new file mode 100644 index 0000000..eda6536 --- /dev/null +++ b/client/ServerBrowser.cs @@ -0,0 +1,738 @@ +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; + } +} diff --git a/src/RustToDust.Core/IClientArenaSession.cs b/src/RustToDust.Core/IClientArenaSession.cs index 0ad5b7e..95942dd 100644 --- a/src/RustToDust.Core/IClientArenaSession.cs +++ b/src/RustToDust.Core/IClientArenaSession.cs @@ -47,6 +47,7 @@ namespace RustToDust.Core IReadOnlyList ActivePods { get; } DropWaveState DropWaveState { get; } IReadOnlyList PodEvents { get; } + LobbySnapshotDto? LobbyState => null; bool IsContenderVisible(int contenderId); bool IsSpectatorVisible(int spectatorId); @@ -56,6 +57,9 @@ namespace RustToDust.Core void DrainSimEvents(List dest); bool RequestEquipCargo(int cargoIndex, string hardpointId); void RequestNewMatch(int seed, ArenaMapKind mapKind); + bool SetLobbyReady(bool ready) => false; + bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false; + bool RequestLobbyStart() => false; (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha); (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha); diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs index 28bd77a..911e974 100644 --- a/src/RustToDust.Core/MatchState.cs +++ b/src/RustToDust.Core/MatchState.cs @@ -6,8 +6,47 @@ namespace RustToDust.Core { public enum MatchPhase { - Active, - Completed + Active = 0, + Completed = 1, + Lobby = 2 + } + + public sealed class LobbySlotState + { + public int SlotId { get; init; } + public string Callsign { get; set; } = string.Empty; + public bool IsHuman { get; set; } + public bool IsReady { get; set; } + } + + public sealed class LobbyState + { + public const float DefaultCountdownSeconds = 5.0f; + + public LobbyState(int contenderCount, ArenaMapKind mapKind, int seed, int? hostSlotId = null, int minHumansToAutoStart = 1) + { + SelectedMap = mapKind; + SelectedSeed = seed; + HostSlotId = hostSlotId; + MinHumansToAutoStart = Math.Max(1, minHumansToAutoStart); + Slots = new LobbySlotState[contenderCount]; + for (int i = 0; i < contenderCount; i++) + { + Slots[i] = new LobbySlotState + { + SlotId = i, + Callsign = $"Contender {i + 1:00}" + }; + } + } + + public int? HostSlotId { get; set; } + public int MinHumansToAutoStart { get; set; } = 1; + public float? CountdownSeconds { get; set; } + public bool ForceLaunched { get; set; } + public ArenaMapKind SelectedMap { get; set; } + public int SelectedSeed { get; set; } + public LobbySlotState[] Slots { get; } } public readonly record struct PlayerInput( @@ -293,11 +332,15 @@ namespace RustToDust.Core private int _nextDropId = 1; private long _nextHitEventId = 1; private int _nextTracerId = 1; + private readonly bool _pendingSkipInitialDrop; + private readonly List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> _pendingLootTargets; + private readonly List<(int ContenderId, float X, float Z, float Yaw)> _pendingContenderTargets; - public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false) + public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false, bool startInLobby = false) { Seed = seed; MapKind = mapKind; + _pendingSkipInitialDrop = skipInitialDrop; Rng = new Random(seed); Broadcast = new BroadcastFeed(); OrbitalDrop = new OrbitalDropSystem(this); @@ -339,7 +382,24 @@ namespace RustToDust.Core lootTargets = BuildInitialLootTargetsDesert(); } - if (skipInitialDrop) + _pendingLootTargets = lootTargets; + _pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count); + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + _pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); + } + + if (startInLobby) + { + Phase = MatchPhase.Lobby; + Lobby = new LobbyState(ContenderCount, mapKind, seed); + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].Lifecycle = ContenderLifecycle.Deploying; + } + } + else if (skipInitialDrop) { for (int i = 0; i < Contenders.Count; i++) { @@ -351,19 +411,51 @@ namespace RustToDust.Core if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis); else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module); } + Broadcast.EmitMatchStart(0f, mapKind); } else { - var contenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count); - for (int i = 0; i < Contenders.Count; i++) - { - var c = Contenders[i]; - contenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); - } - OrbitalDrop.BeginWave0(contenderTargets, lootTargets, DefaultDropSurfaceQuery); + OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, DefaultDropSurfaceQuery); + Broadcast.EmitMatchStart(0f, mapKind); + } + } + + public bool StartFromLobby(DropSurfaceQuery? surfaceQuery = null) + { + if (Phase != MatchPhase.Lobby) + { + return false; } - Broadcast.EmitMatchStart(0f, mapKind); + Phase = MatchPhase.Active; + Time = 0f; + WinnerContenderId = null; + if (Lobby is not null) + { + Lobby.CountdownSeconds = null; + Lobby.ForceLaunched = false; + } + + if (_pendingSkipInitialDrop) + { + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].Lifecycle = ContenderLifecycle.Active; + } + for (int i = 0; i < _pendingLootTargets.Count; i++) + { + var t = _pendingLootTargets[i]; + if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis); + else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module); + } + } + else + { + OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, surfaceQuery ?? DefaultDropSurfaceQuery); + } + + Broadcast.EmitMatchStart(0f, MapKind); + return true; } public int Seed { get; } @@ -372,6 +464,7 @@ namespace RustToDust.Core public Random Rng { get; } public float Time { get; set; } public MatchPhase Phase { get; set; } = MatchPhase.Active; + public LobbyState? Lobby { get; set; } public int? WinnerContenderId { get; set; } public TerrainField Terrain { get; } diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs index 9e70a6c..84211fb 100644 --- a/src/RustToDust.Core/SimEvents.cs +++ b/src/RustToDust.Core/SimEvents.cs @@ -33,6 +33,7 @@ namespace RustToDust.Core [Union(11, typeof(MatchResetEvent))] [Union(12, typeof(DropPodEvent))] [Union(13, typeof(OrdnanceNodeEvent))] + [Union(14, typeof(MatchStartedEvent))] public interface ISimEvent { } @@ -318,6 +319,36 @@ namespace RustToDust.Core [Key(12)] public int CurrentWaveIndex { get; set; } [Key(13)] public bool RespawnCutoffReached { get; set; } [Key(14)] public List ActivePods { get; set; } = new(); + [Key(15)] public LobbySnapshotDto? Lobby { get; set; } + } + + [MessagePackObject] + public sealed class LobbySlotDto + { + [Key(0)] public int SlotId { get; set; } + [Key(1)] public string Callsign { get; set; } = string.Empty; + [Key(2)] public bool IsHuman { get; set; } + [Key(3)] public bool IsReady { get; set; } + } + + [MessagePackObject] + public sealed class LobbySnapshotDto + { + [Key(0)] public int? HostSlotId { get; set; } + [Key(1)] public int MinHumansToAutoStart { get; set; } = 1; + [Key(2)] public float? CountdownSeconds { get; set; } + [Key(3)] public bool ForceLaunched { get; set; } + [Key(4)] public byte SelectedMap { get; set; } + [Key(5)] public int SelectedSeed { get; set; } + [Key(6)] public List Slots { get; set; } = new(); + } + + [MessagePackObject] + public sealed class MatchStartedEvent : ISimEvent + { + [Key(0)] public uint MatchGeneration { get; set; } + [Key(1)] public byte MapKind { get; set; } + [Key(2)] public int Seed { get; set; } } [MessagePackObject] @@ -339,6 +370,11 @@ namespace RustToDust.Core [Union(6, typeof(SimEventBatchMsg))] [Union(7, typeof(EntitySyncSnapshotMsg))] [Union(8, typeof(InteractCmdMsg))] + [Union(9, typeof(LobbyReadyCmdMsg))] + [Union(10, typeof(LobbyConfigCmdMsg))] + [Union(11, typeof(LobbyStartCmdMsg))] + [Union(12, typeof(LobbySnapshotMsg))] + [Union(13, typeof(ClientKeepaliveMsg))] public interface ISchemaWireMessage { } @@ -420,4 +456,38 @@ namespace RustToDust.Core [Key(9)] public byte[] ArmorBytes { get; set; } = Array.Empty(); [Key(10)] public ContenderLoadoutEvent? ContenderLoadout { get; set; } } + + [MessagePackObject] + public sealed class LobbyReadyCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public bool IsReady { get; set; } + } + + [MessagePackObject] + public sealed class LobbyConfigCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public int Seed { get; set; } + [Key(2)] public byte MapKind { get; set; } + } + + [MessagePackObject] + public sealed class LobbyStartCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + } + + [MessagePackObject] + public sealed class LobbySnapshotMsg : ISchemaWireMessage + { + [Key(0)] public uint MatchGeneration { get; set; } + [Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new(); + } + + [MessagePackObject] + public sealed class ClientKeepaliveMsg : ISchemaWireMessage + { + [Key(0)] public uint ClientSendMs { get; set; } + } } diff --git a/src/RustToDust.Directory/DirectoryDtos.cs b/src/RustToDust.Directory/DirectoryDtos.cs new file mode 100644 index 0000000..1b7268c --- /dev/null +++ b/src/RustToDust.Directory/DirectoryDtos.cs @@ -0,0 +1,45 @@ +using System; + +namespace RustToDust.DirectoryService +{ + public sealed class DirectoryHeartbeatRequest + { + public Guid? ServerId { get; set; } + public string? LeaseToken { get; set; } + public string Name { get; set; } = "Rust to Dust"; + public string? PublicHost { get; set; } + public int UdpPort { get; set; } + public string Map { get; set; } = "desert"; + public int Seed { get; set; } = 42; + public int Humans { get; set; } + public int MaxHumans { get; set; } = 12; + public string Phase { get; set; } = "Active"; + public int Wave { get; set; } + public int ProtocolVersion { get; set; } = 1; + public bool HasPassword { get; set; } + } + + public sealed class DirectoryHeartbeatResponse + { + public Guid ServerId { get; set; } + public string LeaseToken { get; set; } = string.Empty; + public int TtlSeconds { get; set; } + } + + public sealed class DirectoryServerView + { + public Guid ServerId { get; set; } + public string Name { get; set; } = string.Empty; + public string PublicHost { get; set; } = string.Empty; + public int UdpPort { get; set; } + public string Map { get; set; } = string.Empty; + public int Seed { get; set; } + public int Humans { get; set; } + public int MaxHumans { get; set; } + public string Phase { get; set; } = string.Empty; + public int Wave { get; set; } + public int ProtocolVersion { get; set; } + public bool HasPassword { get; set; } + public DateTimeOffset ExpiresAtUtc { get; set; } + } +} diff --git a/src/RustToDust.Directory/DirectoryRegistry.cs b/src/RustToDust.Directory/DirectoryRegistry.cs new file mode 100644 index 0000000..cfa1198 --- /dev/null +++ b/src/RustToDust.Directory/DirectoryRegistry.cs @@ -0,0 +1,421 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Security.Cryptography; +using System.Text; + +namespace RustToDust.DirectoryService +{ + public sealed class DirectoryRegistryOptions + { + public TimeSpan EntryTtl { get; set; } = TimeSpan.FromSeconds(25); + public TimeSpan ReaperInterval { get; set; } = TimeSpan.FromSeconds(5); + public int MaxEntries { get; set; } = 256; + public int MaxEntriesPerIp { get; set; } = 8; + public int HeartbeatLimitPerMinute { get; set; } = 120; + public int ListLimitPerMinute { get; set; } = 60; + public Func UtcNow { get; set; } = () => DateTimeOffset.UtcNow; + } + + public enum DirectoryOpStatus + { + Ok = 200, + NoContent = 204, + BadRequest = 400, + Forbidden = 403, + NotFound = 404, + Conflict = 409, + TooManyRequests = 429, + ServiceUnavailable = 503 + } + + public readonly record struct DirectoryOpResult(DirectoryOpStatus Status, T? Value, string? Error = null); + + public sealed class DirectoryRegistry + { + private sealed class RegistryEntry + { + public Guid ServerId; + public string LeaseToken = string.Empty; + public byte[] LeaseTokenBytes = Array.Empty(); + public string OwnerIp = string.Empty; + public string Name = string.Empty; + public string PublicHost = string.Empty; + public int UdpPort; + public string Map = string.Empty; + public int Seed; + public int Humans; + public int MaxHumans; + public string Phase = string.Empty; + public int Wave; + public int ProtocolVersion; + public bool HasPassword; + public DateTimeOffset ExpiresAtUtc; + } + + private sealed class RateWindow + { + public long MinuteBucket; + public int Count; + } + + private readonly object _gate = new(); + private readonly Dictionary _entries = new(); + private readonly Dictionary _heartbeatRates = new(StringComparer.Ordinal); + private readonly Dictionary _listRates = new(StringComparer.Ordinal); + private readonly DirectoryRegistryOptions _options; + + public DirectoryRegistry(DirectoryRegistryOptions? options = null) + { + _options = options ?? new DirectoryRegistryOptions(); + } + + public int Count + { + get + { + lock (_gate) + { + PurgeExpiredLocked(_options.UtcNow()); + return _entries.Count; + } + } + } + + public DirectoryOpResult UpsertHeartbeat(DirectoryHeartbeatRequest req, IPAddress callerIp) + { + if (req is null) + { + return new(DirectoryOpStatus.BadRequest, null, "Request body required."); + } + + IPAddress normalizedCaller = NormalizeIp(callerIp); + string callerKey = normalizedCaller.ToString(); + DateTimeOffset now = _options.UtcNow(); + + lock (_gate) + { + PurgeExpiredLocked(now); + + if (!AllowRateLocked(_heartbeatRates, callerKey, now, _options.HeartbeatLimitPerMinute)) + { + return new(DirectoryOpStatus.TooManyRequests, null, "Heartbeat rate limit exceeded."); + } + + if (req.UdpPort < 1 || req.UdpPort > 65535) + { + return new(DirectoryOpStatus.BadRequest, null, "udpPort must be in 1..65535."); + } + + string resolvedHost; + if (string.IsNullOrWhiteSpace(req.PublicHost) || + string.Equals(req.PublicHost.Trim(), "auto", StringComparison.OrdinalIgnoreCase)) + { + resolvedHost = callerKey; + } + else + { + resolvedHost = req.PublicHost.Trim(); + if (resolvedHost.Length > 253 || ContainsWhitespaceOrControl(resolvedHost)) + { + return new(DirectoryOpStatus.BadRequest, null, "Invalid publicHost."); + } + + if (!IPAddress.IsLoopback(normalizedCaller) && IsLoopbackOrWildcardHost(resolvedHost)) + { + return new(DirectoryOpStatus.BadRequest, null, "Non-loopback callers cannot advertise a loopback or wildcard publicHost."); + } + } + + string cleanName = SanitizeLabel(req.Name, "Rust to Dust", 48); + string cleanMap = SanitizeLabel(req.Map, "desert", 24).ToLowerInvariant(); + string cleanPhase = SanitizeLabel(req.Phase, "Active", 16); + int maxHumans = Math.Clamp(req.MaxHumans, 1, 12); + int humans = Math.Clamp(req.Humans, 0, maxHumans); + int wave = Math.Max(0, req.Wave); + int protocolVersion = Math.Max(1, req.ProtocolVersion); + + if (req.ServerId is { } serverId && serverId != Guid.Empty) + { + if (!_entries.TryGetValue(serverId, out var existing)) + { + return new(DirectoryOpStatus.Conflict, null, "Unknown or expired serverId."); + } + + if (!VerifyLeaseToken(existing, req.LeaseToken)) + { + return new(DirectoryOpStatus.Forbidden, null, "Invalid leaseToken."); + } + + existing.Name = cleanName; + existing.PublicHost = resolvedHost; + existing.UdpPort = req.UdpPort; + existing.Map = cleanMap; + existing.Seed = req.Seed; + existing.Humans = humans; + existing.MaxHumans = maxHumans; + existing.Phase = cleanPhase; + existing.Wave = wave; + existing.ProtocolVersion = protocolVersion; + existing.HasPassword = req.HasPassword; + existing.ExpiresAtUtc = now + _options.EntryTtl; + + return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse + { + ServerId = existing.ServerId, + LeaseToken = existing.LeaseToken, + TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds)) + }); + } + + if (_entries.Count >= _options.MaxEntries) + { + return new(DirectoryOpStatus.ServiceUnavailable, null, "Directory capacity reached."); + } + + int ipCount = 0; + foreach (var entry in _entries.Values) + { + if (string.Equals(entry.OwnerIp, callerKey, StringComparison.Ordinal)) + { + ipCount++; + } + } + if (ipCount >= _options.MaxEntriesPerIp) + { + return new(DirectoryOpStatus.TooManyRequests, null, "Per-IP server registration limit reached."); + } + + Guid newId = Guid.NewGuid(); + string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(24)).ToLowerInvariant(); + var created = new RegistryEntry + { + ServerId = newId, + LeaseToken = token, + LeaseTokenBytes = Encoding.UTF8.GetBytes(token), + OwnerIp = callerKey, + Name = cleanName, + PublicHost = resolvedHost, + UdpPort = req.UdpPort, + Map = cleanMap, + Seed = req.Seed, + Humans = humans, + MaxHumans = maxHumans, + Phase = cleanPhase, + Wave = wave, + ProtocolVersion = protocolVersion, + HasPassword = req.HasPassword, + ExpiresAtUtc = now + _options.EntryTtl + }; + _entries[newId] = created; + + return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse + { + ServerId = created.ServerId, + LeaseToken = created.LeaseToken, + TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds)) + }); + } + } + + public DirectoryOpResult DeleteServer(Guid serverId, string? leaseToken) + { + if (serverId == Guid.Empty) + { + return new(DirectoryOpStatus.BadRequest, null, "Invalid serverId."); + } + + DateTimeOffset now = _options.UtcNow(); + lock (_gate) + { + PurgeExpiredLocked(now); + + if (!_entries.TryGetValue(serverId, out var existing)) + { + return new(DirectoryOpStatus.NotFound, null, "Server not found."); + } + + if (!VerifyLeaseToken(existing, leaseToken)) + { + return new(DirectoryOpStatus.Forbidden, null, "Invalid leaseToken."); + } + + _entries.Remove(serverId); + return new(DirectoryOpStatus.NoContent, null); + } + } + + public DirectoryOpResult> ListServers(IPAddress callerIp) + { + string callerKey = NormalizeIp(callerIp).ToString(); + DateTimeOffset now = _options.UtcNow(); + + lock (_gate) + { + PurgeExpiredLocked(now); + + if (!AllowRateLocked(_listRates, callerKey, now, _options.ListLimitPerMinute)) + { + return new(DirectoryOpStatus.TooManyRequests, null, "List rate limit exceeded."); + } + + var list = new List(_entries.Count); + foreach (var entry in _entries.Values) + { + list.Add(new DirectoryServerView + { + ServerId = entry.ServerId, + Name = entry.Name, + PublicHost = entry.PublicHost, + UdpPort = entry.UdpPort, + Map = entry.Map, + Seed = entry.Seed, + Humans = entry.Humans, + MaxHumans = entry.MaxHumans, + Phase = entry.Phase, + Wave = entry.Wave, + ProtocolVersion = entry.ProtocolVersion, + HasPassword = entry.HasPassword, + ExpiresAtUtc = entry.ExpiresAtUtc + }); + } + + list.Sort((a, b) => + { + int cmp = b.Humans.CompareTo(a.Humans); + return cmp != 0 ? cmp : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + + return new(DirectoryOpStatus.Ok, list); + } + } + + public int SweepExpired() + { + DateTimeOffset now = _options.UtcNow(); + lock (_gate) + { + return PurgeExpiredLocked(now); + } + } + + private int PurgeExpiredLocked(DateTimeOffset now) + { + List? expired = null; + foreach (var kv in _entries) + { + if (kv.Value.ExpiresAtUtc <= now) + { + expired ??= new List(); + expired.Add(kv.Key); + } + } + if (expired is not null) + { + for (int i = 0; i < expired.Count; i++) + { + _entries.Remove(expired[i]); + } + } + + long currentBucket = now.ToUnixTimeSeconds() / 60; + PruneRateBucketsLocked(_heartbeatRates, currentBucket); + PruneRateBucketsLocked(_listRates, currentBucket); + + return expired?.Count ?? 0; + } + + private static void PruneRateBucketsLocked(Dictionary buckets, long currentBucket) + { + if (buckets.Count == 0) return; + List? stale = null; + foreach (var kv in buckets) + { + if (kv.Value.MinuteBucket < currentBucket) + { + stale ??= new List(); + stale.Add(kv.Key); + } + } + if (stale is not null) + { + for (int i = 0; i < stale.Count; i++) + { + buckets.Remove(stale[i]); + } + } + } + + private static bool AllowRateLocked(Dictionary buckets, string key, DateTimeOffset now, int limit) + { + if (limit <= 0) return true; + long bucket = now.ToUnixTimeSeconds() / 60; + if (!buckets.TryGetValue(key, out var win) || win.MinuteBucket != bucket) + { + win = new RateWindow { MinuteBucket = bucket, Count = 0 }; + buckets[key] = win; + } + win.Count++; + return win.Count <= limit; + } + + private static bool VerifyLeaseToken(RegistryEntry entry, string? suppliedToken) + { + if (string.IsNullOrEmpty(suppliedToken)) return false; + byte[] suppliedBytes = Encoding.UTF8.GetBytes(suppliedToken); + return suppliedBytes.Length == entry.LeaseTokenBytes.Length && + CryptographicOperations.FixedTimeEquals(entry.LeaseTokenBytes, suppliedBytes); + } + + private static IPAddress NormalizeIp(IPAddress ip) => + ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip; + + private static bool IsLoopbackOrWildcardHost(string host) + { + if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) || + host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (IPAddress.TryParse(host, out var ip)) + { + ip = NormalizeIp(ip); + return IPAddress.IsLoopback(ip) || + ip.Equals(IPAddress.Any) || + ip.Equals(IPAddress.IPv6Any); + } + + return false; + } + + private static bool ContainsWhitespaceOrControl(string value) + { + for (int i = 0; i < value.Length; i++) + { + char ch = value[i]; + if (char.IsWhiteSpace(ch) || char.IsControl(ch)) + { + return true; + } + } + return false; + } + + private static string SanitizeLabel(string? raw, string fallback, int maxLen) + { + if (string.IsNullOrWhiteSpace(raw)) return fallback; + var sb = new StringBuilder(Math.Min(raw.Length, maxLen)); + string trimmed = raw.Trim(); + for (int i = 0; i < trimmed.Length && sb.Length < maxLen; i++) + { + char ch = trimmed[i]; + if (!char.IsControl(ch)) + { + sb.Append(ch); + } + } + return sb.Length == 0 ? fallback : sb.ToString(); + } + } +} diff --git a/src/RustToDust.Directory/Program.cs b/src/RustToDust.Directory/Program.cs new file mode 100644 index 0000000..08cd4d9 --- /dev/null +++ b/src/RustToDust.Directory/Program.cs @@ -0,0 +1,164 @@ +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace RustToDust.DirectoryService +{ + public static class DirectoryApp + { + public static WebApplication Build(string[] args, DirectoryRegistryOptions? options = null) + { + var builder = WebApplication.CreateBuilder(args); + var resolvedOptions = options ?? new DirectoryRegistryOptions(); + var registry = new DirectoryRegistry(resolvedOptions); + + builder.Services.AddSingleton(resolvedOptions); + builder.Services.AddSingleton(registry); + builder.Services.AddHostedService(); + builder.Services.Configure(opts => + { + opts.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + opts.KnownNetworks.Clear(); + opts.KnownProxies.Clear(); + opts.KnownProxies.Add(IPAddress.Loopback); + opts.KnownProxies.Add(IPAddress.IPv6Loopback); + }); + + var app = builder.Build(); + app.UseForwardedHeaders(); + + app.MapGet("/healthz", (DirectoryRegistry reg) => + Results.Ok(new { status = "ok", activeServers = reg.Count })); + + app.MapGet("/api/v1/servers", (HttpContext ctx, DirectoryRegistry reg) => + { + IPAddress callerIp = ResolveCallerIp(ctx); + var result = reg.ListServers(callerIp); + return result.Status switch + { + DirectoryOpStatus.Ok => Results.Ok(result.Value), + DirectoryOpStatus.TooManyRequests => Results.StatusCode(StatusCodes.Status429TooManyRequests), + _ => Results.BadRequest(new { error = result.Error }) + }; + }); + + app.MapPost("/api/v1/servers/heartbeat", (HttpContext ctx, DirectoryHeartbeatRequest req, DirectoryRegistry reg) => + { + IPAddress callerIp = ResolveCallerIp(ctx); + var result = reg.UpsertHeartbeat(req, callerIp); + return result.Status switch + { + DirectoryOpStatus.Ok => Results.Ok(result.Value), + DirectoryOpStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden), + DirectoryOpStatus.Conflict => Results.Conflict(new { error = result.Error }), + DirectoryOpStatus.TooManyRequests => Results.StatusCode(StatusCodes.Status429TooManyRequests), + DirectoryOpStatus.ServiceUnavailable => Results.StatusCode(StatusCodes.Status503ServiceUnavailable), + _ => Results.BadRequest(new { error = result.Error }) + }; + }); + + app.MapDelete("/api/v1/servers/{serverId:guid}", (HttpContext ctx, Guid serverId, DirectoryRegistry reg) => + { + string? token = ExtractLeaseToken(ctx); + var result = reg.DeleteServer(serverId, token); + return result.Status switch + { + DirectoryOpStatus.NoContent => Results.NoContent(), + DirectoryOpStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden), + DirectoryOpStatus.NotFound => Results.NotFound(new { error = result.Error }), + _ => Results.BadRequest(new { error = result.Error }) + }; + }); + + return app; + } + + private static IPAddress ResolveCallerIp(HttpContext ctx) + { + IPAddress remote = ctx.Connection.RemoteIpAddress ?? IPAddress.Loopback; + if (remote.IsIPv4MappedToIPv6) remote = remote.MapToIPv4(); + + // Only trust X-Real-IP when the immediate TCP peer is loopback (e.g. local nginx). + if (IPAddress.IsLoopback(remote) && + ctx.Request.Headers.TryGetValue("X-Real-IP", out var realIpValues)) + { + string raw = realIpValues.ToString().Trim(); + if (IPAddress.TryParse(raw, out var parsed)) + { + return parsed.IsIPv4MappedToIPv6 ? parsed.MapToIPv4() : parsed; + } + } + + return remote; + } + + private static string? ExtractLeaseToken(HttpContext ctx) + { + if (ctx.Request.Headers.TryGetValue("X-Lease-Token", out var headerVal)) + { + string t = headerVal.ToString().Trim(); + if (!string.IsNullOrEmpty(t)) return t; + } + if (ctx.Request.Headers.TryGetValue("Authorization", out var authVal)) + { + string auth = authVal.ToString().Trim(); + if (auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + string t = auth.Substring("Bearer ".Length).Trim(); + if (!string.IsNullOrEmpty(t)) return t; + } + } + if (ctx.Request.Query.TryGetValue("leaseToken", out var queryVal)) + { + string t = queryVal.ToString().Trim(); + if (!string.IsNullOrEmpty(t)) return t; + } + return null; + } + } + + internal sealed class DirectoryReaperService : BackgroundService + { + private readonly DirectoryRegistry _registry; + private readonly DirectoryRegistryOptions _options; + + public DirectoryReaperService(DirectoryRegistry registry, DirectoryRegistryOptions options) + { + _registry = registry; + _options = options; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + TimeSpan interval = _options.ReaperInterval > TimeSpan.Zero + ? _options.ReaperInterval + : TimeSpan.FromSeconds(5); + using var timer = new PeriodicTimer(interval); + try + { + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + _registry.SweepExpired(); + } + } + catch (OperationCanceledException) + { + } + } + } + + public static class Program + { + public static void Main(string[] args) + { + var app = DirectoryApp.Build(args); + app.Run(); + } + } +} diff --git a/src/RustToDust.Directory/RustToDust.Directory.csproj b/src/RustToDust.Directory/RustToDust.Directory.csproj new file mode 100644 index 0000000..8e854bb --- /dev/null +++ b/src/RustToDust.Directory/RustToDust.Directory.csproj @@ -0,0 +1,10 @@ + + + + net8.0 + LatestMajor + enable + disable + + + diff --git a/src/RustToDust.Net/DirectoryClient.cs b/src/RustToDust.Net/DirectoryClient.cs new file mode 100644 index 0000000..0f44032 --- /dev/null +++ b/src/RustToDust.Net/DirectoryClient.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace RustToDust.Net +{ + public sealed record DirectoryServerInfo( + Guid ServerId, + string Name, + string PublicHost, + int UdpPort, + string Map, + int Seed, + int Humans, + int MaxHumans, + string Phase, + int Wave, + int ProtocolVersion, + bool HasPassword, + DateTimeOffset ExpiresAtUtc); + + public readonly record struct DirectoryHeartbeatSnapshot( + string Name, + string PublicHost, + int UdpPort, + string Map, + int Seed, + int Humans, + int MaxHumans, + string Phase, + int Wave, + int ProtocolVersion = 1, + bool HasPassword = false); + + public static class DirectoryBrowserClient + { + private static readonly HttpClient SharedHttp = new() + { + Timeout = TimeSpan.FromSeconds(5) + }; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + public static string NormalizeBaseUrl(string directoryBaseUrl) + { + string trimmed = (directoryBaseUrl ?? string.Empty).Trim(); + while (trimmed.EndsWith('/')) + { + trimmed = trimmed.Substring(0, trimmed.Length - 1); + } + return trimmed; + } + + public static async Task> FetchServersAsync( + string directoryBaseUrl, + CancellationToken ct = default, + HttpClient? httpClient = null) + { + string baseUrl = NormalizeBaseUrl(directoryBaseUrl); + if (string.IsNullOrEmpty(baseUrl)) + { + return Array.Empty(); + } + + HttpClient client = httpClient ?? SharedHttp; + using var req = new HttpRequestMessage(HttpMethod.Get, $"{baseUrl}/api/v1/servers"); + using var resp = await client.SendAsync(req, ct).ConfigureAwait(false); + resp.EnsureSuccessStatusCode(); + var list = await resp.Content.ReadFromJsonAsync>(JsonOptions, ct).ConfigureAwait(false); + return list ?? (IReadOnlyList)Array.Empty(); + } + } + + public sealed class DirectoryReporter : IDisposable, IAsyncDisposable + { + private sealed record HeartbeatBody( + Guid? ServerId, + string? LeaseToken, + string Name, + string? PublicHost, + int UdpPort, + string Map, + int Seed, + int Humans, + int MaxHumans, + string Phase, + int Wave, + int ProtocolVersion, + bool HasPassword); + + private sealed class HeartbeatAck + { + public Guid ServerId { get; set; } + public string LeaseToken { get; set; } = string.Empty; + public int TtlSeconds { get; set; } + } + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly string _baseUrl; + private readonly Func _snapshotProvider; + private readonly TimeSpan _heartbeatInterval; + private readonly HttpClient _http; + private readonly bool _ownsHttp; + private readonly CancellationTokenSource _cts = new(); + private readonly SemaphoreSlim _wakeSignal = new(0, 1); + private readonly object _leaseGate = new(); + private readonly Task _loopTask; + + private Guid? _serverId; + private string? _leaseToken; + private int _disposed; + + public DirectoryReporter( + string directoryBaseUrl, + Func snapshotProvider, + TimeSpan? heartbeatInterval = null, + HttpClient? httpClient = null) + { + _baseUrl = DirectoryBrowserClient.NormalizeBaseUrl(directoryBaseUrl); + if (string.IsNullOrEmpty(_baseUrl)) + { + throw new ArgumentException("Directory base URL cannot be empty.", nameof(directoryBaseUrl)); + } + _snapshotProvider = snapshotProvider ?? throw new ArgumentNullException(nameof(snapshotProvider)); + _heartbeatInterval = heartbeatInterval ?? TimeSpan.FromSeconds(10); + if (httpClient is not null) + { + _http = httpClient; + _ownsHttp = false; + } + else + { + _http = new HttpClient { Timeout = TimeSpan.FromSeconds(6) }; + _ownsHttp = true; + } + + _loopTask = Task.Run(RunLoopAsync); + } + + public Guid? CurrentServerId + { + get + { + lock (_leaseGate) + { + return _serverId; + } + } + } + + public string? LastError { get; private set; } + + public void NotifyChanged() + { + if (Volatile.Read(ref _disposed) != 0) return; + try + { + if (_wakeSignal.CurrentCount == 0) + { + _wakeSignal.Release(); + } + } + catch (ObjectDisposedException) + { + } + catch (SemaphoreFullException) + { + } + } + + private async Task RunLoopAsync() + { + while (!_cts.IsCancellationRequested) + { + await SendHeartbeatOnceAsync(_cts.Token).ConfigureAwait(false); + + try + { + bool woken = await _wakeSignal.WaitAsync(_heartbeatInterval, _cts.Token).ConfigureAwait(false); + if (woken && !_cts.IsCancellationRequested) + { + await Task.Delay(250, _cts.Token).ConfigureAwait(false); + while (_wakeSignal.CurrentCount > 0) + { + _wakeSignal.Wait(0); + } + } + } + catch (OperationCanceledException) + { + break; + } + } + } + + private async Task SendHeartbeatOnceAsync(CancellationToken ct) + { + try + { + var snap = _snapshotProvider(); + Guid? curServerId; + string? curLeaseToken; + lock (_leaseGate) + { + curServerId = _serverId; + curLeaseToken = _leaseToken; + } + + var body = new HeartbeatBody( + curServerId, + curLeaseToken, + snap.Name, + snap.PublicHost, + snap.UdpPort, + snap.Map, + snap.Seed, + snap.Humans, + snap.MaxHumans, + snap.Phase, + snap.Wave, + snap.ProtocolVersion, + snap.HasPassword); + + using var resp = await _http.PostAsJsonAsync($"{_baseUrl}/api/v1/servers/heartbeat", body, ct).ConfigureAwait(false); + if (resp.StatusCode == HttpStatusCode.Conflict || resp.StatusCode == HttpStatusCode.NotFound) + { + lock (_leaseGate) + { + _serverId = null; + _leaseToken = null; + } + LastError = $"Directory returned {(int)resp.StatusCode}; resetting lease."; + return; + } + + if (!resp.IsSuccessStatusCode) + { + LastError = $"Directory heartbeat HTTP {(int)resp.StatusCode}"; + return; + } + + var ack = await resp.Content.ReadFromJsonAsync(JsonOptions, ct).ConfigureAwait(false); + if (ack is not null && ack.ServerId != Guid.Empty && !string.IsNullOrEmpty(ack.LeaseToken)) + { + lock (_leaseGate) + { + _serverId = ack.ServerId; + _leaseToken = ack.LeaseToken; + } + LastError = null; + } + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + LastError = ex.Message; + } + } + + private (Guid? ServerId, string? LeaseToken) ReadLeaseSnapshot() + { + lock (_leaseGate) + { + return (_serverId, _leaseToken); + } + } + + private async Task SendDeleteOnceAsync(Guid serverId, string leaseToken) + { + try + { + using var deleteCts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var req = new HttpRequestMessage(HttpMethod.Delete, $"{_baseUrl}/api/v1/servers/{serverId}"); + req.Headers.TryAddWithoutValidation("X-Lease-Token", leaseToken); + using var _ = await _http.SendAsync(req, deleteCts.Token).ConfigureAwait(false); + } + catch + { + } + } + + private void DisposeResources() + { + _cts.Dispose(); + _wakeSignal.Dispose(); + if (_ownsHttp) + { + _http.Dispose(); + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + + _cts.Cancel(); + try + { + _loopTask.Wait(TimeSpan.FromSeconds(5)); + } + catch + { + } + + var (serverId, leaseToken) = ReadLeaseSnapshot(); + if (serverId is { } sid && !string.IsNullOrEmpty(leaseToken)) + { + SendDeleteOnceAsync(sid, leaseToken).GetAwaiter().GetResult(); + } + + DisposeResources(); + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + + _cts.Cancel(); + try + { + await _loopTask.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); + } + catch + { + } + + var (serverId, leaseToken) = ReadLeaseSnapshot(); + if (serverId is { } sid && !string.IsNullOrEmpty(leaseToken)) + { + await SendDeleteOnceAsync(sid, leaseToken).ConfigureAwait(false); + } + + DisposeResources(); + } + } +} diff --git a/src/RustToDust.Net/ListenHostArenaSession.cs b/src/RustToDust.Net/ListenHostArenaSession.cs index 7220337..07dcb89 100644 --- a/src/RustToDust.Net/ListenHostArenaSession.cs +++ b/src/RustToDust.Net/ListenHostArenaSession.cs @@ -15,7 +15,10 @@ namespace RustToDust.Net int port, int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, - int maxHumans = MatchState.ContenderCount) + int maxHumans = MatchState.ContenderCount, + bool startInLobby = false, + string serverName = "Rust to Dust", + int minHumansToStart = 1) { _host = new ServerMatchHost( bindAddress, @@ -25,7 +28,10 @@ namespace RustToDust.Net maxHumans: maxHumans, autoRestartSec: 0, allowClientReset: false, - hostContenderId: 0); + hostContenderId: 0, + startInLobby: startInLobby, + serverName: serverName, + minHumansToStart: minHumansToStart); } public ServerMatchHost Host => _host; @@ -34,9 +40,11 @@ namespace RustToDust.Net public ContenderState LocalContender => _host.Session.State.Contenders[0]; public ClientMatchOutcome LocalOutcome => - _host.Session.State.Phase == MatchPhase.Active - ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) - : (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); + _host.Session.State.Phase == MatchPhase.Lobby + ? ClientMatchOutcome.Active + : _host.Session.State.Phase == MatchPhase.Active + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + : (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.DetectedByCount : 0; @@ -59,12 +67,14 @@ namespace RustToDust.Net public IReadOnlyList ActivePods => _host.Session.State.OrbitalDrop.ActivePods; public DropWaveState DropWaveState => _host.Session.State.OrbitalDrop.WaveState; public IReadOnlyList PodEvents => _host.Session.State.PodEvents; + public LobbySnapshotDto? LobbyState => _host.BuildLobbySnapshotDto(); public bool IsContenderVisible(int contenderId) => true; public bool IsSpectatorVisible(int spectatorId) => true; public void BeginRenderFrame(double dt, float physicsAlpha) { + _host.PollStatelessPings(); } public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick) @@ -82,6 +92,10 @@ namespace RustToDust.Net public void RequestNewMatch(int seed, ArenaMapKind mapKind) => _host.ResetMatch(seed, mapKind); + public bool SetLobbyReady(bool ready) => _host.SetLobbyReady(0, ready); + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => _host.ConfigureLobby(0, seed, mapKind); + public bool RequestLobbyStart() => _host.LaunchFromLobby(0); + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) => _host.Session.GetInterpolatedContenderPose(contenderId, alpha); diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index f825cc9..5f527c2 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -78,6 +78,8 @@ namespace RustToDust.Net private int _pingMs; private int _connectedHumans = 1; private long _lastServerPacketUtcMs; + private long _lastKeepaliveUtcMs; + private LobbySnapshotDto? _lobbyState; private float _podStepAccum; private float _timeSinceLastPhysicsPodStep; private bool _physicsPodSteppingActive; @@ -138,9 +140,11 @@ namespace RustToDust.Net public ContenderState LocalContender => _viewState.Contenders[_localContenderId]; public ClientMatchOutcome LocalOutcome => - _viewState.Phase == MatchPhase.Active - ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) - : (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); + _viewState.Phase == MatchPhase.Lobby + ? ClientMatchOutcome.Active + : _viewState.Phase == MatchPhase.Active + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + : (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => _localDetectedByCount; @@ -165,6 +169,7 @@ namespace RustToDust.Net public IReadOnlyList ActivePods => _viewState.OrbitalDrop.ActivePods; public DropWaveState DropWaveState => _viewState.OrbitalDrop.WaveState; public IReadOnlyList PodEvents => _viewState.PodEvents; + public LobbySnapshotDto? LobbyState => _viewState.Phase == MatchPhase.Lobby ? _lobbyState : null; public bool IsContenderVisible(int contenderId) => contenderId >= 0 && contenderId < _contenderVisible.Length && _contenderVisible[contenderId]; @@ -342,6 +347,39 @@ namespace RustToDust.Net }); } + public bool SetLobbyReady(bool ready) + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbyReadyCmdMsg + { + ReqSeq = _nextCmdSeq++, + IsReady = ready + }); + return true; + } + + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbyConfigCmdMsg + { + ReqSeq = _nextCmdSeq++, + Seed = seed, + MapKind = (byte)mapKind + }); + return true; + } + + public bool RequestLobbyStart() + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbyStartCmdMsg + { + ReqSeq = _nextCmdSeq++ + }); + return true; + } + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) { if (contenderId < 0 || contenderId >= _viewState.Contenders.Count) @@ -574,6 +612,12 @@ namespace RustToDust.Net } } + if (_joined && _conn.Connected && _viewState.Phase == MatchPhase.Lobby && (nowUtcMs - _lastKeepaliveUtcMs) >= 1000) + { + _lastKeepaliveUtcMs = nowUtcMs; + SendSchemaMessage(new ClientKeepaliveMsg { ClientSendMs = unchecked((uint)nowUtcMs) }); + } + try { _conn.PollResends(); @@ -659,9 +703,35 @@ namespace RustToDust.Net case EntitySyncSnapshotMsg sync: ApplyEntitySync(sync); break; + case LobbySnapshotMsg lobbySnap: + if (lobbySnap.MatchGeneration == _matchGeneration) + { + ApplyLobbySnapshot(lobbySnap.Snapshot); + } + break; } } + private void ApplyLobbySnapshot(LobbySnapshotDto? snapshot) + { + _lobbyState = snapshot; + if (snapshot is null) return; + for (int i = 0; i < snapshot.Slots.Count && i < _viewState.Contenders.Count; i++) + { + var slot = snapshot.Slots[i]; + if (slot.SlotId >= 0 && slot.SlotId < _viewState.Contenders.Count) + { + var c = _viewState.Contenders[slot.SlotId]; + c.IsHuman = slot.IsHuman; + if (!string.IsNullOrWhiteSpace(slot.Callsign)) + { + c.Name = slot.Callsign; + } + } + } + _connectedHumans = CountHumanContenders(); + } + private static bool ContainsMatchReset(List events) { for (int i = 0; i < events.Count; i++) @@ -724,9 +794,16 @@ namespace RustToDust.Net _viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true) { Time = dto.SimTime, - Phase = dto.Phase == 1 ? MatchPhase.Completed : MatchPhase.Active, + Phase = dto.Phase switch + { + 1 => MatchPhase.Completed, + 2 => MatchPhase.Lobby, + _ => MatchPhase.Active + }, WinnerContenderId = dto.WinnerContenderId }; + _lobbyState = _viewState.Phase == MatchPhase.Lobby ? dto.Lobby : null; + _lastKeepaliveUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); _viewState.Spectators.SetReplicatedSafeRadius(dto.SafeRadius); _viewState.OrbitalDrop.ApplyReplicatedWaveState( dto.CurrentWaveIndex, @@ -1074,6 +1151,10 @@ namespace RustToDust.Net private void ApplyCorePvsSnapshot(DecodedCorePvsSnapshot pkt) { _viewState.Time = pkt.SimTime; + if (_viewState.Phase == MatchPhase.Lobby && pkt.Phase != MatchPhase.Lobby) + { + _lobbyState = null; + } _viewState.Phase = pkt.Phase; _viewState.WinnerContenderId = pkt.WinnerContenderId; _viewState.Spectators.SetReplicatedSafeRadius(pkt.SafeRadius); @@ -1598,6 +1679,13 @@ namespace RustToDust.Net case MatchResetEvent reset: ApplyInitialMatchState(reset.FullInitialState, reset.AssignedContenderId); break; + case MatchStartedEvent started: + if (started.MatchGeneration == _matchGeneration || started.MatchGeneration == 0) + { + _viewState.Phase = MatchPhase.Active; + _lobbyState = null; + } + break; } _pendingClientEvents.Add(batch.Events[i]); } diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs index 033b2a1..d3fe744 100644 --- a/src/RustToDust.Net/ServerMatchHost.cs +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -55,6 +55,10 @@ namespace RustToDust.Net private readonly double _autoRestartSec; private readonly bool _allowClientReset; private readonly int? _hostContenderId; + private readonly string _serverName; + private readonly int _minHumansToStart; + private readonly bool _restartToLobby; + private readonly byte[] _udpPeekBuf = new byte[65535]; private ArenaSession _session; private string _hostCallsign = "Host"; @@ -66,6 +70,7 @@ namespace RustToDust.Net private long _latestOutSeq = 1; private uint _nextPeerId = 1; private float _roundCompletedElapsed; + private int _lastBroadcastCountdownSec = -1; private bool _disposed; public ServerMatchHost( @@ -76,12 +81,19 @@ namespace RustToDust.Net int maxHumans = MatchState.ContenderCount, double autoRestartSec = 8.0, bool allowClientReset = false, - int? hostContenderId = null) + int? hostContenderId = null, + bool startInLobby = false, + string serverName = "Rust to Dust", + int minHumansToStart = 1, + bool restartToLobby = false) { _maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount); _autoRestartSec = autoRestartSec; _allowClientReset = allowClientReset; _hostContenderId = hostContenderId; + _serverName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim(); + _minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans); + _restartToLobby = restartToLobby; _socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp) { @@ -102,18 +114,25 @@ namespace RustToDust.Net }); _server.PeerDisconnected += OnTransportPeerDisconnected; - _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0); + _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby); if (hostContenderId.HasValue) { _session.SetHumanSlot(hostContenderId.Value, true, "Host"); } + InitLobbyMetadata(_session); } public int BoundPort { get; } public ArenaSession Session => _session; public uint MatchGeneration => _matchGeneration; public uint SimTick => _simTick; + public string ServerName => _serverName; + public int MaxHumans => _maxHumans; public int ConnectedHumanCount => _peersByEndpoint.Count + (_hostContenderId.HasValue ? 1 : 0); + public bool AcceptingJoin => ConnectedHumanCount < _maxHumans && (_session.State.Phase == MatchPhase.Lobby || _session.State.Phase == MatchPhase.Active); + public long TransportPacketsDropped => _server.Stats.PacketsDropped; + public CultNetTransportStats TransportStats => _server.Stats; + public LobbyState? Lobby => _session.State.Lobby; public event Action? LogMessage; public void SetHostInput(in PlayerInput input) @@ -145,17 +164,21 @@ namespace RustToDust.Net return ok; } - public void ResetMatch(int seed, ArenaMapKind mapKind) + public void ResetMatch(int seed, ArenaMapKind mapKind) => + ResetMatch(seed, mapKind, startInLobby: false); + + public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) { if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count) { _hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name; } _session.Dispose(); - _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0); + _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby); _matchGeneration++; _simTick = 0; _roundCompletedElapsed = 0f; + _lastBroadcastCountdownSec = -1; _terrainStampHistory.Clear(); _stepEvents.Clear(); _hostPendingEvents.Clear(); @@ -165,6 +188,7 @@ namespace RustToDust.Net { _session.SetHumanSlot(_hostContenderId.Value, true, _hostCallsign); } + InitLobbyMetadata(_session); foreach (var peer in _peersByEndpoint.Values) { @@ -174,6 +198,12 @@ namespace RustToDust.Net peer.LastInteractSeq = 0; _session.SetHumanSlot(slot, true, peer.Callsign); _reconnectTokens[peer.ReconnectToken] = (slot, peer.Callsign); + } + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + int slot = peer.AssignedContenderId; InitPeerTrackers(peer); var reset = new MatchResetEvent { @@ -194,6 +224,246 @@ namespace RustToDust.Net } } + public bool SetLobbyReady(int contenderId, bool ready) + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return false; + } + if (contenderId < 0 || contenderId >= lobby.Slots.Length || !lobby.Slots[contenderId].IsHuman) + { + return false; + } + + lobby.Slots[contenderId].IsReady = ready; + ReevaluateLobbyCountdown(lobby); + BroadcastLobbySnapshot(); + return true; + } + + public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind) + { + if (_session.State.Phase != MatchPhase.Lobby) + { + return false; + } + if (!IsLobbyAuthority(requesterContenderId)) + { + return false; + } + + ResetMatch(seed, mapKind, startInLobby: true); + return true; + } + + public bool LaunchFromLobby(int requesterContenderId) + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return false; + } + if (!IsLobbyAuthority(requesterContenderId)) + { + return false; + } + + if (lobby.ForceLaunched) + { + lobby.CountdownSeconds = 0f; + } + else + { + lobby.ForceLaunched = true; + lobby.CountdownSeconds ??= LobbyState.DefaultCountdownSeconds; + _lastBroadcastCountdownSec = (int)MathF.Ceiling(lobby.CountdownSeconds.Value); + BroadcastLobbySnapshot(); + } + return true; + } + + private bool IsLobbyAuthority(int requesterContenderId) => + _hostContenderId.HasValue + ? requesterContenderId == _hostContenderId.Value + : _allowClientReset; + + private void InitLobbyMetadata(ArenaSession session) + { + if (session.State.Lobby is not { } lobby) return; + lobby.HostSlotId = _hostContenderId; + lobby.MinHumansToAutoStart = _minHumansToStart; + lobby.SelectedMap = session.State.MapKind; + lobby.SelectedSeed = session.State.Seed; + lobby.CountdownSeconds = null; + lobby.ForceLaunched = false; + for (int i = 0; i < session.State.Contenders.Count && i < lobby.Slots.Length; i++) + { + var c = session.State.Contenders[i]; + lobby.Slots[i].IsHuman = c.IsHuman; + lobby.Slots[i].Callsign = c.Name; + lobby.Slots[i].IsReady = false; + } + } + + private void ReevaluateLobbyCountdown(LobbyState lobby) + { + if (lobby.ForceLaunched) + { + lobby.CountdownSeconds ??= LobbyState.DefaultCountdownSeconds; + return; + } + + int humanCount = 0; + bool allReady = true; + for (int i = 0; i < lobby.Slots.Length; i++) + { + if (!lobby.Slots[i].IsHuman) continue; + humanCount++; + if (!lobby.Slots[i].IsReady) + { + allReady = false; + } + } + + if (humanCount >= lobby.MinHumansToAutoStart && allReady) + { + if (!lobby.CountdownSeconds.HasValue) + { + lobby.CountdownSeconds = LobbyState.DefaultCountdownSeconds; + _lastBroadcastCountdownSec = -1; + } + } + else + { + lobby.CountdownSeconds = null; + _lastBroadcastCountdownSec = -1; + } + } + + public LobbySnapshotDto? BuildLobbySnapshotDto() + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return null; + } + + var dto = new LobbySnapshotDto + { + HostSlotId = lobby.HostSlotId, + MinHumansToAutoStart = lobby.MinHumansToAutoStart, + CountdownSeconds = lobby.CountdownSeconds, + ForceLaunched = lobby.ForceLaunched, + SelectedMap = (byte)lobby.SelectedMap, + SelectedSeed = lobby.SelectedSeed, + Slots = new List(lobby.Slots.Length) + }; + for (int i = 0; i < lobby.Slots.Length; i++) + { + var s = lobby.Slots[i]; + dto.Slots.Add(new LobbySlotDto + { + SlotId = s.SlotId, + Callsign = s.Callsign, + IsHuman = s.IsHuman, + IsReady = s.IsReady + }); + } + return dto; + } + + private void BroadcastLobbySnapshot() + { + var dto = BuildLobbySnapshotDto(); + if (dto is null || _peersByEndpoint.Count == 0) return; + + var msg = new LobbySnapshotMsg + { + MatchGeneration = _matchGeneration, + Snapshot = dto + }; + foreach (var peer in _peersByEndpoint.Values) + { + if (peer.Active) + { + SendSchemaToPeer(peer, msg); + } + } + } + + public void PollStatelessPings() + { + if (_disposed) return; + + for (int i = 0; i < 64; i++) + { + try + { + if (!_socket.Poll(0, SelectMode.SelectRead)) + { + break; + } + + // Note: Use Socket.Receive(..., SocketFlags.Peek) rather than ReceiveFrom(byte[], ..., Peek, ref EndPoint); + // on .NET 8/10 Windows, ReceiveFrom(byte[], ..., Peek, ref EndPoint) consumes the datagram instead of peeking. + int peeked = _socket.Receive(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.Peek); + if (peeked <= 0) + { + break; + } + + if (!SnapshotCodec.HasPingMagic(_udpPeekBuf.AsSpan(0, peeked))) + { + // Leave CultNet RUDP / other traffic untouched for _server.TryReceiveOnce. + break; + } + + EndPoint consumeRemote = _socket.AddressFamily == AddressFamily.InterNetworkV6 + ? new IPEndPoint(IPAddress.IPv6Any, 0) + : new IPEndPoint(IPAddress.Any, 0); + int received = _socket.ReceiveFrom(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.None, ref consumeRemote); + if (received > 0 && SnapshotCodec.TryDecodePing(_udpPeekBuf.AsSpan(0, received), out ulong clientNonce)) + { + var summary = new ServerPingSummary( + clientNonce, + ProtocolVersion: 1, + MapKind: _session.State.MapKind, + Phase: _session.State.Phase, + Humans: (byte)Math.Clamp(ConnectedHumanCount, 0, byte.MaxValue), + MaxHumans: (byte)Math.Clamp(_maxHumans, 1, byte.MaxValue), + WaveIndex: (byte)Math.Clamp(_session.State.OrbitalDrop.CurrentWaveIndex, 0, byte.MaxValue), + AcceptingJoin: AcceptingJoin, + HasPassword: false, + Seed: _session.State.Seed, + ServerName: _serverName); + byte[] pong = SnapshotCodec.EncodePong(in summary); + _socket.SendTo(pong, consumeRemote); + } + } + catch (SocketException ex) when ( + ex.SocketErrorCode == SocketError.WouldBlock || + ex.SocketErrorCode == SocketError.TimedOut) + { + break; + } + catch (SocketException ex) when ( + ex.SocketErrorCode == SocketError.ConnectionReset || + ex.SocketErrorCode == SocketError.ConnectionAborted || + ex.SocketErrorCode == SocketError.Shutdown) + { + try + { + EndPoint drainRemote = _socket.AddressFamily == AddressFamily.InterNetworkV6 + ? new IPEndPoint(IPAddress.IPv6Any, 0) + : new IPEndPoint(IPAddress.Any, 0); + _socket.ReceiveFrom(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.None, ref drainRemote); + } + catch + { + } + break; + } + } + } + public void StepOnce(long nowUtcMs) { ObjectDisposedException.ThrowIf(_disposed, this); @@ -202,6 +472,27 @@ namespace RustToDust.Net PollIncoming(nowUtcMs); SweepTimeouts(nowUtcMs); + if (_session.State.Phase == MatchPhase.Lobby && + _session.State.Lobby is { } lobby && + lobby.CountdownSeconds.HasValue) + { + lobby.CountdownSeconds = MathF.Max(0f, lobby.CountdownSeconds.Value - ArenaSession.FixedDt); + if (lobby.CountdownSeconds.Value <= 0f) + { + _lastBroadcastCountdownSec = -1; + _session.StartFromLobby(_matchGeneration); + } + else + { + int wholeSec = (int)MathF.Ceiling(lobby.CountdownSeconds.Value); + if (wholeSec != _lastBroadcastCountdownSec) + { + _lastBroadcastCountdownSec = wholeSec; + BroadcastLobbySnapshot(); + } + } + } + _session.Step(); _simTick++; @@ -237,7 +528,7 @@ namespace RustToDust.Net _roundCompletedElapsed += ArenaSession.FixedDt; if (_roundCompletedElapsed >= _autoRestartSec) { - ResetMatch(_session.State.Seed + 1, _session.State.MapKind); + ResetMatch(_session.State.Seed + 1, _session.State.MapKind, startInLobby: _restartToLobby); } } } @@ -247,6 +538,8 @@ namespace RustToDust.Net int processed = 0; while (processed < 256) { + PollStatelessPings(); + CultNetRudpSocketServerFrame? serverFrame; try { @@ -339,6 +632,33 @@ namespace RustToDust.Net } } break; + case LobbyReadyCmdMsg readyCmd: + if (_peersByEndpoint.TryGetValue(epKey, out var readyPeer) && readyPeer.Active && ReferenceEquals(readyPeer.TransportPeer, transportPeer)) + { + readyPeer.LastHeardUtcMs = nowUtcMs; + SetLobbyReady(readyPeer.AssignedContenderId, readyCmd.IsReady); + } + break; + case LobbyConfigCmdMsg cfgCmd: + if (_peersByEndpoint.TryGetValue(epKey, out var cfgPeer) && cfgPeer.Active && ReferenceEquals(cfgPeer.TransportPeer, transportPeer)) + { + cfgPeer.LastHeardUtcMs = nowUtcMs; + ConfigureLobby(cfgPeer.AssignedContenderId, cfgCmd.Seed, (ArenaMapKind)cfgCmd.MapKind); + } + break; + case LobbyStartCmdMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var startPeer) && startPeer.Active && ReferenceEquals(startPeer.TransportPeer, transportPeer)) + { + startPeer.LastHeardUtcMs = nowUtcMs; + LaunchFromLobby(startPeer.AssignedContenderId); + } + break; + case ClientKeepaliveMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var keepPeer) && keepPeer.Active && ReferenceEquals(keepPeer.TransportPeer, transportPeer)) + { + keepPeer.LastHeardUtcMs = nowUtcMs; + } + break; } } @@ -425,6 +745,15 @@ namespace RustToDust.Net _peersByEndpoint[epKey] = peer; SendJoinAccepted(peer); + if (_session.State.Phase == MatchPhase.Lobby && _session.State.Lobby is { } lobby) + { + if (!lobby.ForceLaunched) + { + lobby.CountdownSeconds = null; + _lastBroadcastCountdownSec = -1; + } + BroadcastLobbySnapshot(); + } LogMessage?.Invoke($"[tick {_simTick}] Peer #{peer.PeerId} '{callsign}' joined slot {slotId} ({epKey}), humans={ConnectedHumanCount}/{_maxHumans}"); _stepEvents.Add(new EntitySlotControlEvent @@ -534,6 +863,11 @@ namespace RustToDust.Net Reason = (byte)reason }); } + if (_session.State.Phase == MatchPhase.Lobby && _session.State.Lobby is { } lobby) + { + ReevaluateLobbyCountdown(lobby); + BroadcastLobbySnapshot(); + } LogMessage?.Invoke($"[tick {_simTick}] Peer #{peer.PeerId} '{peer.Callsign}' disconnected from slot {slot} ({reason}), humans={ConnectedHumanCount}/{_maxHumans}"); } @@ -1287,11 +1621,12 @@ namespace RustToDust.Net MapKind = (byte)_session.State.MapKind, SimTime = _session.State.Time, SafeRadius = _session.State.Spectators.SafeRadius, - Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : 0), + Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : _session.State.Phase == MatchPhase.Lobby ? 2 : 0), WinnerContenderId = _session.State.WinnerContenderId, ConnectedHumans = ConnectedHumanCount, CurrentWaveIndex = _session.State.OrbitalDrop.CurrentWaveIndex, - RespawnCutoffReached = _session.State.OrbitalDrop.RespawnCutoffReached + RespawnCutoffReached = _session.State.OrbitalDrop.RespawnCutoffReached, + Lobby = BuildLobbySnapshotDto() }; var activePods = _session.State.OrbitalDrop.ActivePods; diff --git a/src/RustToDust.Net/ServerPingProbe.cs b/src/RustToDust.Net/ServerPingProbe.cs new file mode 100644 index 0000000..a2234dc --- /dev/null +++ b/src/RustToDust.Net/ServerPingProbe.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; + +namespace RustToDust.Net +{ + public sealed record ServerPingResult( + string Host, + int Port, + IPEndPoint? ResolvedEndPoint, + bool Success, + int RttMs, + ServerPingSummary? Summary); + + public static class ServerPingProbe + { + public static async Task ProbeAsync( + string host, + int port, + TimeSpan timeout, + CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(host) || port < 1 || port > 65535) + { + return new ServerPingResult(host ?? string.Empty, port, null, false, -1, null); + } + + IPAddress? resolvedIp = null; + if (IPAddress.TryParse(host.Trim(), out var parsed)) + { + resolvedIp = parsed; + } + else + { + try + { + var addrs = await Dns.GetHostAddressesAsync(host.Trim(), ct).ConfigureAwait(false); + for (int i = 0; i < addrs.Length; i++) + { + if (addrs[i].AddressFamily == AddressFamily.InterNetwork) + { + resolvedIp = addrs[i]; + break; + } + } + if (resolvedIp is null && addrs.Length > 0) + { + resolvedIp = addrs[0]; + } + } + catch + { + return new ServerPingResult(host, port, null, false, -1, null); + } + } + + if (resolvedIp is null) + { + return new ServerPingResult(host, port, null, false, -1, null); + } + + var ep = new IPEndPoint(resolvedIp, port); + var res = await ProbeAsync(ep, timeout, ct).ConfigureAwait(false); + return res with { Host = host }; + } + + public static async Task ProbeAsync( + IPEndPoint target, + TimeSpan timeout, + CancellationToken ct = default) + { + using var socket = new Socket(target.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint( + target.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, + 0)); + + ulong nonce = BitConverter.ToUInt64(RandomNumberGenerator.GetBytes(8), 0); + byte[] ping = SnapshotCodec.EncodePing(nonce); + byte[] recvBuf = new byte[512]; + + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeoutCts.CancelAfter(timeout); + + try + { + long startTs = Stopwatch.GetTimestamp(); + await socket.SendToAsync(ping, SocketFlags.None, target, timeoutCts.Token).ConfigureAwait(false); + + EndPoint anyRemote = target.AddressFamily == AddressFamily.InterNetworkV6 + ? new IPEndPoint(IPAddress.IPv6Any, 0) + : new IPEndPoint(IPAddress.Any, 0); + + while (!timeoutCts.IsCancellationRequested) + { + var res = await socket.ReceiveFromAsync(recvBuf, SocketFlags.None, anyRemote, timeoutCts.Token).ConfigureAwait(false); + if (SnapshotCodec.TryDecodePong(recvBuf.AsSpan(0, res.ReceivedBytes), out var summary) && + summary.ClientNonce == nonce) + { + int rttMs = Math.Max(1, (int)Math.Round(Stopwatch.GetElapsedTime(startTs).TotalMilliseconds)); + return new ServerPingResult(target.Address.ToString(), target.Port, target, true, rttMs, summary); + } + } + } + catch (OperationCanceledException) + { + } + catch (SocketException) + { + } + + return new ServerPingResult(target.Address.ToString(), target.Port, target, false, -1, null); + } + + public static async Task ProbeManyAsync( + IReadOnlyList<(string Host, int Port)> targets, + TimeSpan timeout, + int maxConcurrency = 16, + CancellationToken ct = default) + { + var results = new ServerPingResult[targets.Count]; + using var gate = new SemaphoreSlim(Math.Max(1, maxConcurrency)); + var tasks = new Task[targets.Count]; + + for (int i = 0; i < targets.Count; i++) + { + int idx = i; + var target = targets[i]; + tasks[i] = Task.Run(async () => + { + await gate.WaitAsync(ct).ConfigureAwait(false); + try + { + results[idx] = await ProbeAsync(target.Host, target.Port, timeout, ct).ConfigureAwait(false); + } + finally + { + gate.Release(); + } + }, ct); + } + + await Task.WhenAll(tasks).ConfigureAwait(false); + return results; + } + } +} diff --git a/src/RustToDust.Net/SnapshotCodec.cs b/src/RustToDust.Net/SnapshotCodec.cs index 91c1168..0f6a904 100644 --- a/src/RustToDust.Net/SnapshotCodec.cs +++ b/src/RustToDust.Net/SnapshotCodec.cs @@ -2,6 +2,7 @@ using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Numerics; +using System.Text; using GameCult.Mesh; using MessagePack; using RustToDust.Core; @@ -130,9 +131,26 @@ namespace RustToDust.Net public List Spectators = new(); } + public readonly record struct ServerPingSummary( + ulong ClientNonce, + ushort ProtocolVersion, + ArenaMapKind MapKind, + MatchPhase Phase, + byte Humans, + byte MaxHumans, + byte WaveIndex, + bool AcceptingJoin, + bool HasPassword, + int Seed, + string ServerName); + public static class SnapshotCodec { public const int MaxLatestDatagramBytes = 1152; + public const int PingPacketBytes = 32; + public const byte PingWireVersion = 1; + public const byte PingKindRequest = 1; + public const byte PingKindResponse = 2; public const string ChannelLatest = "latest"; public const string ChannelSchema = "schema"; public const string SchemaLatestId = "rtd.snap"; @@ -333,8 +351,13 @@ namespace RustToDust.Net BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), echoSendMs); offset += 4; BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), safeRadius); offset += 4; - byte phaseByte = (byte)(phase == MatchPhase.Completed ? 1 : 0); - if (winnerContenderId.HasValue) phaseByte |= 2; + byte phaseByte = phase switch + { + MatchPhase.Completed => 1, + MatchPhase.Lobby => 2, + _ => 0 + }; + if (winnerContenderId.HasValue) phaseByte |= 0x04; buf[offset++] = phaseByte; buf[offset++] = (byte)(sbyte)(winnerContenderId ?? -1); buf[offset++] = detectedByCount; @@ -501,9 +524,14 @@ namespace RustToDust.Net decoded.SafeRadius = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4; byte phaseByte = span[offset++]; - decoded.Phase = (phaseByte & 1) != 0 ? MatchPhase.Completed : MatchPhase.Active; + decoded.Phase = (phaseByte & 0x03) switch + { + 1 => MatchPhase.Completed, + 2 => MatchPhase.Lobby, + _ => MatchPhase.Active + }; sbyte winnerRaw = (sbyte)span[offset++]; - decoded.WinnerContenderId = (phaseByte & 2) != 0 ? winnerRaw : null; + decoded.WinnerContenderId = (phaseByte & 0x04) != 0 ? winnerRaw : null; decoded.DetectedByCount = span[offset++]; ushort arc = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2; @@ -972,5 +1000,127 @@ namespace RustToDust.Net var v = new Vector3(ox, ny, oy); return v.LengthSquared() < 1e-6f ? Vector3.UnitY : Vector3.Normalize(v); } + + public static bool HasPingMagic(ReadOnlySpan buf) => + buf.Length >= 4 && + buf[0] == (byte)'R' && + buf[1] == (byte)'T' && + buf[2] == (byte)'D' && + buf[3] == (byte)'P'; + + public static byte[] EncodePing(ulong clientNonce) + { + byte[] buf = new byte[PingPacketBytes]; + buf[0] = (byte)'R'; + buf[1] = (byte)'T'; + buf[2] = (byte)'D'; + buf[3] = (byte)'P'; + buf[4] = PingWireVersion; + buf[5] = PingKindRequest; + BinaryPrimitives.WriteUInt64LittleEndian(buf.AsSpan(8, 8), clientNonce); + return buf; + } + + public static bool TryDecodePing(ReadOnlySpan buf, out ulong clientNonce) + { + if (buf.Length < 16 || + !HasPingMagic(buf) || + buf[4] != PingWireVersion || + buf[5] != PingKindRequest) + { + clientNonce = 0; + return false; + } + clientNonce = BinaryPrimitives.ReadUInt64LittleEndian(buf.Slice(8, 8)); + return true; + } + + public static byte[] EncodePong(in ServerPingSummary summary) + { + string rawName = string.IsNullOrWhiteSpace(summary.ServerName) ? "Rust to Dust" : summary.ServerName.Trim(); + Span utf8Buf = stackalloc byte[48]; + Encoding.UTF8.GetEncoder().Convert(rawName.AsSpan(), utf8Buf, flush: true, out _, out int nameBytes, out _); + + byte[] buf = new byte[27 + nameBytes]; + var span = buf.AsSpan(); + span[0] = (byte)'R'; + span[1] = (byte)'T'; + span[2] = (byte)'D'; + span[3] = (byte)'P'; + span[4] = PingWireVersion; + span[5] = PingKindResponse; + BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(6, 2), summary.ProtocolVersion); + BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(8, 8), summary.ClientNonce); + span[16] = (byte)summary.MapKind; + span[17] = summary.Phase switch + { + MatchPhase.Completed => 1, + MatchPhase.Lobby => 2, + _ => 0 + }; + span[18] = summary.Humans; + span[19] = summary.MaxHumans; + span[20] = summary.WaveIndex; + byte flags = 0; + if (summary.AcceptingJoin) flags |= 1; + if (summary.HasPassword) flags |= 2; + span[21] = flags; + BinaryPrimitives.WriteInt32LittleEndian(span.Slice(22, 4), summary.Seed); + span[26] = (byte)nameBytes; + if (nameBytes > 0) + { + utf8Buf.Slice(0, nameBytes).CopyTo(span.Slice(27)); + } + return buf; + } + + public static bool TryDecodePong(ReadOnlySpan buf, out ServerPingSummary summary) + { + if (buf.Length < 27 || + !HasPingMagic(buf) || + buf[4] != PingWireVersion || + buf[5] != PingKindResponse) + { + summary = default; + return false; + } + + int nameLen = buf[26]; + if (nameLen > 64 || 27 + nameLen > buf.Length) + { + summary = default; + return false; + } + + ushort proto = BinaryPrimitives.ReadUInt16LittleEndian(buf.Slice(6, 2)); + ulong nonce = BinaryPrimitives.ReadUInt64LittleEndian(buf.Slice(8, 8)); + ArenaMapKind mapKind = (ArenaMapKind)buf[16]; + MatchPhase phase = buf[17] switch + { + 1 => MatchPhase.Completed, + 2 => MatchPhase.Lobby, + _ => MatchPhase.Active + }; + byte humans = buf[18]; + byte maxHumans = buf[19]; + byte waveIndex = buf[20]; + byte flags = buf[21]; + int seed = BinaryPrimitives.ReadInt32LittleEndian(buf.Slice(22, 4)); + string name = nameLen > 0 ? Encoding.UTF8.GetString(buf.Slice(27, nameLen)) : "Rust to Dust"; + + summary = new ServerPingSummary( + nonce, + proto, + mapKind, + phase, + humans, + maxHumans, + waveIndex, + AcceptingJoin: (flags & 1) != 0, + HasPassword: (flags & 2) != 0, + seed, + name); + return true; + } } } diff --git a/src/RustToDust.Server/Program.cs b/src/RustToDust.Server/Program.cs index 4661122..2e1339b 100644 --- a/src/RustToDust.Server/Program.cs +++ b/src/RustToDust.Server/Program.cs @@ -21,6 +21,12 @@ namespace RustToDust.Server double autoRestartSec = 8.0; double durationSec = 0.0; bool allowClientReset = false; + string? directoryUrl = Environment.GetEnvironmentVariable("RTD_DIRECTORY_URL"); + string serverName = Environment.GetEnvironmentVariable("RTD_SERVER_NAME") ?? "Rust to Dust"; + string publicHost = Environment.GetEnvironmentVariable("RTD_PUBLIC_HOST") ?? "auto"; + bool startInLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_LOBBY"), false); + int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1); + bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false); for (int i = 0; i < args.Length; i++) { @@ -42,6 +48,16 @@ namespace RustToDust.Server else if (a == "--allow-client-reset") allowClientReset = true; else if (a == "--assets-dir" && i + 1 < args.Length) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", args[++i]); else if (a.StartsWith("--assets-dir=", StringComparison.Ordinal)) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", a.Substring("--assets-dir=".Length)); + else if (a == "--directory-url" && i + 1 < args.Length) directoryUrl = args[++i]; + else if (a.StartsWith("--directory-url=", StringComparison.Ordinal)) directoryUrl = a.Substring("--directory-url=".Length); + else if (a == "--server-name" && i + 1 < args.Length) serverName = args[++i]; + else if (a.StartsWith("--server-name=", StringComparison.Ordinal)) serverName = a.Substring("--server-name=".Length); + else if (a == "--public-host" && i + 1 < args.Length) publicHost = args[++i]; + else if (a.StartsWith("--public-host=", StringComparison.Ordinal)) publicHost = a.Substring("--public-host=".Length); + else if (a == "--lobby") startInLobby = true; + else if (a == "--min-humans" && i + 1 < args.Length) minHumansToStart = TryParseInt(args[++i], minHumansToStart); + else if (a.StartsWith("--min-humans=", StringComparison.Ordinal)) minHumansToStart = TryParseInt(a.Substring("--min-humans=".Length), minHumansToStart); + else if (a == "--restart-to-lobby") restartToLobby = true; } if (!IPAddress.TryParse(bindStr, out var bindIp)) @@ -64,6 +80,7 @@ namespace RustToDust.Server Console.CancelKeyPress += cancelHandler; AppDomain.CurrentDomain.ProcessExit += exitHandler; + DirectoryReporter? reporter = null; try { using var host = new ServerMatchHost( @@ -73,15 +90,53 @@ namespace RustToDust.Server mapKind, maxHumans, autoRestartSec, - allowClientReset); + allowClientReset, + hostContenderId: null, + startInLobby: startInLobby, + serverName: serverName, + minHumansToStart: minHumansToStart, + restartToLobby: restartToLobby); host.LogMessage += msg => Console.WriteLine(msg); - Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (map={mapKind}, seed={seed}, maxHumans={maxHumans})"); + static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) => + new( + h.ServerName, + hostAddr, + h.BoundPort, + h.Session.State.MapKind == ArenaMapKind.Sion ? "sion" : "desert", + h.Session.State.Seed, + h.ConnectedHumanCount, + h.MaxHumans, + h.Session.State.Phase.ToString(), + h.Session.State.OrbitalDrop.CurrentWaveIndex); + + object dirSnapGate = new(); + DirectoryHeartbeatSnapshot cachedDirSnap = BuildSnapshot(host, publicHost); + + if (!string.IsNullOrWhiteSpace(directoryUrl)) + { + reporter = new DirectoryReporter( + directoryUrl, + () => + { + lock (dirSnapGate) + { + return cachedDirSnap; + } + }); + } + + Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (name=\"{host.ServerName}\", map={mapKind}, seed={seed}, maxHumans={maxHumans}, lobby={startInLobby})"); double tickSec = ArenaSession.FixedDt; var sw = Stopwatch.StartNew(); double nextTickSec = sw.Elapsed.TotalSeconds; double endSec = durationSec > 0.0 ? durationSec : double.PositiveInfinity; + int lastReportedHumans = host.ConnectedHumanCount; + MatchPhase lastReportedPhase = host.Session.State.Phase; + ArenaMapKind lastReportedMap = host.Session.State.MapKind; + int lastReportedSeed = host.Session.State.Seed; + int lastReportedWave = host.Session.State.OrbitalDrop.CurrentWaveIndex; while (!cts.IsCancellationRequested && sw.Elapsed.TotalSeconds < endSec) { @@ -89,6 +144,31 @@ namespace RustToDust.Server if (nowSec >= nextTickSec) { host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + if (reporter is not null) + { + var state = host.Session.State; + int curHumans = host.ConnectedHumanCount; + int curWave = state.OrbitalDrop.CurrentWaveIndex; + if (curHumans != lastReportedHumans || + state.Phase != lastReportedPhase || + state.MapKind != lastReportedMap || + state.Seed != lastReportedSeed || + curWave != lastReportedWave) + { + lastReportedHumans = curHumans; + lastReportedPhase = state.Phase; + lastReportedMap = state.MapKind; + lastReportedSeed = state.Seed; + lastReportedWave = curWave; + DirectoryHeartbeatSnapshot updated = BuildSnapshot(host, publicHost); + lock (dirSnapGate) + { + cachedDirSnap = updated; + } + reporter.NotifyChanged(); + } + } + nextTickSec += tickSec; if (nowSec - nextTickSec > 0.25) { @@ -97,6 +177,7 @@ namespace RustToDust.Server } else { + host.PollStatelessPings(); double remainingMs = (nextTickSec - nowSec) * 1000.0; if (remainingMs > 2.0) { @@ -119,6 +200,7 @@ namespace RustToDust.Server } finally { + reporter?.Dispose(); Console.CancelKeyPress -= cancelHandler; AppDomain.CurrentDomain.ProcessExit -= exitHandler; } @@ -129,5 +211,13 @@ namespace RustToDust.Server private static double TryParseDouble(string? s, double fallback) => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ? v : fallback; + + private static bool TryParseBool(string? s, bool fallback) + { + if (string.IsNullOrWhiteSpace(s)) return fallback; + if (s == "1") return true; + if (s == "0") return false; + return bool.TryParse(s, out bool v) ? v : fallback; + } } } diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 9783dc0..ea6c642 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -35,9 +35,9 @@ namespace RustToDust.Ymir private long _forwardedPodEventId; private bool _disposed; - public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false) + public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false) { - State = new MatchState(seed, mapKind, skipInitialDrop); + State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby); Ordnance = new OrdnanceRuntime(this); _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count]; _forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0; @@ -124,6 +124,15 @@ namespace RustToDust.Ymir { State.GetOrCreateObserverState(contenderId); } + if (State.Lobby is { } lobby && contenderId >= 0 && contenderId < lobby.Slots.Length) + { + lobby.Slots[contenderId].IsHuman = isHuman; + lobby.Slots[contenderId].Callsign = c.Name; + if (!isHuman) + { + lobby.Slots[contenderId].IsReady = false; + } + } if (c.ActivePodId is { } activePodId) { for (int p = 0; p < State.OrbitalDrop.ActivePods.Count; p++) @@ -611,6 +620,14 @@ namespace RustToDust.Ymir SnapshotPreviousPoses(); + if (State.Phase == MatchPhase.Lobby) + { + MatchRules.AdvanceTracers(State, FixedDt); + MatchRules.AdvanceHitEvents(State, FixedDt); + FlushPodEventsToStepEvents(); + return; + } + State.Time += FixedDt; MatchRules.AdvanceTracers(State, FixedDt); MatchRules.AdvanceHitEvents(State, FixedDt); @@ -685,6 +702,38 @@ namespace RustToDust.Ymir PerfWeaponsMs += (t7 - t6) * toMs; } + public bool StartFromLobby(uint matchGeneration = 1) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (State.Phase != MatchPhase.Lobby) + { + return false; + } + + foreach (var kv in _contenderBodies) + { + _world.RemoveBody(kv.Value); + } + _contenderBodies.Clear(); + _contenderWalkers.Clear(); + + if (!State.StartFromLobby(QueryDropSurface)) + { + return false; + } + + SpawnContenderBodies(); + FlushPodEventsToStepEvents(); + _stepEvents.Add(new MatchStartedEvent + { + MatchGeneration = matchGeneration, + MapKind = (byte)State.MapKind, + Seed = State.Seed + }); + UpdateObserverDetectionMemories(); + return true; + } + public static void BuildStaticArena(Box3DSoaWorld world, MatchState state) { if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion) diff --git a/src/RustToDust.Ymir/LocalArenaSession.cs b/src/RustToDust.Ymir/LocalArenaSession.cs index c6b269d..38f05c3 100644 --- a/src/RustToDust.Ymir/LocalArenaSession.cs +++ b/src/RustToDust.Ymir/LocalArenaSession.cs @@ -27,9 +27,11 @@ namespace RustToDust.Ymir public ContenderState LocalContender => Inner.State.Contenders[0]; public ClientMatchOutcome LocalOutcome => - Inner.State.Phase == MatchPhase.Active - ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) - : (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); + Inner.State.Phase == MatchPhase.Lobby + ? ClientMatchOutcome.Active + : Inner.State.Phase == MatchPhase.Active + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + : (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.DetectedByCount : 0; @@ -46,6 +48,7 @@ namespace RustToDust.Ymir public IReadOnlyList ActivePods => Inner.State.OrbitalDrop.ActivePods; public DropWaveState DropWaveState => Inner.State.OrbitalDrop.WaveState; public IReadOnlyList PodEvents => Inner.State.PodEvents; + public LobbySnapshotDto? LobbyState => null; public bool IsContenderVisible(int contenderId) => true; public bool IsSpectatorVisible(int spectatorId) => true; @@ -104,6 +107,10 @@ namespace RustToDust.Ymir } } + public bool SetLobbyReady(bool ready) => false; + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false; + public bool RequestLobbyStart() => false; + public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) => Inner.GetInterpolatedContenderPose(contenderId, alpha); diff --git a/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs new file mode 100644 index 0000000..7704547 --- /dev/null +++ b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs @@ -0,0 +1,637 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Net.Sockets; +using System.Numerics; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Networking; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using RustToDust.Core; +using RustToDust.DirectoryService; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class LobbyAndDirectoryTests + { + private static async Task<(WebApplication App, string BaseUrl)> StartDirectoryServerAsync(DirectoryRegistryOptions? options = null) + { + var opts = options ?? new DirectoryRegistryOptions(); + var app = DirectoryApp.Build(Array.Empty(), opts); + app.Urls.Clear(); + app.Urls.Add("http://127.0.0.1:0"); + await app.StartAsync(); + string baseUrl = app.Urls.First(); + return (app, baseUrl); + } + + private static void PumpHostAndClients(ServerMatchHost host, params RemoteArenaSession[] clients) + { + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + host.StepOnce(nowMs); + for (int i = 0; i < clients.Length; i++) + { + clients[i].PumpNetwork(nowMs); + } + } + + private static void PumpListenHostAndClient(ListenHostArenaSession listenHost, RemoteArenaSession client, int ticks = 1) + { + for (int i = 0; i < ticks; i++) + { + listenHost.SubmitLocalInput(default, isPhysicsTick: true); + client.PumpNetwork(); + Thread.Sleep(2); + } + } + + [Fact] + public async Task Directory_Heartbeat_LeaseTokenSecrecy_AuthRejection_LoopbackSpoof_And_TtlExpiry() + { + var now = DateTimeOffset.UtcNow; + var opts = new DirectoryRegistryOptions + { + EntryTtl = TimeSpan.FromMilliseconds(350), + ReaperInterval = TimeSpan.FromMilliseconds(60), + UtcNow = () => now + }; + + var (app, baseUrl) = await StartDirectoryServerAsync(opts); + try + { + using var http = new HttpClient { BaseAddress = new Uri(baseUrl) }; + + // 1. Register with empty publicHost behind simulated nginx X-Real-IP -> auto-resolves to caller IP + using var regReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat") + { + Content = JsonContent.Create(new DirectoryHeartbeatRequest + { + Name = "Yggdrasil Ring", + PublicHost = "", + UdpPort = 3076, + Map = "sion", + Seed = 77, + Humans = 2, + MaxHumans = 12, + Phase = "Lobby", + Wave = 0 + }) + }; + regReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42"); + using var regResp = await http.SendAsync(regReq); + Assert.Equal(HttpStatusCode.OK, regResp.StatusCode); + + var ack = await regResp.Content.ReadFromJsonAsync(); + Assert.NotNull(ack); + Assert.NotEqual(Guid.Empty, ack!.ServerId); + Assert.False(string.IsNullOrWhiteSpace(ack.LeaseToken)); + Assert.True(ack.TtlSeconds >= 1); + + // 2. GET /api/v1/servers returns resolved publicHost and NEVER exposes leaseToken + string rawListJson = await http.GetStringAsync("/api/v1/servers"); + Assert.DoesNotContain(ack.LeaseToken, rawListJson, StringComparison.Ordinal); + + var list = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); + Assert.Single(list); + Assert.Equal(ack.ServerId, list[0].ServerId); + Assert.Equal("203.0.113.42", list[0].PublicHost); + Assert.Equal("sion", list[0].Map); + Assert.Equal("Lobby", list[0].Phase); + + // 3. Non-loopback X-Real-IP attempting to spoof loopback publicHost is rejected (400) + foreach (string spoofHost in new[] { "127.0.0.1", "localhost", "::1" }) + { + using var spoofReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat") + { + Content = JsonContent.Create(new DirectoryHeartbeatRequest + { + Name = "Spoofed", + PublicHost = spoofHost, + UdpPort = 3076 + }) + }; + spoofReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42"); + using var spoofResp = await http.SendAsync(spoofReq); + Assert.Equal(HttpStatusCode.BadRequest, spoofResp.StatusCode); + } + + // 4. Wrong leaseToken on refresh -> 403, entry stays intact + using var badRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest + { + ServerId = ack.ServerId, + LeaseToken = "wrong-token-value", + Name = "Hijacked", + PublicHost = "203.0.113.42", + UdpPort = 3076 + }); + Assert.Equal(HttpStatusCode.Forbidden, badRefresh.StatusCode); + + // 5. Wrong leaseToken on DELETE -> 403, entry stays intact + using var badDeleteReq = new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/servers/{ack.ServerId}"); + badDeleteReq.Headers.TryAddWithoutValidation("X-Lease-Token", "wrong-token-value"); + using var badDeleteResp = await http.SendAsync(badDeleteReq); + Assert.Equal(HttpStatusCode.Forbidden, badDeleteResp.StatusCode); + + var stillPresent = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); + Assert.Single(stillPresent); + Assert.Equal("Yggdrasil Ring", stillPresent[0].Name); + + // 6. Valid leaseToken refresh succeeds and keeps entry alive + using var goodRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest + { + ServerId = ack.ServerId, + LeaseToken = ack.LeaseToken, + Name = "Yggdrasil Ring Updated", + PublicHost = "203.0.113.42", + UdpPort = 3076, + Humans = 5, + Phase = "Active", + Wave = 1 + }); + Assert.Equal(HttpStatusCode.OK, goodRefresh.StatusCode); + + // 7. Advance clock past TTL -> entry expires cleanly and disappears + now = now + TimeSpan.FromMilliseconds(500); + await Task.Delay(150); + var afterExpiry = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); + Assert.Empty(afterExpiry); + } + finally + { + await app.StopAsync(); + await app.DisposeAsync(); + } + } + + [Fact] + public async Task DirectoryReporter_Registers_Updates_And_DeregistersOnDispose() + { + var (app, baseUrl) = await StartDirectoryServerAsync(); + try + { + int humans = 1; + string phase = "Lobby"; + + var reporter = new DirectoryReporter( + baseUrl, + () => new DirectoryHeartbeatSnapshot( + "Reporter Test Ring", + "127.0.0.1", + 3079, + "desert", + 42, + humans, + 12, + phase, + 0), + heartbeatInterval: TimeSpan.FromSeconds(30)); + + try + { + var deadline = DateTime.UtcNow.AddSeconds(15); + IReadOnlyList servers = Array.Empty(); + while (DateTime.UtcNow < deadline) + { + servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl); + if (servers.Count > 0) break; + await Task.Delay(25); + } + + Assert.Single(servers); + Assert.Equal("Reporter Test Ring", servers[0].Name); + Assert.Equal(1, servers[0].Humans); + + humans = 4; + phase = "Active"; + reporter.NotifyChanged(); + + deadline = DateTime.UtcNow.AddSeconds(15); + while (DateTime.UtcNow < deadline) + { + servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl); + if (servers.Count == 1 && servers[0].Humans == 4 && servers[0].Phase == "Active") break; + await Task.Delay(25); + } + Assert.Equal(4, servers[0].Humans); + Assert.Equal("Active", servers[0].Phase); + } + finally + { + await reporter.DisposeAsync(); + } + + var afterDispose = await DirectoryBrowserClient.FetchServersAsync(baseUrl); + Assert.Empty(afterDispose); + } + finally + { + await app.StopAsync(); + await app.DisposeAsync(); + } + } + + [Fact] + public async Task StatelessUdpPing_CoexistsWithActiveRemoteSession_AndHandlesMalformedPingsSafely() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 77, + mapKind: ArenaMapKind.Desert, + serverName: "Ping Coexistence Arena", + startInLobby: false); + using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "ProbePilot"); + + var joinDeadline = DateTime.UtcNow.AddSeconds(3); + while (!client.IsJoined && DateTime.UtcNow < joinDeadline) + { + PumpHostAndClients(host, client); + await Task.Delay(5); + } + Assert.True(client.IsJoined); + + // Drive and fire concurrently on the active RUDP session while probing RTDP pings + for (int i = 0; i < 15; i++) + { + client.SubmitLocalInput(new PlayerInput(1f, 0.25f, 30f, 40f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true); + PumpHostAndClients(host, client); + } + + var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + var pingTask = Task.Run(async () => + { + var results = new List(4); + for (int i = 0; i < 4; i++) + { + results.Add(await ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2))); + } + return results; + }); + + while (!pingTask.IsCompleted) + { + client.SubmitLocalInput(new PlayerInput(0.8f, -0.1f, 25f, 35f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true); + PumpHostAndClients(host, client); + await Task.Delay(3); + } + + var pingResults = await pingTask; + Assert.Equal(4, pingResults.Count); + foreach (var r in pingResults) + { + Assert.True(r.Success, "Expected stateless RTDP ping to succeed alongside active RUDP session"); + Assert.True(r.Summary.HasValue); + Assert.Equal("Ping Coexistence Arena", r.Summary!.Value.ServerName); + Assert.Equal(1, r.Summary.Value.Humans); + Assert.Equal(12, r.Summary.Value.MaxHumans); + Assert.Equal(MatchPhase.Active, r.Summary.Value.Phase); + Assert.Equal(ArenaMapKind.Desert, r.Summary.Value.MapKind); + Assert.Equal(77, r.Summary.Value.Seed); + Assert.True(r.Summary.Value.AcceptingJoin); + Assert.True(SnapshotCodec.EncodePong(r.Summary.Value).Length < 110); + } + + Assert.Equal(0, host.TransportPacketsDropped); + Assert.True(client.ConnectionStatus.Connected); + + // Send truncated "RTDP" packet (< 16B) and bogus magic packet; host must not crash or drop RUDP peer + using (var rawSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) + { + byte[] truncatedPing = Encoding.ASCII.GetBytes("RTDP\x01\x01short"); // 11 bytes + rawSock.SendTo(truncatedPing, target); + for (int i = 0; i < 4; i++) + { + PumpHostAndClients(host, client); + await Task.Delay(2); + } + Assert.Equal(0, host.TransportPacketsDropped); + + byte[] bogusMagic = Encoding.ASCII.GetBytes("JUNK_NOT_RTDP_OR_CNR0_PAYLOAD_DATA"); + rawSock.SendTo(bogusMagic, target); + for (int i = 0; i < 4; i++) + { + PumpHostAndClients(host, client); + await Task.Delay(2); + } + } + + Assert.True(client.IsJoined); + Assert.True(client.ConnectionStatus.Connected); + + // Valid ping still succeeds after malformed datagrams + var finalPingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)); + while (!finalPingTask.IsCompleted) + { + PumpHostAndClients(host, client); + await Task.Delay(2); + } + var finalPing = await finalPingTask; + Assert.True(finalPing.Success); + } + + [Fact] + public void Lobby_NonHostConfigAndStartRejected_AndLocalOutcomeIsActive() + { + using var listenHost = new ListenHostArenaSession( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + serverName: "Host Authority Lobby"); + using var client = new RemoteArenaSession( + new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), + "Guest"); + + var joinDeadline = DateTime.UtcNow.AddSeconds(3); + while (!client.IsJoined && DateTime.UtcNow < joinDeadline) + { + PumpListenHostAndClient(listenHost, client); + } + Assert.True(client.IsJoined); + + Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase); + Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); + Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome); + Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); + + // Guest attempts unauthorized config change and launch + Assert.True(client.RequestLobbyConfig(999, ArenaMapKind.Sion)); + Assert.True(client.RequestLobbyStart()); + PumpListenHostAndClient(listenHost, client, ticks: 15); + + Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase); + Assert.Equal(ArenaMapKind.Desert, listenHost.ViewState.MapKind); + Assert.Equal(42, listenHost.ViewState.Seed); + Assert.Null(listenHost.LobbyState?.CountdownSeconds); + Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); + Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); + } + + [Fact] + public void Lobby_CountdownStartsWhenAllReady_CancelsOnUnready_AndResetsOnMapSwitch() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + allowClientReset: true, + startInLobby: true, + minHumansToStart: 2); + using var peerA = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Alpha"); + using var peerB = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Bravo"); + + var deadline = DateTime.UtcNow.AddSeconds(3); + while ((!peerA.IsJoined || !peerB.IsJoined) && DateTime.UtcNow < deadline) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(3); + } + Assert.True(peerA.IsJoined); + Assert.True(peerB.IsJoined); + + // Peer A readies up; Peer B not ready -> no countdown yet + Assert.True(peerA.SetLobbyReady(true)); + for (int i = 0; i < 10; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + Assert.Null(host.Lobby?.CountdownSeconds); + + // Peer B readies up -> countdown starts + Assert.True(peerB.SetLobbyReady(true)); + for (int i = 0; i < 15; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + Assert.NotNull(host.Lobby?.CountdownSeconds); + Assert.True(host.Lobby!.CountdownSeconds!.Value > 0f && host.Lobby.CountdownSeconds.Value < 5.0f); + Assert.NotNull(peerA.LobbyState?.CountdownSeconds); + + // Peer B un-readies -> countdown cancels and Wave 0 does NOT launch + Assert.True(peerB.SetLobbyReady(false)); + for (int i = 0; i < 15; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + Assert.Null(host.Lobby?.CountdownSeconds); + Assert.Null(peerA.LobbyState?.CountdownSeconds); + Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase); + Assert.Empty(host.Session.State.OrbitalDrop.ActivePods); + + // Authorized config switch in Lobby resets ready flags and syncs all peers + Assert.True(peerA.SetLobbyReady(true)); + for (int i = 0; i < 6; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + + Assert.True(host.ConfigureLobby(peerA.LocalContenderId, 99, ArenaMapKind.Sion)); + for (int i = 0; i < 15; i++) + { + PumpHostAndClients(host, peerA, peerB); + Thread.Sleep(2); + } + + Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase); + Assert.Equal(ArenaMapKind.Sion, host.Session.State.MapKind); + Assert.Equal(99, host.Session.State.Seed); + Assert.Equal(ArenaMapKind.Sion, peerA.ViewState.MapKind); + Assert.Equal(99, peerA.ViewState.Seed); + Assert.Equal(ArenaMapKind.Sion, peerB.ViewState.MapKind); + Assert.Equal(99, peerB.ViewState.Seed); + Assert.All(host.Lobby!.Slots.Where(s => s.IsHuman), s => Assert.False(s.IsReady)); + Assert.Equal(ClientMatchOutcome.Active, peerA.LocalOutcome); + Assert.Equal(ClientMatchOutcome.Active, peerB.LocalOutcome); + } + + [Fact] + public void Lobby_IdleClientKeptAlivePastIdleTimeout_WithActiveOutcome() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true); + using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "IdlePilot"); + + long simNowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + for (int i = 0; i < 100 && !client.IsJoined; i++) + { + simNowMs += 20; + host.StepOnce(simNowMs); + client.PumpNetwork(simNowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + + // Advance 8.5 seconds (> IdleTimeoutMs 5000ms and > ClientDisconnectTimeoutMs 6000ms) with ZERO SubmitLocalInput + for (int step = 0; step < 170; step++) + { + simNowMs += 50; + host.StepOnce(simNowMs); + client.PumpNetwork(simNowMs); + } + + Assert.True(client.IsJoined); + Assert.True(client.ConnectionStatus.Connected); + Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); + Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); + Assert.Equal(1, host.ConnectedHumanCount); + } + + [Fact] + public void Lobby_SynchronizedLaunch_TransitionsToActiveAndDropsWave0AcrossHostAndRemote() + { + using var listenHost = new ListenHostArenaSession( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + minHumansToStart: 2); + using var remote = new RemoteArenaSession( + new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), + "DropMate"); + + var deadline = DateTime.UtcNow.AddSeconds(3); + while (!remote.IsJoined && DateTime.UtcNow < deadline) + { + PumpListenHostAndClient(listenHost, remote); + } + Assert.True(remote.IsJoined); + + Assert.True(listenHost.SetLobbyReady(true)); + Assert.True(remote.SetLobbyReady(true)); + + // Step 320 ticks (~5.33s at 60Hz) so the 5.0s countdown completes cleanly + for (int tick = 0; tick < 330; tick++) + { + listenHost.SubmitLocalInput(default, isPhysicsTick: true); + remote.PumpNetwork(); + if (listenHost.ViewState.Phase == MatchPhase.Active && + remote.ViewState.Phase == MatchPhase.Active && + remote.ActivePods.Count > 0) + { + break; + } + Thread.Sleep(1); + } + + // Pump a few extra frames to ensure all Wave 0 reliable events arrive on remote + PumpListenHostAndClient(listenHost, remote, ticks: 10); + + Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase); + Assert.Equal(MatchPhase.Active, remote.ViewState.Phase); + Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome); + Assert.Equal(ClientMatchOutcome.Active, remote.LocalOutcome); + + Assert.True(listenHost.ActivePods.Count >= MatchState.ContenderCount); + Assert.Equal(ContenderLifecycle.Deploying, listenHost.LocalContender.Lifecycle); + Assert.Equal(ContenderLifecycle.Deploying, remote.LocalContender.Lifecycle); + Assert.Contains(remote.ActivePods, p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == remote.LocalContenderId); + + var remoteEvents = new List(); + remote.DrainSimEvents(remoteEvents); + Assert.Contains(remoteEvents, e => e is MatchStartedEvent); + } + + [Fact] + public void CorePvs_RoundTripsMatchPhaseLobby_Within1152Bytes() + { + var state = new MatchState(seed: 42, ArenaMapKind.Desert, startInLobby: true); + var local = state.Contenders[0]; + local.Grid.SwapChassis(Catalog.Bastion); + + var contenders = new List(12); + var walkers = new List(12); + var specs = new List(10); + + for (int i = 0; i < 12; i++) + { + contenders.Add(new NetContenderState + { + SlotId = (byte)i, + Alive = true, + IsHuman = i < 2, + Lifecycle = ContenderLifecycle.Deploying, + Pos = new Vector3(i * 10f, 3f, -i * 5f), + Rot = Quaternion.Identity, + Vel = Vector3.Zero, + CoreHpRatio = 1f + }); + var ws = new WalkerVisualSnapshot { LegCount = 4 }; + walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); + } + + byte[] payload = SnapshotCodec.EncodeCorePvs( + 1, 5, 10, 0f, 0, 0, 772f, MatchPhase.Lobby, null, 0, 0xFFF, + local, Vector3.Zero, contenders, walkers, specs); + byte[] wireFrame = SnapshotCodec.WrapLatest(payload, 1, 5); + byte[] rudpDatagram = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket + { + ConnectionId = 0x52544431, + PacketType = CultNetRudpPacketType.Data, + ChannelId = SnapshotCodec.ChannelLatest, + Sequence = 5, + Sequenced = true, + Payload = wireFrame + }); + + Assert.True(rudpDatagram.Length <= SnapshotCodec.MaxLatestDatagramBytes, + $"Lobby CorePvs UDP datagram {rudpDatagram.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + + Assert.True(SnapshotCodec.TryDecodeCorePvs(payload, out var decoded)); + Assert.Equal(MatchPhase.Lobby, decoded.Phase); + Assert.Null(decoded.WinnerContenderId); + + // Also verify Completed + WinnerContenderId still round-trips via bit 2 (0x04) + byte[] completedPayload = SnapshotCodec.EncodeCorePvs( + 1, 6, 12, 100f, 0, 0, 120f, MatchPhase.Completed, 3, 0, 0xFFF, + local, Vector3.Zero, contenders, walkers, specs); + Assert.True(SnapshotCodec.TryDecodeCorePvs(completedPayload, out var decodedCompleted)); + Assert.Equal(MatchPhase.Completed, decodedCompleted.Phase); + Assert.Equal(3, decodedCompleted.WinnerContenderId); + } + + [Fact] + public async Task StatelessUdpPing_HandlesMultiByteUtf8ServerName_WithoutOverflow() + { + string multiByteName = new string('\u2022', 24); + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 77, + mapKind: ArenaMapKind.Desert, + serverName: multiByteName, + startInLobby: true); + + var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + var pingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)); + while (!pingTask.IsCompleted) + { + host.PollStatelessPings(); + await Task.Delay(5); + } + + var res = await pingTask; + Assert.True(res.Success); + Assert.NotNull(res.Summary); + Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName); + } + } +} diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj index 81797aa..e2ea589 100644 --- a/tests/RustToDust.Tests/RustToDust.Tests.csproj +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -9,6 +9,7 @@ + @@ -23,6 +24,7 @@ +