From c6221758e97602d0b0d8ddd61fdda99efb6914bf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 00:43:38 +0100 Subject: [PATCH] WIP pre-reboot checkpoint: Menu Settings Graphics + live VFX res/samples + SDFGI quality --- client/AtmosphereSystem.cs | 25 ++ client/GraphicsSettings.cs | 264 ++++++++++++ client/Main.cs | 192 ++++++++- client/MainMenu.cs | 17 +- client/SettingsOverlay.cs | 407 ++++++++++++++++++ client/VolumetricCompositorEffect.cs | 79 +++- client/flow_field_step.glsl | 1 + client/volumetric_composite.glsl | 135 +++--- client/volumetric_raymarch.glsl | 34 +- client/volumetric_tile_cull.glsl | 38 +- .../RustToDust.Tests/GraphicsSettingsTests.cs | 147 +++++++ .../RustToDust.Tests/RustToDust.Tests.csproj | 1 + 12 files changed, 1222 insertions(+), 118 deletions(-) create mode 100644 client/GraphicsSettings.cs create mode 100644 client/SettingsOverlay.cs create mode 100644 tests/RustToDust.Tests/GraphicsSettingsTests.cs diff --git a/client/AtmosphereSystem.cs b/client/AtmosphereSystem.cs index 8007ed9..17bda3b 100644 --- a/client/AtmosphereSystem.cs +++ b/client/AtmosphereSystem.cs @@ -305,6 +305,31 @@ public partial class AtmosphereSystem : Node _volumetricEffect?.SetEmitterPool(pool); } + public void ApplyGraphicsSettings(GraphicsSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + EnsureInitialized(); + + _volumetricEffect?.ApplyGraphicsSettings(settings); + + SdfgiSettingsConfig sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality); + _env.SdfgiEnabled = sdfgi.Enabled; + if (sdfgi.Enabled) + { + _env.SdfgiMinCellSize = sdfgi.MinCellSize; + _env.SdfgiCascades = sdfgi.Cascades; + } + + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.GISetUseHalfResolution(sdfgi.HalfResolution); + RenderingServer.EnvironmentSetSdfgiRayCount( + sdfgi.RayCount >= 8 + ? RenderingServer.EnvironmentSdfgiRayCount.Count8 + : RenderingServer.EnvironmentSdfgiRayCount.Count4); + } + } + public override void _ExitTree() { if (_worldEnv is not null && GodotObject.IsInstanceValid(_worldEnv)) diff --git a/client/GraphicsSettings.cs b/client/GraphicsSettings.cs new file mode 100644 index 0000000..e0e6461 --- /dev/null +++ b/client/GraphicsSettings.cs @@ -0,0 +1,264 @@ +using System; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RustToDust.Client; + +public enum VfxResolutionScale +{ + Half = 0, + ThreeQuarter = 1, + Full = 2 +} + +public enum VolumetricSamples +{ + Low = 0, + Medium = 1, + High = 2, + Ultra = 3 +} + +public enum SdfgiQuality +{ + Off = 0, + Balanced = 1, + High = 2 +} + +public readonly record struct SdfgiSettingsConfig( + bool Enabled, + float MinCellSize, + int Cascades, + bool HalfResolution, + int RayCount); + +public sealed record GraphicsSettingsData +{ + [JsonPropertyName("vfxResolutionScale")] + public VfxResolutionScale VfxResolution { get; init; } = VfxResolutionScale.Half; + + [JsonPropertyName("volumetricSamples")] + public VolumetricSamples VolumetricSamples { get; init; } = VolumetricSamples.Medium; + + [JsonPropertyName("sdfgiQuality")] + public SdfgiQuality SdfgiQuality { get; init; } = SdfgiQuality.Balanced; + + [JsonPropertyName("borderlessFullscreen")] + public bool BorderlessFullscreen { get; init; } = true; +} + +/// +/// Single persisted authority for live graphics and display settings (user://graphics_settings.json). +/// Pure .NET so unit tests and headless runs share the exact same schema, defaults, and event flow. +/// +public sealed class GraphicsSettings +{ + public const string DefaultFileName = "graphics_settings.json"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly string? _storagePath; + + public GraphicsSettings(string? storagePath = null) + { + _storagePath = string.IsNullOrWhiteSpace(storagePath) ? null : storagePath; + ResetFieldsToDefaults(); + } + + public VfxResolutionScale VfxResolution { get; private set; } + public VolumetricSamples VolumetricSamples { get; private set; } + public SdfgiQuality SdfgiQuality { get; private set; } + public bool BorderlessFullscreen { get; private set; } + + public string? StoragePath => _storagePath; + + public event Action? Changed; + + public GraphicsSettingsData ToData() => new() + { + VfxResolution = VfxResolution, + VolumetricSamples = VolumetricSamples, + SdfgiQuality = SdfgiQuality, + BorderlessFullscreen = BorderlessFullscreen + }; + + public static GraphicsSettings Load(string? storagePath) + { + var settings = new GraphicsSettings(storagePath); + if (string.IsNullOrWhiteSpace(storagePath)) + { + return settings; + } + + try + { + if (File.Exists(storagePath)) + { + string json = File.ReadAllText(storagePath); + settings.LoadFromJson(json); + } + } + catch + { + settings.ResetFieldsToDefaults(); + } + return settings; + } + + public bool LoadFromJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + ResetFieldsToDefaults(); + return false; + } + + try + { + var parsed = JsonSerializer.Deserialize(json, JsonOptions); + if (parsed is null) + { + ResetFieldsToDefaults(); + return false; + } + + VfxResolution = Enum.IsDefined(parsed.VfxResolution) + ? parsed.VfxResolution + : VfxResolutionScale.Half; + VolumetricSamples = Enum.IsDefined(parsed.VolumetricSamples) + ? parsed.VolumetricSamples + : VolumetricSamples.Medium; + SdfgiQuality = Enum.IsDefined(parsed.SdfgiQuality) + ? parsed.SdfgiQuality + : SdfgiQuality.Balanced; + BorderlessFullscreen = parsed.BorderlessFullscreen; + return true; + } + catch + { + ResetFieldsToDefaults(); + return false; + } + } + + public string ToJson() => JsonSerializer.Serialize(ToData(), JsonOptions); + + public bool Save() + { + if (string.IsNullOrWhiteSpace(_storagePath)) + { + return false; + } + + try + { + string? dir = Path.GetDirectoryName(_storagePath); + if (!string.IsNullOrEmpty(dir)) + { + Directory.CreateDirectory(dir); + } + string json = ToJson(); + string tempPath = _storagePath + ".tmp"; + File.WriteAllText(tempPath, json); + File.Move(tempPath, _storagePath, overwrite: true); + return true; + } + catch + { + return false; + } + } + + public void Apply( + VfxResolutionScale vfxResolution, + VolumetricSamples volumetricSamples, + SdfgiQuality sdfgiQuality, + bool borderlessFullscreen, + bool persist = true) + { + VfxResolutionScale safeRes = Enum.IsDefined(vfxResolution) ? vfxResolution : VfxResolutionScale.Half; + VolumetricSamples safeSamples = Enum.IsDefined(volumetricSamples) ? volumetricSamples : VolumetricSamples.Medium; + SdfgiQuality safeSdfgi = Enum.IsDefined(sdfgiQuality) ? sdfgiQuality : SdfgiQuality.Balanced; + + bool changed = VfxResolution != safeRes + || VolumetricSamples != safeSamples + || SdfgiQuality != safeSdfgi + || BorderlessFullscreen != borderlessFullscreen; + + if (!changed) + { + return; + } + + VfxResolution = safeRes; + VolumetricSamples = safeSamples; + SdfgiQuality = safeSdfgi; + BorderlessFullscreen = borderlessFullscreen; + + if (persist) + { + Save(); + } + Changed?.Invoke(this); + } + + public void SetVfxResolution(VfxResolutionScale value, bool persist = true) => + Apply(value, VolumetricSamples, SdfgiQuality, BorderlessFullscreen, persist); + + public void SetVolumetricSamples(VolumetricSamples value, bool persist = true) => + Apply(VfxResolution, value, SdfgiQuality, BorderlessFullscreen, persist); + + public void SetSdfgiQuality(SdfgiQuality value, bool persist = true) => + Apply(VfxResolution, VolumetricSamples, value, BorderlessFullscreen, persist); + + public void SetBorderlessFullscreen(bool value, bool persist = true) => + Apply(VfxResolution, VolumetricSamples, SdfgiQuality, value, persist); + + public void ResetToDefaults(bool persist = true) => + Apply( + VfxResolutionScale.Half, + VolumetricSamples.Medium, + SdfgiQuality.Balanced, + borderlessFullscreen: true, + persist: persist); + + public static float GetResolutionScaleFactor(VfxResolutionScale scale) => scale switch + { + VfxResolutionScale.Half => 0.50f, + VfxResolutionScale.ThreeQuarter => 0.75f, + VfxResolutionScale.Full => 1.00f, + _ => 0.50f + }; + + public static (int MaxSteps, int MaxIter) GetVolumetricStepBudget(VolumetricSamples samples) => samples switch + { + VolumetricSamples.Low => (8, 12), + VolumetricSamples.Medium => (10, 15), + VolumetricSamples.High => (16, 24), + VolumetricSamples.Ultra => (24, 36), + _ => (10, 15) + }; + + public static SdfgiSettingsConfig GetSdfgiConfig(SdfgiQuality quality) => quality switch + { + SdfgiQuality.Off => new SdfgiSettingsConfig(false, 0.8f, 3, true, 4), + SdfgiQuality.Balanced => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4), + SdfgiQuality.High => new SdfgiSettingsConfig(true, 0.4f, 4, false, 8), + _ => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4) + }; + + private void ResetFieldsToDefaults() + { + VfxResolution = VfxResolutionScale.Half; + VolumetricSamples = VolumetricSamples.Medium; + SdfgiQuality = SdfgiQuality.Balanced; + BorderlessFullscreen = true; + } +} diff --git a/client/Main.cs b/client/Main.cs index fb79311..da2603a 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -17,7 +17,8 @@ public enum ClientScreenMode ServerBrowser, Lobby, InMatch, - PauseOverlay + PauseOverlay, + Settings } /// @@ -38,12 +39,16 @@ public partial class Main : Node3D 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"; @@ -122,6 +127,8 @@ public partial class Main : Node3D 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; @@ -139,9 +146,14 @@ public partial class Main : Node3D { 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); @@ -191,8 +203,22 @@ public partial class Main : Node3D } }; _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 += () => @@ -324,12 +350,12 @@ public partial class Main : Node3D } _menuPreviewOut = System.Environment.GetEnvironmentVariable("RTD_MENU_PREVIEW_OUT"); - bool hasWindowOverride = GetCliArg("--windowed", allowBareFlag: true) is not null + _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) + if (!IsAutomatedRun && !_hasWindowOverride) { - DisplayServer.WindowSetMode(DisplayServer.WindowMode.Fullscreen); + ApplyWindowMode(_graphicsSettings.BorderlessFullscreen); } else if (IsAutomatedRun && DisplayServer.GetName() != "headless") { @@ -368,6 +394,10 @@ public partial class Main : Node3D else { EnterMainMenuBackdrop(); + if (System.Environment.GetEnvironmentVariable("RTD_OPEN_SETTINGS") == "1") + { + OpenSettingsFromCurrentScreen(); + } } if (perfCombat && _session is not null) @@ -557,6 +587,7 @@ public partial class Main : Node3D { case ClientScreenMode.MainMenu: _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu); @@ -566,6 +597,7 @@ public partial class Main : Node3D case ClientScreenMode.ServerBrowser: _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); _lobbyScreen.SetLobbyVisible(false); _serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint); @@ -576,6 +608,7 @@ public partial class Main : Node3D case ClientScreenMode.Lobby: _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(true); @@ -584,6 +617,7 @@ public partial class Main : Node3D break; case ClientScreenMode.InMatch: + _settingsOverlay.SetSettingsVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(false); @@ -592,6 +626,7 @@ public partial class Main : Node3D break; case ClientScreenMode.PauseOverlay: + _settingsOverlay.SetSettingsVisible(false); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(false); _arena.Visible = true; @@ -599,6 +634,25 @@ public partial class Main : Node3D _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(); } @@ -955,6 +1009,115 @@ public partial class Main : Node3D } } + 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 (DisplayServer.GetName() == "headless") @@ -962,14 +1125,9 @@ public partial class Main : Node3D return; } var mode = DisplayServer.WindowGetMode(); - if (mode == DisplayServer.WindowMode.Fullscreen || mode == DisplayServer.WindowMode.ExclusiveFullscreen) - { - DisplayServer.WindowSetMode(DisplayServer.WindowMode.Windowed); - } - else - { - DisplayServer.WindowSetMode(DisplayServer.WindowMode.Fullscreen); - } + 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() @@ -1151,6 +1309,14 @@ public partial class Main : Node3D } return; } + if (_screenMode == ClientScreenMode.Settings) + { + if (key.Keycode == Key.Escape) + { + CloseSettings(); + } + return; + } if (key.Keycode == Key.F9) { @@ -1603,7 +1769,7 @@ public partial class Main : Node3D 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} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}"); + 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(_perfViewportGpuMs.Count - 10); diff --git a/client/MainMenu.cs b/client/MainMenu.cs index 10ae5c7..2e1ec20 100644 --- a/client/MainMenu.cs +++ b/client/MainMenu.cs @@ -51,6 +51,7 @@ public sealed partial class MainMenu : CanvasLayer public event Action? QuitRequested; public event Action? ResumeRequested; public event Action? ReturnToMainMenuRequested; + public event Action? SettingsRequested; public bool IsHostPanelOpen => _hostPanel is not null && _hostPanel.Visible; public bool IsTextInputFocused => @@ -256,6 +257,14 @@ public sealed partial class MainMenu : CanvasLayer hostBtn.Pressed += () => SetHostPanelOpen(!IsHostPanelOpen); vbox.AddChild(hostBtn); + var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 38f); + settingsBtn.Pressed += () => + { + SetHostPanelOpen(false); + SettingsRequested?.Invoke(); + }; + vbox.AddChild(settingsBtn); + vbox.AddChild(ImperialChrome.MakeRule()); var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f); @@ -439,8 +448,8 @@ public sealed partial class MainMenu : CanvasLayer panel.AnchorBottom = 0.5f; panel.OffsetLeft = -190f; panel.OffsetRight = 190f; - panel.OffsetTop = -132f; - panel.OffsetBottom = 132f; + panel.OffsetTop = -156f; + panel.OffsetBottom = 156f; _pauseRoot.AddChild(panel); var vbox = new VBoxContainer(); @@ -457,6 +466,10 @@ public sealed partial class MainMenu : CanvasLayer resumeBtn.Pressed += () => ResumeRequested?.Invoke(); vbox.AddChild(resumeBtn); + var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 36f); + settingsBtn.Pressed += () => SettingsRequested?.Invoke(); + vbox.AddChild(settingsBtn); + var menuBtn = ImperialChrome.CreateButton("RETURN TO MAIN MENU", ImperialChrome.OrangeCol, 14, 36f); menuBtn.Pressed += () => ReturnToMainMenuRequested?.Invoke(); vbox.AddChild(menuBtn); diff --git a/client/SettingsOverlay.cs b/client/SettingsOverlay.cs new file mode 100644 index 0000000..e6ce30f --- /dev/null +++ b/client/SettingsOverlay.cs @@ -0,0 +1,407 @@ +using System; +using Godot; + +namespace RustToDust.Client; + +/// +/// Industrial Imperial Settings overlay with left-rail submenu navigation +/// (GRAPHICS active; Audio/Controls placeholders for future passes). +/// Decoupled from persistence: receives values via +/// and emits change/reset/back events. +/// +public sealed partial class SettingsOverlay : CanvasLayer +{ + public enum SettingsCategory + { + Graphics = 0 + } + + private Control _root = null!; + private ImperialChromePanel _panel = null!; + private Button _graphicsTabBtn = null!; + private Control _graphicsPane = null!; + + private readonly Button[] _vfxResButtons = new Button[3]; + private readonly Button[] _volSampleButtons = new Button[4]; + private readonly Button[] _sdfgiButtons = new Button[3]; + private readonly Button[] _displayModeButtons = new Button[2]; + + private VfxResolutionScale _vfxRes = VfxResolutionScale.Half; + private VolumetricSamples _volSamples = VolumetricSamples.Medium; + private SdfgiQuality _sdfgi = SdfgiQuality.Balanced; + private bool _borderlessFullscreen = true; + private bool _built; + + public SettingsOverlay() + { + Layer = 22; + } + + public event Action? GraphicsChanged; + public event Action? ResetDefaultsRequested; + public event Action? BackRequested; + + public bool IsOpen => Visible; + + public override void _Ready() + { + BuildUi(); + SetSettingsVisible(false); + } + + public void SetSettingsVisible(bool visible) + { + Visible = visible; + if (_root is not null) + { + _root.Visible = visible; + } + } + + public void SetGraphicsValues( + VfxResolutionScale vfxRes, + VolumetricSamples volSamples, + SdfgiQuality sdfgi, + bool borderlessFullscreen) + { + _vfxRes = vfxRes; + _volSamples = volSamples; + _sdfgi = sdfgi; + _borderlessFullscreen = borderlessFullscreen; + if (_built) + { + RefreshSelectionVisuals(); + } + } + + private void BuildUi() + { + _root = new Control + { + Name = "SettingsOverlayRoot", + MouseFilter = Control.MouseFilterEnum.Stop + }; + _root.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_root); + + var scrim = new ColorRect + { + Color = ImperialChrome.ScrimCol, + MouseFilter = Control.MouseFilterEnum.Stop + }; + scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _root.AddChild(scrim); + + _panel = ImperialChrome.CreatePanel( + ImperialChrome.OrangeCol, + cornerLen: 18f, + borderPx: 2f, + bgAlpha: 0.94f, + padH: 22, + padV: 20); + _panel.Name = "SettingsPanel"; + _panel.AnchorLeft = 0.5f; + _panel.AnchorRight = 0.5f; + _panel.AnchorTop = 0.5f; + _panel.AnchorBottom = 0.5f; + _panel.OffsetLeft = -440f; + _panel.OffsetRight = 440f; + _panel.OffsetTop = -255f; + _panel.OffsetBottom = 255f; + _root.AddChild(_panel); + + var outerVbox = new VBoxContainer(); + outerVbox.AddThemeConstantOverride("separation", 12); + _panel.AddChild(outerVbox); + + // Header + var headerRow = new HBoxContainer(); + headerRow.AddThemeConstantOverride("separation", 12); + outerVbox.AddChild(headerRow); + + var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + titleCol.AddThemeConstantOverride("separation", 2); + headerRow.AddChild(titleCol); + titleCol.AddChild(ImperialChrome.CreateLabel("SYSTEM CONFIGURATION • SUBMENU", 11, ImperialChrome.GoldCol)); + titleCol.AddChild(ImperialChrome.CreateLabel("SETTINGS", 24, ImperialChrome.TextLight)); + + var liveBadge = ImperialChrome.CreateLabel("LIVE APPLY • NO RESTART", 11, ImperialChrome.CyanCol, HorizontalAlignment.Right); + liveBadge.VerticalAlignment = VerticalAlignment.Bottom; + headerRow.AddChild(liveBadge); + + outerVbox.AddChild(ImperialChrome.MakeRule()); + + // Main Split: Submenu Rail + Content Pane + var split = new HBoxContainer + { + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + split.AddThemeConstantOverride("separation", 18); + outerVbox.AddChild(split); + + var navCol = new VBoxContainer + { + CustomMinimumSize = new Vector2(168f, 0f) + }; + navCol.AddThemeConstantOverride("separation", 8); + split.AddChild(navCol); + + navCol.AddChild(ImperialChrome.CreateLabel("CATEGORIES", 10, ImperialChrome.TextMuted)); + + _graphicsTabBtn = ImperialChrome.CreateButton("GRAPHICS", ImperialChrome.CyanCol, 13, 38f); + StyleSegmentedButton(_graphicsTabBtn, selected: true, ImperialChrome.CyanCol); + _graphicsTabBtn.Pressed += () => SelectCategory(SettingsCategory.Graphics); + navCol.AddChild(_graphicsTabBtn); + + var audioTabBtn = ImperialChrome.CreateButton("AUDIO [SOON]", ImperialChrome.BorderCol, 12, 34f); + audioTabBtn.Disabled = true; + audioTabBtn.TooltipText = "Audio controls arrive in a future pass"; + navCol.AddChild(audioTabBtn); + + var controlsTabBtn = ImperialChrome.CreateButton("CONTROLS [SOON]", ImperialChrome.BorderCol, 12, 34f); + controlsTabBtn.Disabled = true; + controlsTabBtn.TooltipText = "Input bindings arrive in a future pass"; + navCol.AddChild(controlsTabBtn); + + var vSep = new VSeparator(); + vSep.AddThemeStyleboxOverride("separator", new StyleBoxLine + { + Color = new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.75f), + Thickness = 1, + Vertical = true + }); + split.AddChild(vSep); + + _graphicsPane = new VBoxContainer + { + Name = "GraphicsSettingsPane", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + ((VBoxContainer)_graphicsPane).AddThemeConstantOverride("separation", 12); + split.AddChild(_graphicsPane); + + _graphicsPane.AddChild(ImperialChrome.CreateLabel("GRAPHICS • VOLUMETRICS, GI & DISPLAY", 14, ImperialChrome.CyanCol)); + + // 1. VFX / Fog Resolution + AddSettingRow( + _graphicsPane, + "VFX / FOG RESOLUTION", + "Compute resolution for raymarched smoke, fireballs & plumes (Full = 1:1 native)", + new[] + { + ("Half (0.5x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Half))), + ("High (0.75x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.ThreeQuarter))), + ("Full (1.0x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Full))) + }, + _vfxResButtons); + + // 2. Volumetric Sample Count + AddSettingRow( + _graphicsPane, + "VOLUMETRIC SAMPLE COUNT", + "Raymarch step budget per pixel (higher = smoother volume density & gradients)", + new[] + { + ("Low (8)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Low))), + ("Medium (10)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Medium))), + ("High (16)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.High))), + ("Ultra (24)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Ultra))) + }, + _volSampleButtons); + + // 3. Global Illumination (SDFGI) + AddSettingRow( + _graphicsPane, + "GLOBAL ILLUMINATION (SDFGI)", + "Signed-distance multi-bounce sky & terrain indirect lighting", + new[] + { + ("Off", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Off))), + ("Balanced", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Balanced))), + ("High", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.High))) + }, + _sdfgiButtons); + + // 4. Display Mode + AddSettingRow( + _graphicsPane, + "DISPLAY MODE", + "Window presentation mode (also toggleable anytime via Alt+Enter or F11)", + new[] + { + ("Borderless Fullscreen", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: true))), + ("Windowed", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: false))) + }, + _displayModeButtons); + + outerVbox.AddChild(ImperialChrome.MakeRule()); + + // Footer + var footerRow = new HBoxContainer(); + footerRow.AddThemeConstantOverride("separation", 10); + outerVbox.AddChild(footerRow); + + var resetBtn = ImperialChrome.CreateButton("RESET DEFAULTS", ImperialChrome.GoldCol, 13, 36f); + resetBtn.CustomMinimumSize = new Vector2(180f, 36f); + resetBtn.Pressed += () => ResetDefaultsRequested?.Invoke(); + footerRow.AddChild(resetBtn); + + footerRow.AddChild(new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }); + + var backBtn = ImperialChrome.CreateButton("BACK [ESC]", ImperialChrome.OrangeCol, 13, 36f); + backBtn.CustomMinimumSize = new Vector2(160f, 36f); + backBtn.Pressed += () => BackRequested?.Invoke(); + footerRow.AddChild(backBtn); + + _built = true; + RefreshSelectionVisuals(); + } + + private static void AddSettingRow( + Control parent, + string labelText, + string hintText, + (string Text, Action OnSelect)[] options, + Button[] targetButtons) + { + var block = new VBoxContainer(); + block.AddThemeConstantOverride("separation", 4); + parent.AddChild(block); + + var row = new HBoxContainer(); + row.AddThemeConstantOverride("separation", 12); + block.AddChild(row); + + var lbl = ImperialChrome.CreateLabel(labelText, 12, ImperialChrome.TextLight); + lbl.CustomMinimumSize = new Vector2(228f, 0f); + lbl.VerticalAlignment = VerticalAlignment.Center; + row.AddChild(lbl); + + var btnGroup = new HBoxContainer + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + btnGroup.AddThemeConstantOverride("separation", 6); + row.AddChild(btnGroup); + + for (int i = 0; i < options.Length; i++) + { + var (text, onSelect) = options[i]; + var btn = ImperialChrome.CreateButton(text, ImperialChrome.CyanCol, 12, 32f); + btn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + btn.Pressed += onSelect; + btnGroup.AddChild(btn); + targetButtons[i] = btn; + } + + var hint = ImperialChrome.CreateLabel(hintText, 10, ImperialChrome.TextMuted); + block.AddChild(hint); + } + + private void SelectCategory(SettingsCategory category) + { + if (category == SettingsCategory.Graphics && _graphicsPane is not null) + { + _graphicsPane.Visible = true; + } + } + + private void OnGraphicsOptionSelected( + VfxResolutionScale? vfxRes = null, + VolumetricSamples? volSamples = null, + SdfgiQuality? sdfgi = null, + bool? borderlessFullscreen = null) + { + VfxResolutionScale nextRes = vfxRes ?? _vfxRes; + VolumetricSamples nextSamples = volSamples ?? _volSamples; + SdfgiQuality nextSdfgi = sdfgi ?? _sdfgi; + bool nextFullscreen = borderlessFullscreen ?? _borderlessFullscreen; + + if (nextRes == _vfxRes + && nextSamples == _volSamples + && nextSdfgi == _sdfgi + && nextFullscreen == _borderlessFullscreen) + { + return; + } + + _vfxRes = nextRes; + _volSamples = nextSamples; + _sdfgi = nextSdfgi; + _borderlessFullscreen = nextFullscreen; + RefreshSelectionVisuals(); + GraphicsChanged?.Invoke(_vfxRes, _volSamples, _sdfgi, _borderlessFullscreen); + } + + private void RefreshSelectionVisuals() + { + for (int i = 0; i < _vfxResButtons.Length; i++) + { + StyleSegmentedButton(_vfxResButtons[i], i == (int)_vfxRes, ImperialChrome.CyanCol); + } + for (int i = 0; i < _volSampleButtons.Length; i++) + { + StyleSegmentedButton(_volSampleButtons[i], i == (int)_volSamples, ImperialChrome.CyanCol); + } + for (int i = 0; i < _sdfgiButtons.Length; i++) + { + StyleSegmentedButton(_sdfgiButtons[i], i == (int)_sdfgi, ImperialChrome.OliveCol); + } + StyleSegmentedButton(_displayModeButtons[0], _borderlessFullscreen, ImperialChrome.OrangeCol); + StyleSegmentedButton(_displayModeButtons[1], !_borderlessFullscreen, ImperialChrome.OrangeCol); + } + + private static void StyleSegmentedButton(Button btn, bool selected, Color accentColor) + { + if (selected) + { + btn.AddThemeFontSizeOverride("font_size", 12); + btn.AddThemeColorOverride("font_color", Colors.White); + btn.AddThemeColorOverride("font_hover_color", Colors.White); + btn.AddThemeColorOverride("font_pressed_color", accentColor); + + var activeBox = MakeSegmentBox( + new Color(accentColor.R * 0.24f + ImperialChrome.BgPressed.R * 0.76f, + accentColor.G * 0.24f + ImperialChrome.BgPressed.G * 0.76f, + accentColor.B * 0.24f + ImperialChrome.BgPressed.B * 0.76f, + 1f), + accentColor, + borderW: 2); + btn.AddThemeStyleboxOverride("normal", activeBox); + btn.AddThemeStyleboxOverride("hover", activeBox); + btn.AddThemeStyleboxOverride("pressed", activeBox); + btn.AddThemeStyleboxOverride("focus", activeBox); + } + else + { + btn.AddThemeFontSizeOverride("font_size", 12); + btn.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + btn.AddThemeColorOverride("font_hover_color", ImperialChrome.TextLight); + btn.AddThemeColorOverride("font_pressed_color", accentColor); + + var normal = MakeSegmentBox(ImperialChrome.BgInner, ImperialChrome.BorderCol, borderW: 1); + var hover = MakeSegmentBox(ImperialChrome.BgHover, new Color(accentColor.R, accentColor.G, accentColor.B, 0.75f), borderW: 1); + var pressed = MakeSegmentBox(ImperialChrome.BgPressed, accentColor, borderW: 2); + btn.AddThemeStyleboxOverride("normal", normal); + btn.AddThemeStyleboxOverride("hover", hover); + btn.AddThemeStyleboxOverride("pressed", pressed); + btn.AddThemeStyleboxOverride("focus", hover); + } + } + + private static StyleBoxFlat MakeSegmentBox(Color bg, Color border, int borderW) + { + var box = new StyleBoxFlat + { + BgColor = bg, + BorderColor = border, + ContentMarginLeft = 8, + ContentMarginRight = 8, + ContentMarginTop = 5, + ContentMarginBottom = 5 + }; + box.SetBorderWidthAll(borderW); + return box; + } +} diff --git a/client/VolumetricCompositorEffect.cs b/client/VolumetricCompositorEffect.cs index 409f621..debe86c 100644 --- a/client/VolumetricCompositorEffect.cs +++ b/client/VolumetricCompositorEffect.cs @@ -19,7 +19,7 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect public const float FlowVoxelSizeMeters = 3.0f; public const int TileSizeHalfRes = 16; public const int TileStrideBytes = 112; - public const int FrameUboBytes = 256; + public const int FrameUboBytes = 272; [StructLayout(LayoutKind.Sequential, Pack = 4)] private struct VolumetricFrameUbo @@ -37,6 +37,7 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect public Vector4 FlowOriginVoxel; public Vector4 FlowInvExtentDt; public int DeltaX, DeltaY, DeltaZ, ImpulseCount; + public uint MaxSteps, MaxIter, IsFullRes, QualityPad; } private readonly Texture3Drd _flowTexRd; @@ -49,6 +50,8 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect private Color _sunColor = Colors.White; private Color _ambientColor = new(0.28f, 0.34f, 0.42f); private float _globalExtinctionScale = 0.28f; + private VfxResolutionScale _resolutionScale = VfxResolutionScale.Half; + private VolumetricSamples _volumetricSamples = VolumetricSamples.Medium; // Render-thread RD state private RenderingDevice? _rd; @@ -90,6 +93,9 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect public double LastMarchGpuMs { get; private set; } public double LastCompGpuMs { get; private set; } public double LastTotalGpuMs => LastFlowGpuMs + LastCullGpuMs + LastMarchGpuMs + LastCompGpuMs; + public Vector2I LastMarchSize { get; private set; } + public int CurrentMaxSteps { get; private set; } = 10; + public int CurrentMaxIter { get; private set; } = 15; public VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool()) { @@ -110,6 +116,16 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect _emitterPool = pool ?? throw new ArgumentNullException(nameof(pool)); } + public void ApplyGraphicsSettings(GraphicsSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + lock (_atmoLock) + { + _resolutionScale = settings.VfxResolution; + _volumetricSamples = settings.VolumetricSamples; + } + } + public void SetAtmosphere(Vector3 sunDir, float sunEnergy, Color sunColor, Color ambientColor, float extinctionScale = 0.28f) { lock (_atmoLock) @@ -158,12 +174,40 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect return; } - Vector2I halfSize = new(Math.Max(1, (fullSize.X + 1) / 2), Math.Max(1, (fullSize.Y + 1) / 2)); - int tilesX = Math.Max(1, (halfSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes); - int tilesY = Math.Max(1, (halfSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes); - int totalTiles = tilesX * tilesY; + VfxResolutionScale resScale; + VolumetricSamples volSamples; + Vector3 sunDir; + float sunEnergy; + Color sunCol, ambCol; + float extScale; + lock (_atmoLock) + { + resScale = _resolutionScale; + volSamples = _volumetricSamples; + sunDir = _sunDir; + sunEnergy = _sunEnergy; + sunCol = _sunColor; + ambCol = _ambientColor; + extScale = _globalExtinctionScale; + } - EnsureHalfResAndTileBuffers(rd, halfSize, totalTiles); + bool isFullRes = resScale == VfxResolutionScale.Full; + float resFactor = GraphicsSettings.GetResolutionScaleFactor(resScale); + Vector2I marchSize = isFullRes + ? fullSize + : new Vector2I( + Math.Max(1, (int)MathF.Round(fullSize.X * resFactor)), + Math.Max(1, (int)MathF.Round(fullSize.Y * resFactor))); + int tilesX = Math.Max(1, (marchSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes); + int tilesY = Math.Max(1, (marchSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes); + int totalTiles = tilesX * tilesY; + (int maxSteps, int maxIter) = GraphicsSettings.GetVolumetricStepBudget(volSamples); + + LastMarchSize = marchSize; + CurrentMaxSteps = maxSteps; + CurrentMaxIter = maxIter; + + EnsureHalfResAndTileBuffers(rd, marchSize, totalTiles); uint viewCount = Math.Max(1u, sceneData.GetViewCount()); const uint view = 0u; @@ -218,19 +262,6 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect 1f / (FlowDimY * FlowVoxelSizeMeters), 1f / (FlowDimZ * FlowVoxelSizeMeters)); - Vector3 sunDir; - float sunEnergy; - Color sunCol, ambCol; - float extScale; - lock (_atmoLock) - { - sunDir = _sunDir; - sunEnergy = _sunEnergy; - sunCol = _sunColor; - ambCol = _ambientColor; - extScale = _globalExtinctionScale; - } - _frameCounter++; var ubo = new VolumetricFrameUbo { @@ -246,8 +277,8 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect SunColorExt = new Vector4(sunCol.R, sunCol.G, sunCol.B, extScale), AmbientColorFog = new Vector4(ambCol.R, ambCol.G, ambCol.B, zNear), ViewportInfo = new Vector4(fullSize.X, fullSize.Y, zFar, emitterCount), - HalfW = (uint)halfSize.X, - HalfH = (uint)halfSize.Y, + HalfW = (uint)marchSize.X, + HalfH = (uint)marchSize.Y, TilesX = (uint)tilesX, FrameIndex = _frameCounter, FlowOriginVoxel = new Vector4(flowOriginWorld.X, flowOriginWorld.Y, flowOriginWorld.Z, FlowVoxelSizeMeters), @@ -255,7 +286,11 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect DeltaX = flowDelta.X, DeltaY = flowDelta.Y, DeltaZ = flowDelta.Z, - ImpulseCount = impulseCount + ImpulseCount = impulseCount, + MaxSteps = (uint)maxSteps, + MaxIter = (uint)maxIter, + IsFullRes = isFullRes ? 1u : 0u, + QualityPad = 0u }; MemoryMarshal.Write(_uboBytes, in ubo); diff --git a/client/flow_field_step.glsl b/client/flow_field_step.glsl index e95aedf..3fbe2a0 100644 --- a/client/flow_field_step.glsl +++ b/client/flow_field_step.glsl @@ -22,6 +22,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame { vec4 flowOriginVoxel; vec4 flowInvExtentDt; ivec4 flowDeltaImpulse; + uvec4 qualityParams; } u_frame; layout(set = 0, binding = 1, std430) readonly buffer FlowImpulseBuffer { diff --git a/client/volumetric_composite.glsl b/client/volumetric_composite.glsl index d2143c8..327bb28 100644 --- a/client/volumetric_composite.glsl +++ b/client/volumetric_composite.glsl @@ -26,6 +26,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame { vec4 flowOriginVoxel; vec4 flowInvExtentDt; ivec4 flowDeltaImpulse; + uvec4 qualityParams; } u_frame; layout(set = 0, binding = 1) uniform sampler2D u_depthTex; @@ -44,13 +45,14 @@ float linearizeReverseZ(float rawDepth) { return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); } -float halfQuadMaxDepth(ivec2 hpx, ivec2 fullRes) { - ivec2 basePx = hpx * 2; +float marchQuadMaxDepth(ivec2 mpx, ivec2 marchRes, ivec2 fullRes) { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(mpx) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(mpx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); float dMax = 0.0; - for (int dy = 0; dy < 2; dy++) { - for (int dx = 0; dx < 2; dx++) { - ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1)); - dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r)); + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r)); } } return dMax; @@ -63,55 +65,82 @@ void main() { return; } - // Empty-tile fast exit: coherent across the 16x16 workgroup (32x32 full-res tile) - ivec2 tileCoord = px / 32; - uint tileIdx = uint(tileCoord.y) * u_frame.tileGridParams.z + uint(tileCoord.x); - if (u_tiles.tiles[tileIdx].count == 0u) { - return; + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); + uint tilesX = u_frame.tileGridParams.z; + bool isFullRes = u_frame.qualityParams.z != 0u; + + vec4 vol; + if (isFullRes) { + ivec2 tileCoord = px / 16; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + if (u_tiles.tiles[tileIdx].count == 0u) { + return; + } + // Direct 1:1 full-res sample bypassing 2x2 bilateral upsample + vol = texelFetch(u_halfVolTex, min(px, marchRes - ivec2(1)), 0); + } else { + vec2 scaleToMarch = vec2(marchRes) / vec2(fullRes); + vec2 hCoord = (vec2(px) + vec2(0.5)) * scaleToMarch - vec2(0.5); + ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), marchRes - ivec2(1)); + ivec2 h1 = min(h0 + ivec2(1), marchRes - ivec2(1)); + + ivec2 t0 = h0 / 16; + ivec2 t1 = h1 / 16; + if (all(equal(t0, t1))) { + uint tileIdx = uint(t0.y) * tilesX + uint(t0.x); + if (u_tiles.tiles[tileIdx].count == 0u) { + return; + } + } else { + uint anyCount = + u_tiles.tiles[uint(t0.y) * tilesX + uint(t0.x)].count + + u_tiles.tiles[uint(t0.y) * tilesX + uint(t1.x)].count + + u_tiles.tiles[uint(t1.y) * tilesX + uint(t0.x)].count + + u_tiles.tiles[uint(t1.y) * tilesX + uint(t1.x)].count; + if (anyCount == 0u) { + return; + } + } + + float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r); + vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0)); + + float depthScale = max(0.45, 0.055 * dFull); + vec4 volSum = vec4(0.0); + float wSum = 0.0; + float wRawSum = 0.0; + float minMarchDepth = 1e9; + + ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1)); + float spatialW[4] = float[4]( + (1.0 - f.x) * (1.0 - f.y), + f.x * (1.0 - f.y), + (1.0 - f.x) * f.y, + f.x * f.y + ); + + for (int i = 0; i < 4; i++) { + ivec2 hp = min(h0 + offsets[i], marchRes - ivec2(1)); + vec4 vSample = texelFetch(u_halfVolTex, hp, 0); + float dMarch = marchQuadMaxDepth(hp, marchRes, fullRes); + minMarchDepth = min(minMarchDepth, dMarch); + float wDepth = exp(-abs(dFull - dMarch) / depthScale); + float wRaw = spatialW[i] * wDepth; + wRawSum += wRaw; + float w = max(1e-5, wRaw); + volSum += vSample * w; + wSum += w; + } + + // Thin foreground occluder (spark/edge strictly in front of ALL 4 march-res background depth taps): + // do not smear background smoke over it + if (wRawSum < 1e-3 && dFull < minMarchDepth * 0.92) { + return; + } + + vol = volSum / max(1e-5, wSum); } - ivec2 halfRes = ivec2(u_frame.tileGridParams.xy); - float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r); - - // 2x2 depth-aware bilateral upsample from half-res volumetric buffer - vec2 hCoord = (vec2(px) + vec2(0.5)) * 0.5 - vec2(0.5); - ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), halfRes - ivec2(1)); - vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0)); - - float depthScale = max(0.45, 0.055 * dFull); - vec4 volSum = vec4(0.0); - float wSum = 0.0; - float wRawSum = 0.0; - float minHalfDepth = 1e9; - - ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1)); - float spatialW[4] = float[4]( - (1.0 - f.x) * (1.0 - f.y), - f.x * (1.0 - f.y), - (1.0 - f.x) * f.y, - f.x * f.y - ); - - for (int i = 0; i < 4; i++) { - ivec2 hp = min(h0 + offsets[i], halfRes - ivec2(1)); - vec4 vSample = texelFetch(u_halfVolTex, hp, 0); - float dHalf = halfQuadMaxDepth(hp, fullRes); - minHalfDepth = min(minHalfDepth, dHalf); - float wDepth = exp(-abs(dFull - dHalf) / depthScale); - float wRaw = spatialW[i] * wDepth; - wRawSum += wRaw; - float w = max(1e-5, wRaw); - volSum += vSample * w; - wSum += w; - } - - // Thin foreground occluder (spark/edge strictly in front of ALL 4 half-res background depth taps): - // do not smear background smoke over it - if (wRawSum < 1e-3 && dFull < minHalfDepth * 0.92) { - return; - } - - vec4 vol = volSum / max(1e-5, wSum); // Skip write when completely transparent if (vol.a > 0.999 && dot(vol.rgb, vol.rgb) < 1e-7) { return; diff --git a/client/volumetric_raymarch.glsl b/client/volumetric_raymarch.glsl index fea9275..2781bf3 100644 --- a/client/volumetric_raymarch.glsl +++ b/client/volumetric_raymarch.glsl @@ -33,6 +33,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame { vec4 flowOriginVoxel; vec4 flowInvExtentDt; ivec4 flowDeltaImpulse; + uvec4 qualityParams; } u_frame; layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { @@ -221,12 +222,12 @@ void main() { memoryBarrierShared(); barrier(); - ivec2 halfRes = ivec2(u_frame.tileGridParams.xy); + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); ivec2 px = ivec2(gl_GlobalInvocationID.xy); // Empty-tile fast exit (uniform across workgroup) if (sTileCount == 0u) { - if (all(lessThan(px, halfRes))) { + if (all(lessThan(px, marchRes))) { imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0)); } return; @@ -239,22 +240,29 @@ void main() { memoryBarrierShared(); barrier(); - if (any(greaterThanEqual(px, halfRes))) { + if (any(greaterThanEqual(px, marchRes))) { return; } ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); - ivec2 basePx = px * 2; + bool isFullRes = u_frame.qualityParams.z != 0u; float dMax = 0.0; - for (int dy = 0; dy < 2; dy++) { - for (int dx = 0; dx < 2; dx++) { - ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1)); - float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); - dMax = max(dMax, linD); + if (isFullRes) { + ivec2 sp = min(px, fullRes - ivec2(1)); + dMax = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); + } else { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(px) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(px + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + float linD = linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r); + dMax = max(dMax, linD); + } } } - vec2 fullUv = (vec2(px) * 2.0 + vec2(1.0)) / vec2(fullRes); + vec2 fullUv = (vec2(px) + vec2(0.5)) / vec2(marchRes); float invCosView; vec3 rd = computeRayDirWorld(fullUv, invCosView); vec3 ro = u_frame.camPosTime.xyz; @@ -313,10 +321,10 @@ void main() { float t = 0.0; int steps = 0; int iter = 0; - const int MaxSteps = 10; - const int MaxIter = 15; + int maxSteps = clamp(int(u_frame.qualityParams.x), 1, 64); + int maxIter = clamp(int(u_frame.qualityParams.y), 1, 96); - while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.03 && steps < MaxSteps && iter < MaxIter) { + while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.03 && steps < maxSteps && iter < maxIter) { // Empty-space jump directly to nextIdx's t0 whenever no emitter is currently active if (activeMask == 0u) { float minNext = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u); diff --git a/client/volumetric_tile_cull.glsl b/client/volumetric_tile_cull.glsl index baf22a8..2ca2c59 100644 --- a/client/volumetric_tile_cull.glsl +++ b/client/volumetric_tile_cull.glsl @@ -33,6 +33,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame { vec4 flowOriginVoxel; vec4 flowInvExtentDt; ivec4 flowDeltaImpulse; + uvec4 qualityParams; } u_frame; layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { @@ -76,21 +77,30 @@ void main() { memoryBarrierShared(); barrier(); - ivec2 halfRes = ivec2(u_frame.tileGridParams.xy); + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); - ivec2 hx = ivec2(gl_GlobalInvocationID.xy); + ivec2 mx = ivec2(gl_GlobalInvocationID.xy); + bool isFullRes = u_frame.qualityParams.z != 0u; float dMin = u_frame.viewportInfo.z; float dMax = 0.0; - if (all(lessThan(hx, halfRes))) { - ivec2 basePx = hx * 2; - for (int dy = 0; dy < 2; dy++) { - for (int dx = 0; dx < 2; dx++) { - ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1)); - float rawD = texelFetch(u_depthTex, sp, 0).r; - float linD = linearizeReverseZ(rawD); - dMin = min(dMin, linD); - dMax = max(dMax, linD); + if (all(lessThan(mx, marchRes))) { + if (isFullRes) { + ivec2 sp = min(mx, fullRes - ivec2(1)); + float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); + dMin = linD; + dMax = linD; + } else { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(mx) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(mx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + float rawD = texelFetch(u_depthTex, ivec2(sx, sy), 0).r; + float linD = linearizeReverseZ(rawD); + dMin = min(dMin, linD); + dMax = max(dMax, linD); + } } } atomicMin(sMinDepthBits, floatBitsToUint(max(0.0, dMin))); @@ -106,10 +116,8 @@ void main() { } // Tile frustum bounds in view space (view looks down -Z, +X right, +Y up) - vec2 tileMinPx = vec2(tileCoord * 16) * 2.0; - vec2 tileMaxPx = min(vec2((tileCoord + ivec2(1)) * 16) * 2.0, vec2(fullRes)); - vec2 uv0 = tileMinPx / vec2(fullRes); - vec2 uv1 = tileMaxPx / vec2(fullRes); + vec2 uv0 = vec2(tileCoord * 16) / vec2(marchRes); + vec2 uv1 = min(vec2((tileCoord + ivec2(1)) * 16) / vec2(marchRes), vec2(1.0)); float tanY = u_frame.camUpTanHalfFov.w; float aspect = u_frame.camRightAspect.w; diff --git a/tests/RustToDust.Tests/GraphicsSettingsTests.cs b/tests/RustToDust.Tests/GraphicsSettingsTests.cs new file mode 100644 index 0000000..6b9c2a3 --- /dev/null +++ b/tests/RustToDust.Tests/GraphicsSettingsTests.cs @@ -0,0 +1,147 @@ +using System; +using System.IO; +using RustToDust.Client; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class GraphicsSettingsTests +{ + [Fact] + public void Defaults_MatchExpectedBaseline() + { + var settings = new GraphicsSettings(); + Assert.Equal(VfxResolutionScale.Half, settings.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, settings.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, settings.SdfgiQuality); + Assert.True(settings.BorderlessFullscreen); + + Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(settings.VfxResolution)); + Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(settings.VolumetricSamples)); + var sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality); + Assert.True(sdfgi.Enabled); + Assert.Equal(0.8f, sdfgi.MinCellSize); + Assert.Equal(3, sdfgi.Cascades); + Assert.True(sdfgi.HalfResolution); + Assert.Equal(4, sdfgi.RayCount); + } + + [Fact] + public void MissingOrCorruptJson_FallsBackToSafeDefaults() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + string missingPath = Path.Combine(tempDir, "missing.json"); + var missingLoaded = GraphicsSettings.Load(missingPath); + Assert.Equal(VfxResolutionScale.Half, missingLoaded.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, missingLoaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, missingLoaded.SdfgiQuality); + Assert.True(missingLoaded.BorderlessFullscreen); + + string corruptPath = Path.Combine(tempDir, "corrupt.json"); + File.WriteAllText(corruptPath, "{ this is not valid json !!!"); + var corruptLoaded = GraphicsSettings.Load(corruptPath); + Assert.Equal(VfxResolutionScale.Half, corruptLoaded.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, corruptLoaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, corruptLoaded.SdfgiQuality); + Assert.True(corruptLoaded.BorderlessFullscreen); + + var outOfRange = new GraphicsSettings(); + Assert.True(outOfRange.LoadFromJson("""{"vfxResolutionScale":99,"volumetricSamples":42,"sdfgiQuality":77,"borderlessFullscreen":false}""")); + Assert.Equal(VfxResolutionScale.Half, outOfRange.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, outOfRange.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, outOfRange.SdfgiQuality); + Assert.False(outOfRange.BorderlessFullscreen); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void SaveAndReload_RoundtripsAllFieldsAndFiresChanged() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + string path = Path.Combine(tempDir, "graphics_settings.json"); + var settings = GraphicsSettings.Load(path); + int changeEvents = 0; + settings.Changed += _ => changeEvents++; + + settings.Apply( + VfxResolutionScale.Full, + VolumetricSamples.Ultra, + SdfgiQuality.High, + borderlessFullscreen: false, + persist: true); + Assert.Equal(1, changeEvents); + Assert.True(File.Exists(path)); + + // No-op apply must not fire duplicate Changed events + settings.Apply( + VfxResolutionScale.Full, + VolumetricSamples.Ultra, + SdfgiQuality.High, + borderlessFullscreen: false, + persist: true); + Assert.Equal(1, changeEvents); + + var reloaded = GraphicsSettings.Load(path); + Assert.Equal(VfxResolutionScale.Full, reloaded.VfxResolution); + Assert.Equal(VolumetricSamples.Ultra, reloaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.High, reloaded.SdfgiQuality); + Assert.False(reloaded.BorderlessFullscreen); + + reloaded.ResetToDefaults(persist: true); + var afterReset = GraphicsSettings.Load(path); + Assert.Equal(VfxResolutionScale.Half, afterReset.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, afterReset.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, afterReset.SdfgiQuality); + Assert.True(afterReset.BorderlessFullscreen); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void PresetMappings_MatchSpecification() + { + Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Half)); + Assert.Equal(0.75f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.ThreeQuarter)); + Assert.Equal(1.00f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Full)); + + Assert.Equal((8, 12), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Low)); + Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Medium)); + Assert.Equal((16, 24), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.High)); + Assert.Equal((24, 36), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Ultra)); + + Assert.False(GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Off).Enabled); + + var balanced = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Balanced); + Assert.True(balanced.Enabled); + Assert.Equal(0.8f, balanced.MinCellSize); + Assert.Equal(3, balanced.Cascades); + Assert.True(balanced.HalfResolution); + Assert.Equal(4, balanced.RayCount); + + var high = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.High); + Assert.True(high.Enabled); + Assert.Equal(0.4f, high.MinCellSize); + Assert.Equal(4, high.Cascades); + Assert.False(high.HalfResolution); + Assert.Equal(8, high.RayCount); + } +} diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj index 3ab44f7..e833c3a 100644 --- a/tests/RustToDust.Tests/RustToDust.Tests.csproj +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -18,6 +18,7 @@ +