diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 6388ca9dd..1479901e4 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -20,8 +20,8 @@ public static class IniNames public const string Shadows = "shadows"; public const int ShadowsDefaultValue = 3; // Slider 0...1: how many lamps/fires near the hero get URP's per-frame shadow (NPCs and the hero cast in - // it) - 0 = 4 within 20 m, 1 = 12 within 50 m (StationaryLightsService). Lights beyond have no shadow; - // an indoor light skips outdoor surfaces instead. + // it) - 0 = 4 within 20 m, 1 = 12 within 50 m (StationaryLightsService). The others in reach keep their + // cached shadow of walls and VOBs (LightShadowCacheDomain). public const string ShadowRange = "shadowRange"; public const float ShadowRangeDefaultValue = 0.75f; // 1 = "-X HP" numbers over NPC heads and next to the hero's bar, 0 = off (default). diff --git a/Assets/Gothic-Core/Scripts/Domain/Meshes/LightShadowCacheDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Meshes/LightShadowCacheDomain.cs new file mode 100644 index 000000000..f3b56249a --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Domain/Meshes/LightShadowCacheDomain.cs @@ -0,0 +1,367 @@ +using System.Collections.Generic; +using Gothic.Core.Const; +using Gothic.Core.Logging; +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.Core.Domain.Meshes +{ + /// + /// Cached cube shadows of the pooled lamps and fires (PC, option "Shadows" on) - like GD3D11's point light shadows: + /// a light's surroundings (world mesh, VOBs) are drawn once into its 6 faces, the distance to the nearest wall per + /// texel. URP renders its shadow lights every frame (~40 at most) - farther lamps had none, the candles in a house + /// lit its outside walls and the street. StationaryLightsService owns this, picks the lights and writes their + /// slot into the shader arrays (StationaryLighting.hlsl samples _GothicLightShadowCache). + /// Only static things cast: NPCs, items and the hero move - the nearest lights keep URP's shadows for them. + /// A light is drawn again when the colliders around it changed (lazy loaded VOBs, a door's collider). + /// + public class LightShadowCacheDomain + { + /// + /// Texels per face side. Same as GOTHIC_LIGHT_CACHE_FACE_SIZE in StationaryLighting.hlsl. 128: ~8 cm at 5 m - + /// the nearest lamps have URP's sharper ones. + /// + public const int FaceSize = 128; + + /// + /// Lights with a cached shadow (6 slices each, R16 float: 192 KB per light, 48 MB in all). The pool lights ~200 + /// in Khorinis within its 80 m. + /// + public const int Capacity = 256; + + private const int _rendersPerFrame = 3; + private const int _checksPerFrame = 4; + // Same as StationaryLightsService's shadow near plane: the lamp's cage casts its bars, not the flame's own mesh. + private const float _nearPlane = 0.05f; + private const string _passName = "GothicLightCache"; + private const int _maxColliders = 1024; + + private static readonly int _atlasShaderId = Shader.PropertyToID("_GothicLightShadowCache"); + private static readonly int _cacheLightShaderId = Shader.PropertyToID("_GothicLightCacheLight"); + + // Face order and orientation as in StationaryLighting.hlsl (_GothicCacheFaceForward/_GothicCacheFaceUp). + private static readonly Vector3[] _faceForward = + { Vector3.right, Vector3.left, Vector3.up, Vector3.down, Vector3.forward, Vector3.back }; + private static readonly Vector3[] _faceUp = + { Vector3.up, Vector3.up, Vector3.forward, Vector3.forward, Vector3.up, Vector3.up }; + + private sealed class Entry + { + public int Key; + public int Slot; + public Vector3 Position; + public float Range; + public float Distance; + public bool IsRendered; + public bool IsQueued; + public int ColliderCount; + } + + /// + /// A light the cache may take: Key identifies it (StationaryLightsService: the light's instance id), Distance + /// sorts (closest first). + /// + public struct Candidate + { + public int Key; + public Vector3 Position; + public float Range; + public float Distance; + } + + private readonly Dictionary _entries = new(); + private readonly Stack _freeSlots = new(); + private readonly List _renderQueue = new(); + private readonly List _checkList = new(); + private int _checkCursor; + private readonly HashSet _wantedKeys = new(); + private readonly List _removedKeys = new(); + private readonly Collider[] _colliders = new Collider[_maxColliders]; + private readonly HashSet _casters = new(); + private readonly List _materials = new(); + private readonly Dictionary _passIndices = new(); + private readonly Plane[] _planes = new Plane[6]; + private readonly int _casterLayerMask = + (1 << Constants.DefaultLayer) | (1 << Constants.IgnoreRaycastLayer) | (1 << Constants.VobMovableLayer); + + private RenderTexture _atlas; + private RenderTexture _faceTarget; + private Texture2DArray _emptyAtlas; + private CommandBuffer _cmd; + private int _renderedTotal; + + public bool IsEnabled => _atlas != null; + + /// + /// The light's slot in the atlas once its shadow is drawn, -1 otherwise. + /// + public int GetSlot(int key) => _atlas != null && _entries.TryGetValue(key, out var entry) && entry.IsRendered + ? entry.Slot + : -1; + + /// + /// Allocates (48 MB) or frees the atlas. Off: the shader gets a 1 slice dummy, every light loses its slot + /// (the caller rewrites them). + /// + public void SetEnabled(bool isEnabled) + { + if (isEnabled == IsEnabled) + return; + + Clear(); + if (isEnabled) + { + _atlas = new RenderTexture(FaceSize, FaceSize, GraphicsFormat.R16_SFloat, GraphicsFormat.None) + { + name = "GothicLightShadowCache", + dimension = TextureDimension.Tex2DArray, + volumeDepth = Capacity * 6, + useMipMap = false, + filterMode = FilterMode.Point, + wrapMode = TextureWrapMode.Clamp + }; + _atlas.Create(); + _faceTarget = new RenderTexture(FaceSize, FaceSize, GraphicsFormat.R16_SFloat, + GraphicsFormat.D24_UNorm_S8_UInt) + { + name = "GothicLightShadowCacheFace", + useMipMap = false, + filterMode = FilterMode.Point + }; + _faceTarget.Create(); + _cmd ??= new CommandBuffer { name = "GothicLightShadowCache" }; + Shader.SetGlobalTexture(_atlasShaderId, _atlas); + Logger.Log($"[LightShadowCache] on: {Capacity} lights, {FaceSize}px faces", LogCat.Mesh); + } + else + { + _atlas.Release(); + Object.Destroy(_atlas); + _atlas = null; + _faceTarget.Release(); + Object.Destroy(_faceTarget); + _faceTarget = null; + BindEmptyAtlas(); + Logger.Log("[LightShadowCache] off", LogCat.Mesh); + } + } + + /// + /// Forgets every light (new world) - the atlas stays. + /// + public void Clear() + { + _entries.Clear(); + _renderQueue.Clear(); + _checkList.Clear(); + _checkCursor = 0; + _freeSlots.Clear(); + for (var i = Capacity - 1; i >= 0; i--) + _freeSlots.Push(i); + _passIndices.Clear(); + if (_atlas == null) + BindEmptyAtlas(); + } + + /// + /// The lights in reach changed (pool rebalance): the closest Capacity keep or get a slot, the others lose theirs. + /// Keys whose slot is gone land in removedKeys. + /// + public void UpdateWanted(List candidates, List removedKeys) + { + if (_atlas == null) + return; + + candidates.Sort((a, b) => a.Distance.CompareTo(b.Distance)); + _wantedKeys.Clear(); + for (var i = 0; i < candidates.Count && i < Capacity; i++) + _wantedKeys.Add(candidates[i].Key); + + _removedKeys.Clear(); + foreach (var key in _entries.Keys) + if (!_wantedKeys.Contains(key)) + _removedKeys.Add(key); + foreach (var key in _removedKeys) + { + var entry = _entries[key]; + _entries.Remove(key); + _freeSlots.Push(entry.Slot); + entry.IsQueued = false; + if (entry.IsRendered) + removedKeys.Add(key); + } + _renderQueue.RemoveAll(entry => !_entries.ContainsKey(entry.Key)); + + for (var i = 0; i < candidates.Count && i < Capacity; i++) + { + var candidate = candidates[i]; + if (!_entries.TryGetValue(candidate.Key, out var entry)) + { + if (_freeSlots.Count == 0) + break; + entry = new Entry { Key = candidate.Key, Slot = _freeSlots.Pop() }; + _entries.Add(candidate.Key, entry); + } + var hasMoved = entry.Position != candidate.Position || !Mathf.Approximately(entry.Range, candidate.Range); + entry.Position = candidate.Position; + entry.Range = candidate.Range; + entry.Distance = candidate.Distance; + if ((!entry.IsRendered || hasMoved) && !entry.IsQueued) + { + entry.IsQueued = true; + _renderQueue.Add(entry); + } + } + _renderQueue.Sort((a, b) => a.Distance.CompareTo(b.Distance)); + + _checkList.Clear(); + _checkList.AddRange(_entries.Values); + if (_checkCursor >= _checkList.Count) + _checkCursor = 0; + } + + /// + /// Per frame: draws up to _rendersPerFrame queued lights (closest first); with nothing queued it checks a few + /// drawn ones for new or gone colliders around them. Keys whose shadow appeared land in renderedKeys. + /// + public void Render(IReadOnlyCollection worldChunks, List renderedKeys) + { + if (_atlas == null) + return; + + if (_renderQueue.Count == 0) + { + for (var i = 0; i < _checksPerFrame && _checkList.Count > 0; i++) + { + _checkCursor = (_checkCursor + 1) % _checkList.Count; + var entry = _checkList[_checkCursor]; + if (!entry.IsRendered || entry.IsQueued || !_entries.ContainsKey(entry.Key)) + continue; + if (CountColliders(entry) == entry.ColliderCount) + continue; + entry.IsQueued = true; + _renderQueue.Add(entry); + } + } + + var rendered = 0; + while (rendered < _rendersPerFrame && _renderQueue.Count > 0) + { + var entry = _renderQueue[0]; + _renderQueue.RemoveAt(0); + entry.IsQueued = false; + if (!_entries.ContainsKey(entry.Key)) + continue; + + RenderEntry(entry, worldChunks); + rendered++; + if (!entry.IsRendered) + { + entry.IsRendered = true; + renderedKeys.Add(entry.Key); + } + } + + if (rendered > 0 && _renderQueue.Count == 0) + Logger.Log($"[LightShadowCache] {_entries.Count} lights cached ({_renderedTotal} drawn so far)", + LogCat.Mesh); + } + + private int CountColliders(Entry entry) + { + return Physics.OverlapSphereNonAlloc(entry.Position, entry.Range, _colliders, _casterLayerMask, + QueryTriggerInteraction.Ignore); + } + + private void GatherCasters(Entry entry, IReadOnlyCollection worldChunks) + { + _casters.Clear(); + var rangeSqr = entry.Range * entry.Range; + // World chunks: by their bounds - a chunk of noCollDet polygons (bushes) has no collider. + foreach (var chunk in worldChunks) + { + if (chunk != null && chunk.enabled && chunk.bounds.SqrDistance(entry.Position) <= rangeSqr) + _casters.Add(chunk); + } + + var count = CountColliders(entry); + entry.ColliderCount = count; + for (var i = 0; i < count; i++) + { + if (_colliders[i].TryGetComponent(out var renderer) && + renderer.shadowCastingMode != ShadowCastingMode.Off && renderer.gameObject.activeInHierarchy) + _casters.Add(renderer); + } + } + + private int GetPassIndex(Material material) + { + if (!_passIndices.TryGetValue(material, out var pass)) + { + pass = material.FindPass(_passName); + _passIndices.Add(material, pass); + } + return pass; + } + + private void RenderEntry(Entry entry, IReadOnlyCollection worldChunks) + { + GatherCasters(entry, worldChunks); + + var position = entry.Position; + var range = Mathf.Max(entry.Range, _nearPlane * 2f); + var projection = Matrix4x4.Perspective(90f, 1f, _nearPlane, range); + _cmd.Clear(); + _cmd.SetGlobalVector(_cacheLightShaderId, new Vector4(position.x, position.y, position.z, 1f / range)); + + for (var face = 0; face < 6; face++) + { + // Unity's camera convention: looks down -z in view space. + var view = Matrix4x4.Scale(new Vector3(1f, 1f, -1f)) * + Matrix4x4.TRS(position, Quaternion.LookRotation(_faceForward[face], _faceUp[face]), + Vector3.one).inverse; + GeometryUtility.CalculateFrustumPlanes(projection * view, _planes); + + _cmd.SetRenderTarget(_faceTarget); + // 1 = nothing in the light's range. + _cmd.ClearRenderTarget(true, true, Color.white); + _cmd.SetViewProjectionMatrices(view, projection); + foreach (var renderer in _casters) + { + if (renderer == null || !GeometryUtility.TestPlanesAABB(_planes, renderer.bounds)) + continue; + renderer.GetSharedMaterials(_materials); + for (var submesh = 0; submesh < _materials.Count; submesh++) + { + var material = _materials[submesh]; + if (material == null) + continue; + var pass = GetPassIndex(material); + if (pass >= 0) + _cmd.DrawRenderer(renderer, material, submesh, pass); + } + } + _cmd.CopyTexture(_faceTarget, 0, 0, _atlas, entry.Slot * 6 + face, 0); + } + + Graphics.ExecuteCommandBuffer(_cmd); + _renderedTotal++; + } + + private void BindEmptyAtlas() + { + if (_emptyAtlas == null) + { + _emptyAtlas = new Texture2DArray(1, 1, 1, TextureFormat.RHalf, false) + { + name = "GothicLightShadowCacheEmpty" + }; + _emptyAtlas.SetPixelData(new ushort[] { 0x3C00 }, 0, 0); // 1.0 as half + _emptyAtlas.Apply(false, true); + } + Shader.SetGlobalTexture(_atlasShaderId, _emptyAtlas); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Domain/Meshes/LightShadowCacheDomain.cs.meta b/Assets/Gothic-Core/Scripts/Domain/Meshes/LightShadowCacheDomain.cs.meta new file mode 100644 index 000000000..00c0b8f27 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Domain/Meshes/LightShadowCacheDomain.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: de28cf7d68c9c3d43a0abb58158c5bf7 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index 849fc7cfd..1be6f7a91 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -18,6 +18,11 @@ public class StationaryLightsService [Inject] private readonly ConfigService _configService; private readonly WorldLightmapDomain _lightmapDomain = new WorldLightmapDomain().Inject(); + // Cached shadows of every pooled lamp/fire in reach (PC): drawn once, not every frame like URP's shadow lights. + private readonly LightShadowCacheDomain _shadowCache = new LightShadowCacheDomain().Inject(); + private readonly List _cacheCandidates = new(); + private readonly Dictionary _cacheLights = new(); + private readonly List _cacheChangedKeys = new(); /// /// Same as MAX_TOTAL_STATIONARY_LIGHTS in StationaryLighting.hlsl (1023 = Unity's cap, mobile 512). The global @@ -76,7 +81,8 @@ public class StationaryLightsService /// a few; baked lights (in the lightmaps) never - the walls would get them twice. /// // Option "Shadow range" (slider): from 4 lights within 20 m to 12 within 50 m. Every one draws its surroundings - // 6 times per frame - with 40 the frame rate tanked. + // 6 times per frame - with 40 the frame rate tanked. The lamps beyond have their cached shadow + // (LightShadowCacheDomain), these only add the NPCs' and the hero's shadows close by. private const int _minShadowLights = 4; private const int _maxShadowLights = 12; private const float _minShadowLightDistance = 20f; @@ -140,6 +146,13 @@ public void LateUpdate() (_isPoolDirty && Time.time >= _lastPoolRebalance + _poolMinRebalanceInterval)) RebalancePool(); + if (_shadowCache.IsEnabled) + { + _cacheChangedKeys.Clear(); + _shadowCache.Render(_worldChunkRenderers, _cacheChangedKeys); + ApplyCacheSlots(_cacheChangedKeys); + } + // Lights loaded/unloaded this frame are uploaded at once (the whole arrays go to the GPU each time). if (_isUploadDirty) { @@ -563,6 +576,8 @@ public void InitStationaryLights() _dynamicShadowLights.Clear(); _dynamicShadowNearPlanes.Clear(); _heroUnityLight = null; + _shadowCache.Clear(); + _cacheLights.Clear(); _poolPeak = 0; _isPoolDirty = true; @@ -745,6 +760,9 @@ private void RebalancePool() if (cam == null) return; var camPos = cam.transform.position; + // The cache follows the option and the quality level (High) also while the camera stands still. + if (IsShadowCacheWanted() != _shadowCache.IsEnabled) + isDirty = true; if (!isDirty && (camPos - _lastPoolRebalanceCameraPosition).sqrMagnitude < _poolMinCameraMove * _poolMinCameraMove) return; @@ -792,6 +810,7 @@ private void RebalancePool() UpdateShadowLights(camPos); UpdateUnityLights(camPos); + UpdateShadowCache(camPos); if (_wantedLights.Count > _poolPeak) { @@ -866,15 +885,89 @@ public void SetDaylight(float brightness) } /// - /// The slot's color; its alpha marks an indoor light (StationaryLighting.hlsl: no light on outdoor surfaces). + /// The slot's color; its alpha: indoor (StationaryLighting.hlsl: no light on outdoor surfaces without a cached + /// shadow) + 2 * (cached shadow slot + 1). /// private Color GetSlotColor(StationaryLight light) { var color = light.IsOutdoor ? light.RuntimeLinearColor * _outdoorLightFactor : light.RuntimeLinearColor; - color.a = light.IsIndoor ? 1f : 0f; + var cacheSlot = _shadowCache.GetSlot(light.GetInstanceID()); + color.a = (light.IsIndoor ? 1f : 0f) + 2f * (cacheSlot + 1); return color; } + /// + /// Cached shadows (LightShadowCacheDomain) for the pooled lamps/fires closest to the camera - all of them in + /// reach, unlike URP's few shadow lights (those keep theirs: NPCs and the hero cast in them). Not for lights + /// baked into the lightmaps (only VOBs/NPCs get them) or spell lights (they move). Runs with the rebalance. + /// + private void UpdateShadowCache(Vector3 cameraPosition) + { + var isEnabled = IsShadowCacheWanted(); + if (isEnabled != _shadowCache.IsEnabled) + { + _shadowCache.SetEnabled(isEnabled); + _cacheLights.Clear(); + // Every slot loses or gets its cache marker. + foreach (var light in _pooledLights) + if (light != null && light.Index > HeroLightIndex && light.Index < _lightColors.Length) + _lightColors[light.Index] = GetSlotColor(light); + _isUploadDirty = true; + } + if (!isEnabled) + return; + + _cacheCandidates.Clear(); + _cacheLights.Clear(); + foreach (var light in _pooledLights) + { + if (light == null || light.Index <= HeroLightIndex || light.IsBakedIntoWorld || light.IsSpellLight || + !light.isActiveAndEnabled) + continue; + var key = light.GetInstanceID(); + _cacheLights[key] = light; + _cacheCandidates.Add(new LightShadowCacheDomain.Candidate + { + Key = key, + Position = light.CachedPosition, + Range = light.CachedRange, + Distance = Vector3.Distance(light.CachedPosition, cameraPosition) - light.CachedRange + }); + } + + _cacheChangedKeys.Clear(); + _shadowCache.UpdateWanted(_cacheCandidates, _cacheChangedKeys); + ApplyCacheSlots(_cacheChangedKeys); + } + + /// + /// Option "Shadows" on, PC with URP's additional light shadows (High quality) - Quest's shaders don't sample + /// the cache. + /// + private bool IsShadowCacheWanted() + { + return !Application.isMobilePlatform && SystemInfo.supports2DArrayTextures && + UniversalRenderPipeline.asset != null && + UniversalRenderPipeline.asset.supportsAdditionalLightShadows && + _configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue) > 0; + } + + /// + /// Lights whose cached shadow appeared or went away get their slot's alpha rewritten. + /// + private void ApplyCacheSlots(List keys) + { + foreach (var key in keys) + { + if (!_cacheLights.TryGetValue(key, out var light) || light == null) + continue; + if (light.Index <= HeroLightIndex || light.Index >= _lightColors.Length) + continue; + _lightColors[light.Index] = GetSlotColor(light); + _isUploadDirty = true; + } + } + /// /// Position and 1/range² of a slot - negative for a shadow casting light (the shaders look up its shadow). /// @@ -945,6 +1038,7 @@ public void RefreshShadowLights() if (light != null) SetLightShadow(light, true); UpdateShadowLights(cam.transform.position); + UpdateShadowCache(cam.transform.position); } /// diff --git a/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl index f3dd4e78d..b8a577fd8 100644 --- a/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl @@ -5,6 +5,8 @@ // - GOTHIC_SHADOW_ALPHA_CLIP: _MainTex is a texture array with alpha (plants, fences), cut at _Cutoff like the main pass. // - GOTHIC_SHADOW_FATNESS: the vertex is pushed out by _Fatness (NPCs' Mdl_SetModelFatness). // - _WIND (material keyword): the same sway as the main pass (GothicWind.hlsl), or the shadow stays behind the tree. +// - GOTHIC_LIGHT_CACHE: the GothicLightCache pass - writes the distance to the light (_GothicLightCacheLight, divided by +// its range) into the cached cube shadows of the lamps and fires (LightShadowCacheDomain), no shadow bias. #ifndef GOTHIC_SHADOW_CASTER_INCLUDED #define GOTHIC_SHADOW_CASTER_INCLUDED @@ -13,6 +15,8 @@ // Set by URP for the light whose shadow map is drawn. float3 _LightDirection; float3 _LightPosition; +// xyz: position of the light whose cached shadow is drawn, w: 1 / range (LightShadowCacheDomain). +float4 _GothicLightCacheLight; struct GothicShadowAttributes { @@ -28,6 +32,9 @@ struct GothicShadowVaryings #if defined(GOTHIC_SHADOW_ALPHA_CLIP) float4 uv : TEXCOORD0; #endif +#if defined(GOTHIC_LIGHT_CACHE) + float3 positionWS : TEXCOORD1; +#endif }; GothicShadowVaryings GothicShadowVert(GothicShadowAttributes v) @@ -43,6 +50,10 @@ GothicShadowVaryings GothicShadowVert(GothicShadowAttributes v) #if defined(_WIND) positionWS = ApplyWind(positionWS); #endif +#if defined(GOTHIC_LIGHT_CACHE) + o.positionWS = positionWS; + o.positionCS = TransformWorldToHClip(positionWS); +#else float3 normalWS = TransformObjectToWorldNormal(v.normal); #if defined(_CASTING_PUNCTUAL_LIGHT_SHADOW) @@ -57,6 +68,7 @@ GothicShadowVaryings GothicShadowVert(GothicShadowAttributes v) positionCS.z = max(positionCS.z, UNITY_NEAR_CLIP_VALUE); #endif o.positionCS = positionCS; +#endif #if defined(GOTHIC_SHADOW_ALPHA_CLIP) o.uv = float4(v.uv.xy * REFERENCE_TEX_ARRAY_SIZE * _MainTex_TexelSize.xy, v.uv.zw); @@ -64,14 +76,18 @@ GothicShadowVaryings GothicShadowVert(GothicShadowAttributes v) return o; } -half4 GothicShadowFrag(GothicShadowVaryings i) : SV_Target +float4 GothicShadowFrag(GothicShadowVaryings i) : SV_Target { #if defined(GOTHIC_SHADOW_ALPHA_CLIP) // A low mip: the shadow map is coarse anyway, and leaves keep their holes instead of turning into blobs. half alpha = SAMPLE_TEXTURE2D_ARRAY_LOD(_MainTex, sampler_MainTex, i.uv.xy, i.uv.z, min(1, i.uv.w)).a; clip(alpha - _Cutoff); #endif +#if defined(GOTHIC_LIGHT_CACHE) + return length(i.positionWS - _GothicLightCacheLight.xyz) * _GothicLightCacheLight.w; +#else return 0; +#endif } #endif diff --git a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader index cda86ed24..dab5fdc05 100644 --- a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader +++ b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader @@ -89,9 +89,9 @@ Shader "Lit/AlphaToCoverage" for (uint k = 0; k < min(_StationaryLightCount, MAX_AFFECTING_STATIONARY_LIGHTS); k++) { uint lightIndex = _StationaryLightIndices[k / 4][k % 4]; - // Shadow casting lights come per pixel through URP (GothicShadowedLights). - if (!IsStationaryLightShadowed(lightIndex)) - diffuse += AdditionalStationaryDiffuse(lightIndex, worldPos, normal); + // Shadow casting lights come per pixel through URP (GothicShadowedLights), the others with + // their cached shadow. + diffuse += StationaryLightContribution(lightIndex, worldPos, normal, false); } return diffuse; @@ -188,6 +188,49 @@ Shader "Lit/AlphaToCoverage" #include "GothicShadowCaster.hlsl" ENDHLSL } + + Pass + { + // Cached shadows of the lamps and fires (LightShadowCacheDomain): the distance to the light, drawn + // once per light - not by URP (its own LightMode). + Name "GothicLightCache" + Tags { "LightMode" = "GothicLightCache" } + ZWrite On + ZTest LEqual + ColorMask R + AlphaToMask Off + // Gothic's polygons are one-sided: a wall facing away from the light still casts its shadow. + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + TEXTURE2D_ARRAY(_MainTex); + SAMPLER(sampler_MainTex); + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + half _Cutoff; + half _MipScale; + float _DistanceFade; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float _WindStrength; + CBUFFER_END + + #define GOTHIC_SHADOW_ALPHA_CLIP + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #define GOTHIC_LIGHT_CACHE + #include "GothicShadowCaster.hlsl" + ENDHLSL + } Pass { Name "DepthOnly" diff --git a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader index ec2755634..bc9bfb631 100644 --- a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader +++ b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader @@ -150,6 +150,38 @@ Shader "Lit/SingleMesh" #include "GothicShadowCaster.hlsl" ENDHLSL } + + Pass + { + // Cached shadows of the lamps and fires (LightShadowCacheDomain): the distance to the light, drawn + // once per light - not by URP (its own LightMode). + Name "GothicLightCache" + Tags { "LightMode" = "GothicLightCache" } + ZWrite On + ZTest LEqual + ColorMask R + // Gothic's polygons are one-sided: a wall facing away from the light still casts its shadow. + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_ST; + float _Fatness; + CBUFFER_END + + #define GOTHIC_SHADOW_FATNESS + #include "GothicIncludes.hlsl" + #define GOTHIC_LIGHT_CACHE + #include "GothicShadowCaster.hlsl" + ENDHLSL + } Pass { Name "DepthOnly" diff --git a/Assets/Gothic-Core/Shaders/Lit-World.shader b/Assets/Gothic-Core/Shaders/Lit-World.shader index 5505271e5..aaae0f4c7 100644 --- a/Assets/Gothic-Core/Shaders/Lit-World.shader +++ b/Assets/Gothic-Core/Shaders/Lit-World.shader @@ -90,16 +90,15 @@ Shader "Lit/World" #include "GothicShadows.hlsl" // Per pixel: per vertex a torch in the middle of a big cave wall lit nothing (its corners are far away). - // isOutdoorSurface: vertex lit polygons and VOBs outside light mapped areas - indoor lights skip them. + // isOutdoorSurface: vertex lit polygons and VOBs outside light mapped areas - indoor lights without a + // cached shadow skip them. half3 StationaryLighting(half3 normal, float3 worldPos, bool isOutdoorSurface) { half3 diffuse = 0; for (uint k = 0; k < min(_StationaryLightCount, MAX_AFFECTING_STATIONARY_LIGHTS); k++) { uint lightIndex = _StationaryLightIndices[k / 4][k % 4]; - if (!IsStationaryLightShadowed(lightIndex) && - !(isOutdoorSurface && IsStationaryLightIndoor(lightIndex))) - diffuse += AdditionalStationaryDiffuse(lightIndex, worldPos, normal); + diffuse += StationaryLightContribution(lightIndex, worldPos, normal, isOutdoorSurface); } if (_StationaryLightCount >= MAX_AFFECTING_STATIONARY_LIGHTS) { @@ -107,9 +106,7 @@ Shader "Lit/World" MAX_AFFECTING_STATIONARY_LIGHTS); l++) { uint lightIndex2 = _StationaryLightIndices2[l / 4][l % 4]; - if (!IsStationaryLightShadowed(lightIndex2) && - !(isOutdoorSurface && IsStationaryLightIndoor(lightIndex2))) - diffuse += AdditionalStationaryDiffuse(lightIndex2, worldPos, normal); + diffuse += StationaryLightContribution(lightIndex2, worldPos, normal, isOutdoorSurface); } } return diffuse; @@ -212,6 +209,44 @@ Shader "Lit/World" #include "GothicShadowCaster.hlsl" ENDHLSL } + + Pass + { + // Cached shadows of the lamps and fires (LightShadowCacheDomain): the distance to the light, drawn + // once per light - not by URP (its own LightMode). + Name "GothicLightCache" + Tags { "LightMode" = "GothicLightCache" } + ZWrite On + ZTest LEqual + ColorMask R + // Gothic's polygons are one-sided: a wall facing away from the sun still casts its shadow. + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float4x4 _StationaryLightIndices2; + float _WindStrength; + float4 _VobLightTint; + float _FocusBrightness; + CBUFFER_END + + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #define GOTHIC_LIGHT_CACHE + #include "GothicShadowCaster.hlsl" + ENDHLSL + } Pass { Name "DepthOnly" diff --git a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl index 255c7588c..8638466bb 100644 --- a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl +++ b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl @@ -11,17 +11,80 @@ #define MAX_AFFECTING_STATIONARY_LIGHTS 16 float4 _GlobalStationaryLightPositionsAndAttenuation[MAX_TOTAL_STATIONARY_LIGHTS]; -// rgb: color, a: 1 = indoor light (under a light mapped ceiling, IsStationaryLightIndoor). Same 16 byte stride as -// the former real3. +// rgb: color, a: indoor + 2 * (cached shadow slot + 1) - indoor (0/1): under a light mapped ceiling +// (IsStationaryLightIndoor); the slot: its cube in _GothicLightShadowCache (StationaryLightCacheSlot, -1 = none). real4 _GlobalStationaryLightColors[MAX_TOTAL_STATIONARY_LIGHTS]; +// Cached cube shadows of the lamps and fires (LightShadowCacheDomain, PC only): 6 slices per light (+X, -X, +Y, -Y, +// +Z, -Z), each the distance to the nearest wall/VOB divided by the light's range. Drawn once per light - every lamp in +// reach gets its shadow (URP renders only ~40, every frame), a candle in a house no longer lights the street. +#if !defined(SHADER_API_MOBILE) +#define GOTHIC_LIGHT_SHADOW_CACHE +// Same as LightShadowCacheDomain.FaceSize. +#define GOTHIC_LIGHT_CACHE_FACE_SIZE 128 +TEXTURE2D_ARRAY(_GothicLightShadowCache); + +static const float3 _GothicCacheFaceForward[6] = + { float3(1, 0, 0), float3(-1, 0, 0), float3(0, 1, 0), float3(0, -1, 0), float3(0, 0, 1), float3(0, 0, -1) }; +static const float3 _GothicCacheFaceUp[6] = + { float3(0, 1, 0), float3(0, 1, 0), float3(0, 0, 1), float3(0, 0, 1), float3(0, 1, 0), float3(0, 1, 0) }; +// cross(up, forward) - the camera's right in Unity's left-handed space. +static const float3 _GothicCacheFaceRight[6] = + { float3(0, 0, -1), float3(0, 0, 1), float3(-1, 0, 0), float3(1, 0, 0), float3(1, 0, 0), float3(-1, 0, 0) }; +#endif + // A pooled light with w < 0 casts a shadow (StationaryLightsService): the shaders light it through its URP light with // the cube shadow (GothicShadowedLights) and skip it here - URP reaches every object in its range, the pool only the // renderers the light gathered. // A candle in a house doesn't light the house's outside walls (no shadow for it from the walls). bool IsStationaryLightIndoor(uint lightIndex) { - return _GlobalStationaryLightColors[lightIndex].a > 0.5; + float a = _GlobalStationaryLightColors[lightIndex].a; + return a - 2 * floor(a * 0.5) > 0.5; +} + +// The light's slot in _GothicLightShadowCache, -1 without a cached shadow (not drawn yet, too far, Quest). +int StationaryLightCacheSlot(uint lightIndex) +{ +#if defined(GOTHIC_LIGHT_SHADOW_CACHE) + return (int)floor(_GlobalStationaryLightColors[lightIndex].a * 0.5) - 1; +#else + return -1; +#endif +} + +// 1 = lit, 0 = a wall or VOB between the light and the position (bilinear 2x2 of the cached distances). +half StationaryLightCachedShadow(uint lightIndex, int slot, float3 worldPos, half3 normal) +{ +#if defined(GOTHIC_LIGHT_SHADOW_CACHE) + float4 lightPosAndAttenuation = _GlobalStationaryLightPositionsAndAttenuation[lightIndex]; + float invRange = sqrt(abs(lightPosAndAttenuation.w)); + float3 toLight = lightPosAndAttenuation.xyz - worldPos; + // One texel at this distance (90 degrees per face); pushed towards the light by 1.5 of it - the surface itself is + // in the map (Gothic's polygons are drawn both sides), else it shadows itself in stripes. + float texel = length(toLight) * (2.0 / GOTHIC_LIGHT_CACHE_FACE_SIZE); + float3 offsetNormal = dot(normal, toLight) >= 0 ? normal : -normal; + float3 d = worldPos + offsetNormal * (texel * 1.5) - lightPosAndAttenuation.xyz; + + float3 a = abs(d); + int face = a.x >= a.y && a.x >= a.z ? (d.x > 0 ? 0 : 1) : (a.y >= a.z ? (d.y > 0 ? 2 : 3) : (d.z > 0 ? 4 : 5)); + float major = dot(d, _GothicCacheFaceForward[face]); + float2 uv = float2(dot(d, _GothicCacheFaceRight[face]), dot(d, _GothicCacheFaceUp[face])) / major * 0.5 + 0.5; + + // 5 cm against acne on flat walls. + float current = (length(d) - 0.05) * invRange; + float2 coord = uv * GOTHIC_LIGHT_CACHE_FACE_SIZE - 0.5; + float2 f = frac(coord); + int2 c = clamp((int2)floor(coord), 0, GOTHIC_LIGHT_CACHE_FACE_SIZE - 2); + int sliceIndex = slot * 6 + face; + half s00 = step(current, LOAD_TEXTURE2D_ARRAY(_GothicLightShadowCache, c, sliceIndex).r); + half s10 = step(current, LOAD_TEXTURE2D_ARRAY(_GothicLightShadowCache, c + int2(1, 0), sliceIndex).r); + half s01 = step(current, LOAD_TEXTURE2D_ARRAY(_GothicLightShadowCache, c + int2(0, 1), sliceIndex).r); + half s11 = step(current, LOAD_TEXTURE2D_ARRAY(_GothicLightShadowCache, c + int2(1, 1), sliceIndex).r); + return lerp(lerp(s00, s10, f.x), lerp(s01, s11, f.x), f.y); +#else + return 1; +#endif } bool IsStationaryLightShadowed(uint lightIndex) @@ -41,4 +104,19 @@ half3 AdditionalStationaryDiffuse(uint lightIndex, real3 worldPos, real3 normal) return _GlobalStationaryLightColors[lightIndex].rgb * attenuation * _PointLightIntensity; } +// A pooled light without a URP shadow (those come through GothicShadowedLights): with its cached shadow, else without - +// then an indoor light skips outdoor surfaces (the house's walls would have shadowed it). +half3 StationaryLightContribution(uint lightIndex, float3 worldPos, half3 normal, bool isOutdoorSurface) +{ + if (IsStationaryLightShadowed(lightIndex)) + return 0; + int slot = StationaryLightCacheSlot(lightIndex); + if (slot < 0 && isOutdoorSurface && IsStationaryLightIndoor(lightIndex)) + return 0; + half3 diffuse = AdditionalStationaryDiffuse(lightIndex, worldPos, normal); + if (slot >= 0 && any(diffuse > 0)) + diffuse *= StationaryLightCachedShadow(lightIndex, slot, worldPos, normal); + return diffuse; +} + #endif diff --git a/Docs/adr/2026-11-23-cached-lamp-shadows.md b/Docs/adr/2026-11-23-cached-lamp-shadows.md new file mode 100644 index 000000000..3676e81d8 --- /dev/null +++ b/Docs/adr/2026-11-23-cached-lamp-shadows.md @@ -0,0 +1,21 @@ +# ADR: Cached shadows for every lamp and fire in reach (PC) + +- Date: 2026-11-23 +- Technical details: Docs/world-lighting.md (section "Shadows and darkness", cached lamp shadows) + +## Context + +With URP's shadows only the few lamps closest to the player cast a shadow (Docs/adr/2026-11-22-pcvr-shadows-lighting.md, decision 2). URP draws every shadow casting light again in every frame, six times, and takes 256 shadow tiles at most (about 40 lamps); 40 lamps made the frame rate tank. All other lamps lit through walls: candles inside houses glowed on the outside walls and the street, distant buildings showed red patches. GD3D11 gives every light a shadow because it keeps a light's shadow map and draws it again only when something around the light changes. URP has no such cache (only HDRP has). + +## Decisions + +1. **Our own cache of cube shadows for the pooled lamps and fires.** Every lamp and fire in reach (the light pool, up to 256 lights, not lights baked into lightmaps, not moving spell lights) gets its surroundings drawn once into six faces: the distance to the nearest wall or VOB. The world shader looks it up for these lights. Not chosen: more URP shadow lights (too slow), the roof rule alone (decision 3 of the first ADR; it can't stop light going through a wall). +2. **Only static things are in the cache.** The world mesh and VOBs cast; NPCs, items and the hero move and don't. The few lamps closest to the player keep URP's shadow, where NPCs and the hero cast. +3. **A light is drawn again only when the colliders around it change** (a VOB loads or unloads nearby). Steady state costs nothing; a new light costs about 0.4 ms of CPU once (3 per frame at most). +4. **PC only, with the "Shadows" option on.** Quest's shaders compile the lookup away. + +## Consequences + +- 48 MB of video memory on PC (256 lights x 6 faces of 128 x 128, 16 bit). +- An opened door keeps the closed door's shadow until something else makes its lamps draw again. VOBs without a collider cast no cached shadow. +- The cached shadows are 128 texels per face - softer than URP's near ones. Lights brighter in the distance could get bigger faces later. diff --git a/Docs/world-lighting.md b/Docs/world-lighting.md index 5c7f27914..183e1b171 100644 --- a/Docs/world-lighting.md +++ b/Docs/world-lighting.md @@ -72,6 +72,7 @@ and no SSAO, the shaders compile those parts away there. | The sun's shadow darkens only the sun's part: baked light of sun-facing outdoor polygons and VOBs (not light mapped ones), the sun term of objects/NPCs | `Shaders/GothicShadows.hlsl`, `Lit-World`, `Lit-AlphaToCoverage`, `Lit-SingleMesh` | | SSAO (HighFidelity renderer): darkens baked/ambient light, less the sun and lights | `GothicShadows.hlsl` (`GothicGetOcclusion`) | | The pooled lights closest to the camera (option "Shadow range": 4 within 20 m up to 12 within 50 m, spell lights first; not baked into lightmaps) cast cube shadows; the pool marks them (slot w < 0) and skips them, the shaders light them through URP | `Services/World/StationaryLightsService.cs` (`UpdateShadowLights`, `ShadowLightCount`), `StationaryLighting.hlsl`, `GothicShadowedLights` | +| Cached lamp shadows (Docs/adr/2026-11-23-cached-lamp-shadows.md): every pooled lamp/fire in reach (not baked, not spell lights, up to 256) gets 6 faces of distance-to-the-nearest-wall (R16 Texture2DArray, 128 px) drawn once with the `GothicLightCache` pass (world chunks by bounds, VOBs by colliders on Default/Ignore Raycast/VobMovable); drawn again when the collider count around it changes. The slot goes into the light's color alpha (indoor + 2 * (slot + 1)); `StationaryLightContribution` samples it (2x2), lights without a slot fall back to the roof rule | `Domain/Meshes/LightShadowCacheDomain.cs`, `StationaryLightsService` (`UpdateShadowCache`, `IsShadowCacheWanted`), `StationaryLighting.hlsl`, `GothicShadowCaster.hlsl` (`GOTHIC_LIGHT_CACHE`) | | The hero's torch / Light spell (`ClaimHeroLight`) and spell projectiles (`AddDynamicShadowLight`, max 4) cast shadows too; near plane keeps the stick and hand out | `StationaryLightsService`, `VRTorch`, `VRSpellFx`, `VRSpellThrow` | | A light under a light mapped ceiling (`IsIndoor`) skips outdoor surfaces - slot color alpha 1, `normal.w` marks outdoor surfaces | `VobInitializerDomain.CreateLight`, `StationaryLightsService.GetSlotColor`, `Lit-World` (`StationaryLighting`) | | The VR hero body casts shadows; its head (scaled away for the camera) has a `ShadowsOnly` copy following the head bone | `Gothic-VR/.../VRHeroBody.cs` (`CreateShadowHead`), `NpcHeadMeshBuilder` (head without NpcContainer) |