Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Assets/Gothic-Core/Scripts/Const/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
423 changes: 423 additions & 0 deletions Assets/Gothic-Core/Scripts/Domain/Meshes/LightShadowCacheDomain.cs

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

100 changes: 97 additions & 3 deletions Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<LightShadowCacheDomain.Candidate> _cacheCandidates = new();
private readonly Dictionary<int, StationaryLight> _cacheLights = new();
private readonly List<int> _cacheChangedKeys = new();

/// <summary>
/// Same as MAX_TOTAL_STATIONARY_LIGHTS in StationaryLighting.hlsl (1023 = Unity's cap, mobile 512). The global
Expand Down Expand Up @@ -76,7 +81,8 @@ public class StationaryLightsService
/// a few; baked lights (in the lightmaps) never - the walls would get them twice.
/// </summary>
// 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;
Expand Down Expand Up @@ -169,6 +175,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)
{
Expand Down Expand Up @@ -612,6 +625,8 @@ public void InitStationaryLights()
_dynamicShadowNearPlanes.Clear();
_isDynamicShadowCapLogged = false;
_heroUnityLight = null;
_shadowCache.Clear();
_cacheLights.Clear();
_poolPeak = 0;
_isPoolDirty = true;

Expand Down Expand Up @@ -794,6 +809,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;
Expand Down Expand Up @@ -841,6 +859,7 @@ private void RebalancePool()

UpdateShadowLights(camPos);
UpdateUnityLights(camPos);
UpdateShadowCache(camPos);

if (_wantedLights.Count > _poolPeak)
{
Expand Down Expand Up @@ -915,15 +934,89 @@ public void SetDaylight(float brightness)
}

/// <summary>
/// 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).
/// </summary>
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;
}

/// <summary>
/// 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.
/// </summary>
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);
}

/// <summary>
/// Option "Shadows" on, PC with URP's additional light shadows (High quality) - Quest's shaders don't sample
/// the cache.
/// </summary>
private bool IsShadowCacheWanted()
{
return !Application.isMobilePlatform && SystemInfo.supports2DArrayTextures &&
UniversalRenderPipeline.asset != null &&
UniversalRenderPipeline.asset.supportsAdditionalLightShadows &&
_configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue) > 0;
}

/// <summary>
/// Lights whose cached shadow appeared or went away get their slot's alpha rewritten.
/// </summary>
private void ApplyCacheSlots(List<int> 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;
}
}

/// <summary>
/// Position and 1/range² of a slot - negative for a shadow casting light (the shaders look up its shadow).
/// </summary>
Expand Down Expand Up @@ -997,6 +1090,7 @@ public void RefreshShadowLights()
if (light != null)
SetLightShadow(light, true);
UpdateShadowLights(cam.transform.position);
UpdateShadowCache(cam.transform.position);
}

/// <summary>
Expand Down
18 changes: 17 additions & 1 deletion Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
{
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -57,21 +68,26 @@ 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);
#endif
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
49 changes: 46 additions & 3 deletions Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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"
Expand Down
32 changes: 32 additions & 0 deletions Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading