RustToDust/client/Main.cs

2333 lines
92 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using Godot;
using RustToDust.Core;
using RustToDust.Net;
using RustToDust.Ymir;
namespace RustToDust.Client;
public enum ClientScreenMode
{
MainMenu,
ServerBrowser,
Lobby,
InMatch,
PauseOverlay,
Settings
}
/// <summary>
/// Root Godot node for Rust to Dust.
/// Godot physics is Dummy; <see cref="IClientArenaSession"/> drives Solo (<see cref="LocalArenaSession"/>),
/// Listen-Host (<see cref="ListenHostArenaSession"/>), or Remote (<see cref="RemoteArenaSession"/>) play.
/// </summary>
public partial class Main : Node3D
{
private const ulong ContenderStableIdBase = 1000UL;
private const int DefaultNetPort = 3076;
private TerrainRenderer _terrain = null!;
private SionMapRenderer _sionMap = null!;
private ArenaRenderer _arena = null!;
private ArenaAudioSystem _audio = null!;
private Camera3D _camera = null!;
private Hud _hud = null!;
private AtmosphereSystem _atmosphere = null!;
private MainMenu _mainMenu = null!;
private SettingsOverlay _settingsOverlay = null!;
private ServerBrowser _serverBrowser = null!;
private LobbyScreen _lobbyScreen = null!;
private GraphicsSettings _graphicsSettings = new();
private IClientArenaSession? _session;
private MatchState? _boundViewState;
private bool _wasNetConnected;
private ClientScreenMode _screenMode = ClientScreenMode.MainMenu;
private ClientScreenMode _settingsReturnMode = ClientScreenMode.MainMenu;
private bool _hasWindowOverride;
private DirectoryReporter? _directoryReporter;
private string _directoryUrl = ServerBrowser.DefaultDirectoryUrl;
private string _publicHostOverride = "auto";
private string _serverName = "Rust to Dust";
private DirectoryHeartbeatSnapshot _cachedDirectorySnapshot;
private readonly object _dirSnapGate = new();
private int _lastDirHumans = -1;
private MatchPhase _lastDirPhase = (MatchPhase)(-1);
private ArenaMapKind _lastDirMap = (ArenaMapKind)(-1);
private int _lastDirSeed;
private SionMapData? _menuSionData;
private TerrainField? _menuSionTerrain;
private int _menuPreviewTargetFrames;
private int _menuPreviewFrames;
private string? _menuPreviewOut;
private readonly WalkerFootstepTracker _footsteps = new();
private readonly CameraJuiceState _camJuice = new();
private readonly List<ISimEvent> _frameEvents = new(128);
private readonly List<FootstepPulse> _frameFootsteps = new(32);
private ArenaMapKind _mapKind = ArenaMapKind.Sion;
private byte _squadSize = 3;
private string _callsign = "Pilot";
private string _lastEndpoint = $"127.0.0.1:{DefaultNetPort}";
private PlayerInput? _scriptedInput;
private float _cameraYaw;
private float _cameraPitch = Mathf.DegToRad(5f);
private float _cameraZoom = 1.0f;
private float _smoothedShoulderY;
private string? _lastCamChassisId;
private float _orbitalPodCamBlend;
private ContenderLifecycle _prevLocalLifecycle = ContenderLifecycle.Active;
private MeshInstance3D _dropReticleMesh = null!;
private Vector3 _baseCamPos;
private Vector3 _baseLookDir = Vector3.Forward;
private bool _hasBaseCamPose;
private float _elapsedSeconds;
private bool _interactQueued;
private int _seed = 42;
// Temporary Step 1/Step 3 perf probe (enabled only when RTD_PERF_FRAMES is set)
private int _perfTargetFrames;
private int _perfFrameCount;
private int _perfWaitConnectFrames;
private int _perfPhysicsTicks;
private long _perfLastFrameTick;
private int _perfLastDirtyRebakes;
private readonly List<double> _perfFrameMs = new();
private readonly List<double> _perfPhysicsStepMs = new();
private readonly List<double> _perfTerrainSyncMs = new();
private readonly List<double> _perfArenaSyncMs = new();
private readonly List<double> _perfHudMs = new();
private readonly List<int> _perfDirtyRebakeDelta = new();
private readonly List<double> _perfDrawCalls = new();
private readonly List<double> _perfPrimitives = new();
private readonly List<double> _perfObjects = new();
private readonly List<double> _perfNodeCount = new();
private readonly List<double> _perfTimeProcess = new();
private readonly List<double> _perfTimePhysicsProcess = new();
private readonly List<double> _perfViewportGpuMs = new();
private double _perfPendingStepMs;
private double _perfPendingTerrainMs;
private double _perfPendingArenaMs;
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;
public ArenaAudioSystem Audio => _audio;
public WalkerFootstepTracker Footsteps => _footsteps;
public CameraJuiceState CameraJuice => _camJuice;
public Camera3D Camera => _camera;
public Hud Hud => _hud;
public AtmosphereSystem Atmosphere => _atmosphere;
public MainMenu MainMenuOverlay => _mainMenu;
public SettingsOverlay SettingsOverlay => _settingsOverlay;
public GraphicsSettings GraphicsSettings => _graphicsSettings;
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;
internal Vector3 BaseCameraPosition => _baseCamPos;
internal Vector3 BaseCameraLookDir => _baseLookDir;
internal (float AimX, float AimY, float AimZ) ProbeCenterScreenAim() => ComputeCenterScreenAim();
public override void _Ready()
{
ClientAssets.EnsureAssetsRootRegistered();
GetViewport().UseTaa = true;
_graphicsSettings = GraphicsSettings.Load(ResolveGraphicsSettingsPath());
ApplyGraphicsEnvOverrides(_graphicsSettings);
_graphicsSettings.Changed += OnGraphicsSettingsChanged;
_atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" };
AddChild(_atmosphere);
_atmosphere.EnsureInitialized();
_atmosphere.ApplyGraphicsSettings(_graphicsSettings);
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
_sionMap = new SionMapRenderer { Name = "SionMap" };
AddChild(_sionMap);
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
_arena.AssetCache.PreloadAll();
_atmosphere.BindEmitterPool(_arena.Volumetrics);
_audio = new ArenaAudioSystem { Name = "ArenaAudio" };
AddChild(_audio);
_camera = new Camera3D
{
Name = "ShoulderCamera",
Current = true,
Fov = 58f,
Far = 4800f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw, ProjectWorldToHud) { Name = "Hud" };
_hud.JoinRequested += OnJoinRequested;
_hud.HostRequested += OnHostRequested;
_hud.SoloRequested += OnSoloRequested;
_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;
_mainMenu.SettingsRequested += OpenSettingsFromCurrentScreen;
AddChild(_mainMenu);
_settingsOverlay = new SettingsOverlay { Name = "SettingsOverlay" };
_settingsOverlay.SetGraphicsValues(
_graphicsSettings.VfxResolution,
_graphicsSettings.VolumetricSamples,
_graphicsSettings.SdfgiQuality,
_graphicsSettings.BorderlessFullscreen);
_settingsOverlay.GraphicsChanged += (res, samples, sdfgi, fullscreen) =>
_graphicsSettings.Apply(res, samples, sdfgi, fullscreen, persist: !IsAutomatedRun);
_settingsOverlay.ResetDefaultsRequested += () =>
_graphicsSettings.ResetToDefaults(persist: !IsAutomatedRun);
_settingsOverlay.BackRequested += CloseSettings;
AddChild(_settingsOverlay);
_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,
Transparency = BaseMaterial3D.TransparencyEnum.Alpha,
AlbedoColor = new Color(0.27f, 0.85f, 0.91f, 0.82f),
NoDepthTest = false,
CullMode = BaseMaterial3D.CullModeEnum.Disabled
};
_dropReticleMesh = new MeshInstance3D
{
Name = "DropLandingReticle",
Mesh = new TorusMesh { InnerRadius = 2.5f, OuterRadius = 3.05f, Rings = 28, RingSegments = 8 },
MaterialOverride = reticleMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
Visible = false
};
AddChild(_dropReticleMesh);
string? cliConnect = GetCliArg("--connect");
string? cliHost = GetCliArg("--host", allowBareFlag: true);
string? cliName = GetCliArg("--name");
string? cliMap = GetCliArg("--map");
string? cliSeed = GetCliArg("--seed");
string? cliSquadSize = GetCliArg("--squad-size");
if (int.TryParse(cliSquadSize ?? System.Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedSquad))
{
_squadSize = (byte)Math.Clamp(parsedSquad, 1, 4);
}
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))
{
_callsign = cliName.Trim();
}
else if (System.Environment.GetEnvironmentVariable("RTD_NAME") is { Length: > 0 } envName)
{
_callsign = envName.Trim();
}
if (int.TryParse(cliSeed ?? System.Environment.GetEnvironmentVariable("RTD_SEED"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedSeed))
{
_seed = parsedSeed;
}
if (InitialMapKindOverride.HasValue)
{
_mapKind = InitialMapKindOverride.Value;
}
else
{
string? mapVal = cliMap ?? System.Environment.GetEnvironmentVariable("RTD_MAP");
_mapKind = string.Equals(mapVal, "desert", StringComparison.OrdinalIgnoreCase)
? ArenaMapKind.Desert
: ArenaMapKind.Sion;
}
string? connectTarget = !string.IsNullOrWhiteSpace(cliConnect)
? cliConnect
: System.Environment.GetEnvironmentVariable("RTD_CONNECT");
string? hostTarget = cliHost is not null
? cliHost
: (System.Environment.GetEnvironmentVariable("RTD_HOST_PORT") ?? System.Environment.GetEnvironmentVariable("RTD_HOST"));
if (!string.IsNullOrWhiteSpace(connectTarget))
{
_lastEndpoint = connectTarget.Trim();
}
else if (!string.IsNullOrWhiteSpace(hostTarget))
{
_lastEndpoint = hostTarget.Contains(':', StringComparison.Ordinal)
? hostTarget.Trim()
: $"127.0.0.1:{hostTarget.Trim()}";
}
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
{
_perfTargetFrames = perfFrames;
ArenaSession.PerfEnabled = true;
RenderingServer.ViewportSetMeasureRenderTime(GetViewport().GetViewportRid(), true);
if (_atmosphere.VolumetricEffect is not null)
{
_atmosphere.VolumetricEffect.ProfilingEnabled = true;
}
if (_hud?.HbCanvas is not null)
{
_hud.HbCanvas.ProfilingEnabled = true;
}
}
else if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"), out int autoExitFrames) && autoExitFrames > 0)
{
_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");
_hasWindowOverride = GetCliArg("--windowed", allowBareFlag: true) is not null
|| GetCliArg("--resolution", allowBareFlag: true) is not null
|| GetCliArg("-w", allowBareFlag: true) is not null;
if (!IsAutomatedRun && !_hasWindowOverride)
{
ApplyWindowMode(_graphicsSettings.BorderlessFullscreen);
}
else
{
if (IsAutomatedRun && DisplayServer.GetName() != "headless")
{
DisplayServer.WindowSetFlag(DisplayServer.WindowFlags.NoFocus, true);
}
if (_hasWindowOverride && DisplayServer.GetName() != "headless")
{
var winMode = DisplayServer.WindowGetMode();
bool actualFullscreen = winMode == DisplayServer.WindowMode.Fullscreen
|| winMode == DisplayServer.WindowMode.ExclusiveFullscreen;
_graphicsSettings.SetBorderlessFullscreen(actualFullscreen, persist: false);
}
}
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, fromBrowser: false);
}
else if (hostTarget is not null)
{
StartListenHostSession(
hostTarget,
_callsign,
_mapKind,
_serverName,
startInLobby: cliLobby,
listOnPublicDirectory: false,
fallbackToLocalOnFailure: true);
}
else if (autoBypassMenu)
{
Reset(_seed, _mapKind, skipInitialDrop);
}
else
{
EnterMainMenuBackdrop();
}
if (perfCombat && _session is not null)
{
SetupPerfCombatScenario(_session);
}
_perfLastFrameTick = Stopwatch.GetTimestamp();
_perfLastDirtyRebakes = _terrain.DirtyRebakes;
TerrainRenderer.PerfBakeTileMs = 0;
TerrainRenderer.PerfBakeTileCalls = 0;
VehicleVisualInstance.PerfDamageHeatMs = 0;
VehicleVisualInstance.PerfMaterialDupCount = 0;
}
private void SetupPerfCombatScenario(IClientArenaSession session)
{
if (session is LocalArenaSession local)
{
var inner = local.Inner;
var p = inner.State.Contenders[0];
float fwdX = MathF.Sin(p.Yaw);
float fwdZ = MathF.Cos(p.Yaw);
float rightX = -fwdZ;
float rightZ = fwdX;
for (int i = 1; i <= 8 && i < inner.State.Contenders.Count; i++)
{
float dist = 65f + (i % 4) * 11f;
float lat = (i - 4.5f) * 11f;
float tx = p.X + fwdX * dist + rightX * lat;
float tz = p.Z + fwdZ * dist + rightZ * lat;
inner.SetContenderPose(inner.State.Contenders[i].Id, tx, tz, p.Yaw + MathF.PI);
}
for (int i = 0; i < 6 && i < inner.State.Spectators.Spectators.Count; i++)
{
var s = inner.State.Spectators.Spectators[i];
float dist = 78f + (i % 3) * 12f;
float lat = (i - 2.5f) * 16f;
float sx = p.X + fwdX * dist + rightX * lat;
float sz = p.Z + fwdZ * dist + rightZ * lat;
inner.SetSpectatorPose(s.Id, sx, sz, p.Yaw + MathF.PI);
inner.State.Spectators.OnSpectatorDamaged(s, p.Id);
}
var aimTarget = inner.State.Contenders[1];
_scriptedInput = new PlayerInput(
Throttle: 0.4f,
Steer: 0f,
AimWorldX: aimTarget.X,
AimWorldZ: aimTarget.Z,
Fire: true,
InteractPickup: false,
Brake: false);
_arena.Sync(session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
_hud.Sync(session);
return;
}
var localC = session.LocalContender;
_scriptedInput = new PlayerInput(
Throttle: 0.4f,
Steer: 0.12f,
AimWorldX: localC.X + MathF.Sin(localC.Yaw) * 60f,
AimWorldZ: localC.Z + MathF.Cos(localC.Yaw) * 60f,
Fire: true,
InteractPickup: false,
Brake: false);
}
public override void _ExitTree()
{
DisposeSessionAndDirectory();
}
public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false, byte? squadSize = null)
{
_seed = seed;
if (mapKind.HasValue)
{
_mapKind = mapKind.Value;
}
if (squadSize.HasValue)
{
_squadSize = (byte)Math.Clamp((int)squadSize.Value, 1, 4);
}
DisposeSessionAndDirectory();
Failure = null;
_hud.SetNetworkError(null);
try
{
_session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop, squadSize: _squadSize);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
catch (Exception ex)
{
Failure = ex.Message;
GD.PushError("LocalArenaSession startup failed: " + ex);
}
}
private void EnterMainMenuBackdrop()
{
DisposeSessionAndDirectory();
Failure = null;
_hud.SetNetworkError(null);
EnsureMenuSionBackdrop();
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize);
_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.LoadSharedHeightmap(
_menuSionData.Metadata.SizeMeters,
_menuSionData.Metadata.GridRes,
_menuSionData.Metadata.TileGrid,
_menuSionData.BaseDem,
_menuSionData.BaseDemMinY,
_menuSionData.BaseDemScale,
_menuSionData.Metadata.MinY,
_menuSionData.Metadata.MaxY,
42UL);
_terrain.Visible = true;
_sionMap.Visible = true;
_arena.Visible = false;
_dropReticleMesh.Visible = false;
_camera.Far = 4200f;
_atmosphere.ApplyMap(ArenaMapKind.Sion);
_sionMap.EnsureBuilt(_menuSionData);
UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_menuSionTerrain, _menuSionData);
_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.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.ServerBrowser:
_hud.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(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.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(true);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.InMatch:
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
_hud.SetInputBlocked(false);
break;
case ClientScreenMode.PauseOverlay:
_settingsOverlay.SetSettingsVisible(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
_hud.SetInputBlocked(true);
_mainMenu.SetPauseContext(BuildPauseContextLine());
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.PauseOverlay);
break;
case ClientScreenMode.Settings:
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
bool showMatchBehind = _settingsReturnMode == ClientScreenMode.PauseOverlay;
_arena.Visible = showMatchBehind;
_hud.SetMatchHudActive(showMatchBehind);
if (!showMatchBehind)
{
_dropReticleMesh.Visible = false;
}
_settingsOverlay.SetGraphicsValues(
_graphicsSettings.VfxResolution,
_graphicsSettings.VolumetricSamples,
_graphicsSettings.SdfgiQuality,
_graphicsSettings.BorderlessFullscreen);
_settingsOverlay.SetSettingsVisible(true);
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,
byte? squadSize = null)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim();
string cleanServerName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim();
byte activeSquadSize = (byte)Math.Clamp((int)(squadSize ?? _squadSize), 1, 4);
_squadSize = activeSquadSize;
Failure = null;
_hud.SetNetworkError(null);
_mainMenu.SetHostError(null);
try
{
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,
squadSize: activeSquadSize);
hostSession.Host.Session.SetHumanSlot(0, true, nextCallsign);
DisposeSessionAndDirectory();
_session = hostSession;
_callsign = nextCallsign;
_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);
}
catch (Exception ex)
{
Failure = ex.Message;
if (fallbackToLocalOnFailure && _session is null)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize);
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, bool fromBrowser)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
Failure = null;
_hud.SetNetworkError(null);
_serverBrowser.SetError(null);
try
{
IPEndPoint ep = ResolveEndPoint(endpointText, DefaultNetPort);
var remote = new RemoteArenaSession(ep, nextCallsign);
remote.PumpNetwork();
DisposeSessionAndDirectory();
_session = remote;
_callsign = nextCallsign;
_lastEndpoint = endpointText.Trim();
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
SetScreenMode(fromBrowser ? ClientScreenMode.Lobby : ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
catch (Exception ex)
{
Failure = ex.Message;
if (!fromBrowser && _session is null && _screenMode == ClientScreenMode.InMatch)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize);
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, byte squadSize)
{
_callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
Reset(_seed, mapKind, skipInitialDrop: false, squadSize: _squadSize);
}
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, byte squadSize)
{
string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND");
string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture);
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
StartListenHostSession(
hostArg,
callsign,
mapKind,
serverName,
startInLobby: true,
listOnPublicDirectory: listOnPublicDirectory,
fallbackToLocalOnFailure: false,
squadSize: _squadSize);
}
private void OnBrowserJoinRequested(string endpointText, string callsign)
{
StartRemoteSession(endpointText, callsign, fromBrowser: true);
}
private void OnSoloRequested()
{
Reset(_seed, _mapKind);
}
private void OnHostRequested(int port, 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: false,
listOnPublicDirectory: false,
fallbackToLocalOnFailure: true);
}
private void OnJoinRequested(string endpointText, string callsign)
{
StartRemoteSession(endpointText, callsign, fromBrowser: false);
}
private void BindSessionPresentation(bool resetCamera)
{
if (_session is null) return;
var state = _session.ViewState;
_boundViewState = state;
_mapKind = state.MapKind;
_seed = state.Seed;
_wasNetConnected = _session.ConnectionStatus.Connected;
if (resetCamera)
{
var p = _session.LocalContender;
_cameraYaw = p.Yaw;
_prevLocalLifecycle = p.Lifecycle;
if (p.IsInDropPod)
{
_cameraPitch = Mathf.DegToRad(34f);
_orbitalPodCamBlend = 1.0f;
}
else
{
_cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f);
_orbitalPodCamBlend = 0f;
}
_cameraZoom = 1.0f;
_lastCamChassisId = null;
_hasBaseCamPose = false;
_camJuice.Reset();
_footsteps.Clear();
_frameEvents.Clear();
_frameFootsteps.Clear();
_audio.ResetForSession(_session);
_hud.ResetFeedback();
}
else
{
_audio.ResetForSession(_session);
}
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4800f : 2600f;
_atmosphere.ApplyMap(_mapKind);
bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(state.Terrain, state.SionMap);
if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null)
{
_sionMap.Visible = true;
_sionMap.EnsureBuilt(state.SionMap);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
}
else
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_sionMap.Visible = false;
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
}
else
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
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.GpuSparks.Prewarm(startVec);
_arena.PomDecals.PrewarmShader(startVec);
_hud.Sync(_session);
}
else
{
_lobbyScreen.Sync(_session);
}
SyncMouseMode();
}
private bool IsAutomatedRun =>
DisplayServer.GetName() == "headless"
|| InitialMapKindOverride.HasValue
|| InitialSkipDropOverride
|| InitialSkipMenuOverride
|| _perfTargetFrames > 0
|| _menuPreviewTargetFrames > 0
|| string.Equals(GetCliArg("--audio-driver"), "Dummy", StringComparison.OrdinalIgnoreCase)
|| GetCliArg("--script", allowBareFlag: true) is not null
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_NO_CAPTURE"))
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"))
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"))
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_MENU_EXIT_FRAMES"));
public override void _Notification(int what)
{
if (what == NotificationApplicationFocusOut || what == NotificationWMWindowFocusOut)
{
Input.MouseMode = Input.MouseModeEnum.Visible;
}
else if (what == NotificationApplicationFocusIn || what == NotificationWMWindowFocusIn)
{
if (IsInsideTree())
{
SyncMouseMode();
}
}
}
private void OpenSettingsFromCurrentScreen()
{
if (_screenMode == ClientScreenMode.PauseOverlay || _screenMode == ClientScreenMode.MainMenu)
{
_settingsReturnMode = _screenMode;
}
SetScreenMode(ClientScreenMode.Settings);
}
private void CloseSettings()
{
if (_screenMode == ClientScreenMode.Settings)
{
SetScreenMode(_settingsReturnMode);
}
}
private void OnGraphicsSettingsChanged(GraphicsSettings settings)
{
_atmosphere.ApplyGraphicsSettings(settings);
_settingsOverlay?.SetGraphicsValues(
settings.VfxResolution,
settings.VolumetricSamples,
settings.SdfgiQuality,
settings.BorderlessFullscreen);
if (!IsAutomatedRun && DisplayServer.GetName() != "headless")
{
ApplyWindowMode(settings.BorderlessFullscreen);
}
}
private static string? ResolveGraphicsSettingsPath()
{
try
{
return ProjectSettings.GlobalizePath("user://" + GraphicsSettings.DefaultFileName);
}
catch
{
return null;
}
}
private static void ApplyGraphicsEnvOverrides(GraphicsSettings settings)
{
string? resEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_RES");
if (!string.IsNullOrWhiteSpace(resEnv))
{
VfxResolutionScale? parsed = resEnv.Trim().ToLowerInvariant() switch
{
"half" or "0.5" or "0.5x" => VfxResolutionScale.Half,
"threequarter" or "three_quarter" or "high" or "0.75" or "0.75x" => VfxResolutionScale.ThreeQuarter,
"full" or "1.0" or "1.0x" or "native" => VfxResolutionScale.Full,
_ => null
};
if (parsed.HasValue)
{
settings.SetVfxResolution(parsed.Value, persist: false);
}
}
string? samplesEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_SAMPLES");
if (!string.IsNullOrWhiteSpace(samplesEnv))
{
VolumetricSamples? parsed = samplesEnv.Trim().ToLowerInvariant() switch
{
"low" or "8" => VolumetricSamples.Low,
"medium" or "10" => VolumetricSamples.Medium,
"high" or "16" => VolumetricSamples.High,
"ultra" or "24" => VolumetricSamples.Ultra,
_ => null
};
if (parsed.HasValue)
{
settings.SetVolumetricSamples(parsed.Value, persist: false);
}
}
string? sdfgiEnv = System.Environment.GetEnvironmentVariable("RTD_SDFGI_QUALITY");
if (!string.IsNullOrWhiteSpace(sdfgiEnv))
{
SdfgiQuality? parsed = sdfgiEnv.Trim().ToLowerInvariant() switch
{
"off" => SdfgiQuality.Off,
"balanced" => SdfgiQuality.Balanced,
"high" => SdfgiQuality.High,
_ => null
};
if (parsed.HasValue)
{
settings.SetSdfgiQuality(parsed.Value, persist: false);
}
}
}
private static void ApplyWindowMode(bool borderlessFullscreen)
{
if (DisplayServer.GetName() == "headless")
{
return;
}
var current = DisplayServer.WindowGetMode();
bool isFullscreen = current == DisplayServer.WindowMode.Fullscreen || current == DisplayServer.WindowMode.ExclusiveFullscreen;
if (isFullscreen != borderlessFullscreen)
{
DisplayServer.WindowSetMode(borderlessFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed);
}
}
private void ToggleBorderlessFullscreen()
{
if (IsAutomatedRun || DisplayServer.GetName() == "headless")
{
return;
}
var mode = DisplayServer.WindowGetMode();
bool nextFullscreen = !(mode == DisplayServer.WindowMode.Fullscreen || mode == DisplayServer.WindowMode.ExclusiveFullscreen);
DisplayServer.WindowSetMode(nextFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed);
_graphicsSettings.SetBorderlessFullscreen(nextFullscreen, persist: !IsAutomatedRun);
}
private void SyncMouseMode()
{
if (IsAutomatedRun)
{
Input.MouseMode = Input.MouseModeEnum.Visible;
return;
}
if (!IsInsideTree() || GetWindow() is not { } win || !win.HasFocus())
{
Input.MouseMode = Input.MouseModeEnum.Visible;
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;
}
private static string? GetCliArg(string flag, bool allowBareFlag = false)
{
static string? SearchArgs(string[] args, string flagName, bool bare, int startIndex = 0)
{
string prefix = flagName + "=";
for (int i = startIndex; i < args.Length; i++)
{
string a = args[i];
if (a.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return a[prefix.Length..];
}
if (a.Equals(flagName, StringComparison.OrdinalIgnoreCase))
{
if (i + 1 < args.Length && !args[i + 1].StartsWith("-", StringComparison.Ordinal))
{
return args[i + 1];
}
if (bare)
{
return string.Empty;
}
}
}
return null;
}
return SearchArgs(OS.GetCmdlineUserArgs(), flag, allowBareFlag)
?? SearchArgs(OS.GetCmdlineArgs(), flag, allowBareFlag)
?? SearchArgs(System.Environment.GetCommandLineArgs(), flag, allowBareFlag, startIndex: 1);
}
private static void ParseBindAndPort(string? raw, IPAddress defaultIp, int defaultPort, out IPAddress bindIp, out int port)
{
bindIp = defaultIp;
port = defaultPort;
string trimmed = (raw ?? string.Empty).Trim();
if (string.IsNullOrEmpty(trimmed))
{
return;
}
int colon = trimmed.LastIndexOf(':');
if (colon >= 0)
{
string ipPart = trimmed[..colon].Trim();
string portPart = trimmed[(colon + 1)..].Trim();
if (!string.IsNullOrEmpty(ipPart) && IPAddress.TryParse(ipPart, out var parsedIp))
{
bindIp = parsedIp;
}
if (int.TryParse(portPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && p is > 0 and <= 65535)
{
port = p;
}
return;
}
if (int.TryParse(trimmed, NumberStyles.Integer, CultureInfo.InvariantCulture, out int onlyPort) && onlyPort is > 0 and <= 65535)
{
port = onlyPort;
}
else if (IPAddress.TryParse(trimmed, out var onlyIp))
{
bindIp = onlyIp;
}
}
private static IPEndPoint ResolveEndPoint(string endpointText, int defaultPort)
{
string trimmed = (endpointText ?? string.Empty).Trim();
if (string.IsNullOrEmpty(trimmed))
{
throw new ArgumentException("Server endpoint cannot be empty.");
}
string host = trimmed;
int port = defaultPort;
int colon = trimmed.LastIndexOf(':');
if (colon > 0 && trimmed[..colon].IndexOf(':') < 0)
{
host = trimmed[..colon].Trim();
string portStr = trimmed[(colon + 1)..].Trim();
if (!int.TryParse(portStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) || port is <= 0 or > 65535)
{
throw new FormatException($"Invalid port in endpoint '{endpointText}'.");
}
}
if (IPAddress.TryParse(host, out var ip))
{
return new IPEndPoint(ip, port);
}
var addrs = Dns.GetHostAddresses(host);
for (int i = 0; i < addrs.Length; i++)
{
if (addrs[i].AddressFamily == AddressFamily.InterNetwork)
{
return new IPEndPoint(addrs[i], port);
}
}
if (addrs.Length > 0)
{
return new IPEndPoint(addrs[0], port);
}
throw new SocketException((int)SocketError.HostNotFound);
}
public void SetScriptedInput(PlayerInput? input) => _scriptedInput = input;
public override void _Input(InputEvent @event)
{
if (@event is InputEventKey key && key.Pressed && !key.Echo)
{
bool isAltEnter = (key.Keycode == Key.Enter || key.Keycode == Key.KpEnter)
&& key.AltPressed && !key.CtrlPressed && !key.ShiftPressed;
bool isF11 = key.Keycode == Key.F11 && !key.AltPressed && !key.CtrlPressed && !key.ShiftPressed;
if (isAltEnter || isF11)
{
ToggleBorderlessFullscreen();
GetViewport().SetInputAsHandled();
}
}
}
public override void _UnhandledInput(InputEvent @event)
{
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 (_screenMode == ClientScreenMode.Settings)
{
if (key.Keycode == Key.Escape)
{
CloseSettings();
}
return;
}
if (key.Keycode == Key.F9)
{
_hud.ToggleNetworkPanel();
SyncMouseMode();
return;
}
if (key.Keycode == Key.Escape)
{
if (_hud.NetworkPanelOpen)
{
_hud.SetNetworkPanelOpen(false);
SyncMouseMode();
}
else if (_hud.GarageExpanded)
{
_hud.ToggleGarage();
SyncMouseMode();
}
else
{
SetScreenMode(ClientScreenMode.PauseOverlay);
}
return;
}
if (_hud.IsUiTextInputFocused)
{
return;
}
switch (key.Keycode)
{
case Key.E:
_interactQueued = true;
break;
case Key.Tab:
_hud.ToggleGarage();
SyncMouseMode();
break;
case Key.R:
_session?.RequestNewMatch(_seed + 1, _mapKind);
break;
case Key.M:
_session?.RequestNewMatch(_seed, _mapKind == ArenaMapKind.Sion ? ArenaMapKind.Desert : ArenaMapKind.Sion);
break;
}
return;
}
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)
{
_cameraZoom = Math.Clamp(_cameraZoom - 0.08f, 0.75f, 1.6f);
}
else if (mb.ButtonIndex == MouseButton.WheelDown)
{
_cameraZoom = Math.Clamp(_cameraZoom + 0.08f, 0.75f, 1.6f);
}
else if (mb.ButtonIndex == MouseButton.Left &&
Input.MouseMode == Input.MouseModeEnum.Visible &&
!_hud.GarageExpanded &&
!_hud.NetworkPanelOpen &&
!_hud.IsPointerOverInteractiveHud(mb.Position))
{
SyncMouseMode();
}
}
}
public override void _PhysicsProcess(double delta)
{
if (_session is null)
{
return;
}
_elapsedSeconds += (float)delta;
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)
{
long t0 = Stopwatch.GetTimestamp();
_session.SubmitLocalInput(in input, isPhysicsTick: true);
long t1 = Stopwatch.GetTimestamp();
double toMs = 1000.0 / Stopwatch.Frequency;
_perfPendingStepMs += (t1 - t0) * toMs;
_perfPhysicsTicks++;
}
else
{
_session.SubmitLocalInput(in input, isPhysicsTick: true);
}
}
public override void _Process(double delta)
{
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);
if (_perfTargetFrames > 0 && !_wasNetConnected && nowConnected)
{
_perfFrameCount = 0;
_perfPhysicsTicks = 0;
_perfFrameMs.Clear();
_perfPhysicsStepMs.Clear();
_perfTerrainSyncMs.Clear();
_perfArenaSyncMs.Clear();
_perfHudMs.Clear();
_perfDirtyRebakeDelta.Clear();
_perfDrawCalls.Clear();
_perfPrimitives.Clear();
_perfObjects.Clear();
_perfNodeCount.Clear();
_perfTimeProcess.Clear();
_perfTimePhysicsProcess.Clear();
_perfCamMsSum = 0;
_perfLastFrameTick = Stopwatch.GetTimestamp();
}
}
_wasNetConnected = nowConnected;
if (_screenMode == ClientScreenMode.Lobby)
{
_frameEvents.Clear();
_session.DrainSimEvents(_frameEvents);
UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
_lobbyScreen.Sync(_session);
return;
}
if (_perfTargetFrames > 0)
{
if (_session.ConnectionStatus.Mode == NetworkMode.RemoteClient && !nowConnected && _perfWaitConnectFrames < 300)
{
_perfWaitConnectFrames++;
_perfLastFrameTick = Stopwatch.GetTimestamp();
return;
}
double toMs = 1000.0 / Stopwatch.Frequency;
long tt0 = Stopwatch.GetTimestamp();
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
long tt1 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha);
long ta1 = Stopwatch.GetTimestamp();
_perfPendingTerrainMs = (tt1 - tt0) * toMs;
_perfPendingArenaMs = (ta1 - tt1) * toMs;
long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
long th0 = Stopwatch.GetTimestamp();
var localP = _session.LocalContender;
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
_hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio);
_hud.Sync(_session);
long th1 = Stopwatch.GetTimestamp();
_perfCamMsSum += (th0 - tc0) * toMs;
double hudMs = (th1 - th0) * toMs;
long now = Stopwatch.GetTimestamp();
double frameMs = (now - _perfLastFrameTick) * 1000.0 / Stopwatch.Frequency;
_perfLastFrameTick = now;
_perfFrameMs.Add(frameMs);
_perfPhysicsStepMs.Add(_perfPendingStepMs);
_perfTerrainSyncMs.Add(_perfPendingTerrainMs);
_perfArenaSyncMs.Add(_perfPendingArenaMs);
_perfHudMs.Add(hudMs);
_perfPendingStepMs = 0;
_perfPendingTerrainMs = 0;
_perfPendingArenaMs = 0;
int rebakesNow = _terrain.DirtyRebakes;
_perfDirtyRebakeDelta.Add(rebakesNow - _perfLastDirtyRebakes);
_perfLastDirtyRebakes = rebakesNow;
_perfDrawCalls.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalDrawCallsInFrame));
_perfPrimitives.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalPrimitivesInFrame));
_perfObjects.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalObjectsInFrame));
_perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount));
_perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0);
_perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0);
if (ArenaSession.PerfEnabled)
{
_perfViewportGpuMs.Add(RenderingServer.ViewportGetMeasuredRenderTimeGpu(GetViewport().GetViewportRid()));
}
_perfFrameCount++;
if (_perfFrameCount >= _perfTargetFrames)
{
PrintPerfSummaryAndQuit();
}
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha);
UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
var localP = _session.LocalContender;
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
_hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio);
_hud.Sync(_session);
}
}
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)
{
return;
}
_frameEvents.Clear();
_session.DrainSimEvents(_frameEvents);
_frameFootsteps.Clear();
_footsteps.StepSession(_session, dt, alpha, _frameFootsteps, ResolveLiveWalkerFootWorld);
_arena.ConsumeEvents(_session, _frameEvents, _frameFootsteps, dt, SampleCurrentMapGroundTint);
var local = _session.LocalContender;
if (local.Lifecycle == ContenderLifecycle.Deploying && _prevLocalLifecycle != ContenderLifecycle.Deploying)
{
_cameraPitch = Mathf.DegToRad(34f);
_orbitalPodCamBlend = 1.0f;
}
_prevLocalLifecycle = local.Lifecycle;
var localPos = new System.Numerics.Vector3(local.X, local.Y, local.Z);
_camJuice.ConsumeEvents(_frameEvents, _session.LocalContenderId, localPos, _session);
_camJuice.ConsumeFootsteps(_frameFootsteps, _session.LocalContenderId);
OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall;
float camHorizSpeed = local.Speed;
if (local.IsInDropPod)
{
var pods = _session.ActivePods;
for (int i = 0; i < pods.Count; i++)
{
if (pods[i].PodKind == OrbitalPodKind.Contender &&
pods[i].ContenderId == _session.LocalContenderId)
{
localPodPhase = pods[i].Phase;
camHorizSpeed = MathF.Sqrt(pods[i].VelX * pods[i].VelX + pods[i].VelZ * pods[i].VelZ);
if (pods[i].Phase == OrbitalPodPhase.RetroBurn)
{
_camJuice.ApplyOrbitalBurnRumble(1.0f);
}
break;
}
}
}
_camJuice.Update(dt, camHorizSpeed, local.Grid.Spec.IsVtol, local.IsInDropPod, localPodPhase);
}
private static readonly Color DesertDustTint = new(0.76f, 0.59f, 0.40f, 1.0f);
internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) =>
_mapKind == ArenaMapKind.Sion
? _terrain.SampleGroundTint(worldX, worldZ)
: DesertDustTint;
private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex)
{
VehicleVisualInstance? vis = isContender
? _arena.GetContenderVisual(id)
: _arena.GetSpectatorVisual(id);
if (vis is null || vis.IsStaticLod || vis.RigState?.WalkerRig is not { } rig)
{
return null;
}
if ((uint)legIndex >= (uint)rig.Legs.Length)
{
return null;
}
Node3D footNode = rig.Legs[legIndex].Foot.Node;
if (!GodotObject.IsInstanceValid(footNode) || !footNode.IsInsideTree())
{
return null;
}
Vector3 p = footNode.GlobalPosition;
return new System.Numerics.Vector3(p.X, p.Y, p.Z);
}
private void PrintPerfSummaryAndQuit()
{
static double Avg(List<double> v)
{
if (v.Count == 0) return 0;
double s = 0;
foreach (double x in v) s += x;
return s / v.Count;
}
static double P95(List<double> v)
{
if (v.Count == 0) return 0;
var sorted = new List<double>(v);
sorted.Sort();
int idx = Math.Clamp((int)Math.Ceiling(sorted.Count * 0.95) - 1, 0, sorted.Count - 1);
return sorted[idx];
}
double totalMs = 0;
foreach (double x in _perfFrameMs) totalMs += x;
double fps = totalMs > 0 ? (_perfFrameMs.Count * 1000.0 / totalMs) : 0;
double rebakeAvg = 0;
int rebakeTotal = 0;
foreach (int r in _perfDirtyRebakeDelta) rebakeTotal += r;
rebakeAvg = _perfDirtyRebakeDelta.Count > 0 ? (double)rebakeTotal / _perfDirtyRebakeDelta.Count : 0;
double steadyMs = 0;
int steadyCount = Math.Max(0, _perfFrameMs.Count - 10);
for (int i = 10; i < _perfFrameMs.Count; i++) steadyMs += _perfFrameMs[i];
double steadyAvgMs = steadyCount > 0 ? steadyMs / steadyCount : 0;
double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0;
GD.Print("=== PERF BENCHMARK SUMMARY ===");
GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..{_perfFrameMs.Count - 1})={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}");
GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}");
GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}");
GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}");
GD.Print($"arenaSyncMs/frame: avg={Avg(_perfArenaSyncMs):F2} p95={P95(_perfArenaSyncMs):F2}");
GD.Print($"hudMs/frame: avg={Avg(_perfHudMs):F2} p95={P95(_perfHudMs):F2}");
GD.Print($"RenderTotalDrawCallsInFrame: avg={Avg(_perfDrawCalls):F0} max={P95(_perfDrawCalls):F0}");
GD.Print($"RenderTotalPrimitivesInFrame: avg={Avg(_perfPrimitives):F0}");
GD.Print($"RenderTotalObjectsInFrame: avg={Avg(_perfObjects):F0}");
GD.Print($"ObjectNodeCount: avg={Avg(_perfNodeCount):F0}");
GD.Print($"TimeProcessMs: avg={Avg(_perfTimeProcess):F2}");
GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}");
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
int ticks = Math.Max(1, _perfPhysicsTicks);
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / ticks:F2} ai={ArenaSession.PerfAiMs / ticks:F2} drive={ArenaSession.PerfDriveMs / ticks:F2} world={ArenaSession.PerfWorldMs / ticks:F2} sync={ArenaSession.PerfBodySyncMs / ticks:F2} detect={ArenaSession.PerfDetectMs / ticks:F2} weapons={ArenaSession.PerfWeaponsMs / ticks:F2}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} gpuSparksEmitted={_arena.GpuSparks.TotalEmittedCount} volEmitters={_arena.Volumetrics.ActiveEmitterCount} volImpulses={_arena.Volumetrics.ActiveImpulseCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}");
if (_atmosphere.VolumetricEffect is { } volFx)
{
Rid vpRid = GetViewport().GetViewportRid();
double vpGpuMs = RenderingServer.ViewportGetMeasuredRenderTimeGpu(vpRid);
double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid);
GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} marchSize={volFx.LastMarchSize.X}x{volFx.LastMarchSize.Y} maxSteps={volFx.CurrentMaxSteps} maxIter={volFx.CurrentMaxIter} vfxRes={_graphicsSettings.VfxResolution} volSamples={_graphicsSettings.VolumetricSamples} sdfgi={_graphicsSettings.SdfgiQuality} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}");
if (_perfViewportGpuMs.Count > 10)
{
var steadyGpu = new List<double>(_perfViewportGpuMs.Count - 10);
for (int i = 10; i < _perfViewportGpuMs.Count; i++) steadyGpu.Add(_perfViewportGpuMs[i]);
steadyGpu.Sort();
double gpuP50 = steadyGpu[(int)Math.Clamp(Math.Floor(steadyGpu.Count * 0.50), 0, steadyGpu.Count - 1)];
double gpuP95 = steadyGpu[(int)Math.Clamp(Math.Ceiling(steadyGpu.Count * 0.95) - 1, 0, steadyGpu.Count - 1)];
double gpuMax = steadyGpu[^1];
GD.Print($"viewportGpuMsTimeline(10..{_perfViewportGpuMs.Count - 1}): avg={Avg(steadyGpu):F2} p50={gpuP50:F2} p95={gpuP95:F2} max={gpuMax:F2}");
}
}
if (_hud?.HbCanvas is { } hb)
{
GD.Print($"HbGpuHud: drawCalls={hb.LastDrawCallCount} quads={hb.LastQuadCount} gpuMs={hb.LastHbGpuMs:F4}");
}
if (_session is not null)
{
var net = _session.ConnectionStatus;
uint snapSeq = _session is RemoteArenaSession remote ? remote.LastSnapshotSeq : 0u;
GD.Print($"NetStatus: mode={net.Mode} connected={net.Connected} localSlot={_session.LocalContenderId} pingMs={net.PingMs} humans={net.ConnectedHumans}/{net.MaxHumans} snapshotSeq={snapSeq} label='{net.StateLabel}'");
}
if (_mapKind == ArenaMapKind.Sion)
{
GD.Print($"SionMap: terrainTiles={_terrain.BakedTileCount} gpuScarSlots={_terrain.ActiveGpuScarSlots} bldgTiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
}
foreach (var kv in _arena.AssetCache.Vehicles)
{
int tris = 0;
var bm = kv.Value.BakedStaticMesh;
for (int s = 0; s < bm.GetSurfaceCount(); s++)
{
var arr = bm.SurfaceGetArrays(s);
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
tris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3;
}
int farTris = 0;
var fm = kv.Value.BakedLodFarMesh;
for (int s = 0; s < fm.GetSurfaceCount(); s++)
{
var arr = fm.SurfaceGetArrays(s);
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
farTris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3;
}
int nodes = CountSubtreeNodes(kv.Value.SceneTemplate);
GD.Print($" Vehicle '{kv.Key}': nodes={nodes} bakedTris={tris} farTris={farTris} surfs={bm.GetSurfaceCount()} farSurfs={fm.GetSurfaceCount()} detachChunks={kv.Value.DetachableParts.Count}");
}
if (_arena.AssetCache.Vehicles.TryGetValue("paladin", out var palTpl))
{
var names = new List<string>();
CollectNodeNames(palTpl.SceneTemplate, names, 40);
GD.Print($" Paladin sample nodes: {string.Join(", ", names)}");
}
GD.Print("=== END PERF BENCHMARK ===");
string? previewOut = System.Environment.GetEnvironmentVariable("RTD_PREVIEW_OUT");
if (string.IsNullOrWhiteSpace(previewOut))
{
previewOut = System.Environment.GetEnvironmentVariable("RTD_CAPTURE_PREVIEW");
}
if (!string.IsNullOrWhiteSpace(previewOut) && DisplayServer.GetName() != "headless")
{
var img = GetViewport().GetTexture()?.GetImage();
if (img is not null)
{
var err = img.SavePng(previewOut);
GD.Print($"PERF PREVIEW SAVED: {previewOut} ({img.GetWidth()}x{img.GetHeight()}, err={err})");
}
}
GetTree().Quit(0);
}
private static void CollectNodeNames(Node cur, List<string> outNames, int limit)
{
if (outNames.Count >= limit) return;
outNames.Add($"{cur.Name}({cur.GetType().Name})");
for (int i = 0; i < cur.GetChildCount(); i++) CollectNodeNames(cur.GetChild(i), outNames, limit);
}
private static int CountSubtreeNodes(Node cur)
{
int n = 1;
for (int i = 0; i < cur.GetChildCount(); i++) n += CountSubtreeNodes(cur.GetChild(i));
return n;
}
private PlayerInput GatherPlayerInput()
{
var local = Session.LocalContender;
bool inPod = local.IsInDropPod;
var (aimX, aimY, aimZ) = inPod
? (local.X + MathF.Sin(_cameraYaw) * 120f, local.Y - 40f, local.Z + MathF.Cos(_cameraYaw) * 120f)
: ComputeCenterScreenAim();
if (_hud.IsUiTextInputFocused || local.WaitingForRespawn)
{
return new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: aimX,
AimWorldZ: aimZ,
Fire: false,
InteractPickup: false,
Brake: false,
AimWorldY: aimY,
VerticalThrottle: 0f);
}
float throttle = 0f;
if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) throttle += 1f;
if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) throttle -= 1f;
float steer = 0f;
if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f;
bool isVtol = !inPod && local.Grid.Spec.IsVtol;
float verticalThrottle = 0f;
if (!inPod)
{
if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f;
if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f;
}
bool brake = !inPod && (isVtol ? Input.IsKeyPressed(Key.Shift) : Input.IsKeyPressed(Key.Space));
bool pointerOnHud = Input.MouseMode != Input.MouseModeEnum.Captured &&
(_hud.NetworkPanelOpen || _hud.IsPointerOverInteractiveHud(GetViewport().GetMousePosition()));
bool fire = !inPod && !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left);
return new PlayerInput(
Throttle: throttle,
Steer: steer,
AimWorldX: aimX,
AimWorldZ: aimZ,
Fire: fire,
InteractPickup: !inPod && _interactQueued,
Brake: brake,
AimWorldY: aimY,
VerticalThrottle: verticalThrottle);
}
private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim()
{
var player = Session.LocalContender;
var spec = player.Grid.Spec;
Vector2 screenSize = GetViewport().GetVisibleRect().Size;
if (screenSize.X < 2f || screenSize.Y < 2f)
{
return (
player.X + MathF.Sin(_cameraYaw) * 40f,
player.Y,
player.Z + MathF.Cos(_cameraYaw) * 40f);
}
Vector2 center = screenSize * 0.5f;
Vector3 rayOrigin = _hasBaseCamPose
? _baseCamPos + _baseLookDir * _camera.Near
: _camera.ProjectRayOrigin(center);
Vector3 rayDir = _hasBaseCamPose
? _baseLookDir
: _camera.ProjectRayNormal(center);
const float maxAimDist = 450f;
ulong playerStableId = ContenderStableIdBase + (ulong)player.Id;
var (pPos, _, _) = Session.GetInterpolatedContenderPose(player.Id, 1f);
Vector3 playerCenter = new Vector3(pPos.X, pPos.Y, pPos.Z);
float camToCenterProj = (playerCenter - rayOrigin).Dot(rayDir);
float minForwardDot = -MathF.Max(spec.HalfWidth, spec.HalfLength) * 0.35f;
bool IsValidForwardHit(Vector3 pt, float distFromCam) =>
(pt - playerCenter).Dot(rayDir) >= minForwardDot &&
distFromCam >= camToCenterProj - 0.5f;
Vector3 castOrigin = rayOrigin;
float remainingDist = maxAimDist;
float boxDist = maxAimDist;
Vector3 boxHitPt = Vector3.Zero;
bool hasBoxHit = false;
// Cast against session world, skipping the player's own chassis and any surface behind the vehicle's forward plane.
for (int attempt = 0; attempt < 4 && remainingDist > 1f; attempt++)
{
var hit = Session.CastWorldRayClosest(
new System.Numerics.Vector3(castOrigin.X, castOrigin.Y, castOrigin.Z),
new System.Numerics.Vector3(rayDir.X * remainingDist, rayDir.Y * remainingDist, rayDir.Z * remainingDist));
if (!hit.Hit)
{
break;
}
var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
float distFromCam = rayOrigin.DistanceTo(pt);
if (hit.StableId == playerStableId || !IsValidForwardHit(pt, distFromCam))
{
float skip = distFromCam + 0.4f;
castOrigin = rayOrigin + rayDir * skip;
remainingDist = MathF.Max(1f, maxAimDist - skip);
continue;
}
boxHitPt = pt;
boxDist = distFromCam;
hasBoxHit = true;
break;
}
float terrainStartDist = 0f;
bool hasTerrainHit = false;
float tx = 0f, ty = 0f, tz = 0f, terrainDist = maxAimDist;
for (int attempt = 0; attempt < 2 && terrainStartDist < boxDist; attempt++)
{
Vector3 tOrigin = rayOrigin + rayDir * terrainStartDist;
float tMaxDist = boxDist - terrainStartDist;
if (!Session.ViewState.Terrain.Raycast(
tOrigin.X, tOrigin.Y, tOrigin.Z,
rayDir.X, rayDir.Y, rayDir.Z,
maxDistance: tMaxDist,
out float hx, out float hy, out float hz, out float localDist))
{
break;
}
float totalDist = terrainStartDist + localDist;
var hitPt = new Vector3(hx, hy, hz);
if (!IsValidForwardHit(hitPt, totalDist))
{
terrainStartDist = MathF.Max(totalDist + 0.5f, camToCenterProj - 0.4f);
continue;
}
tx = hx;
ty = hy;
tz = hz;
terrainDist = totalDist;
hasTerrainHit = true;
break;
}
if (hasTerrainHit && terrainDist <= boxDist)
{
return (tx, ty, tz);
}
if (hasBoxHit)
{
return (boxHitPt.X, boxHitPt.Y, boxHitPt.Z);
}
Vector3 farPt = rayOrigin + rayDir * 320f;
return (farPt.X, farPt.Y, farPt.Z);
}
private void UpdateCamera(float dt, float alpha)
{
var p = Session.LocalContender;
var spec = p.Grid.Spec;
var (posInterp, _, _) = Session.GetInterpolatedContenderPose(p.Id, alpha);
Vector3 camRight = new(-MathF.Cos(_cameraYaw), 0f, MathF.Sin(_cameraYaw));
Vector3 camFwdHoriz = new(MathF.Sin(_cameraYaw), 0f, MathF.Cos(_cameraYaw));
Vector3 camPos;
Vector3 lookDir;
if (p.WaitingForRespawn)
{
_dropReticleMesh.Visible = false;
float orbitRadius = MathF.Min(Session.ViewState.Spectators.SafeRadius * 0.45f, 165f);
float orbitAngle = _elapsedSeconds * 0.14f + _cameraYaw;
float ox = MathF.Cos(orbitAngle) * orbitRadius;
float oz = MathF.Sin(orbitAngle) * orbitRadius;
float oy = Session.ViewState.Terrain.SampleHeight(ox, oz) + 75f;
camPos = new Vector3(ox, MathF.Max(oy, 110f), oz);
float centerY = Session.ViewState.Terrain.SampleHeight(0f, 0f) + 12f;
lookDir = (new Vector3(0f, centerY, 0f) - camPos).Normalized();
}
else if (p.IsInDropPod)
{
// Live landing ring reticle directly under the descending pod
float surfY = Session.ViewState.Terrain.SampleHeight(posInterp.X, posInterp.Z);
var (nx, ny, nz) = Session.ViewState.Terrain.SampleNormal(posInterp.X, posInterp.Z);
if (_mapKind == ArenaMapKind.Sion && Session.ViewState.SionMap is { } sm &&
sm.TryGetBuildingAt(posInterp.X, posInterp.Z, 1.6f, out var bldg))
{
if (bldg.RoofY > surfY && posInterp.Y >= bldg.RoofY - 1.0f)
{
surfY = bldg.RoofY;
nx = 0f; ny = 1f; nz = 0f;
}
}
Vector3 surfNorm = new Vector3(nx, ny, nz).Normalized();
if (surfNorm.LengthSquared() < 1e-4f) surfNorm = Vector3.Up;
Vector3 upRef = MathF.Abs(surfNorm.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 rRight = upRef.Cross(surfNorm).Normalized();
Vector3 rFwd = surfNorm.Cross(rRight).Normalized();
float pulse = 1.0f + 0.08f * MathF.Sin(_elapsedSeconds * 7.5f);
_dropReticleMesh.Visible = true;
_dropReticleMesh.GlobalTransform = new Transform3D(
new Basis(rRight, surfNorm, rFwd) * Basis.FromScale(new Vector3(pulse, 1f, pulse)),
new Vector3(posInterp.X, surfY + 0.35f, posInterp.Z));
_orbitalPodCamBlend = 1.0f;
float backDist = 28.0f * _cameraZoom;
Vector3 pivot = new(posInterp.X, posInterp.Y + 4.0f, posInterp.Z);
lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized();
float effectiveRight = 1.6f;
if (CastStaticCameraRay(pivot, camRight, effectiveRight, out float rightHitDist))
{
effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist));
}
Vector3 shoulderPos = pivot + camRight * effectiveRight;
float effectiveBack = backDist;
if (CastStaticCameraRay(shoulderPos, -lookDir, backDist, out float backHitDist))
{
effectiveBack = MathF.Min(effectiveBack, SafeCameraPullbackDist(backHitDist));
}
camPos = shoulderPos - lookDir * effectiveBack;
float minTerrainY = Session.ViewState.Terrain.SampleHeight(camPos.X, camPos.Z) + 2.2f;
if (camPos.Y < minTerrainY) camPos.Y = minTerrainY;
_smoothedShoulderY = pivot.Y;
}
else
{
_dropReticleMesh.Visible = false;
if (_orbitalPodCamBlend > 0.001f && dt > 0f && dt < 0.5f)
{
float targetPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(8f) : Mathf.DegToRad(12f);
_cameraPitch = Mathf.Lerp(_cameraPitch, targetPitch, 1f - MathF.Exp(-dt * 4.0f));
_orbitalPodCamBlend *= MathF.Exp(-dt * 4.5f);
if (_orbitalPodCamBlend < 0.005f) _orbitalPodCamBlend = 0f;
}
float rightOffset = MathF.Max(1.6f, spec.HalfWidth * 1.15f + 0.8f);
float heightOffset = spec.HalfHeight * 1.45f + 1.4f;
float boundingR = MathF.Max(spec.HalfWidth, MathF.Max(spec.HalfHeight * 0.72f, spec.HalfLength * 0.90f));
float backDist = Math.Clamp(boundingR * 2.15f + 4.2f, 7.2f, 19.5f) * _cameraZoom;
if (_orbitalPodCamBlend > 0f)
{
backDist = Mathf.Lerp(backDist, 22.0f * _cameraZoom, _orbitalPodCamBlend);
heightOffset = Mathf.Lerp(heightOffset, heightOffset + 2.2f, _orbitalPodCamBlend);
}
float targetShoulderY = (posInterp.Y - spec.HalfHeight) + heightOffset;
if (_lastCamChassisId != spec.Id || dt >= 1f)
{
_smoothedShoulderY = targetShoulderY;
_lastCamChassisId = spec.Id;
}
else
{
float yBlend = 1f - MathF.Exp(-dt * 24f);
_smoothedShoulderY = Mathf.Lerp(_smoothedShoulderY, targetShoulderY, yBlend);
}
var pivot = new Vector3(posInterp.X, _smoothedShoulderY, posInterp.Z);
lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized();
// Segment 1: sweep terrain + static Box3D (StableId < ContenderStableIdBase) from pivot along camRight * rightOffset
float effectiveRight = rightOffset;
if (CastStaticCameraRay(pivot, camRight, rightOffset, out float rightHitDist))
{
effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist));
}
Vector3 shoulderPos = pivot + camRight * effectiveRight;
// Segment 2: sweep terrain + static Box3D from shoulderPos along -lookDir * backDist
float effectiveBack = backDist;
if (CastStaticCameraRay(shoulderPos, -lookDir, backDist, out float backHitDist))
{
effectiveBack = MathF.Min(effectiveBack, SafeCameraPullbackDist(backHitDist));
}
camPos = shoulderPos - lookDir * effectiveBack;
float minTerrainY = Session.ViewState.Terrain.SampleHeight(camPos.X, camPos.Z) + 1.2f;
if (camPos.Y < minTerrainY)
{
camPos.Y = minTerrainY;
}
// Segment 3: verify direct pivot -> camPos LOS against static terrain/buildings so stepped wings cannot occlude player
Vector3 pivotToCam = camPos - pivot;
float pivotToCamDist = pivotToCam.Length();
if (pivotToCamDist > 0.05f)
{
Vector3 pivotToCamDir = pivotToCam / pivotToCamDist;
if (CastStaticCameraRay(pivot, pivotToCamDir, pivotToCamDist, out float wingHitDist))
{
camPos = pivot + pivotToCamDir * SafeCameraPullbackDist(wingHitDist);
}
}
}
_baseCamPos = camPos;
_baseLookDir = lookDir;
_hasBaseCamPose = true;
float targetFov = CameraJuiceState.BaseFovDeg + _camJuice.FovOffsetDeg;
if (MathF.Abs(_camera.Fov - targetFov) > 0.005f)
{
_camera.Fov = targetFov;
}
if (_camJuice.IsIdle)
{
_camera.GlobalPosition = camPos;
_camera.LookAt(camPos + lookDir * 60f, Vector3.Up);
return;
}
_camJuice.ComputeOffsets(
out System.Numerics.Vector3 jOff,
out float pitchOffRad,
out float yawOffRad,
out float rollOffRad);
Vector3 juicedCamPos = camPos
+ camRight * jOff.X
+ Vector3.Up * jOff.Y
- lookDir * jOff.Z;
Vector3 juiceDelta = juicedCamPos - camPos;
float juiceDist = juiceDelta.Length();
if (juiceDist > 0.02f)
{
Vector3 juiceDir = juiceDelta / juiceDist;
if (CastStaticCameraRay(camPos, juiceDir, juiceDist, out float juiceHitDist))
{
juicedCamPos = camPos + juiceDir * SafeCameraPullbackDist(juiceHitDist);
}
}
float minJuicedY = Session.ViewState.Terrain.SampleHeight(juicedCamPos.X, juicedCamPos.Z) + 1.15f;
if (juicedCamPos.Y < minJuicedY)
{
juicedCamPos.Y = minJuicedY;
}
Vector3 juicedLookDir = lookDir;
if (MathF.Abs(yawOffRad) > 1e-6f)
{
juicedLookDir = juicedLookDir.Rotated(Vector3.Up, yawOffRad);
}
if (MathF.Abs(pitchOffRad) > 1e-6f)
{
Vector3 pitchAxis = Vector3.Up.Cross(juicedLookDir);
if (pitchAxis.LengthSquared() > 1e-6f)
{
juicedLookDir = juicedLookDir.Rotated(pitchAxis.Normalized(), pitchOffRad);
}
}
juicedLookDir = juicedLookDir.Normalized();
Vector3 camUp = MathF.Abs(rollOffRad) > 1e-6f
? Vector3.Up.Rotated(juicedLookDir, rollOffRad)
: Vector3.Up;
_camera.GlobalPosition = juicedCamPos;
_camera.LookAt(juicedCamPos + juicedLookDir * 60f, camUp);
}
private static float SafeCameraPullbackDist(float rawDist) =>
MathF.Max(0.0f, rawDist - MathF.Min(0.35f, MathF.Max(0.08f, rawDist * 0.25f)));
private bool CastStaticCameraRay(Vector3 origin, Vector3 dir, float maxDist, out float hitDist)
{
hitDist = maxDist;
if (maxDist <= 0.01f)
{
return false;
}
bool hasHit = false;
if (Session.ViewState.Terrain.Raycast(
origin.X, origin.Y, origin.Z,
dir.X, dir.Y, dir.Z,
maxDist,
out _, out _, out _, out float terrainDist))
{
hitDist = MathF.Min(hitDist, terrainDist);
hasHit = true;
}
Vector3 castOrigin = origin;
float skipped = 0f;
float remaining = hitDist;
for (int attempt = 0; attempt < 16 && remaining > 0.05f; attempt++)
{
var hit = Session.CastWorldRayClosest(
new System.Numerics.Vector3(castOrigin.X, castOrigin.Y, castOrigin.Z),
new System.Numerics.Vector3(dir.X * remaining, dir.Y * remaining, dir.Z * remaining));
if (!hit.Hit)
{
break;
}
var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
float distFromOrigin = origin.DistanceTo(pt);
if (ArenaSession.IsStaticWorldStableId(hit.StableId))
{
if (distFromOrigin < hitDist)
{
hitDist = distFromOrigin;
hasHit = true;
}
break;
}
float nextSkip = MathF.Max(distFromOrigin + 0.15f, skipped + 0.5f);
if (nextSkip >= hitDist)
{
break;
}
skipped = nextSkip;
castOrigin = origin + dir * skipped;
remaining = hitDist - skipped;
}
return hasHit;
}
private void OnEquipCargo(int cargoIndex, string hardpointId)
{
_session?.RequestEquipCargo(cargoIndex, hardpointId);
}
private (bool Valid, bool InFront, Vector2 ScreenPos, System.Numerics.Vector3 CamLocal) ProjectWorldToHud(System.Numerics.Vector3 worldPos)
{
if (_camera is null || !GodotObject.IsInstanceValid(_camera) || !_camera.IsInsideTree())
{
return (false, false, Vector2.Zero, System.Numerics.Vector3.Zero);
}
var wp = new Vector3(worldPos.X, worldPos.Y, worldPos.Z);
Transform3D camXform = _camera.GlobalTransform;
Vector3 rel = wp - camXform.Origin;
Basis b = camXform.Basis;
// Godot Camera3D local axes: +X = right, +Y = up, -Z = forward
float localRight = rel.Dot(b.X);
float localUp = rel.Dot(b.Y);
float localForward = -rel.Dot(b.Z);
var camLocal = new System.Numerics.Vector3(localRight, localUp, localForward);
if (localForward <= 0.1f)
{
return (true, false, Vector2.Zero, camLocal);
}
Vector2 sp = _camera.UnprojectPosition(wp);
if (!float.IsFinite(sp.X) || !float.IsFinite(sp.Y))
{
return (true, false, Vector2.Zero, camLocal);
}
return (true, true, sp, camLocal);
}
}