diff --git a/.gitignore b/.gitignore index 493bdfc..61bea65 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,7 @@ __pycache__/ /dist/ bin/ obj/ +artifacts/ +build/ .godot/ .vs/ diff --git a/RustToDust.slnx b/RustToDust.slnx index cf1fca2..e78085c 100644 --- a/RustToDust.slnx +++ b/RustToDust.slnx @@ -2,6 +2,7 @@ + diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt new file mode 100644 index 0000000..3e7e1bb --- /dev/null +++ b/THIRD_PARTY_NOTICES.txt @@ -0,0 +1,15 @@ +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION + +This product incorporates or bundles the following third-party software and +font assets under their respective licenses: + +1. Monaspace Krypton (Krypton.ttf — Monaspace Krypton Var.ttf v1.400) + Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace) + Reserved Font Names: 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton' + License: SIL Open Font License, Version 1.1 + Full license text: assets/fonts/OFL-1.1.txt + +2. HarfBuzz (15.2.0) — shaping and hb-gpu shader/curve encoder (rtd_hbgpu) + Copyright (C) HarfBuzz Authors (Behdad Esfahbod, Google Inc., Red Hat Inc., et al.) + License: HarfBuzz "Old MIT" License + Full license text: assets/fonts/HARFBUZZ-COPYING.txt diff --git a/assets/fonts/HARFBUZZ-COPYING.txt b/assets/fonts/HARFBUZZ-COPYING.txt new file mode 100644 index 0000000..1dd917e --- /dev/null +++ b/assets/fonts/HARFBUZZ-COPYING.txt @@ -0,0 +1,42 @@ +HarfBuzz is licensed under the so-called "Old MIT" license. Details follow. +For parts of HarfBuzz that are licensed under different licenses see individual +files names COPYING in subdirectories where applicable. + +Copyright © 2010-2022 Google, Inc. +Copyright © 2015-2020 Ebrahim Byagowi +Copyright © 2019,2020 Facebook, Inc. +Copyright © 2012,2015 Mozilla Foundation +Copyright © 2011 Codethink Limited +Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) +Copyright © 2009 Keith Stribley +Copyright © 2011 Martin Hosken and SIL International +Copyright © 2007 Chris Wilson +Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod +Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. +Copyright © 1998-2005 David Turner and Werner Lemberg +Copyright © 2016 Igalia S.L. +Copyright © 2022 Matthias Clasen +Copyright © 2018,2021 Khaled Hosny +Copyright © 2018,2019,2020 Adobe, Inc +Copyright © 2013-2015 Alexei Podtelezhnikov + +For full copyright notices consult the individual files in the package. + + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that the +above copyright notice and the following two paragraphs appear in +all copies of this software. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN +IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/assets/fonts/Krypton.ttf b/assets/fonts/Krypton.ttf new file mode 100644 index 0000000..821c61e Binary files /dev/null and b/assets/fonts/Krypton.ttf differ diff --git a/assets/fonts/OFL-1.1.txt b/assets/fonts/OFL-1.1.txt new file mode 100644 index 0000000..0ad8d06 --- /dev/null +++ b/assets/fonts/OFL-1.1.txt @@ -0,0 +1,94 @@ +Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace) +with Reserved Font Names 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton'. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSIONS & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to remain +under this license does not apply to any document created using the fonts +or their derivatives. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index c185907..e7d6e46 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -24,9 +24,7 @@ public partial class ArenaRenderer : Node3D public required VehicleVisualInstance Visual; public MeshInstance3D? HaloMesh; public StandardMaterial3D? HaloMat; - public MeshInstance3D? LaserMesh; public SpectatorStance? LastHaloStance; - public bool LastLaserVisible; public float RigDtAccum; public int RigSkipFrames; } @@ -728,10 +726,6 @@ public partial class ArenaRenderer : Node3D hiddenVis.Visual.SyncDamageAndHeat(s.Grid, _debris, Vector3.Zero); } hiddenVis.Visual.Root.Visible = false; - if (hiddenVis.LaserMesh is not null) - { - hiddenVis.LaserMesh.Visible = false; - } } continue; } @@ -853,42 +847,6 @@ public partial class ArenaRenderer : Node3D vis.HaloMat.EmissionEnergyMultiplier = pulse; } } - - // Lock-on laser beam when Cleared or Provoked - if (vis.LaserMesh is not null) - { - if (s.Stance != SpectatorStance.Neutral && s.HasTargetLos && target is { Alive: true } && - (target.Id == session.LocalContenderId || session.IsContenderVisible(target.Id))) - { - Vector3 start = specPos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.7f, 0f); - var (targetPos, _, _) = session.GetInterpolatedContenderPose(target.Id, alpha); - Vector3 end = new Vector3(targetPos.X, targetPos.Y + target.Grid.Spec.HalfHeight * 0.3f, targetPos.Z); - float dist = start.DistanceTo(end); - if (dist > 0.5f) - { - if (!vis.LastLaserVisible) - { - vis.LastLaserVisible = true; - vis.LaserMesh.Visible = true; - } - vis.LaserMesh.GlobalPosition = (start + end) * 0.5f; - Vector3 dir = (end - start).Normalized(); - Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.99f ? Vector3.Right : Vector3.Up; - vis.LaserMesh.LookAt(end, up); - vis.LaserMesh.Scale = new Vector3(1f, 1f, dist); - } - else if (vis.LastLaserVisible) - { - vis.LastLaserVisible = false; - vis.LaserMesh.Visible = false; - } - } - else if (vis.LastLaserVisible) - { - vis.LastLaserVisible = false; - vis.LaserMesh.Visible = false; - } - } } } @@ -910,30 +868,11 @@ public partial class ArenaRenderer : Node3D }; instance.Root.AddChild(halo); - var laserMat = new StandardMaterial3D - { - AlbedoColor = new Color(2.2f, 0.24f, 0.20f, 0.85f), - EmissionEnabled = true, - Emission = new Color(1f, 0.12f, 0.1f), - EmissionEnergyMultiplier = 2.2f, - ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, - Transparency = BaseMaterial3D.TransparencyEnum.Alpha - }; - var laser = new MeshInstance3D - { - Mesh = new BoxMesh { Size = new Vector3(0.08f, 0.08f, 1.0f) }, - MaterialOverride = laserMat, - Visible = false, - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off - }; - _actorsGroup.AddChild(laser); - return new ActorVisual { Visual = instance, HaloMesh = halo, - HaloMat = haloMat, - LaserMesh = laser + HaloMat = haloMat }; } diff --git a/client/AtmosphereLutBaker.cs b/client/AtmosphereLutBaker.cs index 312f0c7..5d18af7 100644 --- a/client/AtmosphereLutBaker.cs +++ b/client/AtmosphereLutBaker.cs @@ -90,12 +90,12 @@ public static class AtmosphereLutBaker MieScattering: new Vector3(3.2e-6f, 3.2e-6f, 3.2e-6f), MieG: 0.78f, SolarIrradiance: 17.5f, - CalibratedSunEnergy: 1.28f, + CalibratedSunEnergy: 2.85f, FogMaxLengthMeters: 460f, VolumetricFogDensity: 0.0008f, VolumetricFogDetailSpread: 2.4f, VolumetricFogAnisotropy: 0.62f, - VolumetricFogEmissionEnergy: 0.18f, + VolumetricFogEmissionEnergy: 0f, ValleyVolumeSize: new Vector3(3100f, 110f, 3100f), ValleyVolumePosition: new Vector3(0f, 20f, 0f), ValleyVolumeDensity: 0.0038f, @@ -108,7 +108,7 @@ public static class AtmosphereLutBaker DepthFogAerialPerspective: 0.88f, DepthFogSunScatter: 0.45f, ShadowMaxDistance: 320f, - AmbientLightEnergy: 0.48f, + AmbientLightEnergy: 0.0f, SunDiscIntensity: 8.5f, MieAureoleStrength: 0.24f) : new AtmospherePreset( @@ -120,12 +120,12 @@ public static class AtmosphereLutBaker MieScattering: new Vector3(10.5e-6f, 8.8e-6f, 6.6e-6f), MieG: 0.74f, SolarIrradiance: 16.0f, - CalibratedSunEnergy: 1.42f, + CalibratedSunEnergy: 2.55f, FogMaxLengthMeters: 380f, VolumetricFogDensity: 0.0012f, VolumetricFogDetailSpread: 2.2f, VolumetricFogAnisotropy: 0.68f, - VolumetricFogEmissionEnergy: 0.22f, + VolumetricFogEmissionEnergy: 0f, ValleyVolumeSize: new Vector3(1600f, 56f, 1600f), ValleyVolumePosition: new Vector3(0f, 2f, 0f), ValleyVolumeDensity: 0.0052f, @@ -138,7 +138,7 @@ public static class AtmosphereLutBaker DepthFogAerialPerspective: 0.22f, DepthFogSunScatter: 0.65f, ShadowMaxDistance: 280f, - AmbientLightEnergy: 0.55f, + AmbientLightEnergy: 0.0f, SunDiscIntensity: 8.0f, MieAureoleStrength: 0.30f); diff --git a/client/AtmosphereSystem.cs b/client/AtmosphereSystem.cs index d610144..17bda3b 100644 --- a/client/AtmosphereSystem.cs +++ b/client/AtmosphereSystem.cs @@ -65,14 +65,24 @@ public partial class AtmosphereSystem : Node { BackgroundMode = Godot.Environment.BGMode.Sky, Sky = _sky, - AmbientLightSource = Godot.Environment.AmbientSource.Sky, - AmbientLightEnergy = 0.48f, + AmbientLightSource = Godot.Environment.AmbientSource.Disabled, + AmbientLightEnergy = 0.0f, + + // Option 1 (Low-Gamma): SDFGI multi-bounce + occlusion with zero flat ambient + SdfgiEnabled = true, + SdfgiUseOcclusion = true, + SdfgiReadSkyLight = true, + SdfgiBounceFeedback = 0.60f, + SdfgiCascades = 3, + SdfgiMinCellSize = 0.8f, + SdfgiYScale = Godot.Environment.SdfgiyScale.Scale75Percent, + SdfgiEnergy = 0.85f, // AgX tonemapping preserves orange/amber combat hues while rolling off HDR emitters smoothly TonemapMode = Godot.Environment.ToneMapper.Agx, TonemapAgxWhite = 6.0f, - TonemapAgxContrast = 1.22f, - TonemapExposure = 1.0f, + TonemapAgxContrast = 1.50f, + TonemapExposure = 0.84f, // Normalized additive bloom strictly above GlowHdrThreshold=1.0 (zero diffuse screen smear) GlowEnabled = true, @@ -107,7 +117,7 @@ public partial class AtmosphereSystem : Node VolumetricFogEnabled = true, VolumetricFogTemporalReprojectionEnabled = true, VolumetricFogTemporalReprojectionAmount = 0.88f, - VolumetricFogAmbientInject = 0.25f, + VolumetricFogAmbientInject = 0.0f, VolumetricFogSkyAffect = 0.10f, // Tier 2: Far aerial perspective (340/400m .. horizon peaks) @@ -139,6 +149,10 @@ public partial class AtmosphereSystem : Node if (RenderingServer.GetRenderingDevice() is not null) { + RenderingServer.GISetUseHalfResolution(true); + RenderingServer.EnvironmentSetSdfgiRayCount(RenderingServer.EnvironmentSdfgiRayCount.Count4); + RenderingServer.EnvironmentSetSdfgiFramesToConverge(RenderingServer.EnvironmentSdfgiFramesToConverge.In10Frames); + RenderingServer.EnvironmentSetSdfgiFramesToUpdateLight(RenderingServer.EnvironmentSdfgiFramesToUpdateLight.In8Frames); _flowTexRd = new Texture3Drd(); RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd); _volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool); @@ -196,6 +210,7 @@ public partial class AtmosphereSystem : Node ?? throw new InvalidOperationException("Failed to load res://film_grain.gdshader"); _filmGrainMat = new ShaderMaterial { Shader = grainShader }; _filmGrainMat.SetShaderParameter("grain_strength", 0.018f); + _filmGrainMat.SetShaderParameter("post_gamma", 1.32f); _filmGrainLayer = new CanvasLayer { @@ -249,9 +264,9 @@ public partial class AtmosphereSystem : Node _env.VolumetricFogDensity = preset.VolumetricFogDensity; _env.VolumetricFogDetailSpread = preset.VolumetricFogDetailSpread; _env.VolumetricFogAnisotropy = preset.VolumetricFogAnisotropy; - _env.VolumetricFogEmissionEnergy = preset.VolumetricFogEmissionEnergy; + _env.VolumetricFogEmissionEnergy = 0f; _env.VolumetricFogAlbedo = haze; - _env.VolumetricFogEmission = new Color(haze.R * 0.45f, haze.G * 0.45f, haze.B * 0.45f, 1.0f); + _env.VolumetricFogEmission = Colors.Black; _valleyFog.Size = preset.ValleyVolumeSize; _valleyFog.Position = preset.ValleyVolumePosition; @@ -259,7 +274,7 @@ public partial class AtmosphereSystem : Node _valleyFogMat.HeightFalloff = preset.ValleyVolumeHeightFalloff; _valleyFogMat.EdgeFade = preset.ValleyVolumeEdgeFade; _valleyFogMat.Albedo = haze; - _valleyFogMat.Emission = new Color(haze.R * 0.35f, haze.G * 0.35f, haze.B * 0.35f, 1.0f); + _valleyFogMat.Emission = Colors.Black; _env.FogLightColor = haze; _env.FogDepthBegin = preset.DepthFogBegin; @@ -280,7 +295,7 @@ public partial class AtmosphereSystem : Node baked.SunLightEnergy, baked.SunLightColor, ambCol, - extinctionScale: mapKind == ArenaMapKind.Sion ? 1.85f : 1.70f); + extinctionScale: mapKind == ArenaMapKind.Sion ? 0.95f : 0.85f); } } @@ -290,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..e8e4e60 --- /dev/null +++ b/client/GraphicsSettings.cs @@ -0,0 +1,270 @@ +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, + bool forcePersist = false) + { + 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) + { + if (persist && forcePersist) + { + Save(); + } + 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, + forcePersist: 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/HbGpuCanvas.cs b/client/HbGpuCanvas.cs new file mode 100644 index 0000000..5ba193b --- /dev/null +++ b/client/HbGpuCanvas.cs @@ -0,0 +1,933 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.HbGpu; + +namespace RustToDust.Client; + +/// +/// Single-draw-call HarfBuzz 15.2.0 hb-gpu GLSL renderer on Godot 4.7 Forward+ Vulkan RenderingDevice. +/// Safe in --headless / null-RD mode: preserves CPU shaping/layout without allocating RD resources. +/// +public partial class HbGpuCanvas : Control +{ + public const byte DefaultFontId = 0; + private const int PushConstantBytes = 80; // mat4 (64) + vec2 viewport (8) + vec2 logicalSize (8) + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct PushConstants + { + // Column-major mat4 for GLSL: col 0, col 1, col 2, col 3 + public float C0R0, C0R1, C0R2, C0R3; + public float C1R0, C1R1, C1R2, C1R3; + public float C2R0, C2R1, C2R2, C2R3; + public float C3R0, C3R1, C3R2, C3R3; + public float ViewportX, ViewportY; + public float LogicalW, LogicalH; + } + + private readonly HbGpuFontCache _fontCache = new(); + private readonly HbGpuAtlasAllocator _atlas = new(); + private readonly HbGpuBlobCache _blobCache; + private readonly HbGpuCommandWriter _writer = new(); + + private readonly object _syncLock = new(); + private readonly HbGpuQuadInstance[] _stagedQuads = new HbGpuQuadInstance[HbGpuCommandWriter.MaxQuads]; + private int _stagedQuadCount; + private float _stagedLogicalW = 1280f; + private float _stagedLogicalH = 720f; + private int _stagedPhysW = 1280; + private int _stagedPhysH = 720; + private bool _hasStagedFrame; + + private TextureRect? _outputRect; + private Texture2Drd? _outputTexRd; + private HbGpuVulkanBackend? _backend; + private Callable _renderCallable; + private Callable _disposeCallable; + private bool _disposed; + + public bool ProfilingEnabled { get; set; } + public double LastHbGpuMs => _backend?.LastHbGpuMs ?? 0.0; + public int LastDrawCallCount => _backend?.LastDrawCallCount ?? 0; + public int LastQuadCount { get; private set; } + public bool IsVulkanActive => RenderingServer.GetRenderingDevice() is not null; + + public HbGpuFontCache Fonts => _fontCache; + public HbGpuBlobCache Blobs => _blobCache; + public HbGpuCommandWriter Writer => _writer; + + public HbGpuCanvas() + { + _blobCache = new HbGpuBlobCache(_atlas); + MouseFilter = MouseFilterEnum.Ignore; + } + + public override void _Ready() + { + SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + MouseFilter = MouseFilterEnum.Ignore; + + LoadDefaultKryptonFont(); + + if (RenderingServer.GetRenderingDevice() is not null) + { + _outputTexRd = new Texture2Drd(); + _outputRect = new TextureRect + { + Name = "HbGpuOutput", + MouseFilter = MouseFilterEnum.Ignore, + ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, + StretchMode = TextureRect.StretchModeEnum.Scale, + Texture = _outputTexRd, + Material = new CanvasItemMaterial + { + BlendMode = CanvasItemMaterial.BlendModeEnum.PremultAlpha + } + }; + AddChild(_outputRect); + _outputRect.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _backend = new HbGpuVulkanBackend(_outputTexRd, _atlas); + _renderCallable = Callable.From(RenderOnRenderThread); + _disposeCallable = Callable.From(DisposeOnRenderThread); + } + } + + private void LoadDefaultKryptonFont() + { + if (_fontCache.TryGetMetrics(DefaultFontId, out _)) + { + return; + } + + string path = ResolveKryptonPath(); + _fontCache.RegisterFontFromFile(DefaultFontId, path); + } + + public static string ResolveKryptonPath() + { + ClientAssets.EnsureAssetsRootRegistered(); + string[] candidates = + { + Path.Combine(ClientAssets.LocateAssetsDirectory(), "fonts", "Krypton.ttf"), + Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), "..", "assets", "fonts", "Krypton.ttf")), + Path.Combine(AppContext.BaseDirectory, "assets", "fonts", "Krypton.ttf") + }; + + foreach (string c in candidates) + { + if (File.Exists(c)) + { + return c; + } + } + + throw new FileNotFoundException("Could not locate assets/fonts/Krypton.ttf."); + } + + public void BeginFrame() + { + _blobCache.EnsureBudgetOrReset(); + _writer.BeginFrame(); + } + + public float DrawText( + ReadOnlySpan text, + float x, + float baselineY, + float fontSizePx, + Color color, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default, + bool stemDarken = true, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + return _writer.DrawTextUtf16( + text, x, baselineY, fontSizePx, + color.R, color.G, color.B, color.A, + _fontCache, _blobCache, + DefaultFontId, wght, wdth, slnt, + features, stemDarken, clipMinPacked, clipMaxPacked); + } + + public float MeasureTextWidth( + ReadOnlySpan text, + float fontSizePx, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default) + { + return _writer.MeasureTextWidth(text, fontSizePx, _fontCache, DefaultFontId, wght, wdth, slnt, features); + } + + public void DrawRectFilled(float x, float y, float w, float h, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache); + float cx = x + w * 0.5f; + float cy = y + h * 0.5f; + _writer.DrawBlob( + blob, cx, cy, + w * 0.001f, 0f, 0f, -h * 0.001f, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawLineSegment(float x0, float y0, float x1, float y1, float thicknessPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + float dx = x1 - x0; + float dy = y1 - y0; + float len = MathF.Sqrt(dx * dx + dy * dy); + if (len < 1e-4f || thicknessPx <= 0f) + { + return; + } + + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache); + float cos = dx / len; + float sin = dy / len; + float sx = len * 0.001f; + float sy = thicknessPx * 0.001f; + float cx = (x0 + x1) * 0.5f; + float cy = (y0 + y1) * 0.5f; + // Rotate unit rect (X along segment, Y perpendicular) in Y-down screen coords + _writer.DrawBlob( + blob, cx, cy, + cos * sx, -sin * sy, + sin * sx, cos * sy, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawCircleFilled(float cx, float cy, float radiusPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledCircle(_blobCache); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawCircleRing(float cx, float cy, float radiusPx, float strokePx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + ushort strokeUnits = (ushort)Math.Clamp((int)MathF.Round(strokePx / radiusPx * 500f), 2, 480); + CachedBlob blob = HbGpuVectorShapes.GetUnitRingStroke(_blobCache, strokeUnits); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawTargetBracketCorner(float cornerX, float cornerY, float armPx, float thicknessPx, int quadrant, Color color) + { + if (armPx <= 0f || thicknessPx <= 0f) + { + return; + } + + ushort thickUnits = (ushort)Math.Clamp((int)MathF.Round(thicknessPx / armPx * 1000f), 10, 450); + CachedBlob blob = HbGpuVectorShapes.GetTargetBracketCorner(_blobCache, thickUnits); + float s = armPx * 0.001f; + // Design space: corner at (0,0), X in [0..1000], Y in [-1000..0] (so -emY points down in screen if m11 = -s -> +s). + // Rotate per quadrant: 0=top-left (+X,+Y), 1=top-right (-X,+Y), 2=bottom-right (-X,-Y), 3=bottom-left (+X,-Y) + float sx = (quadrant == 1 || quadrant == 2) ? -s : s; + float sy = (quadrant == 2 || quadrant == 3) ? s : -s; + _writer.DrawBlob( + blob, cornerX, cornerY, + sx, 0f, 0f, sy, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawDirectionalArrow(float cx, float cy, float sizePx, float angleRad, Color color) + { + CachedBlob blob = HbGpuVectorShapes.GetDirectionalArrow(_blobCache); + float s = sizePx * 0.001f; + float cos = MathF.Cos(angleRad); + float sin = MathF.Sin(angleRad); + // Angle 0 points right (+X) in screen space; design arrow points +Y, so rotate by angleRad - PI/2 with Y flip + // Design (0, +500) -> screen (+cos, +sin) * sizePx * 0.5 + _writer.DrawBlob( + blob, cx, cy, + -sin * s, cos * s, + cos * s, sin * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawArcStrokeDynamic(float cx, float cy, float radiusPx, float strokePx, float startRadScreen, float endRadScreen, Color color) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + float halfThickDesign = Math.Clamp(strokePx / radiusPx * 250f, 2f, 200f); + // Screen Y-down angles -> design Y-up angles (negate angles so screen clockwise matches -design angle) + CachedBlob blob = HbGpuVectorShapes.EncodeArcStrokeDynamic(_blobCache, -endRadScreen, -startRadScreen, 500f, halfThickDesign); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void EndFrameAndSubmit() + { + LastQuadCount = _writer.QuadCount; + + if (_backend is null || _disposed) + { + _atlas.ClearPending(); + return; + } + + ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH); + + lock (_syncLock) + { + int count = _writer.QuadCount; + if (count > 0) + { + Array.Copy(_writer.RawBuffer, 0, _stagedQuads, 0, count); + } + _stagedQuadCount = count; + _stagedLogicalW = logicalW; + _stagedLogicalH = logicalH; + _stagedPhysW = physW; + _stagedPhysH = physH; + _hasStagedFrame = true; + _backend.ProfilingEnabled = ProfilingEnabled; + } + + RenderingServer.CallOnRenderThread(_renderCallable); + } + + private void ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH) + { + Viewport? vp = GetViewport(); + if (vp is null) + { + logicalW = MathF.Max(2f, Size.X); + logicalH = MathF.Max(2f, Size.Y); + physW = Math.Max(2, Mathf.RoundToInt(logicalW)); + physH = Math.Max(2, Mathf.RoundToInt(logicalH)); + return; + } + + Vector2 vis = vp.GetVisibleRect().Size; + if (vis.X < 2f || vis.Y < 2f) + { + vis = Size; + } + + logicalW = MathF.Max(2f, vis.X); + logicalH = MathF.Max(2f, vis.Y); + + if (vp is SubViewport sv) + { + physW = Math.Max(2, sv.Size.X); + physH = Math.Max(2, sv.Size.Y); + } + else + { + Vector2 stretchScale = vp.GetStretchTransform().Scale; + physW = Math.Max(2, Mathf.RoundToInt(logicalW * stretchScale.X)); + physH = Math.Max(2, Mathf.RoundToInt(logicalH * stretchScale.Y)); + } + } + + private void RenderOnRenderThread() + { + if (_backend is null || _disposed) + { + return; + } + + int quadCount; + float logicalW, logicalH; + int physW, physH; + lock (_syncLock) + { + if (!_hasStagedFrame) + { + return; + } + _hasStagedFrame = false; + quadCount = _stagedQuadCount; + logicalW = _stagedLogicalW; + logicalH = _stagedLogicalH; + physW = _stagedPhysW; + physH = _stagedPhysH; + _backend.RenderFrame(_stagedQuads, quadCount, logicalW, logicalH, physW, physH); + } + } + + private void DisposeOnRenderThread() + { + _backend?.DisposeRdResources(); + } + + /// + /// Synchronously reads back the current offscreen RGBA8 render target from RenderingDevice. + /// Intended strictly for verification probes/tests. + /// + public bool TryReadbackRgba8(out byte[] data, out int width, out int height) + { + byte[]? captured = null; + int w = 0, h = 0; + + if (_backend is null || RenderingServer.GetRenderingDevice() is null) + { + data = Array.Empty(); + width = 0; + height = 0; + return false; + } + + RenderingServer.CallOnRenderThread(Callable.From(() => + { + _backend.TryReadbackOnRenderThread(out captured, out w, out h); + })); + RenderingServer.ForceSync(); + + if (captured is null || w <= 0 || h <= 0) + { + data = Array.Empty(); + width = 0; + height = 0; + return false; + } + + data = captured; + width = w; + height = h; + return true; + } + + public override void _ExitTree() + { + if (_disposed) + { + return; + } + _disposed = true; + + if (_outputTexRd is not null) + { + _outputTexRd.TextureRdRid = new Rid(); + } + + if (_backend is not null && RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.CallOnRenderThread(_disposeCallable); + RenderingServer.ForceSync(); + } + + _fontCache.Dispose(); + } + + private sealed class HbGpuVulkanBackend + { + private readonly Texture2Drd _outputTexRd; + private readonly HbGpuAtlasAllocator _atlas; + + private readonly byte[] _atlasMirrorBytes = new byte[HbGpuAtlasAllocator.TotalBytes]; + private readonly byte[] _quadUploadBytes = new byte[HbGpuCommandWriter.MaxQuads * 80]; + private readonly byte[] _pushConstantBytes = new byte[PushConstantBytes]; + private static readonly Color[] ClearColors = { new Color(0f, 0f, 0f, 0f) }; + + private RenderingDevice? _rd; + private bool _initialized; + private bool _failed; + + private Rid _shaderRid; + private Rid _pipelineRid; + private Rid _atlasBufRid; + private Rid _quadSsboRid; + private Rid _uniformSetRid; + private Rid _colorTexRid; + private Rid _framebufferRid; + private int _fbWidth; + private int _fbHeight; + + private ulong _frameIndex; + private ulong _lastSampledTimestampFrame = ulong.MaxValue; + + public bool ProfilingEnabled { get; set; } + public double LastHbGpuMs { get; private set; } + public int LastDrawCallCount { get; private set; } + + public HbGpuVulkanBackend(Texture2Drd outputTexRd, HbGpuAtlasAllocator atlas) + { + _outputTexRd = outputTexRd; + _atlas = atlas; + } + + public void RenderFrame( + HbGpuQuadInstance[] quads, + int quadCount, + float logicalW, + float logicalH, + int physW, + int physH) + { + if (_failed) + { + return; + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + bool atlasDirty = _atlas.PendingChunkCount > 0; + if (atlasDirty) + { + _atlas.DrainToMirror(_atlasMirrorBytes); + } + + if (!_initialized) + { + if (!TryInitialize(rd, physW, physH)) + { + _failed = true; + return; + } + } + else + { + if (atlasDirty) + { + RebuildAtlasBufferAndUniformSet(rd); + } + if (physW != _fbWidth || physH != _fbHeight) + { + RecreateRenderTarget(rd, physW, physH); + } + } + + _rd = rd; + _frameIndex++; + + // Upload quad instances into SSBO + if (quadCount > 0) + { + uint byteLen = (uint)(quadCount * 80); + ReadOnlySpan srcBytes = MemoryMarshal.AsBytes(quads.AsSpan(0, quadCount)); + srcBytes.CopyTo(_quadUploadBytes); + rd.BufferUpdate(_quadSsboRid, 0, byteLen, _quadUploadBytes); + } + + bool captureTs = ProfilingEnabled && rd.GetCapturedTimestampsCount() < 180; + if (ProfilingEnabled) + { + SamplePreviousTimestamps(rd); + } + if (captureTs) + { + rd.CaptureTimestamp("HbGpu_Start"); + } + + long dl = rd.DrawListBegin(_framebufferRid, RenderingDevice.DrawFlags.ClearColorAll, ClearColors); + if (quadCount > 0) + { + var pc = new PushConstants + { + C0R0 = 2.0f / logicalW, + C1R1 = 2.0f / logicalH, + C2R2 = 1.0f, + C3R0 = -1.0f, + C3R1 = -1.0f, + C3R3 = 1.0f, + ViewportX = physW, + ViewportY = physH, + LogicalW = logicalW, + LogicalH = logicalH + }; + MemoryMarshal.Write(_pushConstantBytes, in pc); + + rd.DrawListBindRenderPipeline(dl, _pipelineRid); + rd.DrawListBindUniformSet(dl, _uniformSetRid, 0); + rd.DrawListSetPushConstant(dl, _pushConstantBytes, PushConstantBytes); + rd.DrawListDraw(dl, useIndices: false, instances: (uint)quadCount, proceduralVertexCount: 6u); + LastDrawCallCount = 1; + } + else + { + LastDrawCallCount = 0; + } + rd.DrawListEnd(); + + if (captureTs) + { + rd.CaptureTimestamp("HbGpu_End"); + } + } + + private void RebuildAtlasBufferAndUniformSet(RenderingDevice rd) + { + if (_uniformSetRid.IsValid) + { + rd.FreeRid(_uniformSetRid); + _uniformSetRid = new Rid(); + } + if (_atlasBufRid.IsValid) + { + rd.FreeRid(_atlasBufRid); + _atlasBufRid = new Rid(); + } + + _atlasBufRid = rd.TextureBufferCreate( + HbGpuAtlasAllocator.TotalTexels, + RenderingDevice.DataFormat.R16G16B16A16Sint, + _atlasMirrorBytes); + + var u0 = new RDUniform + { + UniformType = RenderingDevice.UniformType.TextureBuffer, + Binding = 0 + }; + u0.AddId(_atlasBufRid); + + var u1 = new RDUniform + { + UniformType = RenderingDevice.UniformType.StorageBuffer, + Binding = 1 + }; + u1.AddId(_quadSsboRid); + + _uniformSetRid = rd.UniformSetCreate(new Godot.Collections.Array { u0, u1 }, _shaderRid, 0); + } + + private void SamplePreviousTimestamps(RenderingDevice rd) + { + uint count = rd.GetCapturedTimestampsCount(); + if (count == 0) + { + return; + } + + ulong tsFrame = rd.GetCapturedTimestampsFrame(); + if (tsFrame == _lastSampledTimestampFrame) + { + return; + } + _lastSampledTimestampFrame = tsFrame; + + ulong tStart = 0, tEnd = 0; + for (uint i = 0; i < count; i++) + { + string name = rd.GetCapturedTimestampName(i); + if (name == "HbGpu_Start") + { + tStart = rd.GetCapturedTimestampGpuTime(i); + } + else if (name == "HbGpu_End") + { + tEnd = rd.GetCapturedTimestampGpuTime(i); + } + } + + if (tStart > 0 && tEnd >= tStart) + { + LastHbGpuMs = (tEnd - tStart) / 1_000_000.0; + } + } + + private bool TryInitialize(RenderingDevice rd, int physW, int physH) + { + _rd = rd; + + string vertSrc = BuildVertexShaderSource(); + string fragSrc = BuildFragmentShaderSource(); + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceVertex = vertSrc, + SourceFragment = fragSrc + }; + + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + if (!string.IsNullOrEmpty(spirv.CompileErrorVertex)) + { + GD.PrintErr($"HbGpuCanvas vertex SPIR-V error: {spirv.CompileErrorVertex}"); + return false; + } + if (!string.IsNullOrEmpty(spirv.CompileErrorFragment)) + { + GD.PrintErr($"HbGpuCanvas fragment SPIR-V error: {spirv.CompileErrorFragment}"); + return false; + } + + _shaderRid = rd.ShaderCreateFromSpirV(spirv, "HbGpuCanvas"); + if (!_shaderRid.IsValid) + { + GD.PrintErr("HbGpuCanvas: ShaderCreateFromSpirV failed."); + return false; + } + + _quadSsboRid = rd.StorageBufferCreate((uint)(HbGpuCommandWriter.MaxQuads * 80)); + RebuildAtlasBufferAndUniformSet(rd); + + RecreateRenderTarget(rd, physW, physH); + + long fbFormat = rd.FramebufferGetFormat(_framebufferRid); + + var rasterState = new RDPipelineRasterizationState + { + CullMode = RenderingDevice.PolygonCullMode.Disabled + }; + var msState = new RDPipelineMultisampleState + { + SampleCount = RenderingDevice.TextureSamples.Samples1 + }; + var dsState = new RDPipelineDepthStencilState(); + var blendAttachment = new RDPipelineColorBlendStateAttachment + { + EnableBlend = true, + SrcColorBlendFactor = RenderingDevice.BlendFactor.One, + DstColorBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha, + ColorBlendOp = RenderingDevice.BlendOperation.Add, + SrcAlphaBlendFactor = RenderingDevice.BlendFactor.One, + DstAlphaBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha, + AlphaBlendOp = RenderingDevice.BlendOperation.Add + }; + var blendState = new RDPipelineColorBlendState(); + blendState.Attachments.Add(blendAttachment); + + _pipelineRid = rd.RenderPipelineCreate( + _shaderRid, + fbFormat, + RenderingDevice.InvalidFormatId, + RenderingDevice.RenderPrimitive.Triangles, + rasterState, + msState, + dsState, + blendState); + + if (!_pipelineRid.IsValid) + { + GD.PrintErr("HbGpuCanvas: RenderPipelineCreate failed."); + return false; + } + + _initialized = true; + return true; + } + + private void RecreateRenderTarget(RenderingDevice rd, int physW, int physH) + { + if (_framebufferRid.IsValid) + { + rd.FreeRid(_framebufferRid); + _framebufferRid = new Rid(); + } + if (_colorTexRid.IsValid) + { + _outputTexRd.TextureRdRid = new Rid(); + rd.FreeRid(_colorTexRid); + _colorTexRid = new Rid(); + } + + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R8G8B8A8Unorm, + Width = (uint)physW, + Height = (uint)physH, + Depth = 1, + ArrayLayers = 1, + Mipmaps = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.ColorAttachmentBit + | RenderingDevice.TextureUsageBits.SamplingBit + | RenderingDevice.TextureUsageBits.CanCopyFromBit + }; + _colorTexRid = rd.TextureCreate(fmt, new RDTextureView()); + _framebufferRid = rd.FramebufferCreate(new Godot.Collections.Array { _colorTexRid }); + _fbWidth = physW; + _fbHeight = physH; + _outputTexRd.TextureRdRid = _colorTexRid; + } + + public void TryReadbackOnRenderThread(out byte[]? data, out int width, out int height) + { + if (_rd is null || !_initialized || !_colorTexRid.IsValid) + { + data = null; + width = 0; + height = 0; + return; + } + + data = _rd.TextureGetData(_colorTexRid, 0); + width = _fbWidth; + height = _fbHeight; + } + + public void DisposeRdResources() + { + if (_rd is null) + { + return; + } + + _outputTexRd.TextureRdRid = new Rid(); + + if (_framebufferRid.IsValid) { _rd.FreeRid(_framebufferRid); _framebufferRid = new Rid(); } + if (_colorTexRid.IsValid) { _rd.FreeRid(_colorTexRid); _colorTexRid = new Rid(); } + if (_uniformSetRid.IsValid) { _rd.FreeRid(_uniformSetRid); _uniformSetRid = new Rid(); } + if (_quadSsboRid.IsValid) { _rd.FreeRid(_quadSsboRid); _quadSsboRid = new Rid(); } + if (_atlasBufRid.IsValid) { _rd.FreeRid(_atlasBufRid); _atlasBufRid = new Rid(); } + if (_pipelineRid.IsValid) { _rd.FreeRid(_pipelineRid); _pipelineRid = new Rid(); } + if (_shaderRid.IsValid) { _rd.FreeRid(_shaderRid); _shaderRid = new Rid(); } + + _initialized = false; + _rd = null; + } + + private static string BuildVertexShaderSource() + { + string sharedVert = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared); + return $@"#version 450 +{sharedVert} + +struct QuadInstance {{ + vec4 em_box; + vec4 pos_anchor; + vec4 xform; + vec4 color; + uvec4 meta; +}}; + +layout(set = 0, binding = 1, std430) readonly buffer Quads {{ + QuadInstance quads[]; +}}; + +layout(push_constant, std430) uniform Push {{ + mat4 u_mvp; + vec2 u_viewport; + vec2 u_logicalSize; +}} pc; + +layout(location = 0) out vec2 v_em; +layout(location = 1) out vec4 v_color; +layout(location = 2) flat out uint v_blob_loc; +layout(location = 3) flat out uint v_flags; +layout(location = 4) flat out uvec2 v_clip_packed; + +void main() {{ + QuadInstance q = quads[gl_InstanceIndex]; + const uint idxMap[6] = uint[6](0u, 1u, 2u, 0u, 2u, 3u); + uint c = idxMap[gl_VertexIndex]; + vec2 uv = vec2((c == 1u || c == 2u) ? 1.0 : 0.0, (c >= 2u) ? 1.0 : 0.0); + vec2 em = mix(q.em_box.xy, q.em_box.zw, uv); + vec2 emSgn = uv * 2.0 - 1.0; + + vec2 dEm = em - q.pos_anchor.xy; + float m00 = q.xform.x; + float m01 = q.xform.y; + float m10 = q.xform.z; + float m11 = q.xform.w; + vec2 pos = q.pos_anchor.zw + vec2(m00 * dEm.x + m01 * dEm.y, m10 * dEm.x + m11 * dEm.y); + + vec2 ax = vec2(m00, m10); + vec2 ay = vec2(m01, m11); + float lx = length(ax); + float ly = length(ay); + vec2 axisX = lx > 1e-8 ? ax / lx : vec2(1.0, 0.0); + vec2 axisY = ly > 1e-8 ? ay / ly : vec2(0.0, 1.0); + vec2 normal = axisX * emSgn.x + axisY * emSgn.y; + + float det = m00 * m11 - m01 * m10; + float invDet = abs(det) > 1e-12 ? (1.0 / det) : 0.0; + vec4 jac = vec4(m11, -m01, -m10, m00) * invDet; + + hb_gpu_dilate(pos, em, normal, jac, pc.u_mvp, pc.u_viewport); + + gl_Position = pc.u_mvp * vec4(pos, 0.0, 1.0); + v_em = em; + v_color = q.color; + v_blob_loc = q.meta.x; + v_flags = q.meta.y; + v_clip_packed = q.meta.zw; +}} +"; + } + + private static string BuildFragmentShaderSource() + { + string sharedFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared); + string drawFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw); + return $@"#version 450 +#define uniform layout(set = 0, binding = 0) uniform +{sharedFrag} +#undef uniform +{drawFrag} + +layout(push_constant, std430) uniform Push {{ + mat4 u_mvp; + vec2 u_viewport; + vec2 u_logicalSize; +}} pc; + +layout(location = 0) in vec2 v_em; +layout(location = 1) in vec4 v_color; +layout(location = 2) flat in uint v_blob_loc; +layout(location = 3) flat in uint v_flags; +layout(location = 4) flat in uvec2 v_clip_packed; + +layout(location = 0) out vec4 frag_color; + +void main() {{ + float cov = hb_gpu_draw(v_em, v_blob_loc); + float ppem = hb_gpu_ppem(v_em, v_blob_loc); + + if ((v_flags & 1u) != 0u && cov > 0.0 && cov < 1.0) {{ + float brightness = dot(v_color.rgb, vec3(1.0 / 3.0)); + cov = hb_gpu_stem_darken(cov, brightness, ppem); + }} + + if (v_clip_packed.y != 0xFFFFFFFFu) {{ + vec2 logicalPos = gl_FragCoord.xy * (pc.u_logicalSize / pc.u_viewport); + vec2 cMin = vec2(float(v_clip_packed.x & 0xFFFFu), float(v_clip_packed.x >> 16u)); + vec2 cMax = vec2(float(v_clip_packed.y & 0xFFFFu), float(v_clip_packed.y >> 16u)); + if (logicalPos.x < cMin.x || logicalPos.y < cMin.y || logicalPos.x > cMax.x || logicalPos.y > cMax.y) {{ + cov = 0.0; + }} + }} + + float a = clamp(v_color.a * cov, 0.0, 1.0); + frag_color = vec4(v_color.rgb * a, a); +}} +"; + } + } +} diff --git a/client/Hud.cs b/client/Hud.cs index 709373b..f2a60f0 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -38,7 +38,7 @@ public partial class Hud : CanvasLayer private readonly Func _getSession; private readonly Action _onEquipCargo; private readonly Func _getCameraYaw; - private readonly Func? _projectWorld; + private readonly Func? _projectWorld; private Label _chassisHeader = null!; private Label _planeBadge = null!; @@ -57,7 +57,7 @@ public partial class Hud : CanvasLayer private Label _mapAttribLabel = null!; private ColorRect _vignetteRect = null!; private ShaderMaterial _vignetteMat = null!; - private SquadChevronOverlay _squadOverlay = null!; + private WorldMarkerOverlay _worldMarkers = null!; private CrosshairOverlay _crosshair = null!; private float _damagePulse; private float _lowCoreRatio; @@ -101,7 +101,7 @@ public partial class Hud : CanvasLayer Func getSession, Action onEquipCargo, Func? getCameraYaw = null, - Func? projectWorld = null) + Func? projectWorld = null) { _getSession = getSession; _onEquipCargo = onEquipCargo; @@ -300,6 +300,7 @@ public partial class Hud : CanvasLayer BuildBottomCenterChyron(); BuildOutcomeBanner(); BuildNetworkPanel(); + _worldMarkers.SetAvoidPanels(_topLeftPanel, _topRightPanel, _bottomLeftPanel, _chyronPanel); } public bool IsPointerOverInteractiveHud(Vector2 screenPos) @@ -505,9 +506,9 @@ public partial class Hud : CanvasLayer _promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text); } - // Squad 3D projected chevrons - _squadOverlay.SetState(session, _projectWorld); - _squadOverlay.QueueRedraw(); + // 3D projected world markers (ally chevrons, visible enemy target boxes, offscreen arrows) + _worldMarkers.SetState(session, _projectWorld); + _worldMarkers.QueueRedraw(); // Crosshair + Heat Arc / Orbital Altimeter + Directional Incoming Hit Arcs _crosshair.SetState(state, player, _getCameraYaw(), localPod); @@ -585,10 +586,10 @@ public partial class Hud : CanvasLayer _vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect); AddChild(_vignetteRect); - _squadOverlay = new SquadChevronOverlay { Name = "SquadChevrons" }; - _squadOverlay.SetAnchorsPreset(Control.LayoutPreset.FullRect); - _squadOverlay.MouseFilter = Control.MouseFilterEnum.Ignore; - AddChild(_squadOverlay); + _worldMarkers = new WorldMarkerOverlay { Name = "WorldMarkers" }; + _worldMarkers.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _worldMarkers.MouseFilter = Control.MouseFilterEnum.Ignore; + AddChild(_worldMarkers); _crosshair = new CrosshairOverlay { Name = "Crosshair" }; _crosshair.SetAnchorsPreset(Control.LayoutPreset.FullRect); @@ -1521,7 +1522,7 @@ public partial class Hud : CanvasLayer if (allDisabled) { DrawString( - ThemeDB.FallbackFont, + UiFonts.Regular, center + new Vector2(-52f, 36f), "WEAPONS STRIPPED", HorizontalAlignment.Left, @@ -1532,7 +1533,7 @@ public partial class Hud : CanvasLayer else if (outOfArc) { DrawString( - ThemeDB.FallbackFont, + UiFonts.Regular, center + new Vector2(-34f, 36f), "OUT OF ARC", HorizontalAlignment.Left, @@ -1570,7 +1571,7 @@ public partial class Hud : CanvasLayer DrawLine(topR + new Vector2(0f, barH - fillH), topR + new Vector2(0f, barH), bracketCol, 3.0f); DrawString( - ThemeDB.FallbackFont, + UiFonts.Regular, center + new Vector2(-88f, 54f), $"ALT {agl:F0}m | HORIZ {horizSpeed:F0} m/s | VERT {vel:F0} m/s", HorizontalAlignment.Left, @@ -1580,7 +1581,7 @@ public partial class Hud : CanvasLayer if (burning) { DrawString( - ThemeDB.FallbackFont, + UiFonts.Regular, center + new Vector2(-46f, -52f), "RETRO BURN ACTIVE", HorizontalAlignment.Left, @@ -1686,7 +1687,7 @@ public partial class Hud : CanvasLayer _ => ("KINETIC HIT", new Color(0.96f, 0.78f, 0.28f, tagAlpha)) }; DrawString( - ThemeDB.FallbackFont, + UiFonts.Regular, center + new Vector2(-36f, 54f), tagText, HorizontalAlignment.Left, @@ -1956,14 +1957,45 @@ public partial class Hud : CanvasLayer private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); } - private sealed partial class SquadChevronOverlay : Control + private sealed partial class WorldMarkerOverlay : Control { + private const float BorderPad = 36f; + private const float PanelAvoidPad = 18f; + private const float OffscreenHostileMaxDistance = 220f; + private const int MaxOffscreenHostileArrows = 6; + + private readonly struct OffscreenMarker + { + public readonly System.Numerics.Vector3 CamLocal; + public readonly float Distance; + public readonly Color Color; + public readonly bool IsLockedOnLocal; + + public OffscreenMarker(System.Numerics.Vector3 camLocal, float distance, Color color, bool isLockedOnLocal) + { + CamLocal = camLocal; + Distance = distance; + Color = color; + IsLockedOnLocal = isLockedOnLocal; + } + } + private IClientArenaSession? _session; - private Func? _projectWorld; + private Func? _projectWorld; + private Control?[] _avoidPanels = Array.Empty(); + private readonly List _offscreenHostiles = new(16); + private readonly Vector2[] _cornerBuf = new Vector2[3]; + private readonly Vector2[] _triBuf = new Vector2[3]; + private readonly Vector2[] _shadowTriBuf = new Vector2[3]; + + public void SetAvoidPanels(params Control?[] panels) + { + _avoidPanels = panels ?? Array.Empty(); + } public void SetState( IClientArenaSession session, - Func? projectWorld) + Func? projectWorld) { _session = session; _projectWorld = projectWorld; @@ -1973,84 +2005,443 @@ public partial class Hud : CanvasLayer { if (_session is null || _projectWorld is null) return; var state = _session.ViewState; - if (state.SquadSize <= 1) return; int localId = _session.LocalContenderId; + if (localId < 0 || localId >= state.Contenders.Count) return; + if (!state.Contenders[localId].Alive) return; + Vector2 viewSize = Size; if (viewSize.X < 64f || viewSize.Y < 64f) return; var (localPos, _, _) = _session.GetInterpolatedContenderPose(localId, 1f); - const float borderPad = 36f; Vector2 center = viewSize * 0.5f; - float halfW = MathF.Max(16f, center.X - borderPad); - float halfH = MathF.Max(16f, center.Y - borderPad); + float halfW = MathF.Max(16f, center.X - BorderPad); + float halfH = MathF.Max(16f, center.Y - BorderPad); + Font font = UiFonts.Regular; + + // 1. Allied squad chevrons (only when SquadSize > 1) + if (state.SquadSize > 1) + { + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Id == localId || !c.Alive || !state.AreAllies(localId, c.Id)) continue; + + var (allyPos, _, _) = _session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (allyPos - localPos).Length(); + float headOffset = c.IsInDropPod ? 3.4f : (c.Grid.Spec.HalfHeight + 1.9f); + var worldHead = new System.Numerics.Vector3(allyPos.X, allyPos.Y + headOffset, allyPos.Z); + var (valid, inFront, sp, camLocal) = _projectWorld(worldHead); + if (!valid) continue; + + bool inFrame = inFront && + sp.X >= BorderPad && sp.X <= viewSize.X - BorderPad && + sp.Y >= BorderPad && sp.Y <= viewSize.Y - BorderPad; + + string label = $"{c.Name} {dist:F0}m"; + if (inFrame) + { + _triBuf[0] = sp + new Vector2(0f, 5f); + _triBuf[1] = sp + new Vector2(-6f, -5f); + _triBuf[2] = sp + new Vector2(6f, -5f); + DrawColoredPolygon(_triBuf, AlliedCol); + DrawString( + font, + sp + new Vector2(-28f, -11f), + label, + HorizontalAlignment.Left, + -1, + 10, + AlliedCol); + } + else + { + Vector2 dir = ComputeOffscreenDirection(camLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + Vector2 perp = new(-dir.Y, dir.X); + + _triBuf[0] = edge + dir * 7f; + _triBuf[1] = edge - dir * 5f + perp * 5f; + _triBuf[2] = edge - dir * 5f - perp * 5f; + DrawColoredPolygon(_triBuf, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.88f)); + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, font, label); + DrawString( + font, + textPos, + label, + HorizontalAlignment.Left, + -1, + 10, + new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.90f)); + } + } + } + + // 2. Visible enemy contenders (strictly obeying fog-of-war / LOS) + var contenderContacts = _session.LocalContenderContacts; + var spectatorContacts = _session.LocalSpectatorContacts; + _offscreenHostiles.Clear(); for (int i = 0; i < state.Contenders.Count; i++) { var c = state.Contenders[i]; - if (c.Id == localId || !c.Alive || !state.AreAllies(localId, c.Id)) continue; + if (c.Id == localId || !c.Alive || state.AreAllies(localId, c.Id)) continue; + if (!_session.IsContenderVisible(c.Id)) continue; + if (!contenderContacts.TryGetValue(c.Id, out var mem) || !mem.VisibleToPlayer) continue; - var (allyPos, _, _) = _session.GetInterpolatedContenderPose(c.Id, 1f); - float dist = (allyPos - localPos).Length(); - float headOffset = c.IsInDropPod ? 3.4f : (c.Grid.Spec.HalfHeight + 1.9f); - var worldHead = new System.Numerics.Vector3(allyPos.X, allyPos.Y + headOffset, allyPos.Z); - var (visible, behind, sp) = _projectWorld(worldHead); - if (!visible) continue; + var (pos, rot, _) = _session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (pos - localPos).Length(); + bool targetingLocal = c.AiTargetContenderId == localId; + Color col = targetingLocal ? RedCol : OrangeCol; + float hpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; - bool inFrame = !behind && - sp.X >= borderPad && sp.X <= viewSize.X - borderPad && - sp.Y >= borderPad && sp.Y <= viewSize.Y - borderPad; + float halfBoundW = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfWidth; + float halfBoundH = c.IsInDropPod ? 1.8f : c.Grid.Spec.HalfHeight; + float halfBoundL = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfLength; - string label = $"{c.Name} {dist:F0}m"; - if (inFrame) + ProcessHostileTarget( + pos, rot, halfBoundW, halfBoundH, halfBoundL, + dist, hpRatio, col, targetingLocal, + viewSize, font); + } + + // 3. Visible hostile/provoked spectators (neutral tourists do NOT get hostile target boxes) + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) continue; + if (!_session.IsSpectatorVisible(s.Id)) continue; + if (!spectatorContacts.TryGetValue(s.Id, out var mem) || !mem.VisibleToPlayer) continue; + + var (pos, rot, _) = _session.GetInterpolatedSpectatorPose(s.Id, 1f); + float dist = (pos - localPos).Length(); + bool lockedOnLocal = s.TargetContenderId == localId; + float hpRatio = s.Grid.MaxCoreHp > 0f ? s.Grid.CoreHp / s.Grid.MaxCoreHp : 1f; + + ProcessHostileTarget( + pos, rot, s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfHeight, s.Grid.Spec.HalfLength, + dist, hpRatio, RedCol, lockedOnLocal, + viewSize, font); + } + + // 4. Off-screen hostile arrows (locked-on threats first, then nearest visible hostiles) + if (_offscreenHostiles.Count > 0) + { + _offscreenHostiles.Sort(static (a, b) => { - var pts = new[] - { - sp + new Vector2(0f, 5f), - sp + new Vector2(-6f, -5f), - sp + new Vector2(6f, -5f) - }; - DrawColoredPolygon(pts, AlliedCol); - DrawString( - ThemeDB.FallbackFont, - sp + new Vector2(-28f, -11f), - label, - HorizontalAlignment.Left, - -1, - 10, - AlliedCol); - } - else + int lockCmp = b.IsLockedOnLocal.CompareTo(a.IsLockedOnLocal); + return lockCmp != 0 ? lockCmp : a.Distance.CompareTo(b.Distance); + }); + + int count = Math.Min(_offscreenHostiles.Count, MaxOffscreenHostileArrows); + for (int i = 0; i < count; i++) { - Vector2 dir = behind ? (center - sp) : (sp - center); - if (dir.LengthSquared() < 1e-4f) dir = Vector2.Up; - else dir = dir.Normalized(); - - float tx = MathF.Abs(dir.X) > 1e-4f ? halfW / MathF.Abs(dir.X) : float.PositiveInfinity; - float ty = MathF.Abs(dir.Y) > 1e-4f ? halfH / MathF.Abs(dir.Y) : float.PositiveInfinity; - Vector2 edge = center + dir * MathF.Min(tx, ty); - Vector2 perp = new(-dir.Y, dir.X); - - var pts = new[] - { - edge + dir * 7f, - edge - dir * 5f + perp * 5f, - edge - dir * 5f - perp * 5f - }; - DrawColoredPolygon(pts, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.88f)); - Vector2 textPos = new( - Math.Clamp(edge.X - 32f, 10f, viewSize.X - 110f), - Math.Clamp(edge.Y + (dir.Y > 0f ? -12f : 18f), 16f, viewSize.Y - 12f)); - DrawString( - ThemeDB.FallbackFont, - textPos, - label, - HorizontalAlignment.Left, - -1, - 10, - new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.90f)); + DrawOffscreenArrow(_offscreenHostiles[i], viewSize, center, halfW, halfH, font); } } } + + private void ProcessHostileTarget( + System.Numerics.Vector3 worldCenter, + System.Numerics.Quaternion rot, + float halfBoundW, + float halfBoundH, + float halfBoundL, + float dist, + float hpRatio, + Color col, + bool isLockedOnLocal, + Vector2 viewSize, + Font font) + { + var (cValid, cInFront, cSp, cCamLocal) = _projectWorld!(worldCenter); + if (!cValid) return; + + bool inFrame = cInFront && + cSp.X >= BorderPad && cSp.X <= viewSize.X - BorderPad && + cSp.Y >= BorderPad && cSp.Y <= viewSize.Y - BorderPad; + + if (!inFrame) + { + if (isLockedOnLocal || dist <= OffscreenHostileMaxDistance) + { + _offscreenHostiles.Add(new OffscreenMarker(cCamLocal, dist, col, isLockedOnLocal)); + } + return; + } + + float minX = float.PositiveInfinity, minY = float.PositiveInfinity; + float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity; + bool allCornersInFront = true; + + for (int sx = -1; sx <= 1; sx += 2) + { + for (int sy = -1; sy <= 1; sy += 2) + { + for (int sz = -1; sz <= 1; sz += 2) + { + var localCorner = new System.Numerics.Vector3(sx * halfBoundW, sy * halfBoundH, sz * halfBoundL); + var worldCorner = worldCenter + System.Numerics.Vector3.Transform(localCorner, rot); + var (valid, inFront, sp, _) = _projectWorld(worldCorner); + if (!valid || !inFront) + { + allCornersInFront = false; + break; + } + if (sp.X < minX) minX = sp.X; + if (sp.X > maxX) maxX = sp.X; + if (sp.Y < minY) minY = sp.Y; + if (sp.Y > maxY) maxY = sp.Y; + } + if (!allCornersInFront) break; + } + if (!allCornersInFront) break; + } + + if (!allCornersInFront) + { + var (topValid, topFront, topSp, _) = _projectWorld(worldCenter + new System.Numerics.Vector3(0f, halfBoundH, 0f)); + var (botValid, botFront, botSp, _) = _projectWorld(worldCenter - new System.Numerics.Vector3(0f, halfBoundH, 0f)); + float rawH = (topValid && topFront && botValid && botFront) + ? MathF.Abs(botSp.Y - topSp.Y) + 8f + : 44f; + float horizRadius = MathF.Max(halfBoundW, halfBoundL); + float rawW = rawH * (horizRadius / MathF.Max(0.4f, halfBoundH)); + minX = cSp.X - rawW * 0.5f; + maxX = cSp.X + rawW * 0.5f; + minY = cSp.Y - rawH * 0.5f; + maxY = cSp.Y + rawH * 0.5f; + } + else + { + minX -= 3f; + maxX += 3f; + minY -= 3f; + maxY += 3f; + } + + float boxW = Math.Clamp(maxX - minX, 22f, 220f); + float boxH = Math.Clamp(maxY - minY, 22f, 220f); + Vector2 boxCenter = new((minX + maxX) * 0.5f, (minY + maxY) * 0.5f); + var rect = new Rect2(boxCenter.X - boxW * 0.5f, boxCenter.Y - boxH * 0.5f, boxW, boxH); + + DrawTargetBox(rect, col, dist, hpRatio, isLockedOnLocal, font); + } + + private void DrawTargetBox(Rect2 rect, Color col, float dist, float hpRatio, bool isLockedOnLocal, Font font) + { + float x0 = rect.Position.X; + float y0 = rect.Position.Y; + float x1 = x0 + rect.Size.X; + float y1 = y0 + rect.Size.Y; + float legX = Math.Clamp(rect.Size.X * 0.22f, 5f, 26f); + float legY = Math.Clamp(rect.Size.Y * 0.22f, 5f, 26f); + + Color shadowCol = new(0.04f, 0.05f, 0.04f, 0.78f); + Color strokeCol = new(col.R, col.G, col.B, 0.95f); + + // Top-left + _cornerBuf[0] = new Vector2(x0, y0 + legY); + _cornerBuf[1] = new Vector2(x0, y0); + _cornerBuf[2] = new Vector2(x0 + legX, y0); + DrawPolyline(_cornerBuf, shadowCol, 3.6f); + DrawPolyline(_cornerBuf, strokeCol, 2.0f); + + // Top-right + _cornerBuf[0] = new Vector2(x1 - legX, y0); + _cornerBuf[1] = new Vector2(x1, y0); + _cornerBuf[2] = new Vector2(x1, y0 + legY); + DrawPolyline(_cornerBuf, shadowCol, 3.6f); + DrawPolyline(_cornerBuf, strokeCol, 2.0f); + + // Bottom-right + _cornerBuf[0] = new Vector2(x1, y1 - legY); + _cornerBuf[1] = new Vector2(x1, y1); + _cornerBuf[2] = new Vector2(x1 - legX, y1); + DrawPolyline(_cornerBuf, shadowCol, 3.6f); + DrawPolyline(_cornerBuf, strokeCol, 2.0f); + + // Bottom-left + _cornerBuf[0] = new Vector2(x0 + legX, y1); + _cornerBuf[1] = new Vector2(x0, y1); + _cornerBuf[2] = new Vector2(x0, y1 - legY); + DrawPolyline(_cornerBuf, shadowCol, 3.6f); + DrawPolyline(_cornerBuf, strokeCol, 2.0f); + + // Thin HP bar right above top bracket + float barW = Math.Clamp(rect.Size.X, 22f, 64f); + float barX = (x0 + x1) * 0.5f - barW * 0.5f; + float barY = y0 - 7f; + DrawRect(new Rect2(barX - 1f, barY - 1f, barW + 2f, 4f), new Color(0.04f, 0.05f, 0.04f, 0.78f)); + DrawRect(new Rect2(barX, barY, barW * Math.Clamp(hpRatio, 0f, 1f), 2f), strokeCol); + + // Distance + LOCK tag above HP bar + string label = isLockedOnLocal ? $"{dist:F0}m LOCK" : $"{dist:F0}m"; + Vector2 textSize = font.GetStringSize(label, HorizontalAlignment.Left, -1, 10); + Vector2 textPos = new((x0 + x1) * 0.5f - textSize.X * 0.5f, barY - 3f); + DrawString(font, textPos + new Vector2(1f, 1f), label, HorizontalAlignment.Left, -1, 10, new Color(0.04f, 0.05f, 0.04f, 0.90f)); + DrawString(font, textPos, label, HorizontalAlignment.Left, -1, 10, strokeCol); + } + + private void DrawOffscreenArrow(OffscreenMarker m, Vector2 viewSize, Vector2 center, float halfW, float halfH, Font font) + { + Vector2 dir = ComputeOffscreenDirection(m.CamLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + Vector2 perp = new(-dir.Y, dir.X); + + _shadowTriBuf[0] = edge + dir * 10f; + _shadowTriBuf[1] = edge - dir * 6.5f + perp * 7f; + _shadowTriBuf[2] = edge - dir * 6.5f - perp * 7f; + DrawColoredPolygon(_shadowTriBuf, new Color(0.04f, 0.05f, 0.04f, 0.74f)); + + _triBuf[0] = edge + dir * 8f; + _triBuf[1] = edge - dir * 5f + perp * 5.2f; + _triBuf[2] = edge - dir * 5f - perp * 5.2f; + Color arrowCol = new(m.Color.R, m.Color.G, m.Color.B, 0.94f); + DrawColoredPolygon(_triBuf, arrowCol); + + string label = m.IsLockedOnLocal ? $"{m.Distance:F0}m !" : $"{m.Distance:F0}m"; + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, font, label); + DrawString(font, textPos + new Vector2(1f, 1f), label, HorizontalAlignment.Left, -1, 10, new Color(0.04f, 0.05f, 0.04f, 0.90f)); + DrawString(font, textPos, label, HorizontalAlignment.Left, -1, 10, arrowCol); + } + + private static Vector2 ComputeOffscreenDirection(System.Numerics.Vector3 camLocal) + { + if (!float.IsFinite(camLocal.X) || !float.IsFinite(camLocal.Y) || !float.IsFinite(camLocal.Z)) + { + return Vector2.Down; + } + + Vector2 dir; + if (camLocal.Z >= 0f) + { + dir = new Vector2(camLocal.X, -camLocal.Y); + } + else + { + float horiz = MathF.Sqrt(camLocal.X * camLocal.X + camLocal.Z * camLocal.Z); + float t = Math.Clamp(-camLocal.Z / MathF.Max(1e-4f, horiz * 0.35f), 0f, 1f); + Vector2 sideDir = new(camLocal.X, -camLocal.Y); + Vector2 behindArcDir = new(camLocal.X, MathF.Max(-camLocal.Z, 0.35f * horiz)); + dir = sideDir.Lerp(behindArcDir, t); + if (MathF.Abs(camLocal.X) < 0.35f * horiz) + { + float minDown = 0.25f * dir.Length(); + if (dir.Y < minDown) + { + dir.Y = MathF.Max(minDown, 0.25f); + } + } + } + + float lenSq = dir.LengthSquared(); + if (!float.IsFinite(lenSq) || lenSq < 1e-6f) + { + return camLocal.Z < 0f ? Vector2.Down : Vector2.Up; + } + return dir / MathF.Sqrt(lenSq); + } + + private Vector2 ComputeSafeEdgePos(Vector2 center, float halfW, float halfH, Vector2 dir) + { + float tx = MathF.Abs(dir.X) > 1e-4f ? halfW / MathF.Abs(dir.X) : float.PositiveInfinity; + float ty = MathF.Abs(dir.Y) > 1e-4f ? halfH / MathF.Abs(dir.Y) : float.PositiveInfinity; + float tBest = MathF.Min(tx, ty); + + for (int i = 0; i < _avoidPanels.Length; i++) + { + var panel = _avoidPanels[i]; + if (panel is null || !panel.Visible) continue; + Rect2 r = panel.GetGlobalRect().Grow(PanelAvoidPad); + if (r.HasPoint(center)) continue; + if (TryRayEnterRect(center, dir, r, out float tEnter) && tEnter > 24f && tEnter < tBest) + { + tBest = tEnter; + } + } + + tBest = MathF.Max(24f, tBest); + return center + dir * tBest; + } + + private static bool TryRayEnterRect(Vector2 origin, Vector2 dir, Rect2 r, out float tEnter) + { + float tMin = 0f; + float tMax = float.PositiveInfinity; + + if (MathF.Abs(dir.X) < 1e-5f) + { + if (origin.X < r.Position.X || origin.X > r.End.X) + { + tEnter = 0f; + return false; + } + } + else + { + float invX = 1f / dir.X; + float t1 = (r.Position.X - origin.X) * invX; + float t2 = (r.End.X - origin.X) * invX; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + if (MathF.Abs(dir.Y) < 1e-5f) + { + if (origin.Y < r.Position.Y || origin.Y > r.End.Y) + { + tEnter = 0f; + return false; + } + } + else + { + float invY = 1f / dir.Y; + float t1 = (r.Position.Y - origin.Y) * invY; + float t2 = (r.End.Y - origin.Y) * invY; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + tEnter = tMin; + return true; + } + + private static Vector2 ComputeInwardLabelPos(Vector2 edge, Vector2 dir, Vector2 viewSize, Font font, string label) + { + Vector2 sz = font.GetStringSize(label, HorizontalAlignment.Left, -1, 10); + Vector2 inward = edge - dir * 14f; + float textX; + float textY; + + if (MathF.Abs(dir.X) >= MathF.Abs(dir.Y)) + { + textX = dir.X > 0f ? (inward.X - sz.X - 4f) : (inward.X + 6f); + textY = inward.Y + sz.Y * 0.3f; + } + else + { + textX = inward.X - sz.X * 0.5f; + textY = dir.Y > 0f ? (inward.Y - 4f) : (inward.Y + sz.Y + 4f); + } + + return new Vector2( + Math.Clamp(textX, 10f, MathF.Max(10f, viewSize.X - sz.X - 10f)), + Math.Clamp(textY, 16f, MathF.Max(16f, viewSize.Y - 10f))); + } } } diff --git a/client/InventoryGridControl.cs b/client/InventoryGridControl.cs index d80d283..98f64ef 100644 --- a/client/InventoryGridControl.cs +++ b/client/InventoryGridControl.cs @@ -724,7 +724,7 @@ public partial class InventoryGridControl : Control // Dark shadow for crisp legibility over bright thermal glow DrawString( - ThemeDB.FallbackFont, + UiFonts.Regular, pos + new Vector2(7f, fontSize + 6f), tag, HorizontalAlignment.Left, @@ -733,7 +733,7 @@ public partial class InventoryGridControl : Control new Color(0.04f, 0.05f, 0.04f, alpha * 0.9f)); DrawString( - ThemeDB.FallbackFont, + UiFonts.Regular, pos + new Vector2(6f, fontSize + 5f), tag, HorizontalAlignment.Left, diff --git a/client/Main.cs b/client/Main.cs index 822051d..c4cce7d 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"; @@ -103,6 +108,7 @@ public partial class Main : Node3D private readonly List _perfNodeCount = new(); private readonly List _perfTimeProcess = new(); private readonly List _perfTimePhysicsProcess = new(); + private readonly List _perfViewportGpuMs = new(); private double _perfPendingStepMs; private double _perfPendingTerrainMs; private double _perfPendingArenaMs; @@ -121,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; @@ -138,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); @@ -190,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 += () => @@ -323,12 +350,26 @@ 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") + { + 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"; @@ -557,6 +598,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 +608,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 +619,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 +628,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 +637,7 @@ public partial class Main : Node3D break; case ClientScreenMode.PauseOverlay: + _settingsOverlay.SetSettingsVisible(false); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(false); _arena.Visible = true; @@ -599,6 +645,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(); } @@ -935,6 +1000,9 @@ public partial class Main : Node3D || 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")); @@ -954,21 +1022,125 @@ public partial class Main : Node3D } } - private void ToggleBorderlessFullscreen() + 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(); - 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() @@ -1150,6 +1322,14 @@ public partial class Main : Node3D } return; } + if (_screenMode == ClientScreenMode.Settings) + { + if (key.Keycode == Key.Escape) + { + CloseSettings(); + } + return; + } if (key.Keycode == Key.F9) { @@ -1411,6 +1591,10 @@ public partial class Main : Node3D _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) @@ -1561,7 +1745,7 @@ public partial class Main : Node3D 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..59)={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}"); + 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}"); @@ -1582,7 +1766,17 @@ 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); + 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 (_session is not null) { @@ -2095,15 +2289,32 @@ public partial class Main : Node3D _session?.RequestEquipCargo(cargoIndex, hardpointId); } - private (bool Visible, bool Behind, Vector2 ScreenPos) ProjectWorldToHud(System.Numerics.Vector3 worldPos) + 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); + return (false, false, Vector2.Zero, System.Numerics.Vector3.Zero); } var wp = new Vector3(worldPos.X, worldPos.Y, worldPos.Z); - bool behind = _camera.IsPositionBehind(wp); + 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); - return (true, behind, sp); + if (!float.IsFinite(sp.X) || !float.IsFinite(sp.Y)) + { + return (true, false, Vector2.Zero, camLocal); + } + return (true, true, sp, camLocal); } } 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/NativeLibraries.cs b/client/NativeLibraries.cs index 3eb19a5..a2973a2 100644 --- a/client/NativeLibraries.cs +++ b/client/NativeLibraries.cs @@ -4,28 +4,41 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Godot; +using RustToDust.HbGpu; using Ymir.Box3D; namespace RustToDust.Client; /// -/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the -/// default probing does not look beside them. A run from the editor or --path loads the library from the -/// project's build directory; an exported run from the data folder Godot puts beside the executable. +/// Resolves native libraries (ymir_box3d, rtd_hbgpu) for Godot's AssemblyLoadContext. /// internal static class NativeLibraries { - private const string Library = "ymir_box3d"; + private const string YmirLibrary = "ymir_box3d"; + private const string HbGpuLibrary = "rtd_hbgpu"; #pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport [ModuleInitializer] - internal static void Register() => + internal static void Register() + { NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve); + NativeLibrary.SetDllImportResolver(typeof(HbGpuNative).Assembly, Resolve); + } private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) { - if (name != Library) return IntPtr.Zero; - string fileName = FileName(); + string? stem = name switch + { + YmirLibrary => YmirLibrary, + HbGpuLibrary => HbGpuLibrary, + _ => null + }; + if (stem is null) + { + return IntPtr.Zero; + } + + string fileName = FileName(stem); if (OS.HasFeature("template")) { @@ -65,8 +78,8 @@ internal static class NativeLibraries : IntPtr.Zero; } - private static string FileName() => - OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so"; + private static string FileName(string stem) => + OperatingSystem.IsWindows() ? $"{stem}.dll" : OperatingSystem.IsMacOS() ? $"lib{stem}.dylib" : $"lib{stem}.so"; private static string Platform() => OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd"; diff --git a/client/RustToDust.Client.csproj b/client/RustToDust.Client.csproj index 29e8ed6..6ed04f3 100644 --- a/client/RustToDust.Client.csproj +++ b/client/RustToDust.Client.csproj @@ -10,6 +10,7 @@ + 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/UiFonts.cs b/client/UiFonts.cs new file mode 100644 index 0000000..c3aba41 --- /dev/null +++ b/client/UiFonts.cs @@ -0,0 +1,35 @@ +using Godot; + +namespace RustToDust.Client; + +/// +/// Central font accessor for custom Control._Draw() canvas calls. +/// Standard controls inherit gui/theme/custom_font from project.godot. +/// +internal static class UiFonts +{ + private const string RegularPath = "res://fonts/MonaspaceKrypton-Regular.otf"; + private const string SemiBoldPath = "res://fonts/MonaspaceKrypton-SemiBold.otf"; + private const string BoldPath = "res://fonts/MonaspaceKrypton-Bold.otf"; + + private static Font? _regular; + private static Font? _semiBold; + private static Font? _bold; + + public static Font Regular => _regular ??= LoadOrFallback(RegularPath, ThemeDB.FallbackFont); + public static Font SemiBold => _semiBold ??= LoadOrFallback(SemiBoldPath, Regular); + public static Font Bold => _bold ??= LoadOrFallback(BoldPath, SemiBold); + + private static Font LoadOrFallback(string path, Font fallback) + { + if (ResourceLoader.Exists(path)) + { + var loaded = GD.Load(path); + if (loaded is not null) + { + return loaded; + } + } + return fallback; + } +} diff --git a/client/VolumetricCompositorEffect.cs b/client/VolumetricCompositorEffect.cs index e587147..debe86c 100644 --- a/client/VolumetricCompositorEffect.cs +++ b/client/VolumetricCompositorEffect.cs @@ -5,7 +5,7 @@ using Godot; namespace RustToDust.Client; /// -/// 4-pass Forward+ Vulkan compute pipeline (PostOpaque) owning: +/// 4-pass Forward+ Vulkan compute pipeline (PostSky) owning: /// Pass 0: flow_field_step.glsl (camera-snapped 3m 64x24x64 RGBA16F ping-pong -> ) /// Pass 1: volumetric_tile_cull.glsl (16x16 half-res tiles + 128-element Bitonic sort) /// Pass 2: volumetric_raymarch.glsl (sorted monotonic sweep-line + Aetheria curl/triNoise + shock cavity + 2 shadow taps) @@ -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()) { @@ -99,7 +105,7 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect { _flowTexRd = flowTexRd; _emitterPool = emitterPool; - EffectCallbackType = EffectCallbackTypeEnum.PostOpaque; + EffectCallbackType = EffectCallbackTypeEnum.PostSky; AccessResolvedColor = true; AccessResolvedDepth = true; Enabled = true; @@ -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) @@ -124,7 +140,7 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect public override void _RenderCallback(int effectCallbackType, RenderData renderData) { - if (effectCallbackType != (int)EffectCallbackTypeEnum.PostOpaque || _rdFailed) + if (effectCallbackType != (int)EffectCallbackTypeEnum.PostSky || _rdFailed) { return; } @@ -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/VolumetricEmitterPool.cs b/client/VolumetricEmitterPool.cs index d9a57ce..b6d567b 100644 --- a/client/VolumetricEmitterPool.cs +++ b/client/VolumetricEmitterPool.cs @@ -170,7 +170,8 @@ public sealed class VolumetricEmitterPool float rA = MathF.Max(0.25f, Mathf.Lerp(s.RadiusA0, s.RadiusA1, t)); float rB = MathF.Max(0.25f, Mathf.Lerp(s.RadiusB0, s.RadiusB1, t)); - float temp = MathF.Max(0f, Mathf.Lerp(s.Temp0, s.Temp1, t)); + float tempT = MathF.Pow(t, 1.45f); + float temp = MathF.Max(0f, Mathf.Lerp(s.Temp0, s.Temp1, tempT)); Color tint = s.Tint0.Lerp(s.Tint1, t); uint ageByte = (uint)Math.Clamp((int)(t * 255f), 0, 255); @@ -483,10 +484,10 @@ public sealed class VolumetricEmitterPool ? new Color(0.24f, 0.62f, 0.14f) : isThermal ? new Color(0.12f, 0.22f, 0.28f) - : gLin * 0.48f + new Color(0.06f, 0.045f, 0.04f); - Color tint1 = new(0.06f, 0.055f, 0.05f); + : gLin * 0.30f + new Color(0.05f, 0.045f, 0.04f); + Color tint1 = new(0.05f, 0.048f, 0.045f); - float temp0 = (isPlasma || isThermal) ? 1.25f : (isAirburst || isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 1.65f : 1.15f); + float temp0 = (isPlasma || isThermal) ? 1.65f : (isAirburst || isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 2.10f : 1.70f); float life = (isRecoilless || wClass == WeaponVisualClass.RocketSalvo) ? 1.55f : (isThermal ? 0.50f : 0.95f); SpawnEmitter( @@ -502,7 +503,7 @@ public sealed class VolumetricEmitterPool density0: 1.85f, density1: 0.26f, temp0: temp0, - temp1: -0.35f, + temp1: 0.0f, tint0: tint0, tint1: tint1, lifetime: life, @@ -597,10 +598,10 @@ public sealed class VolumetricEmitterPool radiusB1: 4.5f * scale, density0: 2.15f, density1: 0.42f, - temp0: 1.65f, - temp1: 0.08f, - tint0: accentCol * 0.45f + new Color(0.14f, 0.11f, 0.09f), - tint1: new Color(0.08f, 0.075f, 0.07f), + temp0: 2.05f, + temp1: 0.10f, + tint0: accentCol * 0.32f + new Color(0.07f, 0.06f, 0.055f), + tint1: new Color(0.055f, 0.05f, 0.048f), lifetime: 2.1f, flowSpeed: 0.8f, softness: 0.40f, @@ -918,8 +919,8 @@ public sealed class VolumetricEmitterPool public void EmitFootstepOrTirePuff(Vector3 pos, Color groundTint, float scale) { - // Strictly gated under 72 active emitters so combat explosions never drop slots and desert stays punchy - if (ActiveEmitterCount >= 72) + // Strictly gated under 48 active emitters so combat explosions never drop slots and desert stays within GPU budget + if (ActiveEmitterCount >= 48) { return; } @@ -934,8 +935,8 @@ public sealed class VolumetricEmitterPool radiusA1: 1.55f * scale, radiusB0: 0.58f * scale, radiusB1: 1.75f * scale, - density0: 0.90f, - density1: 0.10f, + density0: 0.38f, + density1: 0.04f, temp0: 0f, temp1: 0f, tint0: gLin * 1.1f, diff --git a/client/film_grain.gdshader b/client/film_grain.gdshader index 3562d44..6f9cf5a 100644 --- a/client/film_grain.gdshader +++ b/client/film_grain.gdshader @@ -6,6 +6,7 @@ render_mode blend_mix; uniform sampler2D screen_tex : hint_screen_texture, filter_nearest; uniform float grain_strength : hint_range(0.0, 0.1) = 0.018; +uniform float post_gamma : hint_range(0.5, 2.5) = 1.32; float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) { vec2 p = frag_xy + vec2(frame_idx * 17.0, frame_idx * 31.0); @@ -14,12 +15,13 @@ float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) { void fragment() { vec4 src = texture(screen_tex, SCREEN_UV); + vec3 graded = pow(max(src.rgb, vec3(0.0)), vec3(post_gamma)); float frame_idx = mod(floor(fract(TIME * 0.001) * 60000.0), 64.0); float n = interleaved_gradient_noise(FRAGCOORD.xy, frame_idx); - float luma = dot(src.rgb, vec3(0.2126, 0.7152, 0.0722)); + float luma = dot(graded, vec3(0.2126, 0.7152, 0.0722)); float midtone_weight = smoothstep(0.02, 0.18, luma) * (1.0 - 0.65 * smoothstep(0.65, 1.0, luma)); - vec3 grained = clamp(src.rgb + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0)); + vec3 grained = clamp(graded + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0)); COLOR = vec4(grained, src.a); } 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/fonts/MONASPACE_LICENSE.txt b/client/fonts/MONASPACE_LICENSE.txt new file mode 100644 index 0000000..1b82de9 --- /dev/null +++ b/client/fonts/MONASPACE_LICENSE.txt @@ -0,0 +1,93 @@ +Copyright (c) 2023, GitHub https://github.com/githubnext/monaspace +with Reserved Font Name "Monaspace", including subfamilies: "Argon", "Neon", "Xenon", "Radon", and "Krypton" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting — in part or in whole — any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/client/fonts/MonaspaceKrypton-Bold.otf b/client/fonts/MonaspaceKrypton-Bold.otf new file mode 100644 index 0000000..4fafd5f Binary files /dev/null and b/client/fonts/MonaspaceKrypton-Bold.otf differ diff --git a/client/fonts/MonaspaceKrypton-Bold.otf.import b/client/fonts/MonaspaceKrypton-Bold.otf.import new file mode 100644 index 0000000..11f4f1e --- /dev/null +++ b/client/fonts/MonaspaceKrypton-Bold.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dlsxsr034f5sv" +path="res://.godot/imported/MonaspaceKrypton-Bold.otf-a6e22263037c0e08923dee8788f7d7d1.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-Bold.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-Bold.otf-a6e22263037c0e08923dee8788f7d7d1.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/fonts/MonaspaceKrypton-Regular.otf b/client/fonts/MonaspaceKrypton-Regular.otf new file mode 100644 index 0000000..ce21874 Binary files /dev/null and b/client/fonts/MonaspaceKrypton-Regular.otf differ diff --git a/client/fonts/MonaspaceKrypton-Regular.otf.import b/client/fonts/MonaspaceKrypton-Regular.otf.import new file mode 100644 index 0000000..03294fe --- /dev/null +++ b/client/fonts/MonaspaceKrypton-Regular.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://1udxuivwq46s" +path="res://.godot/imported/MonaspaceKrypton-Regular.otf-879dc21ea909cad808c934de94044b6e.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-Regular.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-Regular.otf-879dc21ea909cad808c934de94044b6e.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/fonts/MonaspaceKrypton-SemiBold.otf b/client/fonts/MonaspaceKrypton-SemiBold.otf new file mode 100644 index 0000000..8c9d680 Binary files /dev/null and b/client/fonts/MonaspaceKrypton-SemiBold.otf differ diff --git a/client/fonts/MonaspaceKrypton-SemiBold.otf.import b/client/fonts/MonaspaceKrypton-SemiBold.otf.import new file mode 100644 index 0000000..e76054a --- /dev/null +++ b/client/fonts/MonaspaceKrypton-SemiBold.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://270t27q6bpet" +path="res://.godot/imported/MonaspaceKrypton-SemiBold.otf-c294810382571aa26a9353cf57198e74.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-SemiBold.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-SemiBold.otf-c294810382571aa26a9353cf57198e74.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/project.godot b/client/project.godot index d66247b..c4a58ec 100644 --- a/client/project.godot +++ b/client/project.godot @@ -20,6 +20,10 @@ window/stretch/mode="canvas_items" project/assembly_name="RustToDust.Client" +[gui] + +theme/custom_font="res://fonts/MonaspaceKrypton-Regular.otf" + [physics] ; Godot's physics is switched off: Ymir is the only physics world. ArenaSession ticks at 60 Hz. diff --git a/client/tests/HbGpuProbe.cs b/client/tests/HbGpuProbe.cs new file mode 100644 index 0000000..aa8187c --- /dev/null +++ b/client/tests/HbGpuProbe.cs @@ -0,0 +1,233 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Godot; +using RustToDust.HbGpu; + +namespace RustToDust.Client.Tests; + +/// +/// Cut 14a visual & headless verification probe for HbGpuCanvas (1 Vulkan draw call). +/// Run headless: Godot --headless --audio-driver Dummy --path client res://tests/HbGpuProbe.tscn +/// Run Vulkan: Godot --audio-driver Dummy --windowed --path client res://tests/HbGpuProbe.tscn -- --capture-proof=path.png +/// +public partial class HbGpuProbe : Control +{ + private HbGpuCanvas _canvas = null!; + private bool _done; + private int _frameCount; + private string? _capturePath; + + public override void _Ready() + { + foreach (string arg in OS.GetCmdlineUserArgs()) + { + if (arg.StartsWith("--capture-proof=", StringComparison.Ordinal)) + { + _capturePath = arg["--capture-proof=".Length..]; + } + } + _capturePath ??= System.Environment.GetEnvironmentVariable("RTD_HBGPU_PROOF_PNG"); + + var bg = new ColorRect + { + Color = new Color(0.05f, 0.065f, 0.085f, 1.0f), + MouseFilter = MouseFilterEnum.Ignore + }; + AddChild(bg); + bg.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _canvas = new HbGpuCanvas + { + Name = "HbGpuCanvas", + ProfilingEnabled = true + }; + AddChild(_canvas); + _canvas.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _ = RunVerificationAsync(); + } + + private async Task RunVerificationAsync() + { + try + { + // Render enough frames to warm Vulkan pipeline & collect RD GPU timestamps + int targetFrames = _canvas.IsVulkanActive ? 24 : 3; + for (int i = 0; i < targetFrames; i++) + { + SubmitShowcaseFrame(i); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + _frameCount++; + } + + if (_canvas.LastQuadCount <= 0) + { + Fail("Expected LastQuadCount > 0 after submitting HbGpu showcase frame."); + return; + } + + if (!_canvas.IsVulkanActive) + { + GD.Print($"HBGPU_PROBE PASS (headless null-RD): quads={_canvas.LastQuadCount}, frames={_frameCount}"); + Finish(0); + return; + } + + if (_canvas.LastDrawCallCount != 1) + { + Fail($"Expected LastDrawCallCount == 1 on Vulkan, got {_canvas.LastDrawCallCount}."); + return; + } + + if (!_canvas.TryReadbackRgba8(out byte[] rgba, out int w, out int h)) + { + Fail("HbGpuCanvas.TryReadbackRgba8 returned false on active Vulkan device."); + return; + } + + int nonZero = 0; + int premulViolations = 0; + for (int i = 0; i + 3 < rgba.Length; i += 4) + { + byte r = rgba[i]; + byte g = rgba[i + 1]; + byte b = rgba[i + 2]; + byte a = rgba[i + 3]; + if (a > 0) + { + nonZero++; + } + if (r > a || g > a || b > a) + { + premulViolations++; + } + } + + if (nonZero < 1500) + { + Fail($"Expected >= 1500 rendered pixels in HbGpu Texture2Drd, got {nonZero} ({w}x{h})."); + return; + } + + if (premulViolations != 0) + { + Fail($"Premultiplied alpha invariant violated on {premulViolations} pixels."); + return; + } + + if (!string.IsNullOrWhiteSpace(_capturePath)) + { + SubmitShowcaseFrame(_frameCount); + await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); + Image? vpImg = GetViewport().GetTexture()?.GetImage(); + if (vpImg is null) + { + Fail("Viewport capture returned null Image."); + return; + } + string? dir = Path.GetDirectoryName(_capturePath); + if (!string.IsNullOrEmpty(dir)) + { + Directory.CreateDirectory(dir); + } + Error saveErr = vpImg.SavePng(_capturePath); + if (saveErr != Error.Ok) + { + Fail($"Failed to save proof PNG '{_capturePath}': {saveErr}"); + return; + } + } + + GD.Print( + $"HBGPU_PROBE PASS (Vulkan): size={w}x{h}, quads={_canvas.LastQuadCount}, " + + $"draw_calls={_canvas.LastDrawCallCount}, gpu_ms={_canvas.LastHbGpuMs:F4}, " + + $"non_zero_px={nonZero}, premul_violations={premulViolations}"); + Finish(0); + } + catch (Exception ex) + { + Fail(ex.ToString()); + } + } + + private void SubmitShowcaseFrame(int frameIndex) + { + Color amber = new(0.95f, 0.72f, 0.22f, 1.0f); + Color cyan = new(0.32f, 0.86f, 0.96f, 1.0f); + Color slate = new(0.78f, 0.84f, 0.90f, 1.0f); + Color panelBg = new(0.06f, 0.09f, 0.12f, 0.78f); + Color alert = new(0.96f, 0.28f, 0.22f, 1.0f); + Color emerald = new(0.28f, 0.90f, 0.56f, 1.0f); + + _canvas.BeginFrame(); + + // Top-left panel backdrop + crisp Krypton typography across weights/slants/sizes + _canvas.DrawRectFilled(40f, 36f, 680f, 224f, panelBg); + _canvas.DrawLineSegment(40f, 36f, 720f, 36f, 2f, amber); + _canvas.DrawLineSegment(40f, 260f, 720f, 260f, 1.5f, new Color(amber, 0.5f)); + + _canvas.DrawText("RUST TO DUST // HB-GPU VULKAN", 60f, 84f, 32f, amber, wght: 700f); + _canvas.DrawText("CHASSIS: RAPTOR-7 | ALT: 142.8m | SPD: 28.4m/s", 60f, 124f, 20f, slate, wght: 550f); + _canvas.DrawText("CALT / LIGA: -> ==> != <= >= // 0x4F2A", 60f, 158f, 18f, cyan, wght: 350f); + _canvas.DrawText("SLANT -9 DEG // STEM DARKENED ANALYTIC SLUG", 60f, 192f, 15f, emerald, wght: 400f, slnt: -9f); + _canvas.DrawText("11PX MICRO TELEMETRY: 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ", 60f, 226f, 11f, slate, wght: 250f); + + // Center crosshair reticle + dynamic cubic Bezier thermal heat arc + float cx = 640f; + float cy = 400f; + _canvas.DrawCircleFilled(cx, cy, 3.5f, amber); + _canvas.DrawLineSegment(cx - 28f, cy, cx - 10f, cy, 2.0f, cyan); + _canvas.DrawLineSegment(cx + 10f, cy, cx + 28f, cy, 2.0f, cyan); + _canvas.DrawLineSegment(cx, cy - 28f, cx, cy - 10f, 2.0f, cyan); + _canvas.DrawLineSegment(cx, cy + 10f, cx, cy + 28f, 2.0f, cyan); + + float heatSweep = -2.356f + (0.65f + 0.1f * MathF.Sin(frameIndex * 0.1f)) * 4.712f; + _canvas.DrawArcStrokeDynamic(cx, cy, 62f, 5.5f, -2.356f, heatSweep, amber); + _canvas.DrawArcStrokeDynamic(cx, cy, 82f, 4.0f, -0.34f, 0.34f, alert); + + // Target lock corner brackets (all 4 quadrants) + float bx0 = 860f, by0 = 280f, bx1 = 1040f, by1 = 460f; + _canvas.DrawTargetBracketCorner(bx0, by0, 26f, 3.5f, 0, alert); + _canvas.DrawTargetBracketCorner(bx1, by0, 26f, 3.5f, 1, alert); + _canvas.DrawTargetBracketCorner(bx1, by1, 26f, 3.5f, 2, alert); + _canvas.DrawTargetBracketCorner(bx0, by1, 26f, 3.5f, 3, alert); + _canvas.DrawText("LOCK: SPECTATOR-02 [318m]", bx0, by0 - 12f, 14f, alert, wght: 600f); + + // Offscreen directional arrows + _canvas.DrawDirectionalArrow(1160f, 560f, 28f, 0.55f, amber); + _canvas.DrawDirectionalArrow(120f, 560f, 28f, -2.45f, alert); + + // Radar circle, safe ring, LOS lock line, diamond blip & chevron + float rx = 1080f, ry = 160f, rr = 96f; + _canvas.DrawCircleFilled(rx, ry, rr, new Color(0.04f, 0.07f, 0.09f, 0.85f)); + _canvas.DrawCircleRing(rx, ry, rr, 2.5f, cyan); + _canvas.DrawCircleRing(rx, ry, rr * 0.58f, 1.5f, new Color(emerald, 0.75f)); + _canvas.DrawLineSegment(rx, ry, rx + 44f, ry - 52f, 1.5f, new Color(alert, 0.85f)); + _canvas.Writer.DrawBlob( + HbGpuVectorShapes.GetDiamondBlip(_canvas.Blobs), + rx + 44f, ry - 52f, + 0.012f, 0f, 0f, -0.012f, 0f, 0f, + alert.R, alert.G, alert.B, alert.A); + _canvas.Writer.DrawBlob( + HbGpuVectorShapes.GetChevronTriangle(_canvas.Blobs), + rx, ry, + 0.014f, 0f, 0f, -0.014f, 0f, 0f, + emerald.R, emerald.G, emerald.B, emerald.A); + + _canvas.EndFrameAndSubmit(); + } + + private void Fail(string msg) + { + GD.PrintErr("HBGPU_PROBE FAIL: " + msg); + Finish(1); + } + + private void Finish(int code) + { + if (_done) return; + _done = true; + GetTree().Quit(code); + } +} diff --git a/client/tests/HbGpuProbe.tscn b/client/tests/HbGpuProbe.tscn new file mode 100644 index 0000000..ee00a32 --- /dev/null +++ b/client/tests/HbGpuProbe.tscn @@ -0,0 +1,12 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/HbGpuProbe.cs" id="1"] + +[node name="HbGpuProbe" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1") 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 f710207..63e61aa 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; @@ -268,7 +276,7 @@ void main() { for (uint k = 0u; k < sTileCount; k++) { VolumetricEmitter em = sEmitters[k]; - float rBound = max(em.posRadius.w, em.params.y) * 1.85; + float rBound = max(em.posRadius.w, em.params.y) * 1.95; float t0, t1; if (intersectCapsule(ro, rd, em.posRadius.xyz, em.endRadiusTemp.xyz, rBound, t0, t1)) { t0 = max(2.0, t0); @@ -312,15 +320,18 @@ void main() { uint activeMask = 0u; float t = 0.0; int steps = 0; - const int MaxSteps = 16; + int iter = 0; + int maxSteps = clamp(int(u_frame.qualityParams.x), 1, 64); + int maxIter = clamp(max(int(u_frame.qualityParams.y), maxSteps * 2), 1, 96); + float stepScale = 10.0 / max(float(maxSteps), 1.0); - while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.015 && steps < MaxSteps) { + 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); float nextT1 = hitT1[nextIdx]; float chord = max(0.0, nextT1 - minNext); - float dsLeap = max(0.36, 0.26 + 0.011 * minNext); + float dsLeap = max(0.16, max(0.42, 0.32 + 0.014 * minNext) * stepScale); float jitter = ign * min(dsLeap, max(0.05, chord * 0.45)); t = min(max(t, minNext) + jitter, tEndMax - 1e-4); if (t >= tEndMax) { @@ -328,7 +339,7 @@ void main() { } } - float ds = max(0.36, 0.26 + 0.011 * t); + float ds = max(0.16, max(0.42, 0.32 + 0.014 * t) * stepScale); float tLo = t - 0.5 * ds; float tHi = t + 0.5 * ds; @@ -364,11 +375,10 @@ void main() { float emitNearFade = smoothstep(2.5, 8.5, t); if (nearFade > 0.001) { vec3 worldPos = ro + rd * t; - vec3 flowUv = (worldPos - u_frame.flowOriginVoxel.xyz) * u_frame.flowInvExtentDt.xyz; - vec4 flowSample = (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) - ? textureLod(u_flowField, flowUv, 0.0) - : vec4(0.0); - float shock = clamp(flowSample.a, 0.0, 1.5); + bool hasFlow = false; + vec4 flowSample = vec4(0.0); + float shock = 0.0; + vec3 stepCurl = vec3(0.0); float rhoSum = 0.0; vec3 albedoSum = vec3(0.0); @@ -376,7 +386,6 @@ void main() { float tempSum = 0.0; float noiseSum = 0.0; float plasmaSum = 0.0; - vec3 stepCurl = aetheriaFlow(worldPos - flowSample.rgb * 0.20, 3.0, 0.68, elapsed); uint am = activeMask; while (am != 0u) { @@ -399,43 +408,60 @@ void main() { vec3 ab = B - A; float ab2 = dot(ab, ab); - // Conservative un-displaced distance guard before running triNoise3d + // Conservative squared-distance guard BEFORE sampling 3D flow texture or Tri3D curl (matches 1.95 * rad rBound) float preSegT = ab2 > 1e-5 ? clamp(dot(worldPos - A, ab) / ab2, 0.0, 1.0) : 0.0; float preRad = mix(rA, rB, preSegT); - if (length(worldPos - (A + ab * preSegT)) > 1.05 * preRad + 0.80 * radAvg) { + vec3 preDelta = worldPos - (A + ab * preSegT); + float rGuard = 1.15 * preRad + 0.80 * radAvg; + if (dot(preDelta, preDelta) > rGuard * rGuard) { continue; } - // Bound flow + curl displacement strictly inside rBound (1.85 * rad) so zero spherical/tile clipping occurs - vec3 flowOffset = flowSample.rgb * (0.16 + 0.12 * ageNorm); + if (!hasFlow) { + vec3 flowUv = (worldPos - u_frame.flowOriginVoxel.xyz) * u_frame.flowInvExtentDt.xyz; + flowSample = (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) + ? textureLod(u_flowField, flowUv, 0.0) + : vec4(0.0); + shock = clamp(flowSample.a, 0.0, 1.5); + stepCurl = aetheriaFlow(worldPos - flowSample.rgb * 0.20, 11.0, 0.68, elapsed); + hasFlow = true; + } + + // Uncuffed 3D flow advection + wind/buoyancy shear + age-grown Tri3D curl bounded inside rBound (1.95 * rad) + vec3 flowOffset = flowSample.rgb * (0.28 + 0.45 * ageNorm); + float advSegT = ab2 > 1e-5 ? clamp(dot((worldPos - flowOffset) - A, ab) / ab2, 0.0, 1.0) : 0.0; + flowOffset += vec3(flowSample.r, 0.0, flowSample.b) * (0.32 * advSegT * (0.35 + ageNorm)); float fOffLen = length(flowOffset); - if (fOffLen > 0.30 * radAvg) { - flowOffset *= (0.30 * radAvg) / fOffLen; + if (fOffLen > 0.62 * radAvg) { + flowOffset *= (0.62 * radAvg) / fOffLen; } vec3 advectedPos = worldPos - flowOffset; - float curlScale = 0.48 * radAvg * clamp(0.65 + 0.45 * abs(em.params.z), 0.55, 1.10); + float curlScale = mix(0.24, 0.46, clamp(ageNorm * 1.1 + advSegT * 0.45, 0.0, 1.0)) * radAvg; vec3 evalPos = advectedPos + stepCurl * curlScale; float segT = ab2 > 1e-5 ? clamp(dot(evalPos - A, ab) / ab2, 0.0, 1.0) : 0.0; vec3 closest = A + ab * segT; - float taper = ab2 > 0.15 ? mix(1.02, 0.72, segT) : 1.0; - float rad = mix(rA, rB, segT) * taper * (0.86 + 0.18 * clamp(stepCurl.x + stepCurl.y, -0.8, 0.8)); + float taper = ab2 > 0.15 ? mix(1.02, 0.78, segT) : 1.0; + float rad = mix(rA, rB, segT) * taper; vec3 radialVec = evalPos - closest; float distNorm = length(radialVec) / max(0.15, rad); - if (distNorm < 1.04) { - float softness = clamp(em.tintSoftness.a, 0.18, 0.75); - float baseFall = 1.0 - smoothstep(1.0 - softness, 1.04, distNorm); - if (baseFall > 0.04) { - // Aetheria Volumetric.cginc:201-212 sculpted pocket carving (macro triNoise3d - 0.5 * high-freq triNoise3d) - vec3 nCoord = evalPos / max(1.35, rad * 0.95) + vec3(seed); - float noise1 = triNoise3d(nCoord, elapsed * 0.36); - float noise2 = triNoise3d(nCoord * 5.5, elapsed * 0.56); - float billow = clamp((noise1 - 0.5 * noise2) * 2.55, 0.0, 1.0); - float rawDensity = billow * 0.66 + baseFall * 0.76 - 0.30 * distNorm; - float eroded = smoothstep(0.18, 0.74, rawDensity); - float rho_k = baseFall * eroded * em.params.x * nearFade; + if (distNorm < 1.16) { + // True Aetheria gradient-offset pattern (Volumetric.cginc:210-215): + // triNoise3d ONLY offsets the smooth radial SDF gradient by a small centered displacement << 1.0 + vec3 nCoord = (evalPos / max(1.4, rad * 0.95)) * 0.32 + vec3(seed); + float n1 = triNoise3d(nCoord, elapsed * 0.32); + float n2 = triNoise3d(nCoord * 3.6, elapsed * 0.52); + float dispAmp = 0.35 + 0.65 * clamp(distNorm, 0.0, 1.0); + float disp = ((n1 - 0.45 * n2) - 0.11) * 0.88 * dispAmp; + float warpedDist = clamp(distNorm - disp, 0.0, 1.2); + + if (warpedDist < 1.0) { + float softness = clamp(em.tintSoftness.a, 0.18, 0.75); + float falloffEdge = mix(0.04, 0.14, softness); + float profile = 1.0 - smoothstep(falloffEdge, 1.0, warpedDist); + float rho_k = profile * em.params.x * nearFade; // Shock-front cavity carving + adiabatic compression rim rho_k *= clamp(1.0 - shock * 0.42, 0.32, 1.0) * (1.0 + 0.45 * smoothstep(0.2, 0.9, shock)); @@ -445,11 +471,11 @@ void main() { albedoSum += em.tintSoftness.rgb * rho_k; radialSum += safeNorm(radialVec + vec3(0.0, 0.28 * rad, 0.0)) * rho_k; - // Tight radial temperature falloff: outer 65-75% cools to un-emissive rolling soot - float coreRadial = pow(clamp(1.0 - distNorm, 0.0, 1.0), 1.65); + // Tight radial temperature falloff: outer shell cools to un-emissive rolling soot + float coreRadial = pow(clamp(1.0 - warpedDist, 0.0, 1.0), 2.35); float localTemp = max(em.endRadiusTemp.w * coreRadial, shock * 0.22); tempSum += localTemp * rho_k; - noiseSum += clamp(noise1 * 2.5, 0.0, 1.0) * rho_k; + noiseSum += clamp((n1 - 0.45 * n2) * 2.5 + 0.25, 0.0, 1.0) * rho_k; if (emType == 3u || emType == 4u) { plasmaSum += rho_k; } @@ -465,25 +491,29 @@ void main() { vec3 albedo = albedoSum / rhoSum; vec3 localUpOrRadial = safeNorm(radialSum); - // Layer 1 & 2: Aetheria inverse-density charcoal soot contour (CloudShader.shader:96-97) - // Thin wispy outer rims stay bright sunlit vapor (~0.85-1.0); dense mid-body folds plunge into velvety charcoal soot (~0.10-0.22) - float sootContour = 1.0 / (1.0 + 3.2 * rawDens); - float rimBias = 0.65 + 0.45 * clamp(dot(localUpOrRadial, sunDir), -1.0, 1.0); - vec3 vaporAlbedo = mix(albedo, max(albedo, vec3(0.24, 0.23, 0.22)), 0.35 * sootContour); - float vaporEdgeFade = smoothstep(0.0, 0.10, rawDens); - vec3 scatterLum = vaporAlbedo * (sootContour * vaporEdgeFade) * (sunRad * (rimBias + phase * 2.4) + ambRad * 0.48); + // Layer 1 & 2: Aetheria inverse-density charcoal soot contour (CloudShader.shader:96-97 / Volumetric.cginc:234) + // Dense interiors stay deep velvety charcoal soot; rimBoost (1.65) applies strictly to thin outer sunlit vapor edges + float sootContour = 1.0 / (1.0 + 4.6 * rawDens); + float sunAlignment = clamp(dot(localUpOrRadial, sunDir), -1.0, 1.0); + float rimBias = max(0.0, sunAlignment); + float rimFactor = 1.0 + 0.65 * smoothstep(0.25, 0.72, sootContour); + vec3 sunlitEdgeTint = mix(albedo, albedo * 1.35 + vec3(0.045, 0.040, 0.036), sootContour * smoothstep(0.10, 0.78, max(0.0, sunAlignment) + phase)); + float vaporEdgeFade = smoothstep(0.0, 0.08, rawDens); + vec3 skyBounce = max(0.0, localUpOrRadial.y) * 0.08 * ambRad; + vec3 scatterLum = sunlitEdgeTint * (sootContour * vaporEdgeFade * rimFactor) * (sunRad * (rimBias + phase * 2.6) + skyBounce); - // Layer 3: Sharp turbulent core-only combustion (ignites only in hottest dense inner core pockets) + // Layer 3: Sharp turbulent core-only combustion peeking through dark soot crevices vec3 plasmaEmit = vec3(0.0); - float coreGate = smoothstep(0.68, 0.96, coreTemp * (0.72 + 0.55 * stepNoise)); + float coreSignal = coreTemp * (0.85 + 0.30 * stepNoise); + float coreGate = smoothstep(0.72, 1.05, coreSignal); if (coreGate > 0.001) { - float coreGlow = pow(clamp(rawDens, 0.0, 1.5), 2.3) * coreGate; + float coreGlow = pow(clamp(rawDens, 0.0, 1.4), 2.15) * coreGate; vec3 bb = blackbodyRamp(coreTemp); float plasmaMix = plasmaSum / rhoSum; if (plasmaMix > 0.01) { bb = mix(bb, albedo * (1.55 + 2.05 * coreTemp), 0.75 * plasmaMix); } - plasmaEmit = bb * (coreGlow * 7.2) * emitNearFade; + plasmaEmit = bb * (coreGlow * 5.0) * emitNearFade; } float sigmaT = rawDens * extScale; @@ -493,7 +523,8 @@ void main() { vec3 stepLight = (scatterLum + plasmaEmit) * integDivExt * nearFade; L += T * stepLight; T *= stepTrans; - if (T < 0.015) { + steps++; + if (T < 0.03) { T = 0.0; break; } @@ -502,7 +533,7 @@ void main() { } t += ds; - steps++; + iter++; } imageStore(u_halfVol, px, vec4(min(L, vec3(24.0)), clamp(T, 0.0, 1.0))); diff --git a/client/volumetric_tile_cull.glsl b/client/volumetric_tile_cull.glsl index 8b0bf07..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; @@ -128,7 +136,7 @@ void main() { VolumetricEmitter em = u_emitters.emitters[tid]; float rA = em.posRadius.w; float rB = em.params.y; - float rBound = max(rA, rB) * 1.85; + float rBound = max(rA, rB) * 1.95; vec3 wA = em.posRadius.xyz - u_frame.camPosTime.xyz; vec3 wB = em.endRadiusTemp.xyz - u_frame.camPosTime.xyz; diff --git a/native/rtd_hbgpu/CMakeLists.txt b/native/rtd_hbgpu/CMakeLists.txt new file mode 100644 index 0000000..60f55e7 --- /dev/null +++ b/native/rtd_hbgpu/CMakeLists.txt @@ -0,0 +1,89 @@ +cmake_minimum_required(VERSION 3.22) + +project(rtd_hbgpu VERSION 0.1.0 LANGUAGES C CXX) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +if(MSVC) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +# Resolve pinned HarfBuzz 15.2.0 source +set(RTD_HARFBUZZ_DIR "" CACHE PATH "Path to HarfBuzz 15.2.0 source directory") +if(NOT RTD_HARFBUZZ_DIR AND DEFINED ENV{RTD_HARFBUZZ_DIR} AND EXISTS "$ENV{RTD_HARFBUZZ_DIR}/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "$ENV{RTD_HARFBUZZ_DIR}") +elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz") +elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz") +endif() + +# Minimal HarfBuzz configuration: zero ICU/FreeType/Cairo/Glib/Subset/Raster/Vector bloat +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(HB_HAVE_CAIRO OFF CACHE BOOL "" FORCE) +set(HB_HAVE_FREETYPE OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GRAPHITE2 OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GLIB OFF CACHE BOOL "" FORCE) +set(HB_HAVE_ICU OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GOBJECT OFF CACHE BOOL "" FORCE) +set(HB_HAVE_INTROSPECTION OFF CACHE BOOL "" FORCE) +set(HB_HAVE_CORETEXT OFF CACHE BOOL "" FORCE) +set(HB_HAVE_UNISCRIBE OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GDI OFF CACHE BOOL "" FORCE) +set(HB_HAVE_DIRECTWRITE OFF CACHE BOOL "" FORCE) +set(HB_BUILD_UTILS OFF CACHE BOOL "" FORCE) +set(HB_BUILD_SUBSET OFF CACHE BOOL "" FORCE) +set(HB_BUILD_RASTER OFF CACHE BOOL "" FORCE) +set(HB_BUILD_VECTOR OFF CACHE BOOL "" FORCE) +set(HB_BUILD_GPU ON CACHE BOOL "" FORCE) +set(HB_BUILD_GPU_DEMO OFF CACHE STRING "" FORCE) + +if(RTD_HARFBUZZ_DIR AND EXISTS "${RTD_HARFBUZZ_DIR}/CMakeLists.txt") + add_subdirectory("${RTD_HARFBUZZ_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/harfbuzz" EXCLUDE_FROM_ALL) +else() + include(FetchContent) + FetchContent_Declare( + harfbuzz + URL "https://github.com/harfbuzz/harfbuzz/releases/download/15.2.0/harfbuzz-15.2.0.tar.xz" + URL_HASH SHA256=e2ec49090744383cdbe7df808c1cedaafba06a97be8dc4211fe546ba585f12cb + ) + FetchContent_MakeAvailable(harfbuzz) +endif() + +add_library(rtd_hbgpu SHARED rtd_hbgpu.c) +target_link_libraries(rtd_hbgpu PRIVATE harfbuzz-gpu harfbuzz) +target_include_directories(rtd_hbgpu + PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include" + PRIVATE "${harfbuzz_SOURCE_DIR}/src" +) +if(RTD_HARFBUZZ_DIR) + target_include_directories(rtd_hbgpu PRIVATE "${RTD_HARFBUZZ_DIR}/src") +endif() + +target_compile_features(rtd_hbgpu PRIVATE c_std_17) +target_compile_definitions(rtd_hbgpu PRIVATE RTD_HBGPU_EXPORTS) + +if(MSVC) + set_property(TARGET rtd_hbgpu PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_compile_options(harfbuzz PRIVATE $<$:/O2 /GL /Gy>) + target_compile_options(harfbuzz-gpu PRIVATE $<$:/O2 /GL /Gy>) + target_compile_options(rtd_hbgpu PRIVATE $<$:/O2 /GL /Gy>) + target_link_options(rtd_hbgpu PRIVATE $<$:/OPT:REF /OPT:ICF /LTCG>) +elseif(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(rtd_hbgpu PRIVATE $<$:-O2 -ffunction-sections -fdata-sections>) + if(NOT APPLE) + target_link_options(rtd_hbgpu PRIVATE $<$:-Wl,--gc-sections>) + endif() +endif() + +set_target_properties(rtd_hbgpu PROPERTIES + C_VISIBILITY_PRESET hidden + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" +) +if(MINGW) + set_property(TARGET rtd_hbgpu PROPERTY PREFIX "") +endif() diff --git a/native/rtd_hbgpu/include/rtd_hbgpu.h b/native/rtd_hbgpu/include/rtd_hbgpu.h new file mode 100644 index 0000000..e8fa720 --- /dev/null +++ b/native/rtd_hbgpu/include/rtd_hbgpu.h @@ -0,0 +1,124 @@ +#ifndef RTD_HBGPU_H +#define RTD_HBGPU_H + +#include + +#ifdef _WIN32 + #ifdef RTD_HBGPU_EXPORTS + #define RTD_HBGPU_API __declspec(dllexport) + #else + #define RTD_HBGPU_API __declspec(dllimport) + #endif +#else + #if defined(__GNUC__) || defined(__clang__) + #define RTD_HBGPU_API __attribute__((visibility("default"))) + #else + #define RTD_HBGPU_API + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct rtd_hb_font rtd_hb_font; + +typedef struct rtd_hb_font_metrics { + int32_t upem; + int32_t ascender; + int32_t descender; + int32_t line_gap; +} rtd_hb_font_metrics; + +typedef struct rtd_hb_shaped_glyph { + uint32_t glyph_id; + uint32_t cluster; + int32_t x_advance; + int32_t y_advance; + int32_t x_offset; + int32_t y_offset; +} rtd_hb_shaped_glyph; + +typedef struct rtd_hb_extents { + int32_t min_x; + int32_t min_y; + int32_t max_x; + int32_t max_y; +} rtd_hb_extents; + +enum { + RTD_HB_STAGE_VERTEX = 0, + RTD_HB_STAGE_FRAGMENT = 1 +}; + +enum { + RTD_HB_SHADER_SHARED = 0, + RTD_HB_SHADER_DRAW = 1 +}; + +enum { + RTD_HB_FEAT_NONE = 0, + RTD_HB_FEAT_CALT = 1u << 0, + RTD_HB_FEAT_LIGA = 1u << 1, + RTD_HB_FEAT_DEFAULT = RTD_HB_FEAT_CALT | RTD_HB_FEAT_LIGA +}; + +enum { + RTD_HB_VERB_MOVE = 0, /* 2 args: x, y */ + RTD_HB_VERB_LINE_TO = 1, /* 2 args: x, y */ + RTD_HB_VERB_QUAD_TO = 2, /* 4 args: cx, cy, x, y */ + RTD_HB_VERB_CUBIC_TO = 3, /* 6 args: c1x, c1y, c2x, c2y, x, y */ + RTD_HB_VERB_CLOSE = 4, /* 0 args */ + RTD_HB_VERB_LINE = 5, /* 7 args: x0, y0, w0, x1, y1, w1, cap (0=butt,1=square) */ + RTD_HB_VERB_RECT = 6, /* 5 args: x, y, w, h, stroke_width (NaN or <0 = filled) */ + RTD_HB_VERB_CIRCLE = 7 /* 4 args: cx, cy, r, stroke_width (NaN or <0 = filled) */ +}; + +RTD_HBGPU_API const char* rtd_hb_version_string(void); + +RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind); + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create( + const uint8_t* ttf, + uint32_t len, + uint32_t face_index, + rtd_hb_font_metrics* out_metrics); + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant( + const rtd_hb_font* base_font, + float wght, + float wdth, + float slnt); + +RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f); + +RTD_HBGPU_API uint32_t rtd_hb_shape_utf16( + rtd_hb_font* f, + const uint16_t* utf16, + uint32_t char_len, + uint32_t feature_flags, + rtd_hb_shaped_glyph* out, + uint32_t cap); + +RTD_HBGPU_API int32_t rtd_hb_encode_glyph( + rtd_hb_font* f, + uint32_t glyph_id, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext); + +RTD_HBGPU_API int32_t rtd_hb_encode_path( + uint32_t design_upem, + const uint8_t* verbs, + uint32_t n_verbs, + const float* args, + uint32_t n_args, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext); + +#ifdef __cplusplus +} +#endif + +#endif /* RTD_HBGPU_H */ diff --git a/native/rtd_hbgpu/rtd_hbgpu.c b/native/rtd_hbgpu/rtd_hbgpu.c new file mode 100644 index 0000000..f5ffb2c --- /dev/null +++ b/native/rtd_hbgpu/rtd_hbgpu.c @@ -0,0 +1,348 @@ +#include "rtd_hbgpu.h" + +#include "hb.h" +#include "hb-gpu.h" +#include "hb-ot.h" + +#include +#include +#include + +struct rtd_hb_font { + hb_face_t* face; + hb_font_t* font; + hb_buffer_t* buf; + hb_gpu_draw_t* draw; +}; + +static void fill_extents(const hb_glyph_extents_t* ext, rtd_hb_extents* out_ext) { + if (!out_ext) return; + out_ext->min_x = ext->x_bearing; + out_ext->max_y = ext->y_bearing; + out_ext->max_x = ext->x_bearing + ext->width; + out_ext->min_y = ext->y_bearing + ext->height; +} + +static int32_t finalize_draw_blob( + hb_gpu_draw_t* draw, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + hb_glyph_extents_t hb_ext; + memset(&hb_ext, 0, sizeof(hb_ext)); + + hb_blob_t* blob = hb_gpu_draw_encode(draw, &hb_ext); + if (!blob) { + return -1; + } + + unsigned int byte_len = 0; + const char* data = hb_blob_get_data(blob, &byte_len); + fill_extents(&hb_ext, out_ext); + + if (byte_len == 0) { + hb_gpu_draw_recycle_blob(draw, blob); + return 0; + } + + if ((byte_len & 7u) != 0u) { + hb_gpu_draw_recycle_blob(draw, blob); + return -1; + } + + uint32_t texels = byte_len >> 3u; + if (texels > cap_texels || !out_rgba16i) { + hb_gpu_draw_recycle_blob(draw, blob); + return -(int32_t)texels; + } + + memcpy(out_rgba16i, data, byte_len); + hb_gpu_draw_recycle_blob(draw, blob); + return (int32_t)texels; +} + +RTD_HBGPU_API const char* rtd_hb_version_string(void) { + return hb_version_string(); +} + +RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind) { + hb_gpu_shader_stage_t hb_stage; + if (stage == RTD_HB_STAGE_VERTEX) { + hb_stage = HB_GPU_SHADER_STAGE_VERTEX; + } else if (stage == RTD_HB_STAGE_FRAGMENT) { + hb_stage = HB_GPU_SHADER_STAGE_FRAGMENT; + } else { + return NULL; + } + + if (kind == RTD_HB_SHADER_SHARED) { + return hb_gpu_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL); + } + if (kind == RTD_HB_SHADER_DRAW) { + return hb_gpu_draw_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL); + } + return NULL; +} + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create( + const uint8_t* ttf, + uint32_t len, + uint32_t face_index, + rtd_hb_font_metrics* out_metrics) +{ + if (!ttf || len == 0) return NULL; + + hb_blob_t* blob = hb_blob_create((const char*)ttf, len, HB_MEMORY_MODE_DUPLICATE, NULL, NULL); + if (!blob || hb_blob_get_length(blob) == 0) { + if (blob) hb_blob_destroy(blob); + return NULL; + } + + hb_face_t* face = hb_face_create(blob, face_index); + hb_blob_destroy(blob); + if (!face || face == hb_face_get_empty()) { + if (face) hb_face_destroy(face); + return NULL; + } + + hb_font_t* font = hb_font_create(face); + hb_buffer_t* buf = hb_buffer_create(); + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!font || !buf || !draw) { + if (draw) hb_gpu_draw_destroy(draw); + if (buf) hb_buffer_destroy(buf); + if (font) hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font)); + if (!out) { + hb_gpu_draw_destroy(draw); + hb_buffer_destroy(buf); + hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + out->face = face; + out->font = font; + out->buf = buf; + out->draw = draw; + + if (out_metrics) { + hb_font_extents_t fe; + memset(&fe, 0, sizeof(fe)); + hb_font_get_h_extents(font, &fe); + out_metrics->upem = (int32_t)hb_face_get_upem(face); + out_metrics->ascender = fe.ascender; + out_metrics->descender = fe.descender; + out_metrics->line_gap = fe.line_gap; + } + + return out; +} + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant( + const rtd_hb_font* base_font, + float wght, + float wdth, + float slnt) +{ + if (!base_font || !base_font->face) return NULL; + + hb_face_t* face = hb_face_reference(base_font->face); + hb_font_t* font = hb_font_create(face); + hb_buffer_t* buf = hb_buffer_create(); + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!font || !buf || !draw) { + if (draw) hb_gpu_draw_destroy(draw); + if (buf) hb_buffer_destroy(buf); + if (font) hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + hb_variation_t vars[3] = { + { HB_TAG('w', 'g', 'h', 't'), wght }, + { HB_TAG('w', 'd', 't', 'h'), wdth }, + { HB_TAG('s', 'l', 'n', 't'), slnt } + }; + hb_font_set_variations(font, vars, 3); + + rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font)); + if (!out) { + hb_gpu_draw_destroy(draw); + hb_buffer_destroy(buf); + hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + out->face = face; + out->font = font; + out->buf = buf; + out->draw = draw; + return out; +} + +RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f) { + if (!f) return; + if (f->draw) hb_gpu_draw_destroy(f->draw); + if (f->buf) hb_buffer_destroy(f->buf); + if (f->font) hb_font_destroy(f->font); + if (f->face) hb_face_destroy(f->face); + free(f); +} + +RTD_HBGPU_API uint32_t rtd_hb_shape_utf16( + rtd_hb_font* f, + const uint16_t* utf16, + uint32_t char_len, + uint32_t feature_flags, + rtd_hb_shaped_glyph* out, + uint32_t cap) +{ + if (!f || !f->font || !f->buf) return 0; + if (char_len == 0 || !utf16) return 0; + + hb_buffer_clear_contents(f->buf); + hb_buffer_add_utf16(f->buf, utf16, (int)char_len, 0, (int)char_len); + hb_buffer_guess_segment_properties(f->buf); + + hb_feature_t feats[2] = { + { HB_TAG('c', 'a', 'l', 't'), (feature_flags & RTD_HB_FEAT_CALT) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END }, + { HB_TAG('l', 'i', 'g', 'a'), (feature_flags & RTD_HB_FEAT_LIGA) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END } + }; + hb_shape(f->font, f->buf, feats, 2); + + unsigned int count = 0; + const hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(f->buf, &count); + const hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(f->buf, &count); + + if (out && cap > 0) { + uint32_t to_copy = count < cap ? count : cap; + for (uint32_t i = 0; i < to_copy; i++) { + out[i].glyph_id = infos[i].codepoint; + out[i].cluster = infos[i].cluster; + out[i].x_advance = pos[i].x_advance; + out[i].y_advance = pos[i].y_advance; + out[i].x_offset = pos[i].x_offset; + out[i].y_offset = pos[i].y_offset; + } + } + + return count; +} + +RTD_HBGPU_API int32_t rtd_hb_encode_glyph( + rtd_hb_font* f, + uint32_t glyph_id, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + if (!f || !f->font || !f->draw) return -1; + + hb_gpu_draw_clear(f->draw); + hb_gpu_draw_glyph(f->draw, f->font, glyph_id); + return finalize_draw_blob(f->draw, out_rgba16i, cap_texels, out_ext); +} + +RTD_HBGPU_API int32_t rtd_hb_encode_path( + uint32_t design_upem, + const uint8_t* verbs, + uint32_t n_verbs, + const float* args, + uint32_t n_args, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + if (!verbs || n_verbs == 0 || design_upem == 0) return -1; + + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!draw) return -1; + + hb_gpu_draw_set_scale(draw, (int)design_upem, (int)design_upem); + hb_draw_funcs_t* dfuncs = hb_gpu_draw_get_funcs(draw); + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + + uint32_t arg_idx = 0; + for (uint32_t i = 0; i < n_verbs; i++) { + switch (verbs[i]) { + case RTD_HB_VERB_MOVE: + if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_move_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]); + arg_idx += 2u; + break; + + case RTD_HB_VERB_LINE_TO: + if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_line_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]); + arg_idx += 2u; + break; + + case RTD_HB_VERB_QUAD_TO: + if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_quadratic_to(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3]); + arg_idx += 4u; + break; + + case RTD_HB_VERB_CUBIC_TO: + if (arg_idx + 6u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_cubic_to(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3], + args[arg_idx + 4], args[arg_idx + 5]); + arg_idx += 6u; + break; + + case RTD_HB_VERB_CLOSE: + hb_draw_close_path(dfuncs, draw, &st); + break; + + case RTD_HB_VERB_LINE: + if (arg_idx + 7u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_line(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], args[arg_idx + 2], + args[arg_idx + 3], args[arg_idx + 4], args[arg_idx + 5], + args[arg_idx + 6] >= 0.5f ? HB_DRAW_LINE_CAP_SQUARE : HB_DRAW_LINE_CAP_BUTT); + arg_idx += 7u; + break; + + case RTD_HB_VERB_RECT: { + if (arg_idx + 5u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + float sw = args[arg_idx + 4]; + if (sw < 0.0f) sw = NAN; + hb_draw_rectangle(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3], sw); + arg_idx += 5u; + break; + } + + case RTD_HB_VERB_CIRCLE: { + if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + float sw = args[arg_idx + 3]; + if (sw < 0.0f) sw = NAN; + hb_draw_circle(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], sw); + arg_idx += 4u; + break; + } + + default: + hb_gpu_draw_destroy(draw); + return -1; + } + } + + int32_t res = finalize_draw_blob(draw, out_rgba16i, cap_texels, out_ext); + hb_gpu_draw_destroy(draw); + return res; +} diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs index 8979b54..fdee366 100644 --- a/src/RustToDust.Core/GridChassis.cs +++ b/src/RustToDust.Core/GridChassis.cs @@ -890,6 +890,14 @@ namespace RustToDust.Core UpdateMountedTelemetry(); } + public void ApplyReplicatedCoreHpRatio(float coreHpRatio, bool alive) + { + if (MaxCoreHp <= 0f) return; + CoreHp = alive + ? MathF.Max(0.01f, Math.Clamp(coreHpRatio, 0f, 1f) * MaxCoreHp) + : 0f; + } + public void ApplyReplicatedThermal(ReadOnlySpan quantizedCellTemps, ReadOnlySpan mountedTemps, ReadOnlySpan mountedCooldowns) { int idx = 0; diff --git a/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs b/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs new file mode 100644 index 0000000..c9d2f83 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs @@ -0,0 +1,175 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +/// +/// Manages texel offsets inside the single 262,144-texel (2.0 MiB) RGBA16I GPU atlas: +/// - Persistent zone: [0 .. 229,376) with a 75% (172,032) watermark reset trigger. +/// - Dynamic scratch ring: [229,376 .. 262,144). +/// Queues uploads into pre-allocated staging storage for zero-GC render-thread commits. +/// +public sealed class HbGpuAtlasAllocator +{ + public const uint TotalTexels = 262_144; + public const uint PersistentCapacity = 229_376; + public const uint PersistentResetWatermark = 172_032; // 75% of PersistentCapacity + public const uint DynamicBase = PersistentCapacity; + public const uint DynamicCapacity = TotalTexels - PersistentCapacity; // 32,768 + public const int BytesPerTexel = 8; + public const int TotalBytes = (int)(TotalTexels * BytesPerTexel); + + public struct UploadChunk + { + public uint AtlasTexelOffset; + public uint ShortOffset; + public uint TexelCount; + } + + private readonly short[] _pendingShorts = new short[TotalTexels * 4]; + private readonly UploadChunk[] _pendingChunks = new UploadChunk[2048]; + private uint _pendingShortCursor; + private int _pendingChunkCount; + + public uint PersistentCursor { get; private set; } + public uint DynamicCursor { get; private set; } + public uint Epoch { get; private set; } = 1; + + public bool NeedsPersistentReset => PersistentCursor > PersistentResetWatermark; + + public int PendingChunkCount => _pendingChunkCount; + + public ReadOnlySpan PendingShortPool => _pendingShorts; + + public ReadOnlySpan PendingChunks => _pendingChunks.AsSpan(0, _pendingChunkCount); + + public void ResetPersistent() + { + PersistentCursor = 0; + Epoch++; + } + + public uint AllocatePersistent(ReadOnlySpan rgba16iShorts) + { + if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0) + { + throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts)); + } + + uint texels = (uint)(rgba16iShorts.Length >> 2); + if (PersistentCursor + texels > PersistentCapacity) + { + throw new InvalidOperationException( + $"Persistent atlas overflow: cursor={PersistentCursor}, needed={texels}, cap={PersistentCapacity}."); + } + + uint atlasOffset = PersistentCursor; + PersistentCursor += texels; + QueueUpload(atlasOffset, rgba16iShorts, texels); + return atlasOffset; + } + + public uint AllocateDynamic(ReadOnlySpan rgba16iShorts) + { + if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0) + { + throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts)); + } + + uint texels = (uint)(rgba16iShorts.Length >> 2); + if (texels > DynamicCapacity) + { + throw new InvalidOperationException( + $"Dynamic blob ({texels} texels) exceeds DynamicCapacity ({DynamicCapacity})."); + } + + if (DynamicCursor + texels > DynamicCapacity) + { + DynamicCursor = 0; + } + + uint atlasOffset = DynamicBase + DynamicCursor; + DynamicCursor += texels; + QueueUpload(atlasOffset, rgba16iShorts, texels); + return atlasOffset; + } + + private void QueueUpload(uint atlasOffset, ReadOnlySpan rgba16iShorts, uint texels) + { + if (_pendingChunkCount >= _pendingChunks.Length || + _pendingShortCursor + (uint)rgba16iShorts.Length > (uint)_pendingShorts.Length) + { + // Should never happen in normal HUD usage; reset pending ring head safely if overwhelmed without draining. + throw new InvalidOperationException("Atlas pending upload staging buffer full before render-thread drain."); + } + + rgba16iShorts.CopyTo(_pendingShorts.AsSpan((int)_pendingShortCursor)); + _pendingChunks[_pendingChunkCount++] = new UploadChunk + { + AtlasTexelOffset = atlasOffset, + ShortOffset = _pendingShortCursor, + TexelCount = texels + }; + _pendingShortCursor += (uint)rgba16iShorts.Length; + } + + /// + /// Copies all pending upload chunks into a caller-owned staging byte[] at index 0 + /// and invokes uploadCallback(atlasByteOffset, byteCount). Zero allocations when callback is cached. + /// + public int DrainChunks(byte[] stagingBuffer, Action uploadCallback) + { + int count = _pendingChunkCount; + if (count == 0) + { + return 0; + } + + for (int i = 0; i < count; i++) + { + UploadChunk c = _pendingChunks[i]; + uint byteCount = c.TexelCount * BytesPerTexel; + if (byteCount > (uint)stagingBuffer.Length) + { + throw new InvalidOperationException($"Upload chunk ({byteCount} B) exceeds staging buffer ({stagingBuffer.Length} B)."); + } + Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), stagingBuffer, 0, (int)byteCount); + uploadCallback(c.AtlasTexelOffset * BytesPerTexel, byteCount); + } + + _pendingChunkCount = 0; + _pendingShortCursor = 0; + return count; + } + + /// + /// Copies all pending upload chunks into a full 2 MiB mirror buffer at their atlas byte offsets. + /// Returns how many chunks were drained. Zero allocations. + /// + public int DrainToMirror(byte[] atlasMirrorBytes) + { + int count = _pendingChunkCount; + if (count == 0) + { + return 0; + } + + for (int i = 0; i < count; i++) + { + UploadChunk c = _pendingChunks[i]; + int dstOffset = (int)(c.AtlasTexelOffset * BytesPerTexel); + int byteCount = (int)(c.TexelCount * BytesPerTexel); + Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), atlasMirrorBytes, dstOffset, byteCount); + } + + _pendingChunkCount = 0; + _pendingShortCursor = 0; + return count; + } + + public void ClearPending() + { + _pendingChunkCount = 0; + _pendingShortCursor = 0; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuBlobCache.cs b/src/RustToDust.HbGpu/HbGpuBlobCache.cs new file mode 100644 index 0000000..e560788 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuBlobCache.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.HbGpu; + +/// +/// Encodes and caches RGBA16I Slug blobs for font glyphs and static/dynamic vector shapes +/// using a pre-allocated 65,536-short (128 KiB) scratch buffer. +/// +public sealed unsafe class HbGpuBlobCache +{ + public const int ScratchShortsCapacity = 65_536; + public const uint ScratchTexelsCapacity = ScratchShortsCapacity / 4; // 16,384 texels + + private readonly HbGpuAtlasAllocator _atlas; + private readonly Dictionary _glyphBlobs = new(512); + private readonly Dictionary _vectorBlobs = new(64); + private readonly short[] _scratchShorts = new short[ScratchShortsCapacity]; + + public HbGpuBlobCache(HbGpuAtlasAllocator atlas) + { + _atlas = atlas ?? throw new ArgumentNullException(nameof(atlas)); + } + + public HbGpuAtlasAllocator Atlas => _atlas; + + public int CachedGlyphCount => _glyphBlobs.Count; + + public int CachedVectorCount => _vectorBlobs.Count; + + public bool EnsureBudgetOrReset() + { + if (!_atlas.NeedsPersistentReset) + { + return false; + } + + _atlas.ResetPersistent(); + _glyphBlobs.Clear(); + _vectorBlobs.Clear(); + return true; + } + + public CachedBlob GetOrEncodeGlyph( + HbGpuFontCache fonts, + byte fontId, + uint glyphId, + ushort qWght, + ushort qWdth, + short qSlnt) + { + var key = new GlyphBlobKey(fontId, glyphId, qWght, qWdth, qSlnt); + if (_glyphBlobs.TryGetValue(key, out CachedBlob cached)) + { + return cached; + } + + IntPtr fontHandle = fonts.GetOrCreateStyle(new HbGpuStyleKey(fontId, qWght, qWdth, qSlnt)); + int texelCount; + RtdHbExtents ext; + fixed (short* dst = _scratchShorts) + { + texelCount = HbGpuNative.EncodeGlyph(fontHandle, glyphId, dst, ScratchTexelsCapacity, out ext); + } + + if (texelCount < 0) + { + throw new InvalidOperationException($"rtd_hb_encode_glyph failed for glyph {glyphId} (code {texelCount})."); + } + + CachedBlob blob; + if (texelCount == 0) + { + blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + else + { + if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) + { + _atlas.ResetPersistent(); + _glyphBlobs.Clear(); + _vectorBlobs.Clear(); + } + + uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); + blob = new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + _glyphBlobs[key] = blob; + return blob; + } + + public CachedBlob GetOrEncodeStaticPath( + VectorBlobKey key, + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args) + { + if (_vectorBlobs.TryGetValue(key, out CachedBlob cached)) + { + return cached; + } + + int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext); + CachedBlob blob; + if (texelCount == 0) + { + blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + else + { + if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) + { + _atlas.ResetPersistent(); + _glyphBlobs.Clear(); + _vectorBlobs.Clear(); + } + + uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); + blob = new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + _vectorBlobs[key] = blob; + return blob; + } + + public CachedBlob EncodeDynamicPath( + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args) + { + int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext); + if (texelCount == 0) + { + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + + uint offset = _atlas.AllocateDynamic(_scratchShorts.AsSpan(0, texelCount * 4)); + return new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + private int EncodePathIntoScratch( + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args, + out RtdHbExtents ext) + { + int texelCount; + fixed (byte* vPtr = verbs) + fixed (float* aPtr = args) + fixed (short* dst = _scratchShorts) + { + texelCount = HbGpuNative.EncodePath( + designUpem, + vPtr, + (uint)verbs.Length, + aPtr, + (uint)args.Length, + dst, + ScratchTexelsCapacity, + out ext); + } + + if (texelCount < 0) + { + throw new InvalidOperationException($"rtd_hb_encode_path failed (code {texelCount})."); + } + + return texelCount; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuCommandWriter.cs b/src/RustToDust.HbGpu/HbGpuCommandWriter.cs new file mode 100644 index 0000000..47c0b4c --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuCommandWriter.cs @@ -0,0 +1,246 @@ +using System; + +namespace RustToDust.HbGpu; + +/// +/// Zero-allocation CPU quad builder and text shaper writing 80-byte HbGpuQuadInstance records. +/// +public sealed unsafe class HbGpuCommandWriter +{ + public const int MaxQuads = 4096; + public const int ShapingScratchCapacity = 1024; + + private readonly HbGpuQuadInstance[] _quads = new HbGpuQuadInstance[MaxQuads]; + private readonly RtdHbShapedGlyph[] _shapedScratch = new RtdHbShapedGlyph[ShapingScratchCapacity]; + + public int QuadCount { get; private set; } + + public ReadOnlySpan Quads => _quads.AsSpan(0, QuadCount); + + public HbGpuQuadInstance[] RawBuffer => _quads; + + public void BeginFrame() + { + QuadCount = 0; + } + + public static uint PackClipCoord(float minVal, float maxVal) + { + ushort lo = (ushort)Math.Clamp((int)MathF.Floor(minVal), 0, 65535); + ushort hi = (ushort)Math.Clamp((int)MathF.Ceiling(maxVal), 0, 65535); + return (uint)lo | ((uint)hi << 16); + } + + public static void PackClipRect( + float x, float y, float w, float h, + out uint clipMinPacked, + out uint clipMaxPacked) + { + ushort x0 = (ushort)Math.Clamp((int)MathF.Floor(x), 0, 65535); + ushort y0 = (ushort)Math.Clamp((int)MathF.Floor(y), 0, 65535); + ushort x1 = (ushort)Math.Clamp((int)MathF.Ceiling(x + w), 0, 65535); + ushort y1 = (ushort)Math.Clamp((int)MathF.Ceiling(y + h), 0, 65535); + clipMinPacked = (uint)x0 | ((uint)y0 << 16); + clipMaxPacked = (uint)x1 | ((uint)y1 << 16); + } + + public bool TryAddQuad(in HbGpuQuadInstance quad) + { + if (QuadCount >= MaxQuads) + { + return false; + } + + _quads[QuadCount++] = quad; + return true; + } + + public void DrawBlob( + in CachedBlob blob, + float screenX, + float screenY, + float m00, + float m01, + float m10, + float m11, + float anchorEmX, + float anchorEmY, + float r, + float g, + float b, + float a, + bool stemDarken = false, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (!blob.IsValid || QuadCount >= MaxQuads) + { + return; + } + + _quads[QuadCount++] = new HbGpuQuadInstance + { + EmMinX = blob.MinX, + EmMinY = blob.MinY, + EmMaxX = blob.MaxX, + EmMaxY = blob.MaxY, + AnchorEmX = anchorEmX, + AnchorEmY = anchorEmY, + ScreenX = screenX, + ScreenY = screenY, + M00 = m00, + M01 = m01, + M10 = m10, + M11 = m11, + ColorR = r, + ColorG = g, + ColorB = b, + ColorA = a, + AtlasTexelOffset = blob.AtlasOffset, + Flags = stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u, + ClipMinPacked = clipMinPacked, + ClipMaxPacked = clipMaxPacked + }; + } + + public float MeasureTextWidth( + ReadOnlySpan text, + float fontSizePx, + HbGpuFontCache fonts, + byte fontId = 0, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default) + { + if (text.IsEmpty) + { + return 0f; + } + + HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt); + IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey); + int upem = fonts.GetMetrics(fontId).Upem; + float scale = fontSizePx / upem; + + uint glyphCount; + fixed (char* textPtr = text) + fixed (RtdHbShapedGlyph* outPtr = _shapedScratch) + { + glyphCount = HbGpuNative.ShapeUtf16( + fontHandle, + textPtr, + (uint)text.Length, + (uint)features, + outPtr, + (uint)_shapedScratch.Length); + } + + int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length); + int adv = 0; + for (int i = 0; i < count; i++) + { + adv += _shapedScratch[i].XAdvance; + } + + return adv * scale; + } + + /// + /// Shapes UTF-16 text directly and appends glyph quads. (x, baselineY) is the pen baseline origin in logical pixels (Y-down). + /// Returns the total horizontal advance in logical pixels. + /// + public float DrawTextUtf16( + ReadOnlySpan text, + float x, + float baselineY, + float fontSizePx, + float r, + float g, + float b, + float a, + HbGpuFontCache fonts, + HbGpuBlobCache blobs, + byte fontId = 0, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default, + bool stemDarken = true, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (text.IsEmpty) + { + return 0f; + } + + HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt); + IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey); + int upem = fonts.GetMetrics(fontId).Upem; + float scale = fontSizePx / upem; + + uint glyphCount; + fixed (char* textPtr = text) + fixed (RtdHbShapedGlyph* outPtr = _shapedScratch) + { + glyphCount = HbGpuNative.ShapeUtf16( + fontHandle, + textPtr, + (uint)text.Length, + (uint)features, + outPtr, + (uint)_shapedScratch.Length); + } + + int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length); + float penX = x; + float penY = baselineY; + + for (int i = 0; i < count; i++) + { + RtdHbShapedGlyph sg = _shapedScratch[i]; + CachedBlob blob = blobs.GetOrEncodeGlyph( + fonts, + fontId, + sg.GlyphId, + styleKey.QWght, + styleKey.QWdth, + styleKey.QSlnt); + + if (blob.IsValid && QuadCount < MaxQuads) + { + float gx = penX + sg.XOffset * scale; + float gy = penY - sg.YOffset * scale; // Y-up font offset -> Y-down screen + _quads[QuadCount++] = new HbGpuQuadInstance + { + EmMinX = blob.MinX, + EmMinY = blob.MinY, + EmMaxX = blob.MaxX, + EmMaxY = blob.MaxY, + AnchorEmX = 0f, + AnchorEmY = 0f, + ScreenX = gx, + ScreenY = gy, + M00 = scale, + M01 = 0f, + M10 = 0f, + M11 = -scale, + ColorR = r, + ColorG = g, + ColorB = b, + ColorA = a, + AtlasTexelOffset = blob.AtlasOffset, + Flags = stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u, + ClipMinPacked = clipMinPacked, + ClipMaxPacked = clipMaxPacked + }; + } + + penX += sg.XAdvance * scale; + penY -= sg.YAdvance * scale; + } + + return penX - x; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuFontCache.cs b/src/RustToDust.HbGpu/HbGpuFontCache.cs new file mode 100644 index 0000000..a40500d --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuFontCache.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RustToDust.HbGpu; + +/// +/// Owns loaded font faces and lazy quantized-axis (wght, wdth, slnt) hb_font_t* handles. +/// Avoids per-frame hb_font_set_variations thrash. +/// +public sealed unsafe class HbGpuFontCache : IDisposable +{ + private readonly Dictionary _baseFaces = new(); + private readonly Dictionary _metrics = new(); + private readonly Dictionary _styles = new(); + private bool _disposed; + + public byte RegisterFontFromFile(byte fontId, string path, uint faceIndex = 0) + { + ObjectDisposedException.ThrowIf(_disposed, this); + byte[] bytes = File.ReadAllBytes(path); + return RegisterFont(fontId, bytes, faceIndex); + } + + public byte RegisterFont(byte fontId, ReadOnlySpan ttfBytes, uint faceIndex = 0) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (ttfBytes.IsEmpty) + { + throw new ArgumentException("Font bytes cannot be empty.", nameof(ttfBytes)); + } + + if (_baseFaces.TryGetValue(fontId, out IntPtr existing) && existing != IntPtr.Zero) + { + throw new InvalidOperationException($"FontId {fontId} is already registered."); + } + + fixed (byte* ptr = ttfBytes) + { + IntPtr baseHandle = HbGpuNative.FontCreate(ptr, (uint)ttfBytes.Length, faceIndex, out RtdHbFontMetrics metrics); + if (baseHandle == IntPtr.Zero) + { + throw new InvalidOperationException($"rtd_hb_font_create failed for FontId {fontId}."); + } + + _baseFaces[fontId] = baseHandle; + _metrics[fontId] = metrics; + } + + return fontId; + } + + public RtdHbFontMetrics GetMetrics(byte fontId) => _metrics[fontId]; + + public bool TryGetMetrics(byte fontId, out RtdHbFontMetrics metrics) => + _metrics.TryGetValue(fontId, out metrics); + + public IntPtr GetOrCreateStyle(HbGpuStyleKey key) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_styles.TryGetValue(key, out IntPtr handle)) + { + return handle; + } + + if (!_baseFaces.TryGetValue(key.FontId, out IntPtr baseHandle)) + { + throw new KeyNotFoundException($"FontId {key.FontId} is not registered in HbGpuFontCache."); + } + + float wght = key.QWght; + float wdth = key.QWdth * 0.1f; + float slnt = key.QSlnt * 0.1f; + IntPtr variant = HbGpuNative.FontCreateVariant(baseHandle, wght, wdth, slnt); + if (variant == IntPtr.Zero) + { + throw new InvalidOperationException($"rtd_hb_font_create_variant failed for {key}."); + } + + _styles[key] = variant; + return variant; + } + + public IntPtr GetOrCreateStyle(byte fontId, float wght, float wdth, float slnt) => + GetOrCreateStyle(HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt)); + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + + foreach (IntPtr handle in _styles.Values) + { + if (handle != IntPtr.Zero) + { + HbGpuNative.FontDestroy(handle); + } + } + _styles.Clear(); + + foreach (IntPtr baseHandle in _baseFaces.Values) + { + if (baseHandle != IntPtr.Zero) + { + HbGpuNative.FontDestroy(baseHandle); + } + } + _baseFaces.Clear(); + _metrics.Clear(); + } +} diff --git a/src/RustToDust.HbGpu/HbGpuNative.cs b/src/RustToDust.HbGpu/HbGpuNative.cs new file mode 100644 index 0000000..9e55941 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuNative.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +public static unsafe class HbGpuNative +{ + public const string LibraryName = "rtd_hbgpu"; + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_version_string")] + private static extern IntPtr NativeVersionString(); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shader_source")] + private static extern IntPtr NativeShaderSource(uint stage, uint kind); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create")] + public static extern IntPtr FontCreate( + byte* ttf, + uint len, + uint faceIndex, + out RtdHbFontMetrics outMetrics); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create_variant")] + public static extern IntPtr FontCreateVariant( + IntPtr baseFont, + float wght, + float wdth, + float slnt); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_destroy")] + public static extern void FontDestroy(IntPtr font); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shape_utf16")] + public static extern uint ShapeUtf16( + IntPtr font, + char* utf16, + uint charLen, + uint featureFlags, + RtdHbShapedGlyph* outGlyphs, + uint cap); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_glyph")] + public static extern int EncodeGlyph( + IntPtr font, + uint glyphId, + short* outRgba16i, + uint capTexels, + out RtdHbExtents outExt); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_path")] + public static extern int EncodePath( + uint designUpem, + byte* verbs, + uint nVerbs, + float* args, + uint nArgs, + short* outRgba16i, + uint capTexels, + out RtdHbExtents outExt); + + public static string GetVersionString() => + Marshal.PtrToStringUTF8(NativeVersionString()) ?? string.Empty; + + public static string GetShaderSource(HbGpuShaderStage stage, HbGpuShaderKind kind) => + Marshal.PtrToStringUTF8(NativeShaderSource((uint)stage, (uint)kind)) ?? string.Empty; +} diff --git a/src/RustToDust.HbGpu/HbGpuTypes.cs b/src/RustToDust.HbGpu/HbGpuTypes.cs new file mode 100644 index 0000000..d747c59 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuTypes.cs @@ -0,0 +1,151 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbFontMetrics +{ + public int Upem; + public int Ascender; + public int Descender; + public int LineGap; +} + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbShapedGlyph +{ + public uint GlyphId; + public uint Cluster; + public int XAdvance; + public int YAdvance; + public int XOffset; + public int YOffset; +} + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbExtents +{ + public int MinX; + public int MinY; + public int MaxX; + public int MaxY; +} + +/// +/// 80-byte GPU quad instance matching the std430 SSBO layout in HbGpuCanvas. +/// +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public struct HbGpuQuadInstance +{ + public float EmMinX; + public float EmMinY; + public float EmMaxX; + public float EmMaxY; + + public float AnchorEmX; + public float AnchorEmY; + public float ScreenX; + public float ScreenY; + + public float M00; + public float M01; + public float M10; + public float M11; + + public float ColorR; + public float ColorG; + public float ColorB; + public float ColorA; + + public uint AtlasTexelOffset; + public uint Flags; + public uint ClipMinPacked; + public uint ClipMaxPacked; + + public const uint FlagStemDarken = 1u; + public const uint Unclipped = 0xFFFFFFFFu; +} + +[Flags] +public enum HbGpuFeatureFlags : uint +{ + None = 0u, + Calt = 1u << 0, + Liga = 1u << 1, + Default = Calt | Liga +} + +public enum HbGpuPathVerb : byte +{ + Move = 0, + LineTo = 1, + QuadTo = 2, + CubicTo = 3, + Close = 4, + Line = 5, + Rect = 6, + Circle = 7 +} + +public enum HbGpuShaderStage : uint +{ + Vertex = 0, + Fragment = 1 +} + +public enum HbGpuShaderKind : uint +{ + Shared = 0, + Draw = 1 +} + +public enum VectorShapeKind : ushort +{ + UnitFilledRect = 1, + UnitCircleFill = 2, + UnitRingStroke = 3, + CornerLBracket = 4, + TargetBracketCorner = 5, + DirectionalArrow = 6, + ChevronTriangle = 7, + DiamondBlip = 8, + HitMarkerArm = 9, + StrippedHatchX = 10, + PanelFrame = 11, + HardpointBracket = 12, + ThermalHeatArc = 13, + IncomingHitArc = 14, + Custom = 100 +} + +public readonly record struct HbGpuStyleKey(byte FontId, ushort QWght, ushort QWdth, short QSlnt) +{ + public static ushort QuantizeWeight(float wght) => + (ushort)Math.Clamp((int)MathF.Round(wght), 100, 1000); + + public static ushort QuantizeWidth(float wdth) => + (ushort)Math.Clamp((int)MathF.Round(wdth * 10f), 500, 2000); + + public static short QuantizeSlant(float slnt) => + (short)Math.Clamp((int)MathF.Round(slnt * 10f), -200, 200); + + public static HbGpuStyleKey FromAxes(byte fontId, float wght, float wdth, float slnt) => + new(fontId, QuantizeWeight(wght), QuantizeWidth(wdth), QuantizeSlant(slnt)); +} + +public readonly record struct GlyphBlobKey(byte FontId, uint GlyphId, ushort QWght, ushort QWdth, short QSlnt); + +public readonly record struct VectorBlobKey(VectorShapeKind Kind, ushort ParamA, ushort ParamB, uint ParamC = 0); + +public readonly record struct CachedBlob( + uint AtlasOffset, + short MinX, + short MinY, + short MaxX, + short MaxY, + uint TexelCount, + bool IsEmpty) +{ + public bool IsValid => TexelCount > 0 && !IsEmpty; +} diff --git a/src/RustToDust.HbGpu/HbGpuVectorShapes.cs b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs new file mode 100644 index 0000000..e79dfff --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs @@ -0,0 +1,209 @@ +using System; + +namespace RustToDust.HbGpu; + +/// +/// Encodes canonical UI/HUD vector primitives into HarfBuzz hb-gpu RGBA16I blobs +/// in a 1000-unit design space ([-500 .. +500] or [0 .. 1000]). +/// +public static class HbGpuVectorShapes +{ + public const uint DesignUpem = 1000u; + + private static readonly byte[] RectVerbs = { (byte)HbGpuPathVerb.Rect }; + private static readonly float[] UnitFilledRectArgs = { -500f, -500f, 1000f, 1000f, float.NaN }; + + private static readonly byte[] CircleVerbs = { (byte)HbGpuPathVerb.Circle }; + private static readonly float[] UnitFilledCircleArgs = { 0f, 0f, 500f, float.NaN }; + + // L-corner bracket centered around (0,0) pointing into (+X, +Y), design space 1000x1000 + // Thickness paramB in thousandths (e.g. 100 = 10% of arm length) + private static readonly byte[] CornerBracketVerbs = + { + (byte)HbGpuPathVerb.Move, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.Close + }; + + // Equilateral/tactical chevron pointing +Y (Y-up in design space -> -Y in Y-down screen) + private static readonly byte[] ChevronVerbs = + { + (byte)HbGpuPathVerb.Move, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.Close + }; + private static readonly float[] ChevronArgs = + { + 0f, 500f, + 420f, -380f, + 0f, -140f, + -420f, -380f + }; + + // Solid directional arrow pointing +Y in design space + private static readonly float[] ArrowArgs = + { + 0f, 520f, + 400f, -360f, + 0f, -180f, + -400f, -360f + }; + + // Diamond blip centered at (0,0) + private static readonly float[] DiamondArgs = + { + 0f, 500f, + 500f, 0f, + 0f, -500f, + -500f, 0f + }; + + public static CachedBlob GetUnitFilledRect(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.UnitFilledRect, 0, 0), + DesignUpem, + RectVerbs, + UnitFilledRectArgs); + + public static CachedBlob GetUnitFilledCircle(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.UnitCircleFill, 0, 0), + DesignUpem, + CircleVerbs, + UnitFilledCircleArgs); + + public static CachedBlob GetUnitRingStroke(HbGpuBlobCache cache, ushort strokeUnits = 24) + { + Span args = stackalloc float[] { 0f, 0f, 500f, strokeUnits }; + return cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.UnitRingStroke, strokeUnits, 0), + DesignUpem, + CircleVerbs, + args); + } + + public static CachedBlob GetTargetBracketCorner(HbGpuBlobCache cache, ushort thicknessUnits = 120) + { + float t = Math.Clamp((float)thicknessUnits, 10f, 450f); + Span args = stackalloc float[] + { + 0f, 0f, + 1000f, 0f, + 1000f, -t, + t, -t, + t, -1000f, + 0f, -1000f + }; + return cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.TargetBracketCorner, thicknessUnits, 0), + DesignUpem, + CornerBracketVerbs, + args); + } + + public static CachedBlob GetChevronTriangle(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.ChevronTriangle, 0, 0), + DesignUpem, + ChevronVerbs, + ChevronArgs); + + public static CachedBlob GetDirectionalArrow(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.DirectionalArrow, 0, 0), + DesignUpem, + ChevronVerbs, + ArrowArgs); + + public static CachedBlob GetDiamondBlip(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.DiamondBlip, 0, 0), + DesignUpem, + ChevronVerbs, + DiamondArgs); + + /// + /// Encodes a stroked circular arc in design space (radius=500, Y-up) using cubic Bezier segments. + /// Useful for thermal heat arcs and directional incoming-hit arcs. + /// Angles are in radians counter-clockwise from +X (Y-up). + /// + public static CachedBlob EncodeArcStrokeDynamic( + HbGpuBlobCache cache, + float startRad, + float endRad, + float radius = 500f, + float halfThickness = 32f) + { + float sweep = endRad - startRad; + if (MathF.Abs(sweep) < 1e-4f) + { + return default; + } + + int segs = Math.Clamp((int)MathF.Ceiling(MathF.Abs(sweep) / (MathF.PI * 0.4f)), 1, 8); + float rOut = radius + halfThickness; + float rIn = MathF.Max(1f, radius - halfThickness); + float dt = sweep / segs; + float k = (4f / 3f) * MathF.Tan(dt * 0.25f); + + // 1 Move + segs CubicTo + 1 LineTo + segs CubicTo + 1 Close + int nVerbs = 1 + segs + 1 + segs + 1; + int nArgs = 2 + segs * 6 + 2 + segs * 6; + Span verbs = stackalloc byte[nVerbs]; + Span args = stackalloc float[nArgs]; + + int v = 0; + int a = 0; + + float ca0 = MathF.Cos(startRad); + float sa0 = MathF.Sin(startRad); + verbs[v++] = (byte)HbGpuPathVerb.Move; + args[a++] = rOut * ca0; + args[a++] = rOut * sa0; + + for (int i = 0; i < segs; i++) + { + float t0 = startRad + i * dt; + float t1 = t0 + dt; + float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0); + float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1); + verbs[v++] = (byte)HbGpuPathVerb.CubicTo; + args[a++] = rOut * (c0 - k * s0); + args[a++] = rOut * (s0 + k * c0); + args[a++] = rOut * (c1 + k * s1); + args[a++] = rOut * (s1 - k * c1); + args[a++] = rOut * c1; + args[a++] = rOut * s1; + } + + float ce = MathF.Cos(endRad); + float se = MathF.Sin(endRad); + verbs[v++] = (byte)HbGpuPathVerb.LineTo; + args[a++] = rIn * ce; + args[a++] = rIn * se; + + for (int i = segs - 1; i >= 0; i--) + { + float t1 = startRad + (i + 1) * dt; + float t0 = startRad + i * dt; + float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1); + float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0); + verbs[v++] = (byte)HbGpuPathVerb.CubicTo; + args[a++] = rIn * (c1 + k * s1); + args[a++] = rIn * (s1 - k * c1); + args[a++] = rIn * (c0 - k * s0); + args[a++] = rIn * (s0 + k * c0); + args[a++] = rIn * c0; + args[a++] = rIn * s0; + } + + verbs[v++] = (byte)HbGpuPathVerb.Close; + return cache.EncodeDynamicPath(DesignUpem, verbs[..v], args[..a]); + } +} diff --git a/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj b/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj new file mode 100644 index 0000000..eb31d97 --- /dev/null +++ b/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj @@ -0,0 +1,42 @@ + + + + net8.0 + enable + disable + true + RustToDust.HbGpu + RustToDust.HbGpu + Release + $(MSBuildThisFileDirectory)..\..\native\rtd_hbgpu + $(MSBuildThisFileDirectory)..\..\artifacts\hbgpu-native\$(HbGpuNativeConfiguration) + C:\Program Files\CMake\bin\cmake.exe + cmake + + + + + + + + + + + + + + diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index d8dd6ad..4c1236d 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -1455,6 +1455,7 @@ namespace RustToDust.Net c.ThrottleCmd = nc.Throttle; c.SteerCmd = nc.Steer; c.MaxThermalRatio = nc.MaxThermalRatio; + c.Grid.ApplyReplicatedCoreHpRatio(nc.CoreHpRatio, nc.Alive); c.X = nc.Pos.X; c.Y = nc.Pos.Y; c.Z = nc.Pos.Z; c.CurrRotX = nc.Rot.X; c.CurrRotY = nc.Rot.Y; c.CurrRotZ = nc.Rot.Z; c.CurrRotW = nc.Rot.W; c.VelX = nc.Vel.X; c.VelY = nc.Vel.Y; c.VelZ = nc.Vel.Z; diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 9f5a19b..1862b8f 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -2149,6 +2149,11 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Spectators.Spectators.Count; i++) { _spectatorPvs[obs.Id, i] = false; + if (memState.SpectatorContacts.TryGetValue(State.Spectators.Spectators[i].Id, out var smem)) + { + smem.VisibleToPlayer = false; + smem.FaintHorizonPing = false; + } } continue; } diff --git a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs index 17dc0a2..22052a9 100644 --- a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs +++ b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs @@ -917,6 +917,51 @@ namespace RustToDust.Tests $"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == postResetHostEdgeH ({postResetHostEdgeH:F4}) within 0.001m"); } + [Fact] + public void RemoteArenaSession_AppliesRemoteContenderCoreHpRatioOnPvsSnapshot() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "HpProbe"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); + int localSlot = client.LocalContenderId; + int rivalSlot = localSlot == 0 ? 1 : 0; + + var serverLocal = host.Session.State.Contenders[localSlot]; + var serverRival = host.Session.State.Contenders[rivalSlot]; + host.Session.SetContenderPose(localSlot, 0f, 0f, 0f); + host.Session.SetContenderPose(rivalSlot, 0f, 40f, MathF.PI); + + float targetHp = serverRival.Grid.MaxCoreHp * 0.42f; + serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, targetHp, serverRival.Grid.HitSequence + 1); + float expectedRatio = serverRival.Grid.CoreHp / serverRival.Grid.MaxCoreHp; + + bool synced = PumpUntil(host, new[] { client }, () => + { + if (!client.IsContenderVisible(rivalSlot)) return false; + var c = client.ViewState.Contenders[rivalSlot]; + float r = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + return MathF.Abs(r - expectedRatio) < 0.02f; + }, ref nowMs, 2500); + + var clientRival = client.ViewState.Contenders[rivalSlot]; + float actualRatio = clientRival.Grid.MaxCoreHp > 0f ? clientRival.Grid.CoreHp / clientRival.Grid.MaxCoreHp : 1f; + Assert.True(synced, $"Expected remote contender {rivalSlot} CoreHpRatio ~ {expectedRatio:F3}, got {actualRatio:F3}"); + + // Edge case: living rival at 0.30 HP rounds 8-bit CoreHpRatio to 0, yet must remain Alive on remote client + serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0.30f, serverRival.Grid.HitSequence + 1); + Assert.True(serverRival.Alive); + bool lowHpSynced = PumpUntil(host, new[] { client }, () => + { + var c = client.ViewState.Contenders[rivalSlot]; + return c.Alive && c.Grid.CoreHp > 0f && c.Grid.CoreHp <= 0.5f; + }, ref nowMs, 2500); + Assert.True(lowHpSynced && clientRival.Alive && !clientRival.Grid.IsDestroyed && clientRival.Grid.CoreHp > 0f, + $"Expected living 0.30 HP rival to stay Alive on remote client, got Alive={clientRival.Alive}, CoreHp={clientRival.Grid.CoreHp:F3}"); + } + private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) => CultNetRudpPacketCodec.Encode(new CultNetRudpPacket { diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs index 9bc5c4b..d56296e 100644 --- a/tests/RustToDust.Tests/DetectionLosTests.cs +++ b/tests/RustToDust.Tests/DetectionLosTests.cs @@ -584,5 +584,30 @@ namespace RustToDust.Tests Assert.Equal(0, targetNearest.TargetContenderId); } } + + [Fact] + public void DeadObserver_ClearsSpectatorContactsVisibleToPlayer() + { + using var session = new ArenaSession(seed: 12, slot0Human: true); + var player = session.State.Contenders[0]; + var spec = session.State.Spectators.Spectators.First(s => s.Alive); + + session.SetContenderPose(player.Id, 0f, 0f); + session.SetSpectatorPose(spec.Id, 0f, 35f); + session.State.Spectators.OnSpectatorDamaged(spec, player.Id); + + session.Step(); + var obs0 = session.State.GetOrCreateObserverState(0); + Assert.True(obs0.SpectatorContacts.TryGetValue(spec.Id, out var memBefore) && memBefore.VisibleToPlayer, + "Expected living observer in open LOS to mark provoked spectator VisibleToPlayer=true"); + + // Kill observer and step once; stale SpectatorContacts must clear VisibleToPlayer + player.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0f, player.Grid.HitSequence + 1); + Assert.False(player.Alive); + + session.Step(); + Assert.False(obs0.SpectatorContacts[spec.Id].VisibleToPlayer, + "Expected dead observer to clear SpectatorContacts.VisibleToPlayer"); + } } } diff --git a/tests/RustToDust.Tests/GraphicsSettingsTests.cs b/tests/RustToDust.Tests/GraphicsSettingsTests.cs new file mode 100644 index 0000000..e798424 --- /dev/null +++ b/tests/RustToDust.Tests/GraphicsSettingsTests.cs @@ -0,0 +1,158 @@ +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); + + // ResetToDefaults(persist: true) must unconditionally rewrite a corrupt file even when memory equals defaults + corruptLoaded.ResetToDefaults(persist: true); + string repairedJson = File.ReadAllText(corruptPath); + Assert.DoesNotContain("not valid json", repairedJson, StringComparison.Ordinal); + var repaired = new GraphicsSettings(); + Assert.True(repaired.LoadFromJson(repairedJson)); + Assert.Equal(VfxResolutionScale.Half, repaired.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, repaired.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, repaired.SdfgiQuality); + Assert.True(repaired.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/HbGpuNativeTests.cs b/tests/RustToDust.Tests/HbGpuNativeTests.cs new file mode 100644 index 0000000..efd33b4 --- /dev/null +++ b/tests/RustToDust.Tests/HbGpuNativeTests.cs @@ -0,0 +1,178 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using RustToDust.HbGpu; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class HbGpuNativeTests +{ + private static string RepoRoot + { + get + { + string? dir = AppContext.BaseDirectory; + while (dir is not null) + { + if (File.Exists(Path.Combine(dir, "RustToDust.slnx"))) + { + return dir; + } + dir = Directory.GetParent(dir)?.FullName; + } + throw new DirectoryNotFoundException("Could not locate RustToDust.slnx from test output directory."); + } + } + + [Fact] + public void NativeDllExistsAndMeetsSizeBudget() + { + if (OperatingSystem.IsWindows()) + { + string dllPath = Path.Combine(AppContext.BaseDirectory, "rtd_hbgpu.dll"); + Assert.True(File.Exists(dllPath), $"Expected rtd_hbgpu.dll at '{dllPath}'."); + long size = new FileInfo(dllPath).Length; + Assert.InRange(size, 100_000, 2_621_440); // < 2.5 MiB + } + + string ver = HbGpuNative.GetVersionString(); + Assert.Equal("15.2.0", ver); + + string vertShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared); + string fragShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared); + string fragDraw = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw); + Assert.Contains("hb_gpu_dilate", vertShared); + Assert.Contains("uniform isamplerBuffer hb_gpu_atlas;", fragShared); + Assert.Contains("hb_gpu_draw", fragDraw); + } + + [Fact] + public void KryptonFontAndLicensesAreCompliant() + { + string root = RepoRoot; + string fontPath = Path.Combine(root, "assets", "fonts", "Krypton.ttf"); + string oflPath = Path.Combine(root, "assets", "fonts", "OFL-1.1.txt"); + string hbCopyPath = Path.Combine(root, "assets", "fonts", "HARFBUZZ-COPYING.txt"); + string noticesPath = Path.Combine(root, "THIRD_PARTY_NOTICES.txt"); + + Assert.True(File.Exists(fontPath)); + Assert.True(File.Exists(oflPath)); + Assert.True(File.Exists(hbCopyPath)); + Assert.True(File.Exists(noticesPath)); + + byte[] fontBytes = File.ReadAllBytes(fontPath); + Assert.Equal(1_363_340, fontBytes.Length); + string sha = Convert.ToHexString(SHA256.HashData(fontBytes)).ToLowerInvariant(); + Assert.Equal("6462cae55b336ae6ffb7c8f1932177960510a4207e65803f527b276d42c8a240", sha); + + string oflText = File.ReadAllText(oflPath); + Assert.Contains("Copyright (c) 2023, GitHub", oflText); + Assert.Contains("Krypton", oflText); + } + + [Fact] + public void QuadInstanceStructIs80Bytes() + { + Assert.Equal(80, Unsafe.SizeOf()); + Assert.Equal(80, Marshal.SizeOf()); + } + + [Fact] + public void ShapingAndGlyphEncodingWorkAcrossKryptonAxes() + { + string fontPath = Path.Combine(RepoRoot, "assets", "fonts", "Krypton.ttf"); + using var fonts = new HbGpuFontCache(); + fonts.RegisterFontFromFile(0, fontPath); + + RtdHbFontMetrics metrics = fonts.GetMetrics(0); + Assert.Equal(2000, metrics.Upem); + + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + var writer = new HbGpuCommandWriter(); + + writer.BeginFrame(); + float wReg = writer.DrawTextUtf16("RAPTOR -> 142.8m", 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f); + float wBold = writer.DrawTextUtf16("CHASSIS", 10f, 80f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 700f); + float wSlnt = writer.DrawTextUtf16("SLANT", 10f, 120f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 400f, slnt: -9f); + + Assert.True(wReg > 50f); + Assert.True(wBold > 20f); + Assert.True(wSlnt > 20f); + Assert.True(writer.QuadCount >= 18); // spaces omit quads, visible glyphs emit quads + Assert.True(blobs.CachedGlyphCount >= 15); + Assert.True(atlas.PersistentCursor > 0); + Assert.True(atlas.PendingChunkCount > 0); + + // Space glyph encodes cleanly as empty + CachedBlob spaceBlob = blobs.GetOrEncodeGlyph(fonts, 0, 1 /* glyph or verify space */, 200, 1000, 0); + Assert.True(spaceBlob.TexelCount >= 0); + + // Hot steady-state loop allocates zero managed bytes once glyphs/styles are cached + writer.BeginFrame(); + atlas.ClearPending(); + ReadOnlySpan hotText = "RAPTOR -> 142.8m"; + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 64; i++) + { + writer.BeginFrame(); + writer.DrawTextUtf16(hotText, 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f); + } + long after = GC.GetAllocatedBytesForCurrentThread(); + Assert.Equal(0, after - before); + } + + [Fact] + public void VectorPathsAndAtlasBudgetResetWork() + { + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + + CachedBlob rect = HbGpuVectorShapes.GetUnitFilledRect(blobs); + CachedBlob circle = HbGpuVectorShapes.GetUnitFilledCircle(blobs); + CachedBlob ring = HbGpuVectorShapes.GetUnitRingStroke(blobs, 24); + CachedBlob bracket = HbGpuVectorShapes.GetTargetBracketCorner(blobs, 120); + CachedBlob arrow = HbGpuVectorShapes.GetDirectionalArrow(blobs); + CachedBlob chevron = HbGpuVectorShapes.GetChevronTriangle(blobs); + CachedBlob diamond = HbGpuVectorShapes.GetDiamondBlip(blobs); + CachedBlob arc = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -2.356f, 0.785f); + + Assert.True(rect.IsValid && rect.TexelCount > 2); + Assert.True(circle.IsValid && circle.TexelCount > 2); + Assert.True(ring.IsValid && ring.TexelCount > 4); + Assert.True(bracket.IsValid && bracket.TexelCount > 2); + Assert.True(arrow.IsValid && arrow.TexelCount > 2); + Assert.True(chevron.IsValid && chevron.TexelCount > 2); + Assert.True(diamond.IsValid && diamond.TexelCount > 2); + Assert.True(arc.IsValid && arc.TexelCount > 4); + Assert.True(arc.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase); + + // Also test tapered line verb directly + Span lineVerb = stackalloc byte[] { (byte)HbGpuPathVerb.Line }; + Span lineArgs = stackalloc float[] { -400f, 0f, 20f, 400f, 0f, 60f, 1f }; + CachedBlob lineBlob = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 1, 0), 1000u, lineVerb, lineArgs); + Assert.True(lineBlob.IsValid); + + // Drain uploads with zero allocations + byte[] staging = new byte[HbGpuBlobCache.ScratchShortsCapacity * sizeof(short)]; + int drainedBytes = 0; + Action cb = (_, len) => drainedBytes += (int)len; + int chunks = atlas.DrainChunks(staging, cb); + Assert.True(chunks >= 9); + Assert.True(drainedBytes > 0); + Assert.Equal(0, atlas.PendingChunkCount); + + // Verify dynamic ring wrap-around + for (int i = 0; i < 600; i++) + { + CachedBlob dyn = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -1.5f, 1.5f); + Assert.True(dyn.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase); + Assert.True(dyn.AtlasOffset + dyn.TexelCount <= HbGpuAtlasAllocator.TotalTexels); + atlas.ClearPending(); + } + } +} diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj index e2ea589..e833c3a 100644 --- a/tests/RustToDust.Tests/RustToDust.Tests.csproj +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -18,11 +18,13 @@ + + diff --git a/tools/build_release.ps1 b/tools/build_release.ps1 index b840c8d..72dd1d8 100644 --- a/tools/build_release.ps1 +++ b/tools/build_release.ps1 @@ -323,6 +323,12 @@ Write-Host "`n[3/5] Staging Release ymir_box3d.dll and runtime assets/..." Copy-Item -Path $ymirDllPath -Destination (Join-Path $StageDir "ymir_box3d.dll") -Force Copy-Item -Path $ymirDllPath -Destination (Join-Path $stagedDataDir "ymir_box3d.dll") -Force +$fontLicenseSrc = Join-Path $ClientDir "fonts\MONASPACE_LICENSE.txt" +if (-not (Test-Path $fontLicenseSrc)) { + throw "Required font license notice missing: '$fontLicenseSrc'." +} +Copy-Item -Path $fontLicenseSrc -Destination (Join-Path $StageDir "MONASPACE_LICENSE.txt") -Force + $stagedAssetsDir = Join-Path $StageDir "assets" $vCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "vehicles") -DestDir (Join-Path $stagedAssetsDir "vehicles") -IncludeExtensions @(".glb", ".cc", ".json") $gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir (Join-Path $stagedAssetsDir "gear") -IncludeExtensions @(".glb")