diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset index 13af945fc..a5ae85db6 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset @@ -567,6 +567,26 @@ MonoBehaviour: m_Key: vr.help.ring.text m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Key: menuitem.shadows.label + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Key: menuitem.shadows.description + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Key: menuitem.shadows.value + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Key: menuitem.shadowRange.label + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Key: menuitem.shadowRange.description + m_Metadata: + m_Items: [] m_Metadata: m_Items: [] m_KeyGenerator: diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset index 86544ba3a..cac4bfd0f 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset @@ -469,6 +469,28 @@ MonoBehaviour: m_Localized: "s t\u011Blem|prolnut\xED" m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: "St\xEDny" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Dynamick\xE9 st\xEDny slunce, m\u011Bs\xEDce a sv\u011Btel. Ostr\xE9 + nebo vypnut\xE9 pro slab\u0161\xED PC" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: "Vyp.|Ostr\xE9|St\u0159edn\xED|M\u011Bkk\xE9" + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "Dosah st\xEDn\u016F" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Kolik lamp a oh\u0148\u016F vrh\xE1 st\xEDny a jak daleko. Na slab\u0161\xEDch + PC sni\u017Ete" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset index 8daf4c595..bb872baa0 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset @@ -595,6 +595,28 @@ MonoBehaviour: \"Favoriten-Ring\"." m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Schatten + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Dynamische Schatten von Sonne, Mond und Lichtern. Hart oder aus + f\xFCr langsamere PCs" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: Aus|Hart|Mittel|Weich + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Schattenreichweite + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: Wie viele Lampen und Feuer Schatten werfen und wie weit. Auf langsameren + PCs verringern + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset index 418df7bd8..f4299457c 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset @@ -607,6 +607,28 @@ MonoBehaviour: it off in Immersion: "Favorites ring".' m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Shadows + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: Dynamic shadows of the sun, moon and lights. Hard or off for slower + PCs + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: Off|Hard|Medium|Soft + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Shadow range + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: How many lamps and fires cast shadows, and how far. Lower it on + slower PCs + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset index 57e8ee258..036054e3a 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset @@ -458,6 +458,28 @@ MonoBehaviour: m_Localized: con el cuerpo|fundido m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Sombras + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Sombras din\xE1micas del sol, la luna y las luces. Duras o desactivadas + para PC m\xE1s lentos" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: No|Duras|Medias|Suaves + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Alcance de sombras + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Cu\xE1ntas l\xE1mparas y fuegos proyectan sombras y hasta d\xF3nde. + Red\xFAcelo en PC m\xE1s lentos" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset index a111644b4..1e83c32b2 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset @@ -463,6 +463,28 @@ MonoBehaviour: m_Localized: avec le corps|fondu m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Ombres + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Ombres dynamiques du soleil, de la lune et des lumi\xE8res. Dures + ou d\xE9sactiv\xE9es pour les PC plus lents" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: Non|Dures|Moyennes|Douces + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "Port\xE9e des ombres" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Combien de lampes et de feux projettent des ombres, et jusqu'o\xF9. + \xC0 r\xE9duire sur les PC plus lents" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset index 45f797f75..8b7253e30 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset @@ -459,6 +459,28 @@ MonoBehaviour: m_Localized: col corpo|dissolvenza m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Ombre + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Ombre dinamiche di sole, luna e luci. Nette o disattivate per PC + pi\xF9 lenti" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: No|Nette|Medie|Morbide + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Portata ombre + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Quante lampade e fuochi proiettano ombre e fin dove. Riducila sui + PC pi\xF9 lenti" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset index 9bd41a227..b10874969 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset @@ -465,6 +465,28 @@ MonoBehaviour: dr\u0105\u017Cek, gdy jest otwarty)" m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Cienie + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Dynamiczne cienie s\u0142o\u0144ca, ksi\u0119\u017Cyca i \u015Bwiate\u0142. + Twarde lub wy\u0142\u0105czone na s\u0142absze komputery" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: "Wy\u0142.|Twarde|\u015Arednie|Mi\u0119kkie" + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "Zasi\u0119g cieni" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Ile lamp i ognisk rzuca cienie i jak daleko. Zmniejsz na s\u0142abszych + komputerach" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset index c4fd61883..5ad60190f 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset @@ -549,6 +549,34 @@ MonoBehaviour: m_Localized: "\u0441 \u0442\u0435\u043B\u043E\u043C|\u0437\u0430\u0442\u0435\u043C\u043D\u0435\u043D\u0438\u0435" m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: "\u0422\u0435\u043D\u0438" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "\u0414\u0438\u043D\u0430\u043C\u0438\u0447\u0435\u0441\u043A\u0438\u0435 + \u0442\u0435\u043D\u0438 \u0441\u043E\u043B\u043D\u0446\u0430, \u043B\u0443\u043D\u044B + \u0438 \u043E\u0433\u043D\u0435\u0439. \u0416\u0451\u0441\u0442\u043A\u0438\u0435 + \u0438\u043B\u0438 \u0432\u044B\u043A\u043B. \u0434\u043B\u044F \u0441\u043B\u0430\u0431\u044B\u0445 + \u041F\u041A" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: "\u0412\u044B\u043A\u043B.|\u0416\u0451\u0441\u0442\u043A\u0438\u0435|\u0421\u0440\u0435\u0434\u043D\u0438\u0435|\u041C\u044F\u0433\u043A\u0438\u0435" + m_Metadata: + m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "\u0414\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u0442\u0435\u043D\u0435\u0439" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "\u0421\u043A\u043E\u043B\u044C\u043A\u043E \u043B\u0430\u043C\u043F + \u0438 \u043A\u043E\u0441\u0442\u0440\u043E\u0432 \u043E\u0442\u0431\u0440\u0430\u0441\u044B\u0432\u0430\u044E\u0442 + \u0442\u0435\u043D\u0438 \u0438 \u043A\u0430\u043A \u0434\u0430\u043B\u0435\u043A\u043E. + \u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u0435 \u043D\u0430 \u0441\u043B\u0430\u0431\u044B\u0445 + \u041F\u041A" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset index dfc440af2..a84664623 100644 --- a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset +++ b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset @@ -69,7 +69,7 @@ MonoBehaviour: EnableGameSounds: 1 SunLightColor: {r: 0.69, g: 0.69, b: 0.69, a: 1} SunLightIntensity: 1 - SunUpdateInterval: 1 + SunUpdateInterval: 0 AmbientLightColor: {r: 0.1, g: 0.1, b: 0.1, a: 1} EnableWorldLightmaps: 1 StartTimeHour: 8 diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering.meta b/Assets/Gothic-Core/Scripts/Adapters/Rendering.meta new file mode 100644 index 000000000..f20824315 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d921c222fadc2314eb0119c184af0b35 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs new file mode 100644 index 000000000..94b59af11 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs @@ -0,0 +1,98 @@ +using Gothic.Core.Services.World; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.RenderGraphModule; +using UnityEngine.Rendering.Universal; + +namespace Gothic.Core.Adapters.Rendering +{ + /// + /// Tells the shaders where URP keeps this frame's shadow casting lamps/fires (StationaryLightsService picks them): + /// their index among URP's additional lights. GothicShadowedLights (GothicShadows.hlsl) lights every object in their + /// range with it - URP's per-object list holds 8 lights, a big world chunk near candles and oil lamps didn't get the + /// lamp, its light ended at the chunk's edge. + /// On the renderers with shadows (URP-HighFidelity-Renderer). Costs one loop over the visible lights per camera. + /// + public class GothicShadowLightsFeature : ScriptableRendererFeature + { + // Up to 12 lamps/fires (Shadow range option) + hero light + spell projectiles (StationaryLightsService). + // Same as GothicShadows.hlsl. + private const int _maxShadowLights = 64; + + private static readonly int _indicesShaderId = Shader.PropertyToID("_GothicShadowLightIndices"); + private static readonly int _countShaderId = Shader.PropertyToID("_GothicShadowLightCount"); + + private ShadowLightsPass _pass; + + public override void Create() + { + _pass = new ShadowLightsPass { renderPassEvent = RenderPassEvent.BeforeRenderingShadows }; + } + + public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) + { + renderer.EnqueuePass(_pass); + } + + private class ShadowLightsPass : ScriptableRenderPass + { + private readonly Vector4[] _indices = new Vector4[_maxShadowLights / 4]; + private StationaryLightsService _lightsService; + private float _nextResolveTime; + + /// + /// The service only exists while the game runs (not for the Editor's scene view, not before the boot) - + /// asked again once a second until then. + /// + private StationaryLightsService TryResolveLightsService() + { + if (!Application.isPlaying || Time.unscaledTime < _nextResolveTime || + ReflexProjectInstaller.DIContainer == null) + return null; + + _nextResolveTime = Time.unscaledTime + 1f; + try + { + return ReflexProjectInstaller.DIContainer.Resolve(); + } + catch (System.Exception) + { + return null; + } + } + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + _lightsService ??= TryResolveLightsService(); + var lightData = frameData.Get(); + var visibleLights = lightData.visibleLights; + var count = 0; + + if (_lightsService != null && _lightsService.HasShadowLights) + { + // URP's additional light index: the visible lights in order, without the main light, up to its cap + // (ForwardLights.SetupAdditionalLightConstants). + var additionalIndex = 0; + var maxAdditional = UniversalRenderPipeline.maxVisibleAdditionalLights; + for (var i = 0; i < visibleLights.Length && additionalIndex < maxAdditional; i++) + { + if (i == lightData.mainLightIndex) + continue; + var light = visibleLights[i].light; + if (count < _maxShadowLights && light != null && _lightsService.IsShadowLight(light)) + { + var index = _indices[count / 4]; + index[count % 4] = additionalIndex; + _indices[count / 4] = index; + count++; + } + additionalIndex++; + } + } + + Shader.SetGlobalVectorArray(_indicesShaderId, _indices); + Shader.SetGlobalFloat(_countShaderId, count); + } + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs.meta new file mode 100644 index 000000000..1bb5d928e --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d964ebd92a12dd1428d2e982025fd22a \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs index 606cb7b8f..f72b648d5 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs @@ -141,8 +141,38 @@ public float SpotAngle /// public bool IsBakedIntoWorld { get; set; } + /// + /// Not in a house or cave (no light mapped polygons around): its light dims by day (StationaryLightsService). + /// + public bool IsOutdoor { get; set; } + + /// + /// Under a light mapped ceiling (house, cave, sewer): it doesn't light outdoor surfaces - the candles in a house + /// glowed on its outside walls, the walls had no shadow for them. + /// + public bool IsIndoor { get; set; } + + /// + /// A spell's light (VisualFxLight): it casts a shadow before the lamps (StationaryLightsService). + /// + public bool IsSpellLight { get; set; } + public int AffectedRendererCount => _affectedRenderers.Count; + public IReadOnlyList AffectedRenderers => _affectedRenderers; + + /// + /// The Unity light (objects/NPCs, shadows) - off for lights far from the camera (StationaryLightsService). + /// The pool's slot lights the world either way. + /// + public void SetUnityLightEnabled(bool isEnabled) + { + if (!_unityLight) + _unityLight = GetComponent(); + if (_unityLight.enabled != isEnabled) + _unityLight.enabled = isEnabled; + } + /// /// Color the pool writes into the shader slot it hands out (linear space). /// diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs index 957a7b95c..4fbc6e01a 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs @@ -51,6 +51,7 @@ private void Init(LightPresetLoader.LightPreset preset, float rangeMeters) _light.Color = preset.Color; _light.Range = Mathf.Max(0.01f, _baseRange); _light.RuntimeLinearColor = preset.Color.linear; + _light.IsSpellLight = true; _light.Init(); _gatheredAt = transform.position; Apply(); diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index be0547dfb..6388ca9dd 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -15,6 +15,15 @@ public static class IniNames { // Choice 0 Low / 1 Medium / 2 High: how often moving lights (torch, Light spell) update the world shader. public const string LightRefresh = "lightRefresh"; + // Choice 0 Off / 1 Hard / 2 Medium / 3 Soft (default): the dynamic shadows of the sun, moon and lights. + // Only where the quality level draws shadows at all (PC; Quest has none). + 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. + 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). public const string HitNumbers = "hitNumbers"; // 1 = "HP/MAX" on health bars (and "MANA/MAX" on the hero's mana bar), 0 = off (default). diff --git a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs index 920fe944e..9dbdcc042 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs @@ -20,17 +20,16 @@ public override GameObject Build() return RootGo; } + // Without an NPC (the VR hero body) the head mesh is built anyway - its shadow (VRHeroBody) - only the + // face animation setup is skipped. var npcContainer = RootGo.GetComponentInParent()?.Npc?.GetUserData(); - if (npcContainer == null) + if (npcContainer != null) { - Logger.LogWarning($"NpcContainer not available during head build for {RootGo.name} — skipping head component setup.", LogCat.Mesh); - return RootGo; + // Cache it for faster use during runtime + npcContainer.PrefabProps.Head = headGo.transform; + npcContainer.PrefabProps.HeadMorph = headGo.AddComponent().Inject(); + npcContainer.PrefabProps.HeadMorph.HeadName = npcContainer.Props.BodyData.Head; } - - // Cache it for faster use during runtime - npcContainer.PrefabProps.Head = headGo.transform; - npcContainer.PrefabProps.HeadMorph = headGo.AddComponent().Inject(); - npcContainer.PrefabProps.HeadMorph.HeadName = npcContainer.Props.BodyData.Head; // Fix for G1: Damlurker if (Mmb == null) diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index beb1ff979..716611168 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -653,6 +653,12 @@ private GameObject CreateLight(Light vob, GameObject parent, Vector3 worldPositi // A static light is in the world's lightmaps (EnableWorldLightmaps) - it lights VOBs and NPCs only. lightComp.IsBakedIntoWorld = vob.LightStatic && _stationaryLightsService.HasWorldLightmaps; + // Street lamps and camp fires dim by day (StationaryLightsService.SetDaylight) - not the lights under a + // light mapped ceiling (houses, caves, Khorinis' sewers below the market). + var isUnderCeiling = _stationaryLightsService.HasLightMappedCeiling(worldPosition); + lightComp.IsOutdoor = !isUnderCeiling; + // A light under a roof doesn't light the outside walls through the house (StationaryLighting.hlsl). + lightComp.IsIndoor = isUnderCeiling; // All world lights share the shader slots - the ones closest to the camera get them. lightComp.RuntimeLinearColor = lightComp.Color.linear; diff --git a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs index c47400a2d..2f5083c2c 100644 --- a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs +++ b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs @@ -253,7 +253,8 @@ public class DebugChannelTypesCollection : CollectionWrapper _isRaining; @@ -114,10 +143,12 @@ public void InitWorld() // Remove old world events if necessary. GlobalEventDispatcher.GameTimeSecondChangeCallback.RemoveListener(Interpolate); GlobalEventDispatcher.GameTimeHourChangeCallback.RemoveListener(UpdateRainTime); + GlobalEventDispatcher.PlayerPrefUpdated.RemoveListener(OnPlayerPrefUpdated); // And now re-add the events. GlobalEventDispatcher.GameTimeSecondChangeCallback.AddListener(Interpolate); GlobalEventDispatcher.GameTimeHourChangeCallback.AddListener(UpdateRainTime); + GlobalEventDispatcher.PlayerPrefUpdated.AddListener(OnPlayerPrefUpdated); _isIndoorWorld = _saveGameService.CurrentWorldData?.BspTree?.Type == ZenKit.BspTreeType.Indoor; Logger.Log($"[Sky] Indoor world: {_isIndoorWorld} - day/night light is " + @@ -140,6 +171,12 @@ public void InitWorld() private void InitSky() { RotateSun(_gameTimeService.GetCurrentDateTime()); + // Once per world: a second world load added a second listener. + GlobalEventDispatcher.GameTimeSecondChangeCallback.RemoveListener(RotateSun); + GlobalEventDispatcher.GameTimeMinuteChangeCallback.RemoveListener(RotateSun); + GlobalEventDispatcher.GameTimeHourChangeCallback.RemoveListener(RotateSun); + // Every game second (14 times a second, a 240th of a degree) the sun's shadows move smoothly; once per game + // minute they jumped. switch (_configService.Dev.SunUpdateInterval) { case GameTimeService.GameTimeInterval.EveryGameSecond: @@ -353,12 +390,20 @@ private void SetDayLight(Color polyColor) _polyColor = polyColor; // Indoor worlds (e.g. G1's Old Mine, Orc Temple) have no day/night - like in Gothic. // Indoors no sun - the engine's indoor sky lit the mines like the night. - var dayLight = _isIndoorWorld ? _indoorLight : polyColor; + var nightFactor = Mathf.Lerp(_nightLightFactor, 1f, + Mathf.InverseLerp(_nightBrightness, _duskBrightness, polyColor.grayscale)); + var rainFactor = Mathf.Lerp(1f, _rainLightFactor, _rainWeightAndVolume); + var dayLight = _isIndoorWorld ? _indoorLight : polyColor * (nightFactor * rainFactor); + dayLight.a = 1f; + // Outdoor lamps and fires dim by day. + _stationaryLightsService.SetDaylight(dayLight.grayscale); Shader.SetGlobalColor(_dayLightColorShaderId, dayLight); Shader.SetGlobalColor(_sunColorShaderId, _isIndoorWorld ? Color.black : _configService.Dev.SunLightColor * dayLight); Shader.SetGlobalColor(_ambientShaderId, _configService.Dev.AmbientLightColor * dayLight); + if (_sunLight != null) + _sunLight.color = _configService.Dev.SunLightColor * dayLight; } private void SetShaderProperties() @@ -497,10 +542,86 @@ private SkyState CreatePresetState(SkyState skyState, Action applyPres /// Calculation: 270f is the starting midnight value /// Calculation: One full DateTime == 360°. --> e.g. 15° * 24h + 0min + 0sec == 360° /// + /// + /// The sun rises at 6:00, stands highest at 12:00 and sets at 18:00 (one turn per day); at night the moon takes + /// the opposite place on the same path. _SunDirection was these angles themselves (not a direction) - the + /// shaders' N·L was a switch on the normal's x then. + /// private void RotateSun(DateTime time) { - var xRotation = 270f + 15f * (time.Hour + time.Minute / 60f + time.Second / 3600f); - _sunDirection = new Vector3(xRotation % 360, 0, 0); + var hours = time.Hour + time.Minute / 60f + time.Second / 3600f; + var sunDirection = GetSunPathDirection(270f + 15f * hours); + var isDay = sunDirection.y < 0f; + _sunDirection = isDay ? sunDirection : -sunDirection; + + var elevation = Mathf.Asin(Mathf.Clamp(-_sunDirection.y, -1f, 1f)) * Mathf.Rad2Deg; + _sunShadowFade = Mathf.Clamp01(elevation / _sunHorizonFadeDegrees); + + UpdateSunLight(isDay); + } + + private void OnPlayerPrefUpdated(string key, object value) + { + if (key == Constants.IniNames.Shadows) + ApplyShadowOption(); + } + + /// + /// Option "Shadows": off, hard (cheapest), medium or soft (wider filter, default) - the sun's/moon's shadow. + /// + private void ApplyShadowOption() + { + if (_sunLight == null) + return; + + var option = _configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue); + _sunLight.shadows = option switch + { + 0 => LightShadows.None, + 1 => LightShadows.Hard, + _ => LightShadows.Soft + }; + var lightData = _sunLight.GetUniversalAdditionalLightData(); + lightData.softShadowQuality = option == 2 ? SoftShadowQuality.Low : SoftShadowQuality.High; + Logger.Log($"[Sky] Shadows option {option}: sun {_sunLight.shadows}, soft quality " + + $"{lightData.softShadowQuality}.", LogCat.Loading); + } + + /// + /// Light direction for the angle on the sun's path (0 = sunrise, 90 = noon, from above), tilted by _sunPathTilt. + /// + private static Vector3 GetSunPathDirection(float pathAngle) + { + return Quaternion.AngleAxis(_sunPathTilt, Vector3.forward) * Quaternion.Euler(pathAngle, 0f, 0f) * + Vector3.forward; + } + + /// + /// The "Sun": a directional light along _sunDirection, URP's main light. Its shadow map gives the dynamic + /// shadows; its strength fades out at the horizon and is weaker under the moon. Indoor worlds have none. + /// The URP asset decides whether shadows are drawn at all (PC: on, Quest: off). + /// + private void UpdateSunLight(bool isDay) + { + if (_sunLight == null) + { + var sunGo = new GameObject("Sun"); + _sunLight = sunGo.AddComponent(); + _sunLight.type = LightType.Directional; + _sunLight.shadows = LightShadows.Soft; + _sunLight.intensity = 1f; + RenderSettings.sun = _sunLight; + Logger.Log("[Sky] Sun light created - dynamic sun/moon shadows where the quality level has them.", + LogCat.Loading); + ApplyShadowOption(); + } + + _sunLight.enabled = !_isIndoorWorld; + _sunLight.transform.rotation = Quaternion.LookRotation(_sunDirection); + Shader.SetGlobalVector(_sunDirectionShaderId, _sunDirection); + _sunLight.shadowStrength = (isDay ? _sunShadowStrength : _moonShadowStrength) * _sunShadowFade * + Mathf.Lerp(1f, _rainShadowFactor, _rainWeightAndVolume); + _sunLight.color = _configService.Dev.SunLightColor * _polyColor; } } } diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index c3d4fcc2b..849fc7cfd 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -8,6 +8,7 @@ using JetBrains.Annotations; using Reflex.Attributes; using UnityEngine; +using UnityEngine.Rendering.Universal; using Logger = Gothic.Core.Logging.Logger; namespace Gothic.Core.Services.World @@ -67,10 +68,49 @@ public class StationaryLightsService /// private const float _poolMaxDistance = 80f; + /// + /// Dynamic point light shadows (GD3D11-like): the lights closest to the camera (lamps, fires with a runtime slot) + /// become shadow casting URP lights; the shaders light them through URP with their cube shadow and the pool skips + /// them (w < 0 in the slot). URP reaches every object in their range - the pool only the renderers a light + /// gathered, Khorinis' market stayed dark under its lamps. Every one renders its surroundings 6 times, so only + /// 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. + private const int _minShadowLights = 4; + private const int _maxShadowLights = 12; + private const float _minShadowLightDistance = 20f; + private const float _maxShadowLightDistance = 50f; + private float ShadowRange => Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.ShadowRange, + Constants.IniNames.ShadowRangeDefaultValue)); + private int ShadowLightCount => Mathf.RoundToInt(Mathf.Lerp(_minShadowLights, _maxShadowLights, ShadowRange)); + private float ShadowLightMaxDistance => Mathf.Lerp(_minShadowLightDistance, _maxShadowLightDistance, ShadowRange); + // Geometry closer to the light than this casts no shadow: the lamp's cage casts its bars, not the flame's own + // mesh around the light. + private const float _shadowLightNearPlane = 0.05f; + private readonly HashSet _shadowLights = new(); + // Their Unity lights - GothicShadowLightsFeature finds them among URP's visible lights every frame. + private readonly HashSet _shadowUnityLights = new(); + + public bool HasShadowLights => _shadowUnityLights.Count > 0; + + public bool IsShadowLight(Light light) => _shadowUnityLights.Contains(light); + + /// + /// Only lights this close (m, minus their range) keep their Unity light enabled - URP takes 256 visible lights, + /// the city has ~770: turning the head pushed a lamp out of them, its light and shadow vanished. The Unity + /// light only lights objects/NPCs (and casts the shadow); the pool lights the world, also beyond this. + /// + private const float _unityLightMaxDistance = 40f; + private readonly HashSet _wantedShadowLights = new(); + private readonly List<(float Distance, StationaryLight Light)> _shadowCandidates = new(); + private HashSet _lightMappedCells = new(); private readonly Stack _freeRuntimeSlots = new(); // Who drives the hero light now - the last ClaimHeroLight wins, only it may update or release the slot. private object _heroLightOwner; + // The hero light's Unity light (torch, Light spell) - a dynamic shadow light while the option is on. + private Light _heroUnityLight; private readonly HashSet _pooledLights = new(); // Pooled lights in reach with their reach (distance to the camera minus range), sorted closest first. private readonly List<(float Reach, StationaryLight Light)> _pooledSorted = new(); @@ -150,6 +190,9 @@ public void RemoveLightOnRenderer(StationaryLight light, MeshRenderer renderer) } } + // Lights a renderer's material gets: 16 in _StationaryLightIndices (plants), 16 more in _StationaryLightIndices2. + private const int MaxAffectingLights = 16; + private void UpdateRenderer(MeshRenderer renderer) { if (!renderer) @@ -158,6 +201,19 @@ private void UpdateRenderer(MeshRenderer renderer) } var rendererLights = _lightsPerRenderer[renderer]; + // The shader takes 32 lights (16 on plants): the shadow casting ones first, then the closest. In slot order + // a big world chunk (Khorinis' market) didn't get the lamps right above it. + if (rendererLights.Count > MaxAffectingLights) + { + var center = renderer.bounds.center; + rendererLights.Sort((a, b) => + { + var aShadow = _shadowLights.Contains(a); + if (aShadow != _shadowLights.Contains(b)) + return aShadow ? -1 : 1; + return (a.CachedPosition - center).sqrMagnitude.CompareTo((b.CachedPosition - center).sqrMagnitude); + }); + } var nonAllocMaterials = _rendererMaterials; var indicesMatrix = Matrix4x4.identity; @@ -220,6 +276,11 @@ public StationaryLightsService() { GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ClearWorldLightmaps); GlobalEventDispatcher.MainMenuSceneLoaded.AddListener(ClearWorldLightmaps); + GlobalEventDispatcher.PlayerPrefUpdated.AddListener((key, _) => + { + if (key == Constants.IniNames.Shadows || key == Constants.IniNames.ShadowRange) + RefreshShadowLights(); + }); } /// @@ -307,7 +368,6 @@ public void ClearWorldChunks() public bool IsWorldLit(Renderer renderer) => _worldLitRenderers.Contains(renderer); // Lightmap light per cell (ToCell) of the light mapped world polygons, sampled at their centers by WorldMeshBuilder. private readonly Dictionary _lightmapCells = new(); - private MaterialPropertyBlock _vobLightBlock; /// /// The lightmap light of the world's light mapped polygons per cell (rgb summed, w = polygon count). @@ -378,15 +438,18 @@ public void ApplyWorldLight(GameObject vobGo) if (!light.HasValue) return; - _vobLightBlock ??= new MaterialPropertyBlock(); var tint = new Vector4(light.Value.r, light.Value.g, light.Value.b, 1f); foreach (var renderer in renderers) { if (renderer is MeshRenderer meshRenderer && IsWorldChunk(meshRenderer)) continue; - renderer.GetPropertyBlock(_vobLightBlock); - _vobLightBlock.SetVector(_vobLightTintShaderId, tint); - renderer.SetPropertyBlock(_vobLightBlock); + // Into the renderer's own materials (each has its own - UpdateRenderer writes its light indices there + // too), not a MaterialPropertyBlock: the SRP batcher skips renderers with one, ~1900 VOBs in Khorinis + // were drawn one by one in every pass (with the shadows: sun cascades, lamp cubes). + renderer.GetSharedMaterials(_rendererMaterials); + foreach (var material in _rendererMaterials) + if (material != null) + material.SetVector(_vobLightTintShaderId, tint); _worldLitRenderers.Add(renderer); } } @@ -495,6 +558,11 @@ public void InitStationaryLights() if (light != null && light.Index >= 0) light.DetachSlot(); _pooledLights.Clear(); + _shadowLights.Clear(); + _shadowUnityLights.Clear(); + _dynamicShadowLights.Clear(); + _dynamicShadowNearPlanes.Clear(); + _heroUnityLight = null; _poolPeak = 0; _isPoolDirty = true; @@ -508,8 +576,14 @@ public void InitStationaryLights() /// The owner (a burning torch, a Light spell) takes the hero light - there's one slot, so the previous owner's /// light goes dark (its updates are ignored from now on, IsHeroLightOwner tells it). /// - public void ClaimHeroLight(object owner) + public void ClaimHeroLight(object owner, Light unityLight = null) { + if (_heroUnityLight != null && _heroUnityLight != unityLight) + RemoveDynamicShadowLight(_heroUnityLight); + _heroUnityLight = unityLight; + // The torch's own stick and the hand would hide the flame - geometry closer than this casts nothing. + if (unityLight != null) + AddDynamicShadowLight(unityLight, _heroShadowNearPlane); if (_heroLightOwner != null && !ReferenceEquals(_heroLightOwner, owner)) Logger.Log($"[StationaryLights] Hero light taken over by {owner} from {_heroLightOwner}", LogCat.Vob); _heroLightOwner = owner; @@ -529,8 +603,13 @@ public bool UpdateHeroLight(object owner, Vector3 worldPosition, float rangeMete if (HeroLightIndex < 0 || _lightPositionsAndAttenuation == null) return true; // world not loaded yet + // w < 0: a shadow casting light, the shaders light it through URP (GothicShadowedLights). + var attenuation = 1f / (rangeMeters * rangeMeters); + var isShadowed = _heroUnityLight != null && _shadowUnityLights.Contains(_heroUnityLight); _lightPositionsAndAttenuation[HeroLightIndex] = new Vector4( - worldPosition.x, worldPosition.y, worldPosition.z, 1f / (rangeMeters * rangeMeters)); + worldPosition.x, worldPosition.y, worldPosition.z, isShadowed ? -attenuation : attenuation); + // Alpha 0: the hero's light reaches indoor and outdoor surfaces. + linearColor.a = 0f; _lightColors[HeroLightIndex] = linearColor; UploadGlobalLightArrays(); return true; @@ -545,6 +624,9 @@ public void ReleaseHeroLight(object owner) if (!IsHeroLightOwner(owner)) return; _heroLightOwner = null; + if (_heroUnityLight != null) + RemoveDynamicShadowLight(_heroUnityLight); + _heroUnityLight = null; if (HeroLightIndex < 0 || _lightPositionsAndAttenuation == null) return; @@ -573,6 +655,21 @@ public void SetLightMappedCells(HashSet cells) /// Gothic bakes a static light into the world's vertex light outdoors (we render that already) and into /// lightmaps indoors (caves, houses - we don't). Only lights next to light mapped polygons are worth a slot. /// + /// + /// Light mapped polygons in the 2 m column right above (2 to 8 m up): a roof or a ceiling - the position is + /// indoors (house, cave, sewer). Walls next to it don't count (Khorinis' street lamps stand next to light mapped + /// walls, the sewers' lamps below the open market). + /// + public bool HasLightMappedCeiling(Vector3 position) + { + for (var up = 1; up <= 4; up++) + { + if (_lightMappedCells.Contains(ToCell(position + Vector3.up * (up * _cellSize)))) + return true; + } + return false; + } + public bool IsNearLightMappedPolygons(Vector3 position, float rangeMeters) { if (_lightMappedCells.Count == 0) @@ -593,6 +690,8 @@ public bool IsNearLightMappedPolygons(Vector3 position, float rangeMeters) /// public void RegisterPooledLight(StationaryLight light) { + if (light.IsOutdoor) + light.Intensity = _outdoorLightFactor; if (_pooledLights.Add(light)) _isPoolDirty = true; } @@ -611,10 +710,8 @@ public void UpdatePooledLight(StationaryLight light) return; } - var position = light.CachedPosition; - _lightPositionsAndAttenuation[light.Index] = new Vector4(position.x, position.y, position.z, - 1f / Mathf.Max(0.01f, light.CachedRange * light.CachedRange)); - _lightColors[light.Index] = light.RuntimeLinearColor; + _lightPositionsAndAttenuation[light.Index] = GetSlotPositionAndAttenuation(light); + _lightColors[light.Index] = GetSlotColor(light); _isUploadDirty = true; } @@ -687,14 +784,15 @@ private void RebalancePool() continue; var slot = _freeRuntimeSlots.Pop(); - var position = light.CachedPosition; - _lightPositionsAndAttenuation[slot] = new Vector4(position.x, position.y, position.z, - 1f / (light.CachedRange * light.CachedRange)); - _lightColors[slot] = light.RuntimeLinearColor; light.AttachSlot(slot); + _lightPositionsAndAttenuation[slot] = GetSlotPositionAndAttenuation(light); + _lightColors[slot] = GetSlotColor(light); _isUploadDirty = true; } + UpdateShadowLights(camPos); + UpdateUnityLights(camPos); + if (_wantedLights.Count > _poolPeak) { _poolPeak = _wantedLights.Count; @@ -706,6 +804,8 @@ private void RebalancePool() private void FreeSlot(StationaryLight light) { + if (_shadowLights.Remove(light)) + SetLightShadow(light, false); var slot = light.Index; light.DetachSlot(); if (slot <= HeroLightIndex || slot >= _lightPositionsAndAttenuation.Length) @@ -717,6 +817,233 @@ private void FreeSlot(StationaryLight light) _isUploadDirty = true; } + private void UpdateUnityLights(Vector3 cameraPosition) + { + foreach (var light in _pooledLights) + { + if (light == null) + continue; + var isNear = Vector3.Distance(light.CachedPosition, cameraPosition) - light.CachedRange <= + _unityLightMaxDistance; + // A shadow casting light farther away needs its Unity light for the shadow. + light.SetUnityLightEnabled(isNear || _shadowLights.Contains(light)); + } + } + + /// + /// Outdoor lamps and fires by day: Gothic's lights burn all day, but its bright vertex light hid them. Ours are + /// stronger (StationaryLightFalloff) and the sun's shadow leaves 40% - lamps glowed red on shaded walls at noon. + /// Night (sky brightness up to _lampFullBrightness) full, noon _lampDayFactor. + /// + private const float _lampDayFactor = 0.2f; + private const float _lampFullBrightness = 0.35f; + private float _outdoorLightFactor = 1f; + + /// + /// SkyService: the world's day light changed (its brightness 0..1, indoor worlds dark). Outdoor lights follow. + /// + public void SetDaylight(float brightness) + { + var factor = Mathf.Lerp(1f, _lampDayFactor, Mathf.InverseLerp(_lampFullBrightness, 1f, brightness)); + if (Mathf.Abs(factor - _outdoorLightFactor) < 0.02f) + return; + + _outdoorLightFactor = factor; + if (_lightColors == null) + return; + foreach (var light in _pooledLights) + { + if (light == null || !light.IsOutdoor) + continue; + // The Unity light lights objects/NPCs and the shadow casting lamps' pools. + light.Intensity = factor; + if (light.Index > HeroLightIndex && light.Index < _lightColors.Length) + { + _lightColors[light.Index] = GetSlotColor(light); + _isUploadDirty = true; + } + } + } + + /// + /// The slot's color; its alpha marks an indoor light (StationaryLighting.hlsl: no light on outdoor surfaces). + /// + private Color GetSlotColor(StationaryLight light) + { + var color = light.IsOutdoor ? light.RuntimeLinearColor * _outdoorLightFactor : light.RuntimeLinearColor; + color.a = light.IsIndoor ? 1f : 0f; + return color; + } + + /// + /// Position and 1/range² of a slot - negative for a shadow casting light (the shaders look up its shadow). + /// + private Vector4 GetSlotPositionAndAttenuation(StationaryLight light) + { + var position = light.CachedPosition; + var attenuation = 1f / Mathf.Max(0.01f, light.CachedRange * light.CachedRange); + return new Vector4(position.x, position.y, position.z, + _shadowLights.Contains(light) ? -attenuation : attenuation); + } + + /// + /// The _maxShadowLights pooled lights closest to the camera cast shadows (option "Shadows" not off), the rest + /// not. Runs with the pool's rebalance (camera moved 2 m or every 2 s). + /// + private void UpdateShadowLights(Vector3 cameraPosition) + { + _shadowUnityLights.RemoveWhere(light => light == null); + _dynamicShadowLights.RemoveAll(light => light == null); + _shadowCandidates.Clear(); + _wantedShadowLights.Clear(); + var maxDistance = ShadowLightMaxDistance; + var maxCount = ShadowLightCount; + if (_configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue) > 0) + { + foreach (var light in _pooledLights) + { + if (light == null || light.Index <= HeroLightIndex || light.IsBakedIntoWorld || + !light.isActiveAndEnabled) + continue; + var distance = Vector3.Distance(light.CachedPosition, cameraPosition); + if (distance - light.CachedRange > maxDistance) + continue; + // Spell effects (summoning, fire rain) before lamps - they're short and right next to the hero. + _shadowCandidates.Add((light.IsSpellLight ? distance - maxDistance : distance, light)); + } + _shadowCandidates.Sort((a, b) => a.Distance.CompareTo(b.Distance)); + for (var i = 0; i < _shadowCandidates.Count && i < maxCount; i++) + _wantedShadowLights.Add(_shadowCandidates[i].Light); + } + + _shadowCandidates.Clear(); + foreach (var light in _shadowLights) + if (light == null || !_wantedShadowLights.Contains(light)) + _shadowCandidates.Add((0f, light)); + foreach (var (_, light) in _shadowCandidates) + { + _shadowLights.Remove(light); + if (light != null) + SetLightShadow(light, false); + } + + foreach (var light in _wantedShadowLights) + if (_shadowLights.Add(light)) + SetLightShadow(light, true); + } + + /// + /// Option "Shadows" changed: the shadow lights follow at once (off: none). + /// + public void RefreshShadowLights() + { + RefreshDynamicShadowLights(); + var cam = Camera.main; + if (cam == null || _lightPositionsAndAttenuation == null) + return; + foreach (var light in _shadowLights) + if (light != null) + SetLightShadow(light, true); + UpdateShadowLights(cam.transform.position); + } + + /// + /// Moving lights that cast shadows: the hero's torch / Light spell (ClaimHeroLight) and spell projectiles + /// (VRSpellThrow). URP renders their cube shadow every frame; the shaders light the world with them through + /// URP (GothicShadowLightsFeature) - before, a projectile's light only reached NPCs and objects. + /// Up to _maxDynamicShadowLights at once, more stay plain lights. + /// + private const int _maxDynamicShadowLights = 4; + private const float _heroShadowNearPlane = 0.2f; + private const float _dynamicShadowNearPlane = 0.15f; + private readonly List _dynamicShadowLights = new(); + private readonly Dictionary _dynamicShadowNearPlanes = new(); + + public void AddDynamicShadowLight(Light light, float nearPlane = _dynamicShadowNearPlane) + { + if (light == null || _dynamicShadowLights.Contains(light)) + return; + _dynamicShadowLights.RemoveAll(other => other == null); + if (_dynamicShadowLights.Count >= _maxDynamicShadowLights) + return; + + _dynamicShadowLights.Add(light); + _dynamicShadowNearPlanes[light] = nearPlane; + ApplyDynamicShadow(light); + } + + public void RemoveDynamicShadowLight(Light light) + { + if (light == null || !_dynamicShadowLights.Remove(light)) + return; + _dynamicShadowNearPlanes.Remove(light); + _shadowUnityLights.Remove(light); + light.shadows = LightShadows.None; + light.renderMode = LightRenderMode.Auto; + } + + private void RefreshDynamicShadowLights() + { + _dynamicShadowLights.RemoveAll(light => light == null); + foreach (var light in _dynamicShadowLights) + ApplyDynamicShadow(light); + } + + private void ApplyDynamicShadow(Light light) + { + var option = _configService.Gothic.GetInt(Constants.IniNames.Shadows, + Constants.IniNames.ShadowsDefaultValue); + var isOn = option > 0; + light.shadows = !isOn ? LightShadows.None : option == 1 ? LightShadows.Hard : LightShadows.Soft; + light.renderMode = isOn ? LightRenderMode.ForcePixel : LightRenderMode.Auto; + light.shadowNearPlane = _dynamicShadowNearPlanes.TryGetValue(light, out var nearPlane) + ? nearPlane + : _dynamicShadowNearPlane; + if (isOn) + { + light.GetUniversalAdditionalLightData().softShadowQuality = + option == 2 ? SoftShadowQuality.Low : SoftShadowQuality.High; + _shadowUnityLights.Add(light); + } + else + { + _shadowUnityLights.Remove(light); + } + } + + private void SetLightShadow(StationaryLight light, bool isOn) + { + var unityLight = light.GetComponent(); + if (unityLight == null) + return; + + var option = _configService.Gothic.GetInt(Constants.IniNames.Shadows, + Constants.IniNames.ShadowsDefaultValue); + unityLight.shadows = !isOn ? LightShadows.None : option == 1 ? LightShadows.Hard : LightShadows.Soft; + if (isOn) + _shadowUnityLights.Add(unityLight); + else + _shadowUnityLights.Remove(unityLight); + // URP's 8 lights per object: the shadow casting ones first. + unityLight.renderMode = isOn ? LightRenderMode.ForcePixel : LightRenderMode.Auto; + unityLight.shadowNearPlane = _shadowLightNearPlane; + if (isOn) + { + var lightData = unityLight.GetUniversalAdditionalLightData(); + lightData.softShadowQuality = option == 2 ? SoftShadowQuality.Low : SoftShadowQuality.High; + } + + if (light.Index > HeroLightIndex && light.Index < _lightPositionsAndAttenuation.Length) + { + _lightPositionsAndAttenuation[light.Index] = GetSlotPositionAndAttenuation(light); + _isUploadDirty = true; + } + // Its renderers re-sort their lights (UpdateRenderer: shadow casting ones first). + foreach (var renderer in light.AffectedRenderers) + if (renderer != null) + _dirtiedMeshes.Add(renderer); + } + private void UploadGlobalLightArrays() { // Unity exception: Zero sized arrays aren't allowed for Shader values. diff --git a/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset b/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset index f2a24f0f7..572cbc61c 100644 --- a/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset +++ b/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset @@ -1,5 +1,18 @@ %YAML 1.1 %TAG !u! tag:unity3d.com,2011: +--- !u!114 &-4152970174121565736 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: d964ebd92a12dd1428d2e982025fd22a, type: 3} + m_Name: GothicShadowLights + m_EditorClassIdentifier: Gothic.Core::Gothic.Core.Adapters.Rendering.GothicShadowLightsFeature + m_Active: 1 --- !u!114 &-1878332245247344467 MonoBehaviour: m_ObjectHideFlags: 0 @@ -13,8 +26,8 @@ MonoBehaviour: m_Name: SSAO m_EditorClassIdentifier: m_Active: 1 - m_Shader: {fileID: 4800000, guid: 0849e84e3d62649e8882e9d6f056a017, type: 3} m_Settings: + AOMethod: 1 Downsample: 0 AfterOpaque: 0 Source: 1 @@ -22,7 +35,10 @@ MonoBehaviour: Intensity: 0.5 DirectLightingStrength: 0.25 Radius: 0.25 - SampleCount: 12 + Samples: 0 + BlurQuality: 0 + Falloff: 100 + SampleCount: -1 --- !u!114 &11400000 MonoBehaviour: m_ObjectHideFlags: 0 @@ -36,30 +52,28 @@ MonoBehaviour: m_Name: URP-HighFidelity-Renderer m_EditorClassIdentifier: debugShaders: - debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7, - type: 3} + debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7, type: 3} + hdrDebugViewPS: {fileID: 4800000, guid: 573620ae32aec764abd4d728906d2587, type: 3} + probeVolumeSamplingDebugComputeShader: {fileID: 7200000, guid: 53626a513ea68ce47b59dc1299fe3959, type: 3} + probeVolumeResources: + probeVolumeDebugShader: {fileID: 0} + probeVolumeFragmentationDebugShader: {fileID: 0} + probeVolumeOffsetDebugShader: {fileID: 0} + probeVolumeSamplingDebugShader: {fileID: 0} + probeSamplingDebugMesh: {fileID: 0} + probeSamplingDebugTexture: {fileID: 0} + probeVolumeBlendStatesCS: {fileID: 0} m_RendererFeatures: - {fileID: -1878332245247344467} - m_RendererFeatureMap: adc0de57c6d2eee5 + - {fileID: -4152970174121565736} + m_RendererFeatureMap: adc0de57c6d2eee5d821b148a1af5dc6 m_UseNativeRenderPass: 0 + xrSystemData: {fileID: 0} postProcessData: {fileID: 11400000, guid: 41439944d30ece34e96484bdb6645b55, type: 2} - xrSystemData: {fileID: 11400000, guid: 60e1133243b97e347b653163a8c01b64, type: 2} - shaders: - blitPS: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3} - copyDepthPS: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3} - screenSpaceShadowPS: {fileID: 0} - samplingPS: {fileID: 4800000, guid: 04c410c9937594faa893a11dceb85f7e, type: 3} - stencilDeferredPS: {fileID: 4800000, guid: e9155b26e1bc55942a41e518703fe304, type: 3} - fallbackErrorPS: {fileID: 4800000, guid: e6e9a19c3678ded42a3bc431ebef7dbd, type: 3} - materialErrorPS: {fileID: 4800000, guid: 5fd9a8feb75a4b5894c241777f519d4e, type: 3} - coreBlitPS: {fileID: 4800000, guid: 93446b5c5339d4f00b85c159e1159b7c, type: 3} - coreBlitColorAndDepthPS: {fileID: 4800000, guid: d104b2fc1ca6445babb8e90b0758136b, - type: 3} - cameraMotionVector: {fileID: 4800000, guid: c56b7e0d4c7cb484e959caeeedae9bbf, - type: 3} - objectMotionVector: {fileID: 4800000, guid: 7b3ede40266cd49a395def176e1bc486, - type: 3} - m_AssetVersion: 2 + m_AssetVersion: 3 + m_PrepassLayerMask: + serializedVersion: 2 + m_Bits: 4294967295 m_OpaqueLayerMask: serializedVersion: 2 m_Bits: 4294967295 @@ -77,7 +91,7 @@ MonoBehaviour: m_RenderingMode: 0 m_DepthPrimingMode: 0 m_CopyDepthMode: 0 + m_DepthAttachmentFormat: 0 + m_DepthTextureFormat: 0 m_AccurateGbufferNormals: 0 - m_ClusteredRendering: 0 - m_TileSize: 32 m_IntermediateTextureMode: 1 diff --git a/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl new file mode 100644 index 000000000..f9a6bfddb --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl @@ -0,0 +1,81 @@ +// DepthOnly and DepthNormals passes of Gothic's lit shaders: the world, VOBs, NPCs and plants draw into URP's depth +// and normals textures - screen space ambient occlusion (the renderer's SSAO feature) needs them, without them it saw +// an empty world. Both eyes in one draw (single-pass instanced). +// Included inside the pass after the shader's own UnityPerMaterial buffer and textures. Options like +// GothicShadowCaster.hlsl: GOTHIC_SHADOW_ALPHA_CLIP (texture array alpha cut at _Cutoff), GOTHIC_SHADOW_FATNESS, +// the _WIND keyword. +#ifndef GOTHIC_DEPTH_PASSES_INCLUDED +#define GOTHIC_DEPTH_PASSES_INCLUDED + +struct GothicDepthAttributes +{ + float4 vertex : POSITION; + float3 normal : NORMAL; + float4 uv : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct GothicDepthVaryings +{ + float4 positionCS : SV_POSITION; + half3 normalWS : TEXCOORD0; +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + float4 uv : TEXCOORD1; +#endif + UNITY_VERTEX_OUTPUT_STEREO +}; + +GothicDepthVaryings GothicDepthVert(GothicDepthAttributes v) +{ + GothicDepthVaryings o = (GothicDepthVaryings)0; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + + float3 position = v.vertex.xyz; +#if defined(GOTHIC_SHADOW_FATNESS) + position += v.normal * _Fatness; +#endif + float3 positionWS = TransformObjectToWorld(position); +#if defined(_WIND) + positionWS = ApplyWind(positionWS); +#endif + o.positionCS = TransformWorldToHClip(positionWS); + o.normalWS = TransformObjectToWorldNormal(v.normal); +#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; +} + +void GothicDepthClip(GothicDepthVaryings i) +{ +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + float mipLevel = CalcMipLevel(i.uv.xy * _MainTex_TexelSize.zw); + half alpha = SAMPLE_TEXTURE2D_ARRAY_LOD(_MainTex, sampler_MainTex, i.uv.xy, i.uv.z, clamp(mipLevel, 0, i.uv.w)).a; + clip(alpha - _Cutoff); +#endif +} + +half GothicDepthFrag(GothicDepthVaryings i) : SV_Target +{ + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i); + GothicDepthClip(i); + return i.positionCS.z; +} + +half4 GothicDepthNormalsFrag(GothicDepthVaryings i) : SV_Target +{ + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i); + GothicDepthClip(i); + + float3 normalWS = normalize(i.normalWS); +#if defined(_GBUFFER_NORMALS_OCT) + float2 octNormalWS = PackNormalOctQuadEncode(normalWS); + float2 remappedOctNormalWS = saturate(octNormalWS * 0.5 + 0.5); + return half4(PackFloat2To888(remappedOctNormalWS), 0.0); +#else + return half4(normalWS, 0.0); +#endif +} + +#endif diff --git a/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl.meta b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl.meta new file mode 100644 index 000000000..76d182c3a --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6c53f5fa949160b4d90ba1a3982b516b +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl b/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl index 9c93c0a7a..78f07c859 100644 --- a/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl @@ -29,6 +29,16 @@ float CalcMipLevel(float2 uv) return max(0.0, 0.5 * log2(delta_max_sqr)); } +// Lamps and fires: a bit stronger than their Gothic color - the light sum stops at 1 (GothicClampLight), so pools +// next to each other don't burn out. +#define STATIONARY_LIGHT_STRENGTH 1.4 + +// 1 at the light, 0 at its range: 1 - (d/R)² keeps the pool's middle bright (linear 1 - d/R faded at once). +float StationaryLightFalloff(float distanceSqr, float oneOverRangeSqr) +{ + return saturate(1.0 - distanceSqr * oneOverRangeSqr) * STATIONARY_LIGHT_STRENGTH; +} + float CustomDistanceAttenuation(float distanceSqr, float rcpSqrRange) { return 1 - saturate(distanceSqr * rcpSqrRange); @@ -84,6 +94,13 @@ half3 SunAndAmbientDiffuse(float3 normal, half3 vertexShadowmap) return saturate(diffuseDot * _SunColor * vertexShadowmap + _AmbientColor); } +// The sun's part of SunAndAmbientDiffuse - per vertex; the fragment adds the ambient after the sun's shadow +// (GothicSunAndAmbient in GothicShadows.hlsl). +half3 SunDiffuse(float3 normal, half3 vertexShadowmap) +{ + return saturate(dot(normal, -_SunDirection)) * _SunColor * vertexShadowmap; +} + // Apply underwater color tinting when flag is enabled half3 ApplyUnderWaterEffect(half3 diffuse) { diff --git a/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl new file mode 100644 index 000000000..f3dd4e78d --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl @@ -0,0 +1,77 @@ +// ShadowCaster pass of Gothic's lit shaders: the world, VOBs, NPCs and plants draw into URP's shadow maps (the sun's +// cascades), so they cast dynamic shadows (GothicShadows.hlsl receives them). +// Included inside the pass after the shader's own UnityPerMaterial buffer and textures (same layout in every pass, else +// the SRP batcher breaks). Options, defined before the include: +// - 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. +#ifndef GOTHIC_SHADOW_CASTER_INCLUDED +#define GOTHIC_SHADOW_CASTER_INCLUDED + +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl" + +// Set by URP for the light whose shadow map is drawn. +float3 _LightDirection; +float3 _LightPosition; + +struct GothicShadowAttributes +{ + float4 vertex : POSITION; + float3 normal : NORMAL; + float4 uv : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct GothicShadowVaryings +{ + float4 positionCS : SV_POSITION; +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + float4 uv : TEXCOORD0; +#endif +}; + +GothicShadowVaryings GothicShadowVert(GothicShadowAttributes v) +{ + GothicShadowVaryings o = (GothicShadowVaryings)0; + UNITY_SETUP_INSTANCE_ID(v); + + float3 position = v.vertex.xyz; +#if defined(GOTHIC_SHADOW_FATNESS) + position += v.normal * _Fatness; +#endif + float3 positionWS = TransformObjectToWorld(position); +#if defined(_WIND) + positionWS = ApplyWind(positionWS); +#endif + float3 normalWS = TransformObjectToWorldNormal(v.normal); + +#if defined(_CASTING_PUNCTUAL_LIGHT_SHADOW) + float3 lightDirectionWS = normalize(_LightPosition - positionWS); +#else + float3 lightDirectionWS = _LightDirection; +#endif + float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirectionWS)); +#if UNITY_REVERSED_Z + positionCS.z = min(positionCS.z, UNITY_NEAR_CLIP_VALUE); +#else + positionCS.z = max(positionCS.z, UNITY_NEAR_CLIP_VALUE); +#endif + o.positionCS = positionCS; + +#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 +{ +#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 + return 0; +} + +#endif diff --git a/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl.meta b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl.meta new file mode 100644 index 000000000..ad0be5743 --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 96df4c82260f1094d9647db27fa5321f +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl new file mode 100644 index 000000000..c372368e3 --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl @@ -0,0 +1,132 @@ +// Dynamic sun/moon shadows on Gothic's light (GD3D11-like): the shadow only darkens the light that comes from the sun - +// Gothic's baked vertex light on outdoor polygons, the sun part of objects and NPCs. Ambient light, lightmaps and +// fires/torches stay. Surfaces facing away from the sun get no extra shadow: Gothic's vertex light already has it. +// The shadow map is URP's main light (the "Sun" light of SkyService); its shadowStrength follows the time of day. +// Without the shadow keywords (Quest, shadows off) GothicSunShadow is 1 and compiles away. +#ifndef GOTHIC_SHADOWS_INCLUDED +#define GOTHIC_SHADOWS_INCLUDED + +#if defined(_MAIN_LIGHT_SHADOWS) || defined(_MAIN_LIGHT_SHADOWS_CASCADE) || defined(_MAIN_LIGHT_SHADOWS_SCREEN) + #define GOTHIC_RECEIVE_SUN_SHADOWS +#endif + +// 1 = lit, down to 1 - shadowStrength in the sun's shadow. Faded out towards the shadow distance. +half GothicSunShadow(float3 worldPos) +{ +#if defined(GOTHIC_RECEIVE_SUN_SHADOWS) + float4 shadowCoord = TransformWorldToShadowCoord(worldPos); + half shadow = MainLightRealtimeShadow(shadowCoord); + return lerp(shadow, 1, GetMainLightShadowFade(worldPos)); +#else + return 1; +#endif +} + +// How much of a surface's light comes from the sun's direction: 0 facing away, 1 facing it (a soft edge, so the +// terminator doesn't show the shadow map's bias). _SunDirection points from the sun to the ground. +half GothicSunFacing(half3 normalWS) +{ + return saturate(dot(normalWS, -_SunDirection) * 4); +} + +// Screen space ambient occlusion (URP's SSAO feature, PC): indirect darkens Gothic's baked light and the ambient, +// direct (weaker, the feature's "direct lighting strength") the sun and the fires. 1 without SSAO. +struct GothicOcclusion +{ + half indirect; + half direct; +}; + +GothicOcclusion GothicGetOcclusion(float4 positionCS) +{ + GothicOcclusion occlusion; +#if defined(_SCREEN_SPACE_OCCLUSION) + AmbientOcclusionFactor ao = GetScreenSpaceAmbientOcclusion(GetNormalizedScreenSpaceUV(positionCS)); + occlusion.indirect = ao.indirectAmbientOcclusion; + occlusion.direct = ao.directAmbientOcclusion; +#else + occlusion.indirect = 1; + occlusion.direct = 1; +#endif + return occlusion; +} + +// Gothic's light is 0...1 per channel (8 bit vertex light): a lamp's pool next to another's and the baked light +// burnt the colors out (bright orange) - the sum stops at 1, like in the engine. +half3 GothicClampLight(half3 light) +{ + return min(light, 1.0); +} + +// Objects and plants: sun (shadowed) + ambient, both occluded - SunAndAmbientDiffuse per pixel. +half3 GothicSunAndAmbient(half3 sunDiffuse, float3 worldPos, GothicOcclusion occlusion) +{ + return saturate(sunDiffuse * GothicSunShadow(worldPos) * occlusion.direct + _AmbientColor * occlusion.indirect); +} + +// The few closest lamps, fires and torches are shadow casting URP lights (StationaryLightsService). True for such a +// light of the object's per-object lights. +bool GothicIsShadowedLight(int lightIndex) +{ +#if defined(_ADDITIONAL_LIGHT_SHADOWS) + return GetAdditionalLightShadowParams(lightIndex).w >= 0; +#else + return false; +#endif +} + +// This frame's shadow casting lights: their index among URP's additional lights (GothicShadowLightsFeature) - not +// the object's per-object list (8 lights, a big world chunk near candles didn't get the lamp). +float4 _GothicShadowLightIndices[16]; +float _GothicShadowLightCount; + +// The shadow casting lights, per pixel with their cube shadow. World and plants (isStationaryFalloff): like a +// stationary light (StationaryLightFalloff, no N·L, StationaryLighting.hlsl - which skips them). Objects and NPCs: like their +// other lights (AdditionalUnityLightDiffuse). +half3 GothicShadowedLights(float3 worldPos, half3 normalWS, bool isStationaryFalloff) +{ + half3 diffuse = 0; +#if defined(_ADDITIONAL_LIGHT_SHADOWS) + int count = min(64, (int)_GothicShadowLightCount); + for (int k = 0; k < count; k++) + { + int lightIndex = (int)_GothicShadowLightIndices[k / 4][k % 4]; + + #if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA + float4 lightPositionWS = _AdditionalLightsBuffer[lightIndex].position; + half3 color = _AdditionalLightsBuffer[lightIndex].color.rgb; + half4 distanceAndSpotAttenuation = _AdditionalLightsBuffer[lightIndex].attenuation; + #else + float4 lightPositionWS = _AdditionalLightsPosition[lightIndex]; + half3 color = _AdditionalLightsColor[lightIndex].rgb; + half4 distanceAndSpotAttenuation = _AdditionalLightsAttenuation[lightIndex]; + #endif + float3 lightVector = lightPositionWS.xyz - worldPos * lightPositionWS.w; + float distanceSqr = max(dot(lightVector, lightVector), HALF_MIN); + half3 lightDirection = half3(lightVector * rsqrt(distanceSqr)); + half attenuation = isStationaryFalloff + ? StationaryLightFalloff(distanceSqr, distanceAndSpotAttenuation.x) + : CustomDistanceAttenuation(distanceSqr, distanceAndSpotAttenuation.x) * + saturate(dot(lightDirection, normalWS)); + if (attenuation <= 0) + continue; + + half shadow = AdditionalLightRealtimeShadow(lightIndex, worldPos, lightDirection); + diffuse += color * attenuation * shadow * _PointLightIntensity; + } +#endif + return diffuse; +} + +// The baked light of a sun-facing surface, darkened by the shadow at worldPos. +half3 GothicApplySunShadow(half3 bakedLight, half3 normalWS, float3 worldPos) +{ +#if defined(GOTHIC_RECEIVE_SUN_SHADOWS) + half facing = GothicSunFacing(normalWS); + return bakedLight * lerp(1, GothicSunShadow(worldPos), facing); +#else + return bakedLight; +#endif +} + +#endif diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl.meta b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl.meta new file mode 100644 index 000000000..6d9d9c430 --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c875df6a4009fd646b06ed8ac85f2200 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader index d1fa3b28c..f6352d3a1 100644 --- a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader +++ b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader @@ -127,5 +127,46 @@ Shader "Lit/AlphaToCoverage-Dynamic" } ENDHLSL } + + // Highlighted (hovered by the hand) or faded objects keep their shadow - the swap to this shader dropped it. + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + AlphaToMask Off + Blend Off + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + #pragma editor_sync_compilation + + #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 _FocusBrightness; + CBUFFER_END + + #define GOTHIC_SHADOW_ALPHA_CLIP + #include "GothicIncludes.hlsl" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader index 368dc2a65..cda86ed24 100644 --- a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader +++ b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader @@ -25,6 +25,10 @@ Shader "Lit/AlphaToCoverage" #pragma multi_compile_fog #pragma multi_compile_instancing #pragma multi_compile_local _ _WIND + #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION + #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -45,6 +49,8 @@ Shader "Lit/AlphaToCoverage" float4 uv : TEXCOORD0; float distance : TEXCOORD1; float3 worldPos : TEXCOORD2; + // The sun's part (shadowed per pixel); diffuse: fires/torches. + half3 sunDiffuse : TEXCOORD3; half3 diffuse : COLOR; UNITY_VERTEX_OUTPUT_STEREO @@ -66,10 +72,12 @@ Shader "Lit/AlphaToCoverage" #include "GothicIncludes.hlsl" #include "StationaryLighting.hlsl" #include "GothicWind.hlsl" + #include "GothicShadows.hlsl" - half3 DiffuseLighting(half3 normal, float3 worldPos, half3 color) + // Fires/torches - the sun and the ambient come per pixel (SunAndAmbientShadowed). + half3 DiffuseLighting(half3 normal, float3 worldPos) { - half3 diffuse = SunAndAmbientDiffuse(normal, color); + half3 diffuse = 0; //for (int j = 0; j < min(MAX_VISIBLE_LIGHTS, unity_LightData.y); j++) //{ @@ -80,7 +88,10 @@ Shader "Lit/AlphaToCoverage" for (uint k = 0; k < min(_StationaryLightCount, MAX_AFFECTING_STATIONARY_LIGHTS); k++) { - diffuse += AdditionalStationaryDiffuse(_StationaryLightIndices[k / 4][k % 4], worldPos, normal); + uint lightIndex = _StationaryLightIndices[k / 4][k % 4]; + // Shadow casting lights come per pixel through URP (GothicShadowedLights). + if (!IsStationaryLightShadowed(lightIndex)) + diffuse += AdditionalStationaryDiffuse(lightIndex, worldPos, normal); } return diffuse; @@ -103,7 +114,9 @@ Shader "Lit/AlphaToCoverage" float3 toCamera = o.worldPos - _WorldSpaceCameraPos; o.distance = length(toCamera); o.uv = float4(v.uv.xy * REFERENCE_TEX_ARRAY_SIZE * _MainTex_TexelSize.xy, v.uv.zw); - o.diffuse = DiffuseLighting(TransformObjectToWorldNormal(v.normal), o.worldPos, v.color); + half3 normalWS = TransformObjectToWorldNormal(v.normal); + o.sunDiffuse = SunDiffuse(normalWS, v.color); + o.diffuse = DiffuseLighting(normalWS, o.worldPos); return o; } @@ -120,7 +133,10 @@ Shader "Lit/AlphaToCoverage" albedo.a = lerp((albedo.a - _Cutoff) / max(fwidth(albedo.a), 0.0001) + 0.5, albedo.a, saturate(max(i.distance, 0.0001) / _DistanceFade)); - half3 diffuse = albedo.rgb * i.diffuse; + GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); + half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + + (i.diffuse + GothicShadowedLights(i.worldPos, half3(0, 1, 0), true)) * occlusion.direct; + half3 diffuse = albedo.rgb * GothicClampLight(light); diffuse = ApplyUnderWaterEffect(diffuse); @@ -131,5 +147,119 @@ Shader "Lit/AlphaToCoverage" } ENDHLSL } + + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + 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 + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + + #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" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } + Pass + { + Name "DepthOnly" + Tags { "LightMode" = "DepthOnly" } + ZWrite On + ZTest LEqual + ColorMask R + AlphaToMask Off + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthFrag + #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" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } + Pass + { + Name "DepthNormals" + Tags { "LightMode" = "DepthNormals" } + ZWrite On + ZTest LEqual + AlphaToMask Off + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthNormalsFrag + #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" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader b/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader index 5512339ab..6f7a33a1e 100644 --- a/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader +++ b/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader @@ -110,5 +110,40 @@ Shader "Lit/SingleMesh-Dynamic" } ENDHLSL } + + // Highlighted (hovered by the hand) or faded objects keep their shadow - the swap to this shader dropped it. + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + AlphaToMask Off + Blend Off + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + #pragma editor_sync_compilation + + #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 _FocusBrightness; + float _Alpha; + float _Fatness; + CBUFFER_END + + #define GOTHIC_SHADOW_FATNESS + #include "GothicIncludes.hlsl" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader index c1d5d2dd5..ec2755634 100644 --- a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader +++ b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader @@ -22,6 +22,10 @@ Shader "Lit/SingleMesh" #pragma fragment frag #pragma multi_compile_fog #pragma multi_compile_instancing + #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION + #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -41,6 +45,9 @@ Shader "Lit/SingleMesh" float4 vertex : SV_POSITION; half2 uv : TEXCOORD0; float3 worldPos : TEXCOORD1; + // The sun's part (shadowed per pixel); diffuse: lights. + half3 sunDiffuse : TEXCOORD2; + half3 normalWS : TEXCOORD3; half3 diffuse : COLOR; UNITY_VERTEX_OUTPUT_STEREO @@ -57,14 +64,19 @@ Shader "Lit/SingleMesh" CBUFFER_END #include "GothicIncludes.hlsl" + #include "GothicShadows.hlsl" - half3 DiffuseLighting(half3 normal, float3 worldPos, half3 color) + // Lights - the sun and the ambient come per pixel (SunAndAmbientShadowed). + half3 DiffuseLighting(half3 normal, float3 worldPos) { - half3 diffuse = SunAndAmbientDiffuse(normal, color); + half3 diffuse = 0; for (int j = 0; j < min(MAX_VISIBLE_LIGHTS, unity_LightData.y); j++) { int lightIndex = GetPerObjectLightIndex(j); + // Shadow casting lights come per pixel (GothicShadowedLights). + if (GothicIsShadowedLight(lightIndex)) + continue; Light light = CustomGetAdditionalPerObjectLight(lightIndex, worldPos); diffuse += AdditionalUnityLightDiffuse(light, normal); } @@ -84,14 +96,20 @@ Shader "Lit/SingleMesh" o.worldPos = TransformObjectToWorld(position); o.vertex = TransformObjectToHClip(position); o.uv = TRANSFORM_TEX(v.uv, _MainTex); - o.diffuse = DiffuseLighting(TransformObjectToWorldNormal(v.normal), o.worldPos, v.color); + half3 normalWS = TransformObjectToWorldNormal(v.normal); + o.sunDiffuse = SunDiffuse(normalWS, v.color); + o.normalWS = normalWS; + o.diffuse = DiffuseLighting(normalWS, o.worldPos); return o; } half4 frag(v2f i) : SV_Target { half4 albedo = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv); - half3 diffuse = albedo.rgb * i.diffuse; + GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); + half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + + (i.diffuse + GothicShadowedLights(i.worldPos, normalize(i.normalWS), false)) * occlusion.direct; + half3 diffuse = albedo.rgb * GothicClampLight(light); diffuse = ApplyUnderWaterEffect(diffuse); @@ -102,5 +120,86 @@ Shader "Lit/SingleMesh" } ENDHLSL } + + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + // 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_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + + #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" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } + Pass + { + Name "DepthOnly" + Tags { "LightMode" = "DepthOnly" } + ZWrite On + ZTest LEqual + ColorMask R + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthFrag + #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" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } + Pass + { + Name "DepthNormals" + Tags { "LightMode" = "DepthNormals" } + ZWrite On + ZTest LEqual + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthNormalsFrag + #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" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/Lit-World.shader b/Assets/Gothic-Core/Shaders/Lit-World.shader index 1a0f2d4f2..5505271e5 100644 --- a/Assets/Gothic-Core/Shaders/Lit-World.shader +++ b/Assets/Gothic-Core/Shaders/Lit-World.shader @@ -27,12 +27,15 @@ Shader "Lit/World" #pragma multi_compile_fog #pragma multi_compile_instancing #pragma multi_compile_local _ _WIND + // Dynamic sun/moon shadows (GothicShadows.hlsl) - only where the URP asset has main light shadows. + #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION + #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" - float _FocusBrightness; - struct appdata { float4 vertex : POSITION; @@ -53,7 +56,8 @@ Shader "Lit/World" float4 uv : TEXCOORD0; float3 worldPos : TEXCOORD1; float4 lightmapUv : TEXCOORD2; - half3 normal : TEXCOORD3; + // w = 1 where the sun reaches: outdoor (vertex lit) polygons and VOBs outside of light mapped areas. + half4 normal : TEXCOORD3; half3 baseLight : COLOR; UNITY_VERTEX_OUTPUT_STEREO @@ -68,6 +72,8 @@ Shader "Lit/World" SAMPLER(sampler_WorldLightmaps); float _WorldLightmapBrightness; + // Every material property in here, the same in every pass - else the SRP batcher skips the world and + // every pass (sun cascades, lamp cube shadows, depth for SSAO) draws chunk by chunk. CBUFFER_START(UnityPerMaterial) float4 _MainTex_TexelSize; int _StationaryLightCount; @@ -75,27 +81,35 @@ Shader "Lit/World" float4x4 _StationaryLightIndices2; float _WindStrength; float4 _VobLightTint; + float _FocusBrightness; CBUFFER_END #include "GothicIncludes.hlsl" #include "StationaryLighting.hlsl" #include "GothicWind.hlsl" + #include "GothicShadows.hlsl" // Per pixel: per vertex a torch in the middle of a big cave wall lit nothing (its corners are far away). - half3 StationaryLighting(half3 normal, float3 worldPos) + // isOutdoorSurface: vertex lit polygons and VOBs outside light mapped areas - indoor lights 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++) { - diffuse += AdditionalStationaryDiffuse(_StationaryLightIndices[k / 4][k % 4], worldPos, normal); + uint lightIndex = _StationaryLightIndices[k / 4][k % 4]; + if (!IsStationaryLightShadowed(lightIndex) && + !(isOutdoorSurface && IsStationaryLightIndoor(lightIndex))) + diffuse += AdditionalStationaryDiffuse(lightIndex, worldPos, normal); } if (_StationaryLightCount >= MAX_AFFECTING_STATIONARY_LIGHTS) { for (uint l = 0; l < min(_StationaryLightCount - MAX_AFFECTING_STATIONARY_LIGHTS, MAX_AFFECTING_STATIONARY_LIGHTS); l++) { - diffuse += AdditionalStationaryDiffuse(_StationaryLightIndices2[l / 4][l % 4], worldPos, - normal); + uint lightIndex2 = _StationaryLightIndices2[l / 4][l % 4]; + if (!IsStationaryLightShadowed(lightIndex2) && + !(isOutdoorSurface && IsStationaryLightIndoor(lightIndex2))) + diffuse += AdditionalStationaryDiffuse(lightIndex2, worldPos, normal); } } return diffuse; @@ -117,7 +131,7 @@ Shader "Lit/World" #endif o.uv = float4(v.uv.xy * REFERENCE_TEX_ARRAY_SIZE * _MainTex_TexelSize.xy, v.uv.zw); o.lightmapUv = v.lightmapUv; - o.normal = TransformObjectToWorldNormal(v.normal.xyz); + o.normal = half4(TransformObjectToWorldNormal(v.normal.xyz), v.normal.w * (1 - _VobLightTint.a)); // Gothic's baked vertex light; outdoor polygons follow the time of day. o.baseLight = v.color * lerp(half3(1, 1, 1), _DayLightColor, v.normal.w); // A VOB standing in a cave/house takes the light of the floor below it, like the engine's VOB lighting. @@ -139,8 +153,19 @@ Shader "Lit/World" i.lightmapUv.z).rgb * _WorldLightmapBrightness; } - half3 light = baseLight + StationaryLighting(normalize(i.normal), i.worldPos); - half3 diffuse = albedo.rgb * light * _FocusBrightness; + half3 normal = normalize(i.normal.xyz); + // The sun's shadow darkens Gothic's baked (sun) light outdoors - not lightmaps, not the fires. + if (i.normal.w > 0.5) + { + baseLight = GothicApplySunShadow(baseLight, normal, i.worldPos); + } + + GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); + half3 light = baseLight * occlusion.indirect + + (StationaryLighting(normal, i.worldPos, i.normal.w > 0.5) + + GothicShadowedLights(i.worldPos, normal, true)) * + occlusion.direct; + half3 diffuse = albedo.rgb * GothicClampLight(light) * _FocusBrightness; diffuse = ApplyUnderWaterEffect(diffuse); @@ -151,5 +176,104 @@ Shader "Lit/World" } ENDHLSL } + + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + // 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 + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + + #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" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } + Pass + { + Name "DepthOnly" + Tags { "LightMode" = "DepthOnly" } + ZWrite On + ZTest LEqual + ColorMask R + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthFrag + #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" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } + Pass + { + Name "DepthNormals" + Tags { "LightMode" = "DepthNormals" } + ZWrite On + ZTest LEqual + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthNormalsFrag + #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" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl index ab17a16f0..255c7588c 100644 --- a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl +++ b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl @@ -11,7 +11,23 @@ #define MAX_AFFECTING_STATIONARY_LIGHTS 16 float4 _GlobalStationaryLightPositionsAndAttenuation[MAX_TOTAL_STATIONARY_LIGHTS]; -real3 _GlobalStationaryLightColors[MAX_TOTAL_STATIONARY_LIGHTS]; +// rgb: color, a: 1 = indoor light (under a light mapped ceiling, IsStationaryLightIndoor). Same 16 byte stride as +// the former real3. +real4 _GlobalStationaryLightColors[MAX_TOTAL_STATIONARY_LIGHTS]; + +// 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; +} + +bool IsStationaryLightShadowed(uint lightIndex) +{ + return _GlobalStationaryLightPositionsAndAttenuation[lightIndex].w < 0; +} half3 AdditionalStationaryDiffuse(uint lightIndex, real3 worldPos, real3 normal) { @@ -19,10 +35,10 @@ half3 AdditionalStationaryDiffuse(uint lightIndex, real3 worldPos, real3 normal) float3 lightVector = lightPosAndAttenuation.xyz - worldPos; float distanceSqr = max(dot(lightVector, lightVector), HALF_MIN); - // Linear distance falloff (1 - d/R) - float attenuation = saturate(1.0 - sqrt(distanceSqr * lightPosAndAttenuation.w)); + // w = 1/R², negative for a shadow casting light. + float attenuation = StationaryLightFalloff(distanceSqr, abs(lightPosAndAttenuation.w)); - return _GlobalStationaryLightColors[lightIndex] * attenuation * _PointLightIntensity; + return _GlobalStationaryLightColors[lightIndex].rgb * attenuation * _PointLightIntensity; } #endif diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs index b713ff5bf..8dffec994 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs @@ -56,6 +56,9 @@ public class VRHeroBody : MonoBehaviour private const float _torsoBackOffset = 0.15f; private const float _hiddenBoneScale = 0.001f; + // A copy of the head (and what sits on it - helmet, hood) that only casts the shadow: the head bone is scaled + // away so the camera never sees inside it, the shadow had no head. Follows the head bone every frame. + private Transform _shadowHead; private const string _headBoneName = "BIP01 HEAD"; private const float _minScale = 0.5f; private const float _maxScale = 1.3f; @@ -230,7 +233,10 @@ private void LateUpdate() var feetY = rig.Root.position.y; if (_downPose.UpdateDown(head, feetY, _standingScale, rig)) + { + UpdateShadowHead(); return; + } // Crouching (sneaking) lowers the head, not the body size - keep the standing scale then. The crouch // button's camera offset doesn't count: standing up the camera rises slowly, the body shrank and grew // with it. @@ -258,6 +264,7 @@ private void LateUpdate() } SolveArms(); + UpdateShadowHead(); } /// @@ -291,6 +298,47 @@ private void UpdateCrouchHeight(IVrRig rig, float scale) rig.CrouchHeightOverride = height; } + /// + /// Shadow-only copies of the renderers on the head bone (before it's scaled away), under an anchor that follows + /// the bone (UpdateShadowHead). The camera never draws them, the lights do. + /// + private void CreateShadowHead() + { + var headRenderers = _headBone.GetComponentsInChildren(true); + if (headRenderers.Length == 0) + return; + + _shadowHead = new GameObject("_ShadowHead").transform; + _shadowHead.SetParent(_body.transform, false); + _shadowHead.SetPositionAndRotation(_headBone.position, _headBone.rotation); + foreach (var headRenderer in headRenderers) + { + var meshFilter = headRenderer.GetComponent(); + if (meshFilter == null || meshFilter.sharedMesh == null) + continue; + + var copy = new GameObject(headRenderer.name); + copy.transform.SetParent(_shadowHead, false); + copy.transform.SetPositionAndRotation(headRenderer.transform.position, headRenderer.transform.rotation); + copy.transform.localScale = headRenderer.transform.lossyScale; + copy.AddComponent().sharedMesh = meshFilter.sharedMesh; + var copyRenderer = copy.AddComponent(); + copyRenderer.sharedMaterials = headRenderer.sharedMaterials; + copyRenderer.shadowCastingMode = ShadowCastingMode.ShadowsOnly; + copyRenderer.allowOcclusionWhenDynamic = false; + // The original sits on the scaled-away bone: off, also when the body's visibility switches back. + headRenderer.enabled = false; + _renderers.Remove(headRenderer); + _renderers.Add(copyRenderer); + } + } + + private void UpdateShadowHead() + { + if (_shadowHead != null && _headBone != null) + _shadowHead.SetPositionAndRotation(_headBone.position, _headBone.rotation); + } + private void SolveArms() { GetSecondHandGripPoses(out var leftGrip, out var rightGrip); @@ -411,7 +459,8 @@ private void EnsureBody(NpcContainer hero) _renderers.AddRange(_body.GetComponentsInChildren(true)); foreach (var r in _renderers) { - r.shadowCastingMode = ShadowCastingMode.Off; + // The hero's own shadow (sun, lamps, torch) - immersion; the body is lit, its shadow was missing. + r.shadowCastingMode = ShadowCastingMode.On; if (_bodyRenderer == null && r is SkinnedMeshRenderer skinnedRenderer) _bodyRenderer = skinnedRenderer; } @@ -447,6 +496,7 @@ private void EnsureBody(NpcContainer hero) foreach (var bone in bones.Values) lowestY = Mathf.Min(lowestY, bone.position.y); _modelHeadHeight = Mathf.Max(0.5f, _headBone.position.y - lowestY + _neckBelowEyes); + CreateShadowHead(); _headBone.localScale = Vector3.one * _hiddenBoneScale; } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs index 6593fb4b5..c844ff8eb 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs @@ -156,7 +156,7 @@ public void Build(GameObject body, NpcProperties props, string mdhName, armorBones.TryGetValue(nakedRenderer.rootBone.name.ToUpperInvariant(), out var rootBone)) forearm.rootBone = rootBone; forearm.updateWhenOffscreen = true; - forearm.shadowCastingMode = ShadowCastingMode.Off; + forearm.shadowCastingMode = ShadowCastingMode.On; forearm.enabled = false; _bareForearms.Add(forearm); _bareForearmMeshes[forearm] = (forearmMesh, diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs index ba14a048c..f1c74288c 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs @@ -519,7 +519,8 @@ public void ToggleLightSpell() stationaryLight.Range = _lightRange; stationaryLight.Intensity = _lightIntensity; stationaryLight.Index = _stationaryLightsService.HeroLightIndex; - _stationaryLightsService.ClaimHeroLight(lightGo); + // Its Unity light casts the Light spell's shadow (Shadows option). + _stationaryLightsService.ClaimHeroLight(lightGo, stationaryLight.GetComponent()); stationaryLight.Init(); _meshService.CreateVobPfx("MFX_LIGHT_INIT", parent: lightGo); diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs index 8122ce638..b52a77e2c 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs @@ -11,6 +11,7 @@ using Gothic.Core.Services.Npc; using Gothic.VR.Interaction.Models; using Gothic.VR.Services; +using Gothic.Core.Services.World; using Reflex.Attributes; using UnityEngine; using ZenKit.Daedalus; @@ -30,6 +31,7 @@ public class VRSpellThrow [Inject] private readonly MeshService _meshService; [Inject] private readonly VmCacheService _vmCacheService; [Inject] private readonly MultiTypeCacheService _multiTypeCacheService; + [Inject] private readonly StationaryLightsService _stationaryLightsService; private readonly ParticleEffectEmitKeyInstance _castKey; private readonly string _mfxName; @@ -197,6 +199,9 @@ public void Throw(Vector3 origin, Vector3 direction, int level, int investLevel, light.range = 3f; light.intensity = 2f; light.color = GetSpellLightColor(mfxName); + // A flying fireball lights the walls it passes and throws shadows (Shadows option) - gone with the + // projectile (the service drops destroyed lights). + _stationaryLightsService.AddDynamicShadowLight(light); var homingTarget = lockedTarget?.Go != null ? lockedTarget diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs index 156535c15..52ae749a7 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs @@ -94,7 +94,8 @@ private void Light() _light.Range = visual.LightRange; _light.Intensity = 1f; _light.Index = _stationaryLightsService.HeroLightIndex; - _stationaryLightsService.ClaimHeroLight(this); + // Its Unity light casts the torch's shadow (Shadows option). + _stationaryLightsService.ClaimHeroLight(this, _light.GetComponent()); _light.Init(); StartCoroutine(DriveLight(visual)); diff --git a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs index 519fa7535..f746ed1e6 100644 --- a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs +++ b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs @@ -140,7 +140,9 @@ public void UpdateMainMenu(AbstractMenuInstance mainMenu) CreateToggleChoice(gameMenu, "HEALTH_NUMBERS", Constants.IniNames.HealthNumbers)), (CreateToggleLabel(gameMenu, "DIALOG_FREE_MOVEMENT", "dialogFreeMovement"), CreateToggleChoice(gameMenu, "DIALOG_FREE_MOVEMENT", Constants.IniNames.DialogFreeMovement)), - (CreateToggleLabel(gameMenu, "LIGHT_REFRESH", "lightRefresh"), CreateLightRefreshChoice(gameMenu)) + (CreateToggleLabel(gameMenu, "LIGHT_REFRESH", "lightRefresh"), CreateLightRefreshChoice(gameMenu)), + (CreateToggleLabel(gameMenu, "SHADOWS", "shadows"), CreateShadowsChoice(gameMenu)), + (CreateToggleLabel(gameMenu, "SHADOW_RANGE", "shadowRange"), CreateShadowRangeSlider(gameMenu)) }; // DeveloperConfig.EnableHeroHands: the hero's own fists instead of the VR hand models (needs the hero body). if (_configService.Dev.EnableHeroHands && _configService.Dev.EnableVrHeroBody) @@ -274,6 +276,34 @@ private MutableMenuItemInstance CreateLightRefreshChoice(AbstractMenuInstance ga return item; } + /// + /// Dynamic shadows (Core, SkyService): off, hard, medium, soft - slower PCs pick hard or off. + /// + private MutableMenuItemInstance CreateShadowsChoice(AbstractMenuInstance gameMenu) + { + var item = CreateToggleChoice(gameMenu, "SHADOWS", Constants.IniNames.Shadows, + Constants.IniNames.ShadowsDefaultValue); + item.SetText(0, _localizationService.GetText("menuitem.shadows.value")); + return item; + } + + /// + /// How many lamps/fires cast shadows and how far (Core, StationaryLightsService) - slower PCs slide it down. + /// + private AbstractMenuItemInstance CreateShadowRangeSlider(AbstractMenuInstance gameMenu) + { + var mouseSlider = gameMenu.FindMenuItem("MENUITEM_MSENSITIVITY_SLIDER", out _); + var slider = new MutableMenuItemInstance("MENUITEM_GOTHIC_OPT_VR_IMMERSION_SHADOW_RANGE_SLIDER", + mouseSlider); + + slider.SetUserFloat(0, VRConstants.SmoothRotationSettingAmount); // Steps. + slider.SetUserFloat(3, Constants.IniNames.ShadowRangeDefaultValue); + slider.OnChgSetOption = Constants.IniNames.ShadowRange; + slider.OnChgSetOptionSection = VRConstants.IniSectionImmersion; + + return slider; + } + private AbstractMenuItemInstance CreateHitNumbersSizeSlider(AbstractMenuInstance gameMenu) { var mouseSlider = gameMenu.FindMenuItem("MENUITEM_MSENSITIVITY_SLIDER", out _); diff --git a/Docs/adr/2026-11-22-pcvr-shadows-lighting.md b/Docs/adr/2026-11-22-pcvr-shadows-lighting.md new file mode 100644 index 000000000..19033e401 --- /dev/null +++ b/Docs/adr/2026-11-22-pcvr-shadows-lighting.md @@ -0,0 +1,27 @@ +# ADR: Dynamic shadows and lighting on PC (GD3D11-like) + +- Date: 2026-11-22 +- Technical details: Docs/world-lighting.md (section "Shadows and darkness") + +## Context + +Gothic bakes its lighting: the sun's shadows are in the world's vertex light, the light of lamps and fires is in the lightmaps or added flat. Nothing casts a shadow at runtime, and at night the world stays fairly bright. GD3D11, the well-known D3D11 renderer mod for the original games, adds dynamic sun shadows, shadows of lamps and fires, ambient occlusion and darker nights, while keeping Gothic's look. In VR these shadows make a big difference to immersion. Our shaders could neither cast nor receive shadows, and the world had no sun light. The shaders' "sun direction" was a set of angles, not a direction. + +## Decisions + +1. **The sun and moon cast dynamic shadows on PC.** The sun rises at 6, is highest at 12 (60 degrees, so shadows never vanish under objects) and sets at 18. At night the moon takes its place with a weaker shadow, and the shadows fade out at the horizon. The shadow darkens only the sun's part of the light, so lightmaps, ambient light and fires stay as they are. That is how GD3D11 does it, and it keeps the baked Gothic look. Not chosen: replacing Gothic's baked light with Unity's lighting, which would be a different game. +2. **The few lights closest to the player cast shadows too.** 4 to 12 lamps and fires within 20 to 50 m (not lights baked into lightmaps; the "Shadow range" option) get a real shadow: a street lamp throws its iron cage onto the ground, NPCs and the hero cast shadows in it. The hero's torch, the Light spell and spell projectiles cast shadows as well. Every such light renders its surroundings six times per frame - with 40 of them the frame rate tanked - so all lights casting shadows this way would be far too expensive. Not chosen: shadows for every light. +3. **A light under a roof doesn't light outdoor surfaces.** A light whose position has a light mapped ceiling above (house, cave, sewer) skips vertex lit polygons and VOBs outside light mapped areas: the candles in a house no longer glow on its outside walls and the street. A stand-in for a real shadow where the light has none. +4. **The VR hero's body casts its shadow.** The head is scaled away so the camera doesn't see into it; a shadow-only copy of it casts the head's shadow, the camera never draws it. +5. **Ambient occlusion on PC.** It gives soft contact shadows in corners and under objects, and darkens the baked and ambient light more than the sun and fires (like GD3D11). +6. **Gothic's light stops at full brightness.** Lamps next to each other no longer burn the colors out. The engine's 8-bit vertex light worked the same way. +7. **Nights, mines and rain are darker; lamps and fires outdoors dim by day.** Lights stand out at night, mines are lit by their lamps and the hero's torch, and a street lamp doesn't glow on a shaded wall at noon. Lights under a roof (houses, caves, sewers) stay as they are. Gothic's lamps burn all day too, but its bright vertex light hid them. Ours are stronger, so we dim them, which is a deliberate difference from the original. +8. **Options in the VR Immersion menu: "Shadows" (off, hard, medium, soft; default soft) and "Shadow range" (how many lamps get a shadow).** Not every PC is fast. Quest stays without shadows and ambient occlusion: its quality level has them off. +9. **Gothic's world shader stays SRP batcher compatible.** Every pass of Lit/World has the same material buffer with every material property, and VOBs get their lightmap tint in their own material, not in a property block. Without it every shadow pass drew the world chunk by chunk (3100 SetPass calls in Khorinis, 190 with it). + +## Consequences + +- PC costs GPU time for the shadow maps (the sun's cascades plus up to 12 point lights) and ambient occlusion. Players with slower PCs pick hard shadows, a shorter shadow range or switch them off. +- Lamps beyond the shadow range have no shadow; walls between them and the player don't stop their light (only the roof rule of decision 3). Lights baked into lightmaps cast none. +- New Gothic shader passes must keep the material buffer identical, or the SRP batcher drops the world again. +- Not done in this step: height fog, god rays, bloom and tonemapping, water reflections. diff --git a/Docs/world-lighting.md b/Docs/world-lighting.md index 4e720ef16..5c7f27914 100644 --- a/Docs/world-lighting.md +++ b/Docs/world-lighting.md @@ -58,3 +58,29 @@ Core code is in `Assets/Gothic-Core/Scripts/`. | Rule | Lives in | |------|----------| | A world whose BSP tree is indoor (mines, temples) has no sun and no fog, the time of day doesn't darken it | `Services/World/SkyService.cs` | + +## Shadows and darkness + +Why: Docs/adr/2026-11-22-pcvr-shadows-lighting.md. PC only - the Quest quality level (URP-Performant) draws no shadows +and no SSAO, the shaders compile those parts away there. + +| Rule | Lives in | +|------|----------| +| The "Sun" directional light is URP's main light (shadow map only, Gothic's shaders take `_SunColor`): rises 6:00, highest 12:00 (60°, path tilted), sets 18:00; at night the moon on the same path with a weaker shadow, faded out at the horizon. Moves every game second | `Services/World/SkyService.cs` (`RotateSun`, `UpdateSunLight`), `DeveloperConfig.SunUpdateInterval` | +| `_SunDirection` is the light's direction (sun/moon to the ground) - it used to be Euler angles | `SkyService`, `Shaders/GothicIncludes.hlsl` | +| Gothic's lit shaders cast shadows with the main pass' wind, alpha cut (plants) and fatness (NPCs); depth/normals passes feed SSAO | `Shaders/GothicShadowCaster.hlsl`, `Shaders/GothicDepthPasses.hlsl` | +| 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` | +| 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) | +| Their index among URP's additional lights, every frame - URP's 8 per-object lights cut a lamp off at a world chunk's edge | `Adapters/Rendering/GothicShadowLightsFeature.cs` (on `URP-HighFidelity-Renderer`) | +| Only Unity lights within 40 m stay enabled: URP takes 256 visible lights, the city has ~770 | `StationaryLightsService.UpdateUnityLights` | +| Renderers list their lights shadow casting first, then closest | `StationaryLightsService.UpdateRenderer` | +| Lamps/fires: falloff 1 - (d/R)², strength 1.4; the light sum stops at 1 like Gothic's 8 bit vertex light | `GothicIncludes.hlsl` (`StationaryLightFalloff`), `GothicShadows.hlsl` (`GothicClampLight`) | +| Nights: the world gets 50% of the night sky's light; rain 70% and a 35% sun shadow; indoor worlds (mines) 0.12 | `SkyService` (`SetDayLight`) | +| Outdoor lamps/fires (no light mapped ceiling 2-8 m above) dim by day: 100% at night, 20% at noon | `StationaryLightsService.SetDaylight`, `HasLightMappedCeiling`, `VobInitializerDomain.CreateLight` | +| Option "Shadows" (Immersion, Gothic.ini `shadows`): 0 off, 1 hard, 2 medium, 3 soft (default) - sun and point lights | `Constants.IniNames.Shadows`, `VRContextMenuService.CreateShadowsChoice` | +| Option "Shadow range" (Immersion, Gothic.ini `shadowRange`, slider 0..1, default 0.75) | `Constants.IniNames.ShadowRange`, `VRContextMenuService.CreateShadowRangeSlider` | +| Lit/World is SRP batcher compatible: every pass has the same `UnityPerMaterial` with every material property (`_FocusBrightness` too); the VOB lightmap tint goes into the renderer's own material, no MaterialPropertyBlock. Check: `ShaderUtil.GetSRPBatcherCompatibilityCode` | `Shaders/Lit-World.shader`, `StationaryLightsService.ApplyWorldLight` |