diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index 9cca7d3..f0d56aa 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -603,7 +603,7 @@ public partial class ArenaRenderer : Node3D vis.Visual.Root.Transform = new Transform3D(new Basis(q), pos); float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; - bool castShadows = !hasCam || c.Id == localId || distSq <= 55f * 55f; + bool castShadows = !hasCam || c.Id == localId || distSq <= 120f * 120f; bool useStaticLod = hasCam && c.Id != localId && !vis.Visual.HasAnyStrippedCell && (vis.Visual.IsStaticLod ? distSq > 64f * 64f : distSq > 68f * 68f); vis.Visual.SetLodState(useStaticLod, castShadows); @@ -706,7 +706,7 @@ public partial class ArenaRenderer : Node3D if (hasCam) { float distSq = specPos.DistanceSquaredTo(camPos); - castShadows = distSq <= 55f * 55f; + castShadows = distSq <= 120f * 120f; if (!vis.Visual.HasAnyStrippedCell) { useStaticLod = vis.Visual.IsStaticLod ? distSq > 50f * 50f : distSq > 55f * 55f; @@ -777,14 +777,14 @@ public partial class ArenaRenderer : Node3D } else if (s.Stance == SpectatorStance.Cleared) { - vis.HaloMat.AlbedoColor = new Color(1.0f, 0.22f, 0.18f, 0.9f); + vis.HaloMat.AlbedoColor = new Color(1.8f, 0.32f, 0.24f, 0.9f); vis.HaloMat.Emission = new Color(1.0f, 0.2f, 0.15f); vis.HaloMat.EmissionEnergyMultiplier = 2.0f; } else { float pulse = 1.6f + 1.2f * MathF.Sin(elapsedSeconds * 10f); - vis.HaloMat.AlbedoColor = new Color(1.0f, 0.1f, 0.1f, 0.95f); + vis.HaloMat.AlbedoColor = new Color(pulse, 0.14f, 0.12f, 0.95f); vis.HaloMat.Emission = new Color(1.0f, 0.08f, 0.08f); vis.HaloMat.EmissionEnergyMultiplier = pulse; } @@ -848,7 +848,7 @@ public partial class ArenaRenderer : Node3D var laserMat = new StandardMaterial3D { - AlbedoColor = new Color(1f, 0.15f, 0.15f, 0.85f), + AlbedoColor = new Color(2.2f, 0.24f, 0.20f, 0.85f), EmissionEnabled = true, Emission = new Color(1f, 0.12f, 0.1f), EmissionEnergyMultiplier = 2.2f, @@ -973,9 +973,11 @@ public partial class ArenaRenderer : Node3D if (discCount < _dropDiscMm.InstanceCount) { _dropDiscMm.SetInstanceTransform(discCount, new Transform3D(Basis.Identity, new Vector3(d.X, entry.BaseY + bob + 0.08f, d.Z))); + Color goldLin = TouristGold.SrgbToLinear(); + Color oliveLin = OlivePaint.SrgbToLinear(); Color dCol = entry.IsImperial - ? new Color(TouristGold.R * 2.2f, TouristGold.G * 2.2f, TouristGold.B * 2.2f, 0.82f) - : new Color(OlivePaint.R * 1.5f, OlivePaint.G * 1.5f, OlivePaint.B * 1.5f, 0.72f); + ? new Color(goldLin.R * 2.2f, goldLin.G * 2.2f, goldLin.B * 2.2f, 0.82f) + : new Color(oliveLin.R * 1.35f, oliveLin.G * 1.35f, oliveLin.B * 1.35f, 0.72f); _dropDiscMm.SetInstanceCustomData(discCount, dCol); discCount++; } @@ -993,7 +995,7 @@ public partial class ArenaRenderer : Node3D if (hasCam) { useFarLod = cv.IsStaticLod ? distSq > 50f * 50f : distSq > 55f * 55f; - castShadows = distSq <= 70f * 70f; + castShadows = distSq <= 120f * 120f; } cv.SetLodState(useFarLod, castShadows); cv.SubmitToPool(_partPool); @@ -1001,7 +1003,8 @@ public partial class ArenaRenderer : Node3D if (discCount < _dropDiscMm.InstanceCount) { _dropDiscMm.SetInstanceTransform(discCount, new Transform3D(Basis.FromScale(new Vector3(2.4f, 1f, 2.4f)), new Vector3(d.X, entry.BaseY + 0.06f, d.Z))); - _dropDiscMm.SetInstanceCustomData(discCount, new Color(CyanSalvage.R * 1.8f, CyanSalvage.G * 1.8f, CyanSalvage.B * 1.8f, 0.65f)); + Color cyanLin = CyanSalvage.SrgbToLinear(); + _dropDiscMm.SetInstanceCustomData(discCount, new Color(cyanLin.R * 1.8f, cyanLin.G * 1.8f, cyanLin.B * 1.8f, 0.65f)); discCount++; } } @@ -1049,7 +1052,7 @@ public partial class ArenaRenderer : Node3D float scorch = Math.Clamp(pod.Scorch * 0.7f, 0f, 0.55f); Color custom = new(scorch, heat, roleIdx, 1f); - bool wantsShadow = !hasCam || pos.DistanceSquaredTo(camPos) <= 65f * 65f; + bool wantsShadow = !hasCam || pos.DistanceSquaredTo(camPos) <= 160f * 160f; _partPool.Submit(podTpl.CoreMesh, in podXf, in custom, wantsShadow); for (int p = 0; p < 4; p++) diff --git a/client/AtmosphereLutBaker.cs b/client/AtmosphereLutBaker.cs new file mode 100644 index 0000000..1baddad --- /dev/null +++ b/client/AtmosphereLutBaker.cs @@ -0,0 +1,637 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Deterministic CPU precomputation of Bruneton / Hillaire planetary atmospheric scattering LUTs +/// (Transmittance 256x64, MultiScattering 32x32, SkyView 256x128 in +/// ), plus matching solar irradiance and horizon haze evaluation. +/// Zero Vulkan compute dependency so headless (Dummy) tests and Forward+ share identical data. +/// +public static class AtmosphereLutBaker +{ + public const int TransmittanceWidth = 256; + public const int TransmittanceHeight = 64; + public const int MultiScatteringSize = 32; + public const int SkyViewWidth = 256; + public const int SkyViewHeight = 128; + + public const float PlanetRadiusM = 6_360_000f; + public const float AtmosphereRadiusM = 6_460_000f; + public const float AtmosphereHeightM = AtmosphereRadiusM - PlanetRadiusM; + + private const float RayleighScaleHeightM = 8_000f; + private static readonly Vector3 RayleighScattering = new(5.802e-6f, 13.558e-6f, 33.100e-6f); + private const float MieSingleScatterAlbedo = 0.90f; + private static readonly Vector3 OzoneAbsorption = new(0.650e-6f, 1.881e-6f, 0.085e-6f); + private static readonly Vector3 GroundAlbedo = new(0.28f, 0.24f, 0.20f); + + public sealed record AtmospherePreset( + ArenaMapKind MapKind, + float AltitudeMeters, + float SunPitchDeg, + float SunYawDeg, + float MieScaleHeightMeters, + Vector3 MieScattering, + float MieG, + float SolarIrradiance, + float CalibratedSunEnergy, + float FogMaxLengthMeters, + float VolumetricFogDensity, + float VolumetricFogDetailSpread, + float VolumetricFogAnisotropy, + float VolumetricFogEmissionEnergy, + Vector3 ValleyVolumeSize, + Vector3 ValleyVolumePosition, + float ValleyVolumeDensity, + float ValleyVolumeHeightFalloff, + float ValleyVolumeEdgeFade, + float DepthFogBegin, + float DepthFogEnd, + float DepthFogCurve, + float DepthFogDensity, + float DepthFogAerialPerspective, + float DepthFogSunScatter, + float ShadowMaxDistance, + float AmbientLightEnergy, + float SunDiscIntensity, + float MieAureoleStrength); + + public sealed class BakedAtmosphere + { + public required AtmospherePreset Preset { get; init; } + public required Image TransmittanceImage { get; init; } + public required Image MultiScatteringImage { get; init; } + public required Image SkyViewImage { get; init; } + public required ImageTexture TransmittanceTexture { get; init; } + public required ImageTexture MultiScatteringTexture { get; init; } + public required ImageTexture SkyViewTexture { get; init; } + public required Vector3 SunDirection { get; init; } + public required Vector3 SunTransmittance { get; init; } + public required Color SunLightColor { get; init; } + public required float SunLightEnergy { get; init; } + public required Color HazeColor { get; init; } + public required float ZenithTransmittanceMean { get; init; } + public required float HorizonElevationRad { get; init; } + } + + private static readonly Dictionary Cache = new(); + + public static AtmospherePreset GetPreset(ArenaMapKind mapKind) => mapKind == ArenaMapKind.Sion + ? new AtmospherePreset( + MapKind: ArenaMapKind.Sion, + AltitudeMeters: 490f, + SunPitchDeg: -36f, + SunYawDeg: 28f, + MieScaleHeightMeters: 1_200f, + MieScattering: new Vector3(3.2e-6f, 3.2e-6f, 3.2e-6f), + MieG: 0.78f, + SolarIrradiance: 17.5f, + CalibratedSunEnergy: 1.28f, + FogMaxLengthMeters: 460f, + VolumetricFogDensity: 0.0008f, + VolumetricFogDetailSpread: 2.4f, + VolumetricFogAnisotropy: 0.62f, + VolumetricFogEmissionEnergy: 0.18f, + ValleyVolumeSize: new Vector3(3100f, 110f, 3100f), + ValleyVolumePosition: new Vector3(0f, 20f, 0f), + ValleyVolumeDensity: 0.0038f, + ValleyVolumeHeightFalloff: 1.65f, + ValleyVolumeEdgeFade: 0.12f, + DepthFogBegin: 400f, + DepthFogEnd: 2950f, + DepthFogCurve: 0.85f, + DepthFogDensity: 0.36f, + DepthFogAerialPerspective: 0.88f, + DepthFogSunScatter: 0.45f, + ShadowMaxDistance: 320f, + AmbientLightEnergy: 0.48f, + SunDiscIntensity: 8.5f, + MieAureoleStrength: 0.24f) + : new AtmospherePreset( + MapKind: ArenaMapKind.Desert, + AltitudeMeters: 200f, + SunPitchDeg: -22f, + SunYawDeg: 36f, + MieScaleHeightMeters: 1_800f, + MieScattering: new Vector3(10.5e-6f, 8.8e-6f, 6.6e-6f), + MieG: 0.74f, + SolarIrradiance: 16.0f, + CalibratedSunEnergy: 1.42f, + FogMaxLengthMeters: 380f, + VolumetricFogDensity: 0.0012f, + VolumetricFogDetailSpread: 2.2f, + VolumetricFogAnisotropy: 0.68f, + VolumetricFogEmissionEnergy: 0.22f, + ValleyVolumeSize: new Vector3(1600f, 56f, 1600f), + ValleyVolumePosition: new Vector3(0f, 2f, 0f), + ValleyVolumeDensity: 0.0052f, + ValleyVolumeHeightFalloff: 1.85f, + ValleyVolumeEdgeFade: 0.15f, + DepthFogBegin: 340f, + DepthFogEnd: 1400f, + DepthFogCurve: 0.90f, + DepthFogDensity: 0.46f, + DepthFogAerialPerspective: 0.82f, + DepthFogSunScatter: 0.55f, + ShadowMaxDistance: 280f, + AmbientLightEnergy: 0.55f, + SunDiscIntensity: 8.0f, + MieAureoleStrength: 0.30f); + + public static BakedAtmosphere GetOrBake(ArenaMapKind mapKind) + { + if (Cache.TryGetValue(mapKind, out var cached)) + { + return cached; + } + + var baked = BakePreset(GetPreset(mapKind)); + Cache[mapKind] = baked; + return baked; + } + + public static Vector3 ComputeSunDirection(float pitchDeg, float yawDeg) + { + Basis basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(pitchDeg), Mathf.DegToRad(yawDeg), 0f), EulerOrder.Yxz); + // DirectionalLight3D shines along -Z; direction toward the sun is +Z. + return basis.Z.Normalized(); + } + + private static BakedAtmosphere BakePreset(AtmospherePreset preset) + { + Vector3[] transmittanceBuf = BakeTransmittanceBuffer(preset); + Vector3[] multiScatterBuf = BakeMultiScatteringBuffer(preset, transmittanceBuf); + Vector3 sunDir = ComputeSunDirection(preset.SunPitchDeg, preset.SunYawDeg); + float r0 = PlanetRadiusM + preset.AltitudeMeters; + float horizonElev = -MathF.Acos(Math.Clamp(PlanetRadiusM / r0, -1f, 1f)); + Vector3[] skyViewBuf = BakeSkyViewBuffer(preset, transmittanceBuf, multiScatterBuf, sunDir, r0, horizonElev); + + Image transImg = CreateRgbahImage(TransmittanceWidth, TransmittanceHeight, transmittanceBuf); + Image msImg = CreateRgbahImage(MultiScatteringSize, MultiScatteringSize, multiScatterBuf); + Image skyImg = CreateRgbahImage(SkyViewWidth, SkyViewHeight, skyViewBuf); + + Vector3 sunT = SampleTransmittanceLut(transmittanceBuf, r0, sunDir.Y); + Vector3 zenithT = SampleTransmittanceLut(transmittanceBuf, r0, 1.0f); + float zenithMean = (zenithT.X + zenithT.Y + zenithT.Z) / 3f; + + Color sunColor = DeriveSunLightColor(sunT); + float sunEnergy = DeriveSunLightEnergy(preset, sunT); + Color hazeColor = DeriveHorizonHazeColor(skyViewBuf, preset.SolarIrradiance); + + return new BakedAtmosphere + { + Preset = preset, + TransmittanceImage = transImg, + MultiScatteringImage = msImg, + SkyViewImage = skyImg, + TransmittanceTexture = ImageTexture.CreateFromImage(transImg), + MultiScatteringTexture = ImageTexture.CreateFromImage(msImg), + SkyViewTexture = ImageTexture.CreateFromImage(skyImg), + SunDirection = sunDir, + SunTransmittance = sunT, + SunLightColor = sunColor, + SunLightEnergy = sunEnergy, + HazeColor = hazeColor, + ZenithTransmittanceMean = zenithMean, + HorizonElevationRad = horizonElev + }; + } + + private static Color DeriveSunLightColor(Vector3 sunT) + { + float maxC = MathF.Max(1e-4f, MathF.Max(sunT.X, MathF.Max(sunT.Y, sunT.Z))); + Vector3 norm = sunT / maxC; + return new Color( + Math.Clamp(norm.X, 0.1f, 1.0f), + Math.Clamp(norm.Y, 0.1f, 1.0f), + Math.Clamp(norm.Z, 0.1f, 1.0f), + 1.0f); + } + + private static float DeriveSunLightEnergy(AtmospherePreset preset, Vector3 sunT) + { + float luma = sunT.X * 0.2126f + sunT.Y * 0.7152f + sunT.Z * 0.0722f; + float refLuma = preset.MapKind == ArenaMapKind.Sion ? 0.86f : 0.68f; + float ratio = Math.Clamp(luma / refLuma, 0.92f, 1.08f); + return preset.CalibratedSunEnergy * ratio; + } + + private static Color DeriveHorizonHazeColor(Vector3[] skyViewBuf, float solarIrradiance) + { + // Integrate SkyView across all azimuths at +3 deg .. +6 deg above horizon (just above v = 0.5) + Vector3 accum = Vector3.Zero; + int samples = 0; + int yStart = SkyViewHeight / 2 + 6; + int yEnd = Math.Min(SkyViewHeight - 1, SkyViewHeight / 2 + 16); + for (int y = yStart; y <= yEnd; y++) + { + for (int x = 0; x < SkyViewWidth; x++) + { + accum += skyViewBuf[y * SkyViewWidth + x]; + samples++; + } + } + + Vector3 mean = samples > 0 ? accum / samples : new Vector3(0.55f, 0.62f, 0.72f); + // Normalize relative to sky exposure into a clean linear scattering albedo (0.45..0.92) + float scale = 1.15f / MathF.Max(0.25f, MathF.Max(mean.X, MathF.Max(mean.Y, mean.Z))); + Vector3 norm = mean * MathF.Min(scale, 2.2f); + return new Color( + Math.Clamp(norm.X, 0.25f, 0.94f), + Math.Clamp(norm.Y, 0.25f, 0.94f), + Math.Clamp(norm.Z, 0.22f, 0.94f), + 1.0f); + } + + private static Vector3[] BakeTransmittanceBuffer(AtmospherePreset preset) + { + var buf = new Vector3[TransmittanceWidth * TransmittanceHeight]; + float H = MathF.Sqrt(AtmosphereRadiusM * AtmosphereRadiusM - PlanetRadiusM * PlanetRadiusM); + const int steps = 36; + + for (int y = 0; y < TransmittanceHeight; y++) + { + float v = (y + 0.5f) / TransmittanceHeight; + float rho = H * v; + float r = MathF.Sqrt(rho * rho + PlanetRadiusM * PlanetRadiusM); + float dMin = AtmosphereRadiusM - r; + float dMax = rho + H; + + for (int x = 0; x < TransmittanceWidth; x++) + { + float u = (x + 0.5f) / TransmittanceWidth; + float d = dMin + u * (dMax - dMin); + float mu = d <= 1e-3f ? 1f : Math.Clamp((H * H - rho * rho - d * d) / (2f * r * d), -1f, 1f); + + float stepLen = d / steps; + Vector3 opticalDepth = Vector3.Zero; + for (int i = 0; i < steps; i++) + { + float t = (i + 0.5f) * stepLen; + float ri = MathF.Sqrt(MathF.Max(PlanetRadiusM * PlanetRadiusM, r * r + t * t + 2f * r * t * mu)); + float hi = MathF.Max(0f, ri - PlanetRadiusM); + opticalDepth += EvaluateExtinction(preset, hi) * stepLen; + } + + buf[y * TransmittanceWidth + x] = new Vector3( + MathF.Exp(-opticalDepth.X), + MathF.Exp(-opticalDepth.Y), + MathF.Exp(-opticalDepth.Z)); + } + } + + return buf; + } + + private static Vector3[] BakeMultiScatteringBuffer(AtmospherePreset preset, Vector3[] transBuf) + { + var buf = new Vector3[MultiScatteringSize * MultiScatteringSize]; + const int dirCount = 64; + const int marchSteps = 20; + const float goldenRatio = 1.618033988749895f; + + Vector3[] dirs = new Vector3[dirCount]; + for (int i = 0; i < dirCount; i++) + { + float theta = 2f * MathF.PI * i / goldenRatio; + float z = 1f - 2f * (i + 0.5f) / dirCount; + float rxy = MathF.Sqrt(MathF.Max(0f, 1f - z * z)); + dirs[i] = new Vector3(rxy * MathF.Cos(theta), z, rxy * MathF.Sin(theta)); + } + + for (int y = 0; y < MultiScatteringSize; y++) + { + float v = (y + 0.5f) / MultiScatteringSize; + float r = PlanetRadiusM + v * AtmosphereHeightM; + Vector3 pos = new(0f, r, 0f); + + for (int x = 0; x < MultiScatteringSize; x++) + { + float u = (x + 0.5f) / MultiScatteringSize; + float muS = u * 2f - 1f; + Vector3 sunDir = new(MathF.Sqrt(MathF.Max(0f, 1f - muS * muS)), muS, 0f); + + Vector3 l2Sum = Vector3.Zero; + Vector3 fmsSum = Vector3.Zero; + + for (int d = 0; d < dirCount; d++) + { + Vector3 rayDir = dirs[d]; + float maxDist = RaySphereExit(r, rayDir.Y, out bool hitGround); + if (maxDist <= 0f) + { + continue; + } + + float dt = maxDist / marchSteps; + Vector3 throughput = Vector3.One; + Vector3 l2 = Vector3.Zero; + Vector3 fms = Vector3.Zero; + + for (int s = 0; s < marchSteps; s++) + { + float t = (s + 0.5f) * dt; + Vector3 p = pos + rayDir * t; + float ri = p.Length(); + float hi = MathF.Max(0f, ri - PlanetRadiusM); + + SampleMedia(preset, hi, out Vector3 sigmaS, out Vector3 sigmaE); + Vector3 stepT = new( + MathF.Exp(-sigmaE.X * dt), + MathF.Exp(-sigmaE.Y * dt), + MathF.Exp(-sigmaE.Z * dt)); + + Vector3 up = p / MathF.Max(1f, ri); + float muSunAtP = up.Dot(sunDir); + if (!HitsPlanet(ri, muSunAtP)) + { + Vector3 tSun = SampleTransmittanceLut(transBuf, ri, muSunAtP); + // Isotropic phase 1 / (4*PI) cancels with 4*PI sphere integral when divided by dirCount + Vector3 scatterIn = sigmaS * tSun; + Vector3 sInt = SafeScatterIntegral(scatterIn, stepT, sigmaE, dt); + l2 += throughput * sInt; + } + + Vector3 fmsInt = SafeScatterIntegral(sigmaS, stepT, sigmaE, dt); + fms += throughput * fmsInt; + throughput *= stepT; + } + + if (hitGround) + { + Vector3 gp = pos + rayDir * maxDist; + Vector3 gUp = gp.Normalized(); + float nDotL = MathF.Max(0f, gUp.Dot(sunDir)); + if (nDotL > 0f) + { + Vector3 tGroundSun = SampleTransmittanceLut(transBuf, PlanetRadiusM, nDotL); + l2 += throughput * tGroundSun * GroundAlbedo * (nDotL / MathF.PI); + } + } + + l2Sum += l2; + fmsSum += fms; + } + + Vector3 l2Avg = l2Sum / dirCount; + Vector3 fmsAvg = fmsSum / dirCount; + Vector3 psi = new( + l2Avg.X / MathF.Max(0.02f, 1f - MathF.Min(0.98f, fmsAvg.X)), + l2Avg.Y / MathF.Max(0.02f, 1f - MathF.Min(0.98f, fmsAvg.Y)), + l2Avg.Z / MathF.Max(0.02f, 1f - MathF.Min(0.98f, fmsAvg.Z))); + buf[y * MultiScatteringSize + x] = psi; + } + } + + return buf; + } + + private static Vector3[] BakeSkyViewBuffer( + AtmospherePreset preset, + Vector3[] transBuf, + Vector3[] msBuf, + Vector3 sunDir, + float r0, + float horizonElev) + { + var buf = new Vector3[SkyViewWidth * SkyViewHeight]; + const int steps = 28; + Vector3 viewPos = new(0f, r0, 0f); + + Vector2 sunXz = new(sunDir.X, sunDir.Z); + if (sunXz.LengthSquared() < 1e-6f) + { + sunXz = new Vector2(0f, 1f); + } + else + { + sunXz = sunXz.Normalized(); + } + Vector2 sunPerp = new(sunXz.Y, -sunXz.X); + + for (int y = 0; y < SkyViewHeight; y++) + { + float v = (y + 0.5f) / SkyViewHeight; + float elev; + if (v >= 0.5f) + { + float l = 2f * v - 1f; + elev = horizonElev + l * l * (MathF.PI * 0.5f - horizonElev); + } + else + { + float l = 1f - 2f * v; + elev = horizonElev - l * l * (MathF.PI * 0.5f + horizonElev); + } + + float cosElev = MathF.Cos(elev); + float sinElev = MathF.Sin(elev); + + for (int x = 0; x < SkyViewWidth; x++) + { + float u = (x + 0.5f) / SkyViewWidth; + float dphi = u * 2f * MathF.PI; + Vector2 dirXz = sunXz * MathF.Cos(dphi) + sunPerp * MathF.Sin(dphi); + Vector3 rayDir = new Vector3(dirXz.X * cosElev, sinElev, dirXz.Y * cosElev).Normalized(); + + float maxDist = RaySphereExit(r0, rayDir.Y, out bool hitGround); + if (maxDist <= 0f) + { + buf[y * SkyViewWidth + x] = Vector3.Zero; + continue; + } + + float cosTheta = rayDir.Dot(sunDir); + float phaseR = RayleighPhase(cosTheta); + float phaseM = CornetteShanksPhase(cosTheta, preset.MieG); + const float phaseIso = 1f / (4f * MathF.PI); + + float dt = maxDist / steps; + Vector3 throughput = Vector3.One; + Vector3 luminance = Vector3.Zero; + + for (int s = 0; s < steps; s++) + { + float t = (s + 0.5f) * dt; + Vector3 p = viewPos + rayDir * t; + float ri = p.Length(); + float hi = MathF.Max(0f, ri - PlanetRadiusM); + + SampleRayleighMie(preset, hi, out Vector3 sigR, out Vector3 sigM, out Vector3 sigE); + Vector3 stepT = new( + MathF.Exp(-sigE.X * dt), + MathF.Exp(-sigE.Y * dt), + MathF.Exp(-sigE.Z * dt)); + + Vector3 up = p / MathF.Max(1f, ri); + float muSun = up.Dot(sunDir); + + Vector3 sunVis = HitsPlanet(ri, muSun) + ? Vector3.Zero + : SampleTransmittanceLut(transBuf, ri, muSun); + Vector3 multiScatter = SampleMultiScatteringLut(msBuf, ri, muSun); + + Vector3 sigS = sigR + sigM; + Vector3 phaseS = sigR * phaseR + sigM * phaseM; + Vector3 inScatter = sunVis * phaseS + multiScatter * sigS * phaseIso; + luminance += throughput * SafeScatterIntegral(inScatter, stepT, sigE, dt); + throughput *= stepT; + } + + if (hitGround) + { + Vector3 gp = viewPos + rayDir * maxDist; + Vector3 gUp = gp.Normalized(); + float nDotL = MathF.Max(0f, gUp.Dot(sunDir)); + if (nDotL > 0f) + { + Vector3 tSunG = SampleTransmittanceLut(transBuf, PlanetRadiusM, nDotL); + luminance += throughput * tSunG * GroundAlbedo * (nDotL / MathF.PI); + } + } + + buf[y * SkyViewWidth + x] = luminance * preset.SolarIrradiance; + } + } + + return buf; + } + + private static Vector3 EvaluateExtinction(AtmospherePreset preset, float altitudeM) + { + SampleMedia(preset, altitudeM, out _, out Vector3 sigmaE); + return sigmaE; + } + + private static void SampleMedia(AtmospherePreset preset, float altitudeM, out Vector3 sigmaS, out Vector3 sigmaE) + { + SampleRayleighMie(preset, altitudeM, out Vector3 sigR, out Vector3 sigM, out sigmaE); + sigmaS = sigR + sigM; + } + + private static void SampleRayleighMie( + AtmospherePreset preset, + float altitudeM, + out Vector3 sigR, + out Vector3 sigM, + out Vector3 sigE) + { + float h = MathF.Max(0f, altitudeM); + float dR = MathF.Exp(-h / RayleighScaleHeightM); + float dM = MathF.Exp(-h / preset.MieScaleHeightMeters); + float dO = MathF.Max(0f, 1f - MathF.Abs(h - 25_000f) / 15_000f); + + sigR = RayleighScattering * dR; + sigM = preset.MieScattering * dM; + Vector3 extM = sigM / MieSingleScatterAlbedo; + Vector3 absO = OzoneAbsorption * dO; + sigE = sigR + extM + absO; + } + + private static float RayleighPhase(float cosTheta) + { + return (3f / (16f * MathF.PI)) * (1f + cosTheta * cosTheta); + } + + private static float CornetteShanksPhase(float cosTheta, float g) + { + float g2 = g * g; + float num = 3f * (1f - g2) * (1f + cosTheta * cosTheta); + float denom = 8f * MathF.PI * (2f + g2) * MathF.Pow(MathF.Max(1e-4f, 1f + g2 - 2f * g * cosTheta), 1.5f); + return num / denom; + } + + private static Vector3 SafeScatterIntegral(Vector3 inScatter, Vector3 stepT, Vector3 sigmaE, float dt) + { + return new Vector3( + sigmaE.X > 1e-8f ? inScatter.X * (1f - stepT.X) / sigmaE.X : inScatter.X * dt, + sigmaE.Y > 1e-8f ? inScatter.Y * (1f - stepT.Y) / sigmaE.Y : inScatter.Y * dt, + sigmaE.Z > 1e-8f ? inScatter.Z * (1f - stepT.Z) / sigmaE.Z : inScatter.Z * dt); + } + + private static bool HitsPlanet(float r, float mu) + { + float disc = r * r * (mu * mu - 1f) + PlanetRadiusM * PlanetRadiusM; + return mu < 0f && disc >= 0f; + } + + private static float RaySphereExit(float r, float mu, out bool hitGround) + { + float discGround = r * r * (mu * mu - 1f) + PlanetRadiusM * PlanetRadiusM; + if (mu < 0f && discGround >= 0f) + { + hitGround = true; + return MathF.Max(0f, -r * mu - MathF.Sqrt(MathF.Max(0f, discGround))); + } + + hitGround = false; + float discAtmo = r * r * (mu * mu - 1f) + AtmosphereRadiusM * AtmosphereRadiusM; + return MathF.Max(0f, -r * mu + MathF.Sqrt(MathF.Max(0f, discAtmo))); + } + + private static Vector3 SampleTransmittanceLut(Vector3[] buf, float r, float mu) + { + float clampedR = Math.Clamp(r, PlanetRadiusM, AtmosphereRadiusM); + float H = MathF.Sqrt(AtmosphereRadiusM * AtmosphereRadiusM - PlanetRadiusM * PlanetRadiusM); + float rho = MathF.Sqrt(MathF.Max(0f, clampedR * clampedR - PlanetRadiusM * PlanetRadiusM)); + float v = rho / H; + + float disc = clampedR * clampedR * (mu * mu - 1f) + AtmosphereRadiusM * AtmosphereRadiusM; + float d = MathF.Max(0f, -clampedR * mu + MathF.Sqrt(MathF.Max(0f, disc))); + float dMin = AtmosphereRadiusM - clampedR; + float dMax = rho + H; + float u = (d - dMin) / MathF.Max(1e-4f, dMax - dMin); + + return SampleBilinear(buf, TransmittanceWidth, TransmittanceHeight, u, v); + } + + private static Vector3 SampleMultiScatteringLut(Vector3[] buf, float r, float muS) + { + float u = 0.5f + 0.5f * Math.Clamp(muS, -1f, 1f); + float v = Math.Clamp((r - PlanetRadiusM) / AtmosphereHeightM, 0f, 1f); + return SampleBilinear(buf, MultiScatteringSize, MultiScatteringSize, u, v); + } + + private static Vector3 SampleBilinear(Vector3[] buf, int w, int h, float u, float v) + { + float fx = Math.Clamp(u, 0f, 1f) * w - 0.5f; + float fy = Math.Clamp(v, 0f, 1f) * h - 0.5f; + int x0 = Math.Clamp((int)MathF.Floor(fx), 0, w - 1); + int y0 = Math.Clamp((int)MathF.Floor(fy), 0, h - 1); + int x1 = Math.Min(x0 + 1, w - 1); + int y1 = Math.Min(y0 + 1, h - 1); + float tx = Math.Clamp(fx - x0, 0f, 1f); + float ty = Math.Clamp(fy - y0, 0f, 1f); + + Vector3 c00 = buf[y0 * w + x0]; + Vector3 c10 = buf[y0 * w + x1]; + Vector3 c01 = buf[y1 * w + x0]; + Vector3 c11 = buf[y1 * w + x1]; + Vector3 c0 = c00.Lerp(c10, tx); + Vector3 c1 = c01.Lerp(c11, tx); + return c0.Lerp(c1, ty); + } + + private static Image CreateRgbahImage(int w, int h, Vector3[] pixels) + { + Image img = Image.CreateEmpty(w, h, false, Image.Format.Rgbah); + for (int y = 0; y < h; y++) + { + int row = y * w; + for (int x = 0; x < w; x++) + { + Vector3 c = pixels[row + x]; + img.SetPixel(x, y, new Color( + MathF.Max(0f, c.X), + MathF.Max(0f, c.Y), + MathF.Max(0f, c.Z), + 1.0f)); + } + } + return img; + } +} diff --git a/client/AtmosphereSystem.cs b/client/AtmosphereSystem.cs new file mode 100644 index 0000000..80b953d --- /dev/null +++ b/client/AtmosphereSystem.cs @@ -0,0 +1,237 @@ +using System; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Single authority for Forward+ Vulkan atmospheric skybox, Sky IBL, 4-split PSSM sun light, +/// two-tier volumetric valley fog + aerial perspective, SSR, SSAO, AgX tonemapping, +/// normalized additive HDR bloom, and post-tonemap film grain ( Layer 5). +/// +public partial class AtmosphereSystem : Node +{ + private WorldEnvironment _worldEnv = null!; + private Godot.Environment _env = null!; + private Sky _sky = null!; + private ShaderMaterial _skyMat = null!; + private DirectionalLight3D _sun = null!; + private FogVolume _valleyFog = null!; + private FogMaterial _valleyFogMat = null!; + private CanvasLayer _filmGrainLayer = null!; + private ColorRect _filmGrainRect = null!; + private ShaderMaterial _filmGrainMat = null!; + private bool _initialized; + + public WorldEnvironment WorldEnvironment => _worldEnv; + public Godot.Environment Environment => _env; + public DirectionalLight3D Sun => _sun; + public FogVolume ValleyFogVolume => _valleyFog; + public CanvasLayer FilmGrainLayer => _filmGrainLayer; + public AtmosphereLutBaker.BakedAtmosphere? CurrentBaked { get; private set; } + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + Shader skyShader = GD.Load("res://sky_atmosphere.gdshader") + ?? throw new InvalidOperationException("Failed to load res://sky_atmosphere.gdshader"); + _skyMat = new ShaderMaterial { Shader = skyShader }; + + _sky = new Sky + { + SkyMaterial = _skyMat, + ProcessMode = Sky.ProcessModeEnum.Quality, + RadianceSize = Sky.RadianceSizeEnum.Size128 + }; + + _env = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Sky, + Sky = _sky, + AmbientLightSource = Godot.Environment.AmbientSource.Sky, + AmbientLightEnergy = 0.48f, + + // 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, + + // Normalized additive bloom strictly above GlowHdrThreshold=1.0 (zero diffuse screen smear) + GlowEnabled = true, + GlowNormalized = true, + GlowBlendMode = Godot.Environment.GlowBlendModeEnum.Additive, + GlowHdrThreshold = 1.0f, + GlowHdrScale = 1.8f, + GlowHdrLuminanceCap = 12.0f, + GlowBloom = 0.0f, + GlowIntensity = 0.40f, + GlowStrength = 0.72f, + + // Screen-space reflections for visors, optics, bare steel, and Sion window_glass + SsrEnabled = true, + SsrMaxSteps = 32, + SsrFadeIn = 0.15f, + SsrFadeOut = 2.0f, + SsrDepthTolerance = 0.22f, + + // Screen-space ambient occlusion for mech foot & building contact grounding + SsaoEnabled = true, + SsaoRadius = 1.15f, + SsaoIntensity = 1.85f, + SsaoPower = 1.5f, + SsaoDetail = 0.45f, + SsaoHorizon = 0.06f, + SsaoSharpness = 0.98f, + SsaoLightAffect = 0.12f, + SsaoAOChannelAffect = 0.5f, + + // Tier 1: Froxel volumetric fog (0..380/460m) + VolumetricFogEnabled = true, + VolumetricFogTemporalReprojectionEnabled = true, + VolumetricFogTemporalReprojectionAmount = 0.88f, + VolumetricFogAmbientInject = 0.25f, + VolumetricFogSkyAffect = 0.10f, + + // Tier 2: Far aerial perspective (340/400m .. horizon peaks) + FogEnabled = true, + FogMode = Godot.Environment.FogModeEnum.Depth, + FogSkyAffect = 0.0f + }; + + _env.SetGlowLevel(0, 0.0f); + _env.SetGlowLevel(1, 0.25f); + _env.SetGlowLevel(2, 0.55f); + _env.SetGlowLevel(3, 0.85f); + _env.SetGlowLevel(4, 0.65f); + _env.SetGlowLevel(5, 0.35f); + _env.SetGlowLevel(6, 0.15f); + + _worldEnv = new WorldEnvironment + { + Name = "WorldEnv", + Environment = _env + }; + AddChild(_worldEnv); + + _sun = new DirectionalLight3D + { + Name = "SunLight", + ShadowEnabled = true, + DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel4Splits, + DirectionalShadowMaxDistance = 320f, + DirectionalShadowSplit1 = 0.08f, + DirectionalShadowSplit2 = 0.25f, + DirectionalShadowSplit3 = 0.56f, + DirectionalShadowBlendSplits = true, + DirectionalShadowFadeStart = 0.85f, + DirectionalShadowPancakeSize = 20f, + ShadowBlur = 1.25f, + ShadowBias = 0.06f, + ShadowNormalBias = 1.6f, + LightAngularDistance = 0.53f + }; + AddChild(_sun); + + _valleyFogMat = new FogMaterial + { + Density = 0.0038f, + HeightFalloff = 1.65f, + EdgeFade = 0.12f + }; + _valleyFog = new FogVolume + { + Name = "ValleyMistVolume", + Shape = RenderingServer.FogVolumeShape.Box, + Material = _valleyFogMat + }; + AddChild(_valleyFog); + + Shader grainShader = GD.Load("res://film_grain.gdshader") + ?? throw new InvalidOperationException("Failed to load res://film_grain.gdshader"); + _filmGrainMat = new ShaderMaterial { Shader = grainShader }; + _filmGrainMat.SetShaderParameter("grain_strength", 0.018f); + + _filmGrainLayer = new CanvasLayer + { + Name = "FilmGrainLayer", + Layer = 5 + }; + _filmGrainRect = new ColorRect + { + Name = "FilmGrainRect", + MouseFilter = Control.MouseFilterEnum.Ignore, + Material = _filmGrainMat, + Color = Colors.White, + AnchorLeft = 0f, + AnchorTop = 0f, + AnchorRight = 1f, + AnchorBottom = 1f, + OffsetLeft = 0f, + OffsetTop = 0f, + OffsetRight = 0f, + OffsetBottom = 0f + }; + _filmGrainLayer.AddChild(_filmGrainRect); + AddChild(_filmGrainLayer); + } + + public void ApplyMap(ArenaMapKind mapKind) + { + EnsureInitialized(); + + AtmosphereLutBaker.BakedAtmosphere baked = AtmosphereLutBaker.GetOrBake(mapKind); + AtmosphereLutBaker.AtmospherePreset preset = baked.Preset; + CurrentBaked = baked; + + _skyMat.SetShaderParameter("skyview_lut", baked.SkyViewTexture); + _skyMat.SetShaderParameter("sun_dir", baked.SunDirection); + _skyMat.SetShaderParameter("sun_transmittance", baked.SunTransmittance); + _skyMat.SetShaderParameter("horizon_elev", baked.HorizonElevationRad); + _skyMat.SetShaderParameter("sun_disc_intensity", preset.SunDiscIntensity); + _skyMat.SetShaderParameter("mie_aureole_strength", preset.MieAureoleStrength); + _skyMat.SetShaderParameter("sky_exposure", 1.0f); + + _sun.RotationDegrees = new Vector3(preset.SunPitchDeg, preset.SunYawDeg, 0f); + _sun.LightColor = baked.SunLightColor; + _sun.LightEnergy = baked.SunLightEnergy; + _sun.DirectionalShadowMaxDistance = preset.ShadowMaxDistance; + + _env.AmbientLightEnergy = preset.AmbientLightEnergy; + + Color haze = baked.HazeColor; + _env.VolumetricFogLength = preset.FogMaxLengthMeters; + _env.VolumetricFogDensity = preset.VolumetricFogDensity; + _env.VolumetricFogDetailSpread = preset.VolumetricFogDetailSpread; + _env.VolumetricFogAnisotropy = preset.VolumetricFogAnisotropy; + _env.VolumetricFogEmissionEnergy = preset.VolumetricFogEmissionEnergy; + _env.VolumetricFogAlbedo = haze; + _env.VolumetricFogEmission = new Color(haze.R * 0.45f, haze.G * 0.45f, haze.B * 0.45f, 1.0f); + + _valleyFog.Size = preset.ValleyVolumeSize; + _valleyFog.Position = preset.ValleyVolumePosition; + _valleyFogMat.Density = preset.ValleyVolumeDensity; + _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); + + _env.FogLightColor = haze; + _env.FogDepthBegin = preset.DepthFogBegin; + _env.FogDepthEnd = preset.DepthFogEnd; + _env.FogDepthCurve = preset.DepthFogCurve; + _env.FogDensity = preset.DepthFogDensity; + _env.FogAerialPerspective = preset.DepthFogAerialPerspective; + _env.FogSunScatter = preset.DepthFogSunScatter; + } +} diff --git a/client/Main.cs b/client/Main.cs index fcdbeb2..2beeea3 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -27,9 +27,7 @@ public partial class Main : Node3D private ArenaAudioSystem _audio = null!; private Camera3D _camera = null!; private Hud _hud = null!; - private DirectionalLight3D _sun = null!; - private ProceduralSkyMaterial _skyMat = null!; - private Godot.Environment _env = null!; + private AtmosphereSystem _atmosphere = null!; private IClientArenaSession? _session; private MatchState? _boundViewState; private bool _wasNetConnected; @@ -90,6 +88,7 @@ public partial class Main : Node3D public CameraJuiceState CameraJuice => _camJuice; public Camera3D Camera => _camera; public Hud Hud => _hud; + public AtmosphereSystem Atmosphere => _atmosphere; public ArenaMapKind MapKind => _mapKind; public ArenaMapKind? InitialMapKindOverride { get; set; } public bool InitialSkipDropOverride { get; set; } @@ -102,7 +101,10 @@ public partial class Main : Node3D public override void _Ready() { - SetupLightingAndSky(); + GetViewport().UseTaa = true; + _atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" }; + AddChild(_atmosphere); + _atmosphere.EnsureInitialized(); _terrain = new TerrainRenderer { Name = "Terrain" }; AddChild(_terrain); @@ -460,7 +462,7 @@ public partial class Main : Node3D } _camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f; - ApplyEnvironmentForMap(_mapKind); + _atmosphere.ApplyMap(_mapKind); if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null) { @@ -1485,81 +1487,4 @@ public partial class Main : Node3D { _session?.RequestEquipCargo(cargoIndex, hardpointId); } - - private void SetupLightingAndSky() - { - _sun = new DirectionalLight3D - { - Name = "DesertSun", - LightColor = new Color(1.0f, 0.92f, 0.78f), - LightEnergy = 1.45f, - ShadowEnabled = true, - DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits, - DirectionalShadowMaxDistance = 88f, - RotationDegrees = new Vector3(-48f, 32f, 0f) - }; - AddChild(_sun); - - _skyMat = new ProceduralSkyMaterial - { - SkyTopColor = new Color(0.24f, 0.34f, 0.44f), - SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f), - GroundBottomColor = new Color(0.32f, 0.22f, 0.14f), - GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f) - }; - _env = new Godot.Environment - { - BackgroundMode = Godot.Environment.BGMode.Sky, - Sky = new Sky { SkyMaterial = _skyMat }, - AmbientLightSource = Godot.Environment.AmbientSource.Sky, - AmbientLightEnergy = 0.55f, - FogEnabled = true, - FogMode = Godot.Environment.FogModeEnum.Depth, - FogLightColor = new Color(0.76f, 0.57f, 0.39f), - FogDensity = 0.72f, - FogDepthBegin = 380f, - FogDepthEnd = 1100f - }; - AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = _env }); - } - - private void ApplyEnvironmentForMap(ArenaMapKind mapKind) - { - if (mapKind == ArenaMapKind.Sion) - { - _sun.LightColor = new Color(1.0f, 0.95f, 0.87f); - _sun.LightEnergy = 1.25f; - _sun.DirectionalShadowMaxDistance = 120f; - _sun.RotationDegrees = new Vector3(-42f, 28f, 0f); - - _skyMat.SkyTopColor = new Color(0.18f, 0.36f, 0.62f); - _skyMat.SkyHorizonColor = new Color(0.68f, 0.79f, 0.89f); - _skyMat.GroundBottomColor = new Color(0.24f, 0.26f, 0.22f); - _skyMat.GroundHorizonColor = new Color(0.58f, 0.67f, 0.74f); - - _env.AmbientLightEnergy = 0.42f; - _env.FogLightColor = new Color(0.70f, 0.79f, 0.88f); - _env.FogDensity = 0.42f; - _env.FogDepthBegin = 850f; - _env.FogDepthEnd = 3000f; - } - else - { - _sun.LightColor = new Color(1.0f, 0.92f, 0.78f); - _sun.LightEnergy = 1.45f; - _sun.DirectionalShadowMaxDistance = 88f; - _sun.RotationDegrees = new Vector3(-48f, 32f, 0f); - - _skyMat.SkyTopColor = new Color(0.24f, 0.34f, 0.44f); - _skyMat.SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f); - _skyMat.GroundBottomColor = new Color(0.32f, 0.22f, 0.14f); - _skyMat.GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f); - - _env.AmbientLightEnergy = 0.55f; - _env.FogLightColor = new Color(0.76f, 0.57f, 0.39f); - _env.FogDensity = 0.72f; - _env.FogDepthBegin = 380f; - _env.FogDepthEnd = 1100f; - } - } } diff --git a/client/MultiMeshPartPool.cs b/client/MultiMeshPartPool.cs index 20578a6..5ed7689 100644 --- a/client/MultiMeshPartPool.cs +++ b/client/MultiMeshPartPool.cs @@ -110,10 +110,10 @@ public partial class MultiMeshPartPool : Node3D return; } - bool castShadow = wantsShadow && bucket.LocalRadius >= 1.15f; + bool castShadow = wantsShadow && bucket.LocalRadius >= 0.45f; if (castShadow && _hasFrustum) { - float maxShadowDist = 45f + scaledRadius; + float maxShadowDist = 120f + scaledRadius; if (worldCenter.DistanceSquaredTo(_camPos) > maxShadowDist * maxShadowDist) { castShadow = false; diff --git a/client/ParticlePool.cs b/client/ParticlePool.cs index bd59c0d..894a560 100644 --- a/client/ParticlePool.cs +++ b/client/ParticlePool.cs @@ -8,7 +8,7 @@ namespace RustToDust.Client; /// /// Single-draw-call GPU billboard particle pool ( backed by /// particle_billboard.gdshader) plus the strictly capped [2] -/// dynamic combat flash pool for OpenGL 3.3 (gl_compatibility). +/// dynamic combat flash pool for Forward+ Vulkan. /// public partial class ParticlePool : Node3D { @@ -135,6 +135,7 @@ public partial class ParticlePool : Node3D OmniAttenuation = 1.6f, OmniRange = 14f, LightEnergy = 0f, + LightVolumetricFogEnergy = 0f, Visible = false }; AddChild(light); @@ -144,7 +145,7 @@ public partial class ParticlePool : Node3D /// /// Pre-warms the pooled nodes on startup for 1 rendered frame - /// with near-zero energy so OpenGL 3.3 compiles lit shader variants before combat begins. + /// with near-zero energy so Forward+ compiles lit shader variants before combat begins. /// public void PrewarmFlashLights(Vector3 nearPos, Vector3 forwardHoriz) { diff --git a/client/SionMapRenderer.cs b/client/SionMapRenderer.cs index df8e491..135ae4e 100644 --- a/client/SionMapRenderer.cs +++ b/client/SionMapRenderer.cs @@ -16,7 +16,7 @@ public partial class SionMapRenderer : Node3D { public const float Lod1DistanceM = 520f; public const float CullDistanceM = 2200f; - public const float ShadowDistanceM = 220f; + public const float ShadowDistanceM = 360f; private const int ChunkGridVerts = 129; // 128 quads per 512m chunk (4m spacing) private sealed class BuildingTileEntry @@ -203,10 +203,10 @@ public partial class SionMapRenderer : Node3D float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045; float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0); - vec3 col = clamp(base_col + vec3(macro + grit * near_fade), vec3(0.0), vec3(1.0)); + vec3 col = clamp(base_col * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), vec3(0.0), vec3(1.0)); ALBEDO = col; ROUGHNESS = mix(0.88, 0.96, slope); - METALLIC = 0.03; + METALLIC = 0.02; } """ }; diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs index 7f3c8ec..769737e 100644 --- a/client/TerrainRenderer.cs +++ b/client/TerrainRenderer.cs @@ -28,13 +28,29 @@ public partial class TerrainRenderer : Node3D new(1f, 1f), new(0f, 1f) }; + private static readonly Vector2[] UnitQuadPoly = + { + new(-1f, -1f), + new(1f, -1f), + new(1f, 1f), + new(-1f, 1f) + }; + private static readonly Vector2[] ClearQuadPoly = + { + new(0f, 0f), + new(ViewportSize, 0f), + new(ViewportSize, ViewportSize), + new(0f, ViewportSize) + }; private sealed class TileNode { public SubViewport HeightViewport = null!; public Node2D HeightCanvas = null!; + public readonly List HeightQuads = new(64); public SubViewport AlbedoViewport = null!; public Node2D AlbedoCanvas = null!; + public readonly List AlbedoQuads = new(48); public MeshInstance3D SurfaceMesh = null!; public int BakedVersion = -1; } @@ -48,6 +64,10 @@ public partial class TerrainRenderer : Node3D private Shader _brushSubShader = null!; private Shader _brushAlbedoShader = null!; private Shader _surfaceShader = null!; + private ShaderMaterial _heightClearMat = null!; + private ShaderMaterial _albedoClearMat = null!; + private readonly Dictionary<(Shader Shader, int Kind, float HeightDelta), ShaderMaterial> _heightBrushMatCache = new(); + private readonly Dictionary<(int Kind, float R, float G, float B, float HeightDelta), ShaderMaterial> _albedoBrushMatCache = new(); private const int MaxDirtyRebakesPerSync = 2; private TerrainField? _lastTerrain; private int _rebakeCursor; @@ -81,9 +101,9 @@ public partial class TerrainRenderer : Node3D Code = """ shader_type canvas_item; render_mode blend_disabled; - uniform vec4 clear_color = vec4(0.0, 0.0, 0.0, 1.0); + uniform vec4 clear_vec = vec4(0.0, 0.0, 0.0, 1.0); void fragment() { - COLOR = clear_color; + COLOR = clear_vec; } """ }; @@ -92,6 +112,11 @@ public partial class TerrainRenderer : Node3D _brushAlbedoShader = GD.Load("res://terrain_brush_albedo.gdshader"); _surfaceShader = GD.Load("res://terrain_surface.gdshader"); + _heightClearMat = new ShaderMaterial { Shader = _clearShader }; + _heightClearMat.SetShaderParameter("clear_vec", new Vector4(HeightClearColor.R, HeightClearColor.G, HeightClearColor.B, HeightClearColor.A)); + _albedoClearMat = new ShaderMaterial { Shader = _clearShader }; + _albedoClearMat.SetShaderParameter("clear_vec", new Vector4(AlbedoClearColor.R, AlbedoClearColor.G, AlbedoClearColor.B, AlbedoClearColor.A)); + BuildTileGrid(); } @@ -184,7 +209,7 @@ public partial class TerrainRenderer : Node3D public void UpdateTileLod(Vector3 camPos) { const float nearRadiusSq = 240f * 240f; - const float shadowRadiusSq = 155f * 155f; + const float shadowRadiusSq = 220f * 220f; for (int tz = 0; tz < TerrainField.TileGridCount; tz++) { for (int tx = 0; tx < TerrainField.TileGridCount; tx++) @@ -281,10 +306,12 @@ public partial class TerrainRenderer : Node3D tile.HeightViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Height", useHdr: true, out var heightCanvas); tile.HeightCanvas = heightCanvas; + heightCanvas.AddChild(CreateClearQuad(_heightClearMat, _white1x1)); AddChild(tile.HeightViewport); tile.AlbedoViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Albedo", useHdr: false, out var albedoCanvas); tile.AlbedoCanvas = albedoCanvas; + albedoCanvas.AddChild(CreateClearQuad(_albedoClearMat, _white1x1)); AddChild(tile.AlbedoViewport); var mat = new ShaderMaterial { Shader = _surfaceShader }; @@ -350,18 +377,15 @@ public partial class TerrainRenderer : Node3D private void BakeTile(int tx, int tz, TileNode tile, TerrainField terrain) { long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; - ClearCanvasChildren(tile.HeightCanvas); - ClearCanvasChildren(tile.AlbedoCanvas); - - // Full-tile base clear quads (Polygon2D avoids GUI pixel snapping) - tile.HeightCanvas.AddChild(CreateClearQuad(HeightClearColor, _clearShader, _white1x1)); - tile.AlbedoCanvas.AddChild(CreateClearQuad(AlbedoClearColor, _clearShader, _white1x1)); float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; IReadOnlyList indices = terrain.GetTileBrushIndices(tx, tz); var brushes = terrain.Brushes; + int hCount = 0; + int aCount = 0; + for (int i = 0; i < indices.Count; i++) { var b = brushes[indices[i]]; @@ -380,33 +404,30 @@ public partial class TerrainRenderer : Node3D if (b.Kind == TerrainBrushKind.Crater) { // Crater uses subtractive pit + additive ejecta rim/scorch - tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta, _white1x1)); - tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta, _white1x1)); + SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); + SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); } else if (b.Kind == TerrainBrushKind.Track) { - tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta, _white1x1)); - tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta, _white1x1)); + SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); + SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); } else if (b.Kind == TerrainBrushKind.Road || b.HeightDelta < 0f) { - tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta, _white1x1)); + SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); } else { - tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta, _white1x1)); + SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); } // 2. Albedo brush pass - var albedoQuad = CreateOrientedQuad(px, py, rxPx, rzPx, b.RotationRad, _white1x1); - var albedoMat = new ShaderMaterial { Shader = _brushAlbedoShader }; - albedoMat.SetShaderParameter("brush_kind", kindInt); - albedoMat.SetShaderParameter("brush_albedo", new Vector3(b.AlbedoR, b.AlbedoG, b.AlbedoB)); - albedoMat.SetShaderParameter("height_delta", b.HeightDelta); - albedoQuad.Material = albedoMat; - tile.AlbedoCanvas.AddChild(albedoQuad); + SetQuad(tile.AlbedoCanvas, tile.AlbedoQuads, ref aCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateAlbedoBrushMat(kindInt, b.AlbedoR, b.AlbedoG, b.AlbedoB, b.HeightDelta), _white1x1); } + HideUnusedQuads(tile.HeightQuads, hCount); + HideUnusedQuads(tile.AlbedoQuads, aCount); + tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; if (t0 != 0) @@ -416,72 +437,94 @@ public partial class TerrainRenderer : Node3D } } - private static Polygon2D CreateClearQuad(Color color, Shader clearShader, ImageTexture whiteTex) + private ShaderMaterial GetOrCreateHeightBrushMat(Shader shader, int kindInt, float heightDelta) + { + var key = (shader, kindInt, heightDelta); + if (!_heightBrushMatCache.TryGetValue(key, out var mat)) + { + mat = new ShaderMaterial { Shader = shader }; + mat.SetShaderParameter("brush_kind", kindInt); + mat.SetShaderParameter("height_delta", heightDelta); + mat.SetShaderParameter("height_span", HeightSpan); + _heightBrushMatCache[key] = mat; + } + return mat; + } + + private ShaderMaterial GetOrCreateAlbedoBrushMat(int kindInt, float r, float g, float b, float heightDelta) + { + var key = (kindInt, r, g, b, heightDelta); + if (!_albedoBrushMatCache.TryGetValue(key, out var mat)) + { + mat = new ShaderMaterial { Shader = _brushAlbedoShader }; + mat.SetShaderParameter("brush_kind", kindInt); + mat.SetShaderParameter("brush_albedo", new Vector3(r, g, b)); + mat.SetShaderParameter("height_delta", heightDelta); + _albedoBrushMatCache[key] = mat; + } + return mat; + } + + private static Polygon2D CreateClearQuad(ShaderMaterial mat, ImageTexture whiteTex) { - var mat = new ShaderMaterial { Shader = clearShader }; - mat.SetShaderParameter("clear_color", color); return new Polygon2D { - Polygon = new[] - { - new Vector2(0f, 0f), - new Vector2(ViewportSize, 0f), - new Vector2(ViewportSize, ViewportSize), - new Vector2(0f, ViewportSize) - }, + Polygon = ClearQuadPoly, UV = BrushUv, Texture = whiteTex, Material = mat }; } - private static Polygon2D CreateOrientedQuad( + private static void SetQuad( + Node2D canvas, + List pool, + ref int index, float px, float py, float rxPx, float rzPx, float rotationRad, + ShaderMaterial mat, ImageTexture whiteTex) { - return new Polygon2D + Polygon2D quad; + if (index < pool.Count) { - Position = new Vector2(px, py), - Rotation = rotationRad, - Polygon = new[] + quad = pool[index]; + quad.Position = new Vector2(px, py); + quad.Rotation = rotationRad; + quad.Scale = new Vector2(rxPx, rzPx); + quad.Material = mat; + if (!quad.Visible) { - new Vector2(-rxPx, -rzPx), - new Vector2(rxPx, -rzPx), - new Vector2(rxPx, rzPx), - new Vector2(-rxPx, rzPx) - }, - UV = BrushUv, - Texture = whiteTex - }; - } - - private static Polygon2D CreateBrushQuad( - float px, float py, - float rxPx, float rzPx, - float rotationRad, - Shader shader, - int kindInt, - float heightDelta, - ImageTexture whiteTex) - { - var quad = CreateOrientedQuad(px, py, rxPx, rzPx, rotationRad, whiteTex); - var mat = new ShaderMaterial { Shader = shader }; - mat.SetShaderParameter("brush_kind", kindInt); - mat.SetShaderParameter("height_delta", heightDelta); - mat.SetShaderParameter("height_span", HeightSpan); - quad.Material = mat; - return quad; - } - - private static void ClearCanvasChildren(Node2D canvas) - { - for (int i = canvas.GetChildCount() - 1; i >= 0; i--) + quad.Visible = true; + } + } + else { - var child = canvas.GetChild(i); - canvas.RemoveChild(child); - child.QueueFree(); + quad = new Polygon2D + { + Position = new Vector2(px, py), + Rotation = rotationRad, + Scale = new Vector2(rxPx, rzPx), + Polygon = UnitQuadPoly, + UV = BrushUv, + Texture = whiteTex, + Material = mat + }; + pool.Add(quad); + canvas.AddChild(quad); + } + index++; + } + + private static void HideUnusedQuads(List pool, int usedCount) + { + for (int i = usedCount; i < pool.Count; i++) + { + if (pool[i].Visible) + { + pool[i].Visible = false; + } } } } diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs index 64741a2..ea15d10 100644 --- a/client/VehicleAssetCache.cs +++ b/client/VehicleAssetCache.cs @@ -1515,6 +1515,15 @@ public sealed class VehicleAssetCache : IDisposable return; } + if (mName.Contains("glass") || mName.Contains("visor") || mName.Contains("canopy") || mName.Contains("lens")) + { + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 8; + roughness = Math.Clamp(sm.Roughness, 0.08f, 0.16f); + return; + } + Color lin = sm.AlbedoColor.SrgbToLinear(); linearColor = new Vector3(lin.R, lin.G, lin.B); band = sm.Metallic >= 0.70f ? 2 : (sm.Metallic >= 0.35f ? 1 : 0); diff --git a/client/decal_pom.gdshader b/client/decal_pom.gdshader index b3e334d..0239a1f 100644 --- a/client/decal_pom.gdshader +++ b/client/decal_pom.gdshader @@ -1,7 +1,7 @@ shader_type spatial; render_mode blend_mix, depth_draw_never, cull_back; -// OpenGL 3.3 (gl_compatibility) Parallax Occlusion Mapping (POM) decal shader for MultiMeshInstance3D. +// Forward+ Vulkan Parallax Occlusion Mapping (POM) decal shader for MultiMeshInstance3D. // Renders hundreds of hard-surface vents, hatches, stencils, and live combat hits in 1 draw call. // // INSTANCE_CUSTOM layout: diff --git a/client/film_grain.gdshader b/client/film_grain.gdshader new file mode 100644 index 0000000..3562d44 --- /dev/null +++ b/client/film_grain.gdshader @@ -0,0 +1,25 @@ +shader_type canvas_item; +render_mode blend_mix; + +// Forward+ Vulkan post-tonemap temporal film grain (CanvasLayer Layer=5 < Hud Layer=10). +// Runs strictly after AgX tonemapping & normalized additive bloom so HUD text stays razor-sharp. + +uniform sampler2D screen_tex : hint_screen_texture, filter_nearest; +uniform float grain_strength : hint_range(0.0, 0.1) = 0.018; + +float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) { + vec2 p = frag_xy + vec2(frame_idx * 17.0, frame_idx * 31.0); + return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); +} + +void fragment() { + vec4 src = texture(screen_tex, SCREEN_UV); + 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 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)); + + COLOR = vec4(grained, src.a); +} diff --git a/client/hud_vignette.gdshader b/client/hud_vignette.gdshader index fbfaede..a22a771 100644 --- a/client/hud_vignette.gdshader +++ b/client/hud_vignette.gdshader @@ -1,7 +1,7 @@ shader_type canvas_item; render_mode blend_mix; -// OpenGL 3.3 (gl_compatibility) fullscreen combat vignette for damage impact, low core HP, and thermal overheat. +// Forward+ Vulkan fullscreen combat vignette for damage impact, low core HP, and thermal overheat. uniform float damage_pulse : hint_range(0.0, 1.0) = 0.0; uniform float low_core_ratio : hint_range(0.0, 1.0) = 0.0; uniform float overheat_pulse : hint_range(0.0, 1.0) = 0.0; diff --git a/client/inventory_grid.gdshader b/client/inventory_grid.gdshader index fac4847..fce4ae7 100644 --- a/client/inventory_grid.gdshader +++ b/client/inventory_grid.gdshader @@ -1,7 +1,7 @@ shader_type canvas_item; render_mode blend_premul_alpha; -// Port of Aetheria's UI/Inventory Grid shader to Godot 4 gl_compatibility (OpenGL 3.3). +// Port of Aetheria's UI/Inventory Grid shader to Godot 4 Forward+ Vulkan. // Evaluates analytical corner-folded texel boxes for hull/hardpoint silhouettes, L-brackets, // hairline rules, direct bilinear heat glow, hit-pulse flash, and 45-degree fracture hatching. // diff --git a/client/mech_paint.gdshader b/client/mech_paint.gdshader index 646f2c3..4c7089f 100644 --- a/client/mech_paint.gdshader +++ b/client/mech_paint.gdshader @@ -1,7 +1,7 @@ shader_type spatial; render_mode cull_back, depth_draw_opaque; -// Real-time GLSL 330 (gl_compatibility) port of Brokkr's 6-layer MechPaint. +// Real-time Forward+ Vulkan port of Brokkr's 6-layer MechPaint. // Samples 3D procedural noise in rest-pose object space (v_local_pos, v_local_nrm) // so weathering never swims during skeletal/joint animation or chassis motion. // @@ -177,6 +177,7 @@ void fragment() { float mat_metal = metallic; float mat_wear = wear; float mat_mud = mud; + float mat_grime = grime; float mat_static_emit = 0.0; if (use_vertex_material) { int band = int(floor((v_mat_data.w + 0.5) * 0.5)); @@ -200,6 +201,11 @@ void fragment() { mat_mud = 0.0; } else if (band == 6) { mat_metal = 0.26; + } else if (band == 8) { + mat_metal = 0.35; + mat_wear = 0.0; + mat_mud = 0.0; + mat_grime = 0.15; } else { mat_metal = 0.65; } @@ -243,8 +249,8 @@ void fragment() { col *= clamp(1.0 + shade * mottle, 0.55, 1.35); // Layer 2: Cavity grime darkening + roughness boost from (1 - AO) - float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(mid_n, 0.30, 0.65, 0.45, 1.0) * grime, 0.0, 1.0); - float film = clamp(map_range(n_macro * 0.5 + n_mid * 0.5, 0.54, 0.72, 0.0, 1.0) * 0.30 * grime, 0.0, 1.0); + float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(mid_n, 0.30, 0.65, 0.45, 1.0) * mat_grime, 0.0, 1.0); + float film = clamp(map_range(n_macro * 0.5 + n_mid * 0.5, 0.54, 0.72, 0.0, 1.0) * 0.30 * mat_grime, 0.0, 1.0); float grime_amt = max(cavity, film); col = mix(col, grime_color.rgb, min(grime_amt, 0.85)); @@ -290,11 +296,11 @@ void fragment() { float out_metallic = mix(mat_metal, chip_metallic, chip_metal_mask); out_metallic *= (1.0 - mud_amt) * (1.0 - grime_amt * 0.70); - float out_rough = mat_rough + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(grime, 0.0, 1.0); + float out_rough = mat_rough + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(mat_grime, 0.0, 1.0); out_rough = mix(out_rough, chip_roughness, chip_metal_mask); out_rough -= wet_amt * 0.18; out_rough += mud_amt * 0.18; - out_rough = clamp(out_rough, 0.12, 0.98); + out_rough = clamp(out_rough, 0.08, 0.98); // Live combat channel 1: scorch (char/soot darkening + matte roughness) float soot_pat = mix(0.65, 1.0, mid_n); diff --git a/client/particle_billboard.gdshader b/client/particle_billboard.gdshader index d494803..eb44cea 100644 --- a/client/particle_billboard.gdshader +++ b/client/particle_billboard.gdshader @@ -1,9 +1,9 @@ shader_type spatial; render_mode unshaded, cull_disabled, blend_mix, depth_draw_never; -// OpenGL 3.3 (gl_compatibility) single-draw-call billboard particle shader for MultiMeshInstance3D. +// Forward+ Vulkan single-draw-call billboard particle shader for MultiMeshInstance3D. // Zero texture binds; packs shape mode, normalized age, HDR emissive, and 2D rotation into INSTANCE_CUSTOM, -// and RGB tint + alpha fade into COLOR. +// and sRGB RGB tint (converted to linear in vertex()) + alpha fade into COLOR. // // INSTANCE_CUSTOM layout: // x = mode (0.0 = soft wisp dust/smoke, 1.0 = 4-point HDR muzzle starburst, 2.0 = spark/ember streak, 3.0 = steam/fireball puff) @@ -24,8 +24,14 @@ float soft_noise(vec2 p) { return 0.5 + 0.25 * sin(p.x * 2.7 + p.y * 1.9) + 0.25 * cos(p.y * 2.3 - p.x * 1.7); } +vec3 srgb_to_linear(vec3 c) { + vec3 lo = c / 12.92; + vec3 hi = pow((c + vec3(0.055)) / 1.055, vec3(2.4)); + return mix(lo, hi, step(vec3(0.04045), c)); +} + void vertex() { - v_color = COLOR; + v_color = vec4(srgb_to_linear(max(COLOR.rgb, vec3(0.0))), COLOR.a); v_custom = INSTANCE_CUSTOM; float rot = INSTANCE_CUSTOM.w; diff --git a/client/project.godot b/client/project.godot index d214e57..e4d7449 100644 --- a/client/project.godot +++ b/client/project.godot @@ -29,5 +29,12 @@ common/physics_interpolation=true [rendering] -renderer/rendering_method="gl_compatibility" -renderer/rendering_method.mobile="gl_compatibility" +renderer/rendering_method="forward_plus" +renderer/rendering_method.mobile="forward_plus" +anti_aliasing/quality/use_taa=true +anti_aliasing/screen_space_roughness_limiter/enabled=true +lights_and_shadows/directional_shadow/size=2048 +lights_and_shadows/directional_shadow/soft_shadow_filter_quality=2 +environment/volumetric_fog/volume_size=64 +environment/volumetric_fog/volume_depth=96 +environment/screen_space_reflection/half_size=true diff --git a/client/sky_atmosphere.gdshader b/client/sky_atmosphere.gdshader new file mode 100644 index 0000000..c56dcf9 --- /dev/null +++ b/client/sky_atmosphere.gdshader @@ -0,0 +1,58 @@ +shader_type sky; + +// Forward+ Vulkan precomputed Bruneton/Hillaire atmospheric scattering skybox. +// Single bilinear LUT lookup per fragment + analytic limb-darkened solar disc & Mie aureole. + +uniform sampler2D skyview_lut : filter_linear, repeat_enable; +uniform vec3 sun_dir = vec3(0.41, 0.59, 0.69); +uniform vec3 sun_transmittance = vec3(0.88, 0.85, 0.78); +uniform float horizon_elev = -0.0124; +uniform float sun_disc_intensity = 8.5; +uniform float mie_aureole_strength = 0.24; +uniform float sky_exposure = 1.0; + +void sky() { + vec3 dir = normalize(EYEDIR); + vec3 sdir = normalize(sun_dir); + + vec2 dir_xz = dir.xz; + vec2 sun_xz = sdir.xz; + float dir_len = length(dir_xz); + float sun_len = length(sun_xz); + float u = 0.0; + if (dir_len > 1e-5 && sun_len > 1e-5) { + vec2 d2 = dir_xz / dir_len; + vec2 s2 = sun_xz / sun_len; + float c = clamp(dot(d2, s2), -1.0, 1.0); + float s = d2.x * s2.y - d2.y * s2.x; + float dphi = atan(s, c); + if (dphi < 0.0) { + dphi += 2.0 * PI; + } + u = dphi / (2.0 * PI); + } + + float alpha = asin(clamp(dir.y, -1.0, 1.0)); + float v; + if (alpha >= horizon_elev) { + float l = sqrt(clamp((alpha - horizon_elev) / max(0.0001, PI * 0.5 - horizon_elev), 0.0, 1.0)); + v = 0.5 + 0.5 * l; + } else { + float l = sqrt(clamp((horizon_elev - alpha) / max(0.0001, PI * 0.5 + horizon_elev), 0.0, 1.0)); + v = 0.5 - 0.5 * l; + } + v = clamp(v, 0.5 / 128.0, 127.5 / 128.0); + + vec3 sky_rad = textureLod(skyview_lut, vec2(u, v), 0.0).rgb * sky_exposure; + + if (!AT_CUBEMAP_PASS && LIGHT0_ENABLED) { + float sun_dot = dot(dir, sdir); + float disc = smoothstep(0.99985, 0.99997, sun_dot); + float limb = smoothstep(0.99985, 0.99999, sun_dot) * 0.35 + 0.65; + float aureole = pow(max(sun_dot, 0.0), 64.0) * mie_aureole_strength; + float horizon_fade = smoothstep(-0.02, 0.04, dir.y); + sky_rad += sun_transmittance * (disc * limb * sun_disc_intensity + aureole) * horizon_fade; + } + + COLOR = sky_rad; +} diff --git a/client/terrain_brush.gdshader b/client/terrain_brush.gdshader index eb66b71..ccbe36f 100644 --- a/client/terrain_brush.gdshader +++ b/client/terrain_brush.gdshader @@ -3,7 +3,7 @@ render_mode blend_add; // Encodes positive height deltas into R ([-18m, +52m] => span 70m), // roughness delta into G, scorch/track wear into B, and ALWAYS A = 1.0 -// (required for gl_compatibility TransparentBg=false blend equations). +// (required for TransparentBg=false UseHdr2D=true blend equations in forward_plus). uniform int brush_kind = 0; uniform float height_delta = 0.0; uniform float height_span = 70.0; diff --git a/client/terrain_surface.gdshader b/client/terrain_surface.gdshader index eaf2609..706c6db 100644 --- a/client/terrain_surface.gdshader +++ b/client/terrain_surface.gdshader @@ -2,7 +2,7 @@ shader_type spatial; render_mode cull_back, depth_draw_opaque; uniform sampler2D height_tex : filter_linear, repeat_disable; -uniform sampler2D albedo_tex : filter_linear, repeat_disable; +uniform sampler2D albedo_tex : source_color, filter_linear, repeat_disable; uniform float height_min = -18.0; uniform float height_max = 52.0; uniform float tile_size = 192.0; @@ -45,12 +45,12 @@ void fragment() { vec4 mat = texture(height_tex, uv_baked); vec3 alb = texture(albedo_tex, uv_baked).rgb; - // Subtle desert sand grain so dunes read crisply under sunlight + // Subtle desert sand grain so dunes read crisply under sunlight (multiplicative in linear HDR) float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; float scorch = clamp(mat.b, 0.0, 1.0); - alb = clamp(alb + vec3(grain), 0.0, 1.0) * (1.0 - 0.30 * scorch); + alb = clamp(alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch); ALBEDO = alb; - ROUGHNESS = clamp(mat.g, 0.25, 1.0); - METALLIC = 0.05; + ROUGHNESS = clamp(mat.g, 0.35, 1.0); + METALLIC = 0.02; } diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index bf6bd97..28b9d9a 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -10,7 +10,7 @@ using RustToDust.Ymir; namespace RustToDust.Client.Tests; /// -/// Headless Godot smoke test: instantiates Main, drives 60 frames with throttle + fire + crater stamp, +/// Headless & Vulkan Forward+ Godot smoke test: instantiates Main, drives 60 frames with throttle + fire + crater stamp, /// verifies terrain tile baking and Ymir physics integration, and exits with code 0 on pass. /// godot --headless --path client res://tests/Smoke.tscn /// @@ -277,6 +277,7 @@ public partial class Smoke : Node await VerifyMaxLoadPaladinGarageAsync(); await VerifySionMapAsync(); await VerifyOrbitalDropSequenceAsync(); + VerifyForwardPlusAtmosphere(); } private async Task VerifyHudAndShadersAsync(bool isHeadless) @@ -388,7 +389,7 @@ public partial class Smoke : Node return; } - // GPU verification on OpenGL 3.3: render isolated InventoryGridControl (ambient vs live bilinear heat) & panel_chrome.gdshader + // GPU verification on Forward+ Vulkan: render isolated InventoryGridControl (ambient vs live bilinear heat) & panel_chrome.gdshader var gridVp = new SubViewport { Size = new Vector2I(240, 240), @@ -2006,6 +2007,84 @@ public partial class Smoke : Node GD.Print($"SMOKE INFO: Cut 6b OrbitalDrop verified (touchdownTick={touchdownTick}, debris={debrisAtTouchdown}, postDisp={postDisp:F2}m, bucketsDelta={bucketsDuringDrop - bucketsBefore}, matDups={VehicleVisualInstance.PerfMaterialDupCount})"); } + private void VerifyForwardPlusAtmosphere() + { + string method = RenderingServer.GetCurrentRenderingMethod(); + Check(method == "forward_plus", $"Expected RenderingMethod 'forward_plus', got '{method}'"); + + var sionBaked = AtmosphereLutBaker.GetOrBake(ArenaMapKind.Sion); + var desertBaked = AtmosphereLutBaker.GetOrBake(ArenaMapKind.Desert); + CheckFinitePositiveLut("Sion.Transmittance", sionBaked.TransmittanceImage, AtmosphereLutBaker.TransmittanceWidth, AtmosphereLutBaker.TransmittanceHeight); + CheckFinitePositiveLut("Sion.MultiScattering", sionBaked.MultiScatteringImage, AtmosphereLutBaker.MultiScatteringSize, AtmosphereLutBaker.MultiScatteringSize); + CheckFinitePositiveLut("Sion.SkyView", sionBaked.SkyViewImage, AtmosphereLutBaker.SkyViewWidth, AtmosphereLutBaker.SkyViewHeight); + CheckFinitePositiveLut("Desert.Transmittance", desertBaked.TransmittanceImage, AtmosphereLutBaker.TransmittanceWidth, AtmosphereLutBaker.TransmittanceHeight); + CheckFinitePositiveLut("Desert.MultiScattering", desertBaked.MultiScatteringImage, AtmosphereLutBaker.MultiScatteringSize, AtmosphereLutBaker.MultiScatteringSize); + CheckFinitePositiveLut("Desert.SkyView", desertBaked.SkyViewImage, AtmosphereLutBaker.SkyViewWidth, AtmosphereLutBaker.SkyViewHeight); + + Check(sionBaked.ZenithTransmittanceMean > desertBaked.ZenithTransmittanceMean, + $"Expected Sion zenith transmittance ({sionBaked.ZenithTransmittanceMean:F4}) > Desert ({desertBaked.ZenithTransmittanceMean:F4})"); + + var atmo = _main.Atmosphere; + var env = atmo.Environment; + Check(env.TonemapMode == Godot.Environment.ToneMapper.Agx, $"Expected ToneMapper.Agx, got {env.TonemapMode}"); + Check(env.GlowEnabled && env.GlowNormalized, $"Expected GlowEnabled && GlowNormalized, got enabled={env.GlowEnabled} norm={env.GlowNormalized}"); + Check(env.GlowBlendMode == Godot.Environment.GlowBlendModeEnum.Additive, $"Expected GlowBlendModeEnum.Additive, got {env.GlowBlendMode}"); + Check(env.SsrEnabled, "Expected SsrEnabled == true"); + Check(env.SsaoEnabled, "Expected SsaoEnabled == true"); + Check(env.VolumetricFogEnabled && env.VolumetricFogTemporalReprojectionEnabled, + $"Expected VolumetricFogEnabled && TemporalReprojection, got vf={env.VolumetricFogEnabled} tr={env.VolumetricFogTemporalReprojectionEnabled}"); + Check(env.FogEnabled && env.FogAerialPerspective > 0.7f, + $"Expected FogEnabled && FogAerialPerspective > 0.7f, got fog={env.FogEnabled} ap={env.FogAerialPerspective:F2}"); + + var sun = atmo.Sun; + Check(sun.DirectionalShadowMode == DirectionalLight3D.ShadowMode.Parallel4Splits && sun.DirectionalShadowMaxDistance >= 280f, + $"Expected Parallel4Splits & maxDist >= 280m, got {sun.DirectionalShadowMode} maxDist={sun.DirectionalShadowMaxDistance:F1}"); + + Check(GetViewport().UseTaa, "Expected GetViewport().UseTaa == true"); + + int checkedLights = 0; + foreach (Node ch in _main.Arena.Particles.GetChildren()) + { + if (ch is OmniLight3D omni) + { + checkedLights++; + Check(omni.LightVolumetricFogEnergy == 0f, + $"Expected {omni.Name}.LightVolumetricFogEnergy == 0f to prevent temporal fog ghosting, got {omni.LightVolumetricFogEnergy}"); + } + } + Check(checkedLights == ParticlePool.MaxFlashLights, $"Expected {ParticlePool.MaxFlashLights} ParticlePool OmniLight3D nodes, found {checkedLights}"); + + Check(atmo.FilmGrainLayer.Layer == 5 && atmo.FilmGrainLayer.Layer < _main.Hud.Layer, + $"Expected FilmGrainLayer.Layer == 5 < Hud.Layer ({_main.Hud.Layer}), got {atmo.FilmGrainLayer.Layer}"); + + GD.Print($"SMOKE INFO: Cut 8 Forward+ verified (method={method}, sionZenithT={sionBaked.ZenithTransmittanceMean:F4}, desertZenithT={desertBaked.ZenithTransmittanceMean:F4}, grainLayer={atmo.FilmGrainLayer.Layer})"); + } + + private void CheckFinitePositiveLut(string label, Image img, int expectedW, int expectedH) + { + Check(img.GetFormat() == Image.Format.Rgbah, $"Expected {label} format Rgbah, got {img.GetFormat()}"); + Check(img.GetWidth() == expectedW && img.GetHeight() == expectedH, + $"Expected {label} size {expectedW}x{expectedH}, got {img.GetWidth()}x{img.GetHeight()}"); + bool allValid = true; + float maxSum = 0f; + int w = img.GetWidth(); + int h = img.GetHeight(); + for (int y = 0; y < h; y += Math.Max(1, h / 8)) + { + for (int x = 0; x < w; x += Math.Max(1, w / 8)) + { + Color c = img.GetPixel(x, y); + if (!float.IsFinite(c.R) || !float.IsFinite(c.G) || !float.IsFinite(c.B) || + c.R < 0f || c.G < 0f || c.B < 0f) + { + allValid = false; + } + maxSum = MathF.Max(maxSum, c.R + c.G + c.B); + } + } + Check(allValid && maxSum > 0f, $"Expected finite positive values in {label} LUT (valid={allValid}, maxSum={maxSum:F4})"); + } + private static int CountPremulViolations(Image img, float tolerance) { int count = 0; diff --git a/client/tests/VisualProbe.cs b/client/tests/VisualProbe.cs index 05cb784..b12c146 100644 --- a/client/tests/VisualProbe.cs +++ b/client/tests/VisualProbe.cs @@ -3,11 +3,12 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Godot; +using RustToDust.Core; namespace RustToDust.Client.Tests; /// -/// Live OpenGL 3.3 (gl_compatibility) visual verification probe for: +/// Live Forward+ (Vulkan) visual verification probe for: /// - Baked COLOR_0 vertex weathering (AO, edge curvature, per-island hash, rest height) /// - Brokkr 6-layer MechPaint spatial shader (mech_paint.gdshader) + INSTANCE_CUSTOM scorch/heat /// - 4x4 POM MultiMesh decal atlas + decal_pom.gdshader in 1 draw call @@ -207,7 +208,7 @@ public partial class VisualProbe : Node3D cam.GlobalPosition = new Vector3(2.8f, 4.3f, 13.4f); cam.LookAt(new Vector3(0.0f, 4.4f, 0.2f), Vector3.Up); - // Wait several rendered frames so OpenGL 3.3 compiles all shaders and finishes drawing + // Wait several rendered frames so Vulkan Forward+ compiles all shaders and finishes drawing for (int f = 0; f < 6; f++) { await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); @@ -249,43 +250,11 @@ public partial class VisualProbe : Node3D private void SetupEnvironment() { - var sun = new DirectionalLight3D - { - Name = "DesertSun", - LightColor = new Color(1.0f, 0.93f, 0.82f), - LightEnergy = 1.85f, - ShadowEnabled = true, - DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits, - RotationDegrees = new Vector3(-38f, 36f, 0f) - }; - AddChild(sun); - - // Cool oblique fill light so POM recesses & metal rims catch clear specular highlights - var fill = new DirectionalLight3D - { - Name = "SkyFill", - LightColor = new Color(0.68f, 0.80f, 0.98f), - LightEnergy = 0.55f, - ShadowEnabled = false, - RotationDegrees = new Vector3(-25f, -125f, 0f) - }; - AddChild(fill); - - var skyMat = new ProceduralSkyMaterial - { - SkyTopColor = new Color(0.24f, 0.34f, 0.44f), - SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f), - GroundBottomColor = new Color(0.28f, 0.20f, 0.14f), - GroundHorizonColor = new Color(0.68f, 0.48f, 0.32f) - }; - var env = new Godot.Environment - { - BackgroundMode = Godot.Environment.BGMode.Sky, - Sky = new Sky { SkyMaterial = skyMat }, - AmbientLightSource = Godot.Environment.AmbientSource.Sky, - AmbientLightEnergy = 0.65f - }; - AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env }); + GetViewport().UseTaa = true; + var atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" }; + AddChild(atmosphere); + atmosphere.ApplyMap(ArenaMapKind.Desert); + atmosphere.Sun.RotationDegrees = new Vector3(-38f, 36f, 0f); } private void VerifyBakedVertexColors(string name, ArrayMesh mesh)