Decompiled source of ShadowThrottle v0.6.0

ShadowThrottle.dll

Decompiled 4 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ShadowThrottle")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.6.0.0")]
[assembly: AssemblyInformationalVersion("0.6.0+64fd544189cb9cb2e5acbb238d4985002846feb6")]
[assembly: AssemblyProduct("ShadowThrottle")]
[assembly: AssemblyTitle("ShadowThrottle")]
[assembly: AssemblyVersion("0.6.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ShadowThrottle
{
	internal static class AtlasSetup
	{
		public static int MaxPunctualRes = 0;

		public static int MaxDirectionalRes = 0;

		private static int[] _dirLevels = new int[0];

		private static int[] _levels = new int[0];

		private static HDRenderPipelineAsset Asset
		{
			get
			{
				RenderPipelineAsset obj = QualitySettingsPipeline() ?? GraphicsSettings.defaultRenderPipeline;
				return (HDRenderPipelineAsset)(object)((obj is HDRenderPipelineAsset) ? obj : null);
			}
		}

		private static RenderPipelineAsset QualitySettingsPipeline()
		{
			try
			{
				return QualitySettings.renderPipeline;
			}
			catch
			{
				return null;
			}
		}

		public static void Apply(int wantedCachedAtlas)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			HDRenderPipelineAsset asset = Asset;
			if ((Object)(object)asset == (Object)null)
			{
				Plugin.Log.LogWarning((object)"HDRP asset not found, atlas setup skipped");
				return;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(HDRenderPipelineAsset), "m_RenderPipelineSettings");
			if (fieldInfo == null)
			{
				Plugin.Log.LogWarning((object)"m_RenderPipelineSettings not found");
				return;
			}
			RenderPipelineSettings val = (RenderPipelineSettings)fieldInfo.GetValue(asset);
			HDShadowInitParameters hdShadowInitParams = val.hdShadowInitParams;
			MaxPunctualRes = hdShadowInitParams.maxPunctualShadowMapResolution;
			MaxDirectionalRes = hdShadowInitParams.maxDirectionalShadowMapResolution;
			_dirLevels = new int[4];
			for (int i = 0; i < 4; i++)
			{
				try
				{
					_dirLevels[i] = ((ScalableSetting<int>)(object)hdShadowInitParams.shadowResolutionDirectional)[i];
				}
				catch
				{
					_dirLevels[i] = 0;
				}
			}
			Plugin.Log.LogInfo((object)string.Format("HDRP sun shadows: max directional res {0}, directional levels [{1}]", MaxDirectionalRes, string.Join(",", _dirLevels)));
			_levels = new int[4];
			for (int j = 0; j < 4; j++)
			{
				try
				{
					_levels[j] = ((ScalableSetting<int>)(object)hdShadowInitParams.shadowResolutionPunctual)[j];
				}
				catch
				{
					_levels[j] = 0;
				}
			}
			Plugin.Log.LogInfo((object)($"HDRP shadows: atlas {hdShadowInitParams.punctualLightShadowAtlas.shadowAtlasResolution}, cached atlas {hdShadowInitParams.cachedPunctualLightShadowAtlas}, " + string.Format("max punctual res {0}, punctual levels [{1}]", MaxPunctualRes, string.Join(",", _levels))));
			if (wantedCachedAtlas <= 0 || hdShadowInitParams.cachedPunctualLightShadowAtlas >= wantedCachedAtlas)
			{
				return;
			}
			hdShadowInitParams.cachedPunctualLightShadowAtlas = wantedCachedAtlas;
			val.hdShadowInitParams = hdShadowInitParams;
			fieldInfo.SetValue(asset, val);
			if (RenderPipelineManager.currentPipeline != null)
			{
				MethodInfo method = typeof(RenderPipelineManager).GetMethod("CleanupRenderPipeline", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (method != null)
				{
					try
					{
						method.Invoke(null, null);
						Plugin.Log.LogInfo((object)$"Cached shadow atlas -> {wantedCachedAtlas}, HDRP pipeline recreated");
						return;
					}
					catch (Exception arg)
					{
						Plugin.Log.LogError((object)$"Pipeline rebuild failed: {arg}");
						return;
					}
				}
				Plugin.Log.LogWarning((object)"CleanupRenderPipeline not found: new atlas size applies after the pipeline is recreated");
			}
			else
			{
				Plugin.Log.LogInfo((object)$"Cached shadow atlas -> {wantedCachedAtlas} (pipeline not created yet)");
			}
		}

		public static int EffectiveDirectionalResolution(HDAdditionalLightData hd)
		{
			IntScalableSettingValue shadowResolution = hd.shadowResolution;
			int num = (((ScalableSettingValue<int>)(object)shadowResolution).useOverride ? ((ScalableSettingValue<int>)(object)shadowResolution).@override : ((((ScalableSettingValue<int>)(object)shadowResolution).level >= 0 && ((ScalableSettingValue<int>)(object)shadowResolution).level < _dirLevels.Length) ? _dirLevels[((ScalableSettingValue<int>)(object)shadowResolution).level] : 0));
			if (num <= 0)
			{
				num = 2048;
			}
			if (MaxDirectionalRes > 0)
			{
				num = Math.Min(num, MaxDirectionalRes);
			}
			return num;
		}

		public static int EffectiveResolution(HDAdditionalLightData hd)
		{
			IntScalableSettingValue shadowResolution = hd.shadowResolution;
			int num = (((ScalableSettingValue<int>)(object)shadowResolution).useOverride ? ((ScalableSettingValue<int>)(object)shadowResolution).@override : ((((ScalableSettingValue<int>)(object)shadowResolution).level >= 0 && ((ScalableSettingValue<int>)(object)shadowResolution).level < _levels.Length) ? _levels[((ScalableSettingValue<int>)(object)shadowResolution).level] : 0));
			if (num <= 0)
			{
				num = 512;
			}
			if (MaxPunctualRes > 0)
			{
				num = Math.Min(num, MaxPunctualRes);
			}
			return num;
		}
	}
	internal static class CasterCuller
	{
		private class Caster
		{
			public Renderer R;

			public ShadowCastingMode Orig;

			public bool Culled;
		}

		public static bool On;

		private static readonly List<Caster> Casters = new List<Caster>();

		private static readonly HashSet<Renderer> Known = new HashSet<Renderer>();

		private static int _cursor;

		private static float _nextScan;

		public static int CulledCount;

		public static void Rescan()
		{
			_nextScan = 0f;
		}

		public static void Tick(Camera cam)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			if (!On)
			{
				Off();
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime >= _nextScan)
			{
				_nextScan = unscaledTime + Plugin.CasterRescanSeconds.Value;
				Scan();
			}
			if (Casters.Count == 0)
			{
				return;
			}
			Vector3 position = ((Component)cam).transform.position;
			float value = Plugin.SmallSize.Value;
			float value2 = Plugin.MediumSize.Value;
			float value3 = Plugin.SmallDistance.Value;
			float value4 = Plugin.MediumDistance.Value;
			int num = Mathf.Min(Plugin.CastersPerFrame.Value, Casters.Count);
			for (int i = 0; i < num; i++)
			{
				if (_cursor >= Casters.Count)
				{
					_cursor = 0;
				}
				Caster caster = Casters[_cursor++];
				if ((Object)(object)caster.R == (Object)null)
				{
					continue;
				}
				Bounds bounds = caster.R.bounds;
				Vector3 size = ((Bounds)(ref bounds)).size;
				float magnitude = ((Vector3)(ref size)).magnitude;
				float num2 = ((magnitude < value) ? value3 : ((magnitude < value2) ? value4 : (-1f)));
				if (num2 < 0f)
				{
					if (caster.Culled)
					{
						Uncull(caster);
					}
					continue;
				}
				float num3 = ((Bounds)(ref bounds)).SqrDistance(position);
				if (!caster.Culled && num3 > num2 * num2 * 1.21f)
				{
					ShadowCastingMode shadowCastingMode = caster.R.shadowCastingMode;
					if ((int)shadowCastingMode != 0)
					{
						caster.Orig = shadowCastingMode;
						caster.R.shadowCastingMode = (ShadowCastingMode)0;
						caster.Culled = true;
						CulledCount++;
					}
				}
				else if (caster.Culled && num3 < num2 * num2)
				{
					Uncull(caster);
				}
			}
		}

		private static void Uncull(Caster c)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if ((int)c.R.shadowCastingMode == 0)
			{
				c.R.shadowCastingMode = c.Orig;
			}
			c.Culled = false;
			CulledCount--;
		}

		private static void Scan()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			Casters.RemoveAll(delegate(Caster c)
			{
				if ((Object)(object)c.R != (Object)null)
				{
					return false;
				}
				if (c.Culled)
				{
					CulledCount--;
				}
				return true;
			});
			Known.RemoveWhere((Renderer r) => (Object)(object)r == (Object)null);
			Renderer[] array = Object.FindObjectsOfType<Renderer>();
			foreach (Renderer val in array)
			{
				if (!Known.Contains(val) && (val is MeshRenderer || val is SkinnedMeshRenderer) && (int)val.shadowCastingMode != 0)
				{
					Known.Add(val);
					Casters.Add(new Caster
					{
						R = val,
						Orig = val.shadowCastingMode
					});
				}
			}
		}

		public static void Off()
		{
			if (CulledCount == 0)
			{
				return;
			}
			foreach (Caster caster in Casters)
			{
				if (caster.Culled && (Object)(object)caster.R != (Object)null)
				{
					Uncull(caster);
				}
			}
			CulledCount = 0;
		}
	}
	[BepInPlugin("shadowthrottle", "ShadowThrottle", "0.6.0")]
	public class Plugin : BaseUnityPlugin
	{
		public enum Preset
		{
			Quality,
			Balanced,
			Potato,
			Custom
		}

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<Key> ToggleKey;

		internal static ConfigEntry<int> MaxCachedLights;

		internal static ConfigEntry<float> NearDistance;

		internal static ConfigEntry<float> MidDistance;

		internal static ConfigEntry<int> NearInterval;

		internal static ConfigEntry<int> MidInterval;

		internal static ConfigEntry<int> FarInterval;

		internal static ConfigEntry<bool> MovingEveryFrame;

		internal static ConfigEntry<float> RescanSeconds;

		internal static ConfigEntry<bool> DebugLog;

		internal static ConfigEntry<int> CachedAtlasSize;

		internal static ConfigEntry<int> MidResolution;

		internal static ConfigEntry<int> FarResolution;

		internal static ConfigEntry<bool> LampsEnabled;

		internal static ConfigEntry<bool> SunEnabled;

		internal static ConfigEntry<bool> CastersEnabled;

		internal static ConfigEntry<float> VeryFarDistance;

		internal static ConfigEntry<float> VeryFarSeconds;

		internal static ConfigEntry<string> SunCascadeIntervals;

		internal static ConfigEntry<string> SunCascadeMoveLimits;

		internal static ConfigEntry<float> SunAngleRefresh;

		internal static ConfigEntry<float> SunMaxShadowDistance;

		internal static ConfigEntry<int> SunBoostCascades;

		internal static ConfigEntry<int> SunCascadeCount;

		internal static ConfigEntry<bool> SunShipRefresh;

		internal static ConfigEntry<string> SunCascadeSplits;

		internal static ConfigEntry<int> SunResolution;

		internal static ConfigEntry<Preset> PresetEntry;

		internal static ConfigEntry<float> SmallSize;

		internal static ConfigEntry<float> MediumSize;

		internal static ConfigEntry<float> SmallDistance;

		internal static ConfigEntry<float> MediumDistance;

		internal static ConfigEntry<float> CasterRescanSeconds;

		internal static ConfigEntry<int> CastersPerFrame;

		internal static bool RuntimeOn;

		public static bool LampsOn;

		public static bool New05 = true;

		internal static ConfigEntry<bool> ShipLightsEnabled;

		internal static void ApplyPreset()
		{
			Preset p = PresetEntry.Value;
			if (p != Preset.Custom)
			{
				CachedAtlasSize.Value = Pick<int>(4096, 4096, 4096);
				MaxCachedLights.Value = Pick<int>(128, 128, 128);
				NearDistance.Value = Pick<float>(12f, 12f, 6f);
				NearInterval.Value = Pick<int>(1, 2, 1);
				MidDistance.Value = Pick<float>(30f, 30f, 15f);
				MidInterval.Value = Pick<int>(2, 4, 6);
				FarInterval.Value = Pick<int>(4, 8, 20);
				MidResolution.Value = Pick<int>(256, 256, 128);
				FarResolution.Value = Pick<int>(256, 128, 64);
				VeryFarDistance.Value = Pick<float>(80f, 60f, 40f);
				VeryFarSeconds.Value = Pick<float>(0.5f, 1f, 1f);
				SunCascadeIntervals.Value = Pick<string>("1,1,4,15", "1,2,8,30", "1,2,8,45");
				SunCascadeMoveLimits.Value = Pick<string>("0.3,1,4,10", "0.5,1.5,6,15", "0.5,1.5,6,15");
				SunBoostCascades.Value = Pick<int>(2, 2, 2);
				SunCascadeCount.Value = Pick<int>(0, 0, 0);
				SunMaxShadowDistance.Value = Pick<float>(0f, 0f, 0f);
				SunCascadeSplits.Value = Pick<string>("", "", "");
				SunResolution.Value = Pick<int>(0, 0, 512);
				SmallSize.Value = Pick<float>(2f, 2f, 2f);
				SmallDistance.Value = Pick<float>(40f, 25f, 15f);
				MediumSize.Value = Pick<float>(8f, 8f, 8f);
				MediumDistance.Value = Pick<float>(80f, 50f, 30f);
				Log.LogInfo((object)$"Preset {p} applied");
			}
			T Pick<T>(T q, T b, T po)
			{
				if (p != Preset.Quality)
				{
					if (p != Preset.Potato)
					{
						return b;
					}
					return po;
				}
				return q;
			}
		}

		internal static void ApplySwitches()
		{
			LampsOn = RuntimeOn && LampsEnabled.Value;
			SunCache.On = RuntimeOn && SunEnabled.Value;
			CasterCuller.On = RuntimeOn && CastersEnabled.Value;
			ShipItemLights.On = RuntimeOn && ShipLightsEnabled.Value;
		}

		private void Awake()
		{
			//IL_05ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_05dd: Expected O, but got Unknown
			//IL_0575: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0599: Expected O, but got Unknown
			//IL_0605: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master switch (the in-game toggle key does not change this).");
			ToggleKey = ((BaseUnityPlugin)this).Config.Bind<Key>("General", "ToggleKey", (Key)97, "Turn the mod on/off in game for A/B comparison. None = no key.");
			MaxCachedLights = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxCachedLights", 32, "At most this many lights use cached shadows at once. The mod also learns the real atlas capacity and stays below it.");
			NearDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Schedule", "NearDistance", 12f, "Lights closer than this (m) to the camera are 'near'.");
			NearInterval = ((BaseUnityPlugin)this).Config.Bind<int>("Schedule", "NearInterval", 2, "Near lights refresh their shadow every N frames.");
			MidDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Schedule", "MidDistance", 30f, "Lights closer than this (m) are 'mid', farther ones are 'far'.");
			MidInterval = ((BaseUnityPlugin)this).Config.Bind<int>("Schedule", "MidInterval", 4, "Mid lights refresh every N frames.");
			FarInterval = ((BaseUnityPlugin)this).Config.Bind<int>("Schedule", "FarInterval", 8, "Far lights refresh every N frames.");
			MovingEveryFrame = ((BaseUnityPlugin)this).Config.Bind<bool>("Schedule", "MovingLightsVanilla", true, "Lights that move (held flashlights, vehicle headlights...) are left vanilla (every frame).");
			RescanSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Advanced", "FullRescanSeconds", 30f, "Safety full scan for lights (FindObjectsOfType costs a few ms). New lights are normally picked up instantly via OnEnable.");
			CachedAtlasSize = ((BaseUnityPlugin)this).Config.Bind<int>("Atlas", "CachedAtlasSize", 2048, "Size of HDRP's cached shadow atlas (more space = more lights can be cached). 2048 = 16 MB of VRAM. 0 = don't touch.");
			MidResolution = ((BaseUnityPlugin)this).Config.Bind<int>("Atlas", "MidResolution", 256, "Max shadow resolution for cached 'mid' lights (smaller = more lights fit). 0 = keep the light's own.");
			FarResolution = ((BaseUnityPlugin)this).Config.Bind<int>("Atlas", "FarResolution", 128, "Max shadow resolution for cached 'far' lights. 0 = keep the light's own.");
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Advanced", "DebugLog", false, "Log every promote/demote.");
			LampsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Features", "Lamps", true, "Cache and throttle spot/point light shadows.");
			SunEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Features", "Sun", true, "Cache the sun's shadow cascades and refresh far cascades rarely.");
			CastersEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Features", "DistanceCasterCulling", true, "Small/medium objects far away stop casting shadows.");
			ShipLightsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Features", "ShipItemLightsOff", true, "Lights of scrap lying in the ship are switched off (flashlights excluded).");
			VeryFarDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Schedule", "VeryFarDistance", 60f, "Lamps farther than this (m) are refreshed by time instead of by frames.");
			VeryFarSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Schedule", "VeryFarSeconds", 1f, "Very far lamps refresh their shadow every N seconds.");
			SunCascadeIntervals = ((BaseUnityPlugin)this).Config.Bind<string>("Sun", "CascadeIntervals2", "1,2,8,30", "Refresh every N frames, per cascade from near to far (comma separated).");
			SunCascadeMoveLimits = ((BaseUnityPlugin)this).Config.Bind<string>("Sun", "CascadeMoveLimits2", "0.5,1.5,6,15", "A cascade is refreshed early once the camera moved this many metres since its last refresh.");
			SunBoostCascades = ((BaseUnityPlugin)this).Config.Bind<int>("Sun", "BoostCascadesWhileMoving", 2, "While the camera moves (walking, jumping, driving) this many nearest cascades refresh every frame.");
			SunShipRefresh = ((BaseUnityPlugin)this).Config.Bind<bool>("Sun", "RefreshAllWhileShipMoves", true, "All cascades refresh every frame while the ship lands / takes off.");
			SunCascadeCount = ((BaseUnityPlugin)this).Config.Bind<int>("Sun", "CascadeCount", 0, "Override the number of sun cascades (1-4). 0 = keep the game's.");
			SunMaxShadowDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Sun", "MaxShadowDistance", 0f, "Override how far sun shadows reach (m). 0 = keep the game's.");
			SunCascadeSplits = ((BaseUnityPlugin)this).Config.Bind<string>("Sun", "CascadeSplits", "", "Override where cascades end, as fractions of MaxShadowDistance, e.g. '0.05,0.15,0.4'. Empty = keep the game's.");
			SunResolution = ((BaseUnityPlugin)this).Config.Bind<int>("Sun", "ShadowResolution", 0, "Max resolution of the sun's shadow map (e.g. 1024, 512). Only ever lowers it. 0 = keep the game's.");
			SunAngleRefresh = ((BaseUnityPlugin)this).Config.Bind<float>("Sun", "SunAngleRefresh", 0.5f, "Refresh all cascades when the sun rotated more than this many degrees.");
			SmallSize = ((BaseUnityPlugin)this).Config.Bind<float>("Casters", "SmallSize", 2f, "Objects smaller than this (bounding box diagonal, m) are 'small'.");
			SmallDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Casters", "SmallDistance", 25f, "Small objects stop casting shadows beyond this distance (m).");
			MediumSize = ((BaseUnityPlugin)this).Config.Bind<float>("Casters", "MediumSize", 8f, "Objects smaller than this are 'medium'. Bigger ones always cast shadows.");
			MediumDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Casters", "MediumDistance", 50f, "Medium objects stop casting shadows beyond this distance (m).");
			CastersPerFrame = ((BaseUnityPlugin)this).Config.Bind<int>("Casters", "CheckedPerFrame", 300, "How many objects are re-checked per frame (spreads the cost).");
			CasterRescanSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Casters", "RescanSeconds", 15f, "How often new objects are picked up (also on every level load).");
			PresetEntry = ((BaseUnityPlugin)this).Config.Bind<Preset>("General", "Preset", Preset.Balanced, "Quality = gentle, Balanced = default, Potato = everything turned down for very weak PCs. Any preset except Custom OVERWRITES the detailed settings below every time the game starts; pick Custom to tune them yourself.");
			PresetEntry.SettingChanged += delegate
			{
				ApplyPreset();
			};
			ApplyPreset();
			RuntimeOn = Enabled.Value;
			ApplySwitches();
			if (Enabled.Value)
			{
				try
				{
					AtlasSetup.Apply(CachedAtlasSize.Value);
				}
				catch (Exception arg)
				{
					Log.LogError((object)$"Atlas setup failed: {arg}");
				}
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(HDAdditionalLightData), "OnEnable", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				try
				{
					new Harmony("shadowthrottle").Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Scheduler), "OnLightEnabled", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("OnEnable hook failed, falling back to periodic scans: " + ex.Message));
					Scheduler.NoHook = true;
				}
			}
			else
			{
				Scheduler.NoHook = true;
			}
			GameObject val = new GameObject("ShadowThrottle")
			{
				hideFlags = (HideFlags)61
			};
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<Scheduler>();
			Log.LogInfo((object)string.Format("ShadowThrottle loaded ({0}, toggle: {1})", RuntimeOn ? "enabled" : "disabled", ToggleKey.Value));
		}
	}
	internal class Scheduler : MonoBehaviour
	{
		private class Entry
		{
			public HDAdditionalLightData Hd;

			public Light Light;

			public Transform T;

			public int Phase;

			public float LastMoved = -999f;

			public float LastVisible = -999f;

			public float BlockedUntil;

			public float LastRequest;

			public bool Visible;

			public bool WasVisible;

			public bool Moving;

			public bool Active;

			public float Distance;

			public bool Cached;

			public bool Placed;

			public int UnplacedFrames;

			public bool OrigUseOverride;

			public int OrigOverride;

			public int OrigRes;

			public int CurRes;
		}

		internal static readonly List<HDAdditionalLightData> Pending = new List<HDAdditionalLightData>();

		internal static bool NoHook;

		private bool _fullScanQueued = true;

		private readonly Dictionary<HDAdditionalLightData, Entry> _entries = new Dictionary<HDAdditionalLightData, Entry>();

		private readonly List<Entry> _list = new List<Entry>();

		private readonly List<Entry> _candidates = new List<Entry>();

		private readonly Plane[] _planes = (Plane[])(object)new Plane[6];

		private float _nextScan;

		private int _frame;

		private bool _lastRuntimeOn = true;

		private int _cachedCount;

		private int _capacity = int.MaxValue;

		private float _capacityRetryAt;

		internal static void OnLightEnabled(HDAdditionalLightData __instance)
		{
			Pending.Add(__instance);
		}

		private void Awake()
		{
			SceneManager.sceneLoaded += delegate
			{
				_fullScanQueued = true;
				SunCache.Rescan();
				CasterCuller.Rescan();
			};
		}

		private void LateUpdate()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Invalid comparison between Unknown and I4
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_042a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0454: Unknown result type (might be due to invalid IL or missing references)
			//IL_0459: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0471: Unknown result type (might be due to invalid IL or missing references)
			//IL_0783: Unknown result type (might be due to invalid IL or missing references)
			Keyboard current = Keyboard.current;
			Key value = Plugin.ToggleKey.Value;
			if (current != null && (int)value != 0 && ((ButtonControl)current[value]).wasPressedThisFrame)
			{
				Plugin.RuntimeOn = !Plugin.RuntimeOn;
				Plugin.ApplySwitches();
				Plugin.Log.LogInfo((object)("ShadowThrottle " + (Plugin.RuntimeOn ? "ON" : "OFF")));
				try
				{
					ShowTip(Plugin.RuntimeOn ? "ON" : "OFF");
				}
				catch
				{
				}
			}
			float unscaledTime = Time.unscaledTime;
			_frame++;
			if (Plugin.RuntimeOn != _lastRuntimeOn)
			{
				_lastRuntimeOn = Plugin.RuntimeOn;
				Plugin.ApplySwitches();
			}
			if (!Plugin.RuntimeOn)
			{
				if (_cachedCount > 0)
				{
					foreach (Entry item in _list)
					{
						if (item.Cached)
						{
							Demote(item, "mod off");
						}
					}
				}
				SunCache.Off();
				CasterCuller.Off();
				ShipItemLights.Off();
				return;
			}
			if (Pending.Count > 0)
			{
				foreach (HDAdditionalLightData item2 in Pending)
				{
					if ((Object)(object)item2 != (Object)null)
					{
						Register(item2);
					}
				}
				Pending.Clear();
			}
			if (_fullScanQueued || unscaledTime >= _nextScan)
			{
				_fullScanQueued = false;
				_nextScan = unscaledTime + (NoHook ? 3f : Plugin.RescanSeconds.Value);
				Rescan();
			}
			if (_capacity != int.MaxValue && unscaledTime >= _capacityRetryAt)
			{
				_capacity = int.MaxValue;
			}
			Camera camera = GetCamera();
			if ((Object)(object)camera == (Object)null)
			{
				return;
			}
			if (Plugin.New05)
			{
				try
				{
					SunCache.Tick(camera, _frame);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"SunCache: {arg}");
					SunCache.On = false;
				}
			}
			else
			{
				SunCache.Off();
			}
			bool @new = Plugin.New05;
			if (@new)
			{
				try
				{
					CasterCuller.Tick(camera);
				}
				catch (Exception arg2)
				{
					Plugin.Log.LogError((object)$"CasterCuller: {arg2}");
					CasterCuller.On = false;
				}
			}
			else
			{
				CasterCuller.Off();
			}
			if (@new)
			{
				try
				{
					ShipItemLights.Tick();
				}
				catch (Exception arg3)
				{
					Plugin.Log.LogError((object)$"ShipItemLights: {arg3}");
					ShipItemLights.On = false;
				}
			}
			else
			{
				ShipItemLights.Off();
			}
			if (!Plugin.LampsOn)
			{
				if (_cachedCount <= 0)
				{
					return;
				}
				{
					foreach (Entry item3 in _list)
					{
						if (item3.Cached)
						{
							Demote(item3, "lamps off");
						}
					}
					return;
				}
			}
			GeometryUtility.CalculateFrustumPlanes(camera, _planes);
			Vector3 position = ((Component)camera).transform.position;
			float value2 = Plugin.NearDistance.Value;
			float value3 = Plugin.MidDistance.Value;
			int num = Mathf.Max(1, Plugin.NearInterval.Value);
			int num2 = Mathf.Max(1, Plugin.MidInterval.Value);
			int num3 = Mathf.Max(1, Plugin.FarInterval.Value);
			bool value4 = Plugin.MovingEveryFrame.Value;
			for (int i = 0; i < _list.Count; i++)
			{
				Entry entry = _list[i];
				if ((Object)(object)entry.Hd == (Object)null || (Object)(object)entry.Light == (Object)null)
				{
					entry.Active = false;
					continue;
				}
				entry.Active = ((Behaviour)entry.Light).isActiveAndEnabled && (int)entry.Light.shadows > 0;
				if (!entry.Active)
				{
					if (entry.Cached)
					{
						Demote(entry, "disabled");
					}
					entry.WasVisible = false;
					continue;
				}
				if (entry.T.hasChanged)
				{
					entry.T.hasChanged = false;
					entry.LastMoved = unscaledTime;
				}
				entry.Moving = value4 && unscaledTime - entry.LastMoved < 1f;
				Vector3 position2 = entry.T.position;
				float range = entry.Light.range;
				entry.Visible = GeometryUtility.TestPlanesAABB(_planes, new Bounds(position2, new Vector3(range, range, range) * 2f));
				entry.Distance = Mathf.Max(0f, Vector3.Distance(position, position2) - range * 0.5f);
				if (entry.Visible)
				{
					entry.LastVisible = unscaledTime;
				}
				if (!entry.Cached)
				{
					entry.WasVisible = entry.Visible;
					continue;
				}
				if (entry.Moving)
				{
					Demote(entry, "moving");
					continue;
				}
				if (unscaledTime - entry.LastVisible > 2f)
				{
					Demote(entry, "out of view");
					continue;
				}
				if (!entry.Placed)
				{
					if (HDCachedShadowManager.instance.LightHasBeenPlacedInAtlas(entry.Hd))
					{
						entry.Placed = true;
					}
					else if (++entry.UnplacedFrames > 20)
					{
						int num4 = 0;
						foreach (Entry item4 in _list)
						{
							if (item4.Cached && item4.Placed)
							{
								num4++;
							}
						}
						_capacity = Mathf.Max(1, num4);
						_capacityRetryAt = unscaledTime + 30f;
						entry.BlockedUntil = unscaledTime + 10f;
						Demote(entry, "atlas full");
						Plugin.Log.LogInfo((object)$"Cached shadow atlas full: capacity now {_capacity} lights");
						continue;
					}
				}
				if (!entry.Visible)
				{
					entry.WasVisible = false;
					continue;
				}
				bool flag = !entry.WasVisible || !entry.Placed;
				entry.WasVisible = true;
				int num5 = ((entry.Distance < value2) ? num : ((entry.Distance < value3) ? num2 : num3));
				int num6 = WantedRes(entry, value2, value3);
				if (num6 > entry.CurRes)
				{
					ApplyRes(entry, num6);
					flag = true;
					entry.Placed = false;
					entry.UnplacedFrames = 0;
				}
				bool flag2 = ((!Plugin.New05 || !(entry.Distance >= Plugin.VeryFarDistance.Value)) ? (num5 == 1 || (_frame + entry.Phase) % num5 == 0) : (unscaledTime - entry.LastRequest >= Plugin.VeryFarSeconds.Value));
				if (flag || flag2)
				{
					entry.Hd.RequestShadowMapRendering();
					entry.LastRequest = unscaledTime;
				}
			}
			if (_frame % 10 != 0)
			{
				return;
			}
			int num7 = Mathf.Min(Plugin.MaxCachedLights.Value, _capacity) - _cachedCount;
			if (num7 <= 0)
			{
				return;
			}
			_candidates.Clear();
			foreach (Entry item5 in _list)
			{
				if (item5.Active && !item5.Cached && item5.Visible && !item5.Moving && unscaledTime >= item5.BlockedUntil && (int)item5.Hd.shadowUpdateMode == 0)
				{
					_candidates.Add(item5);
				}
			}
			_candidates.Sort((Entry a, Entry b) => b.Distance.CompareTo(a.Distance));
			int num8 = Mathf.Min(num7, _candidates.Count);
			for (int num9 = 0; num9 < num8; num9++)
			{
				Promote(_candidates[num9]);
			}
		}

		private int WantedRes(Entry e, float near, float mid)
		{
			int num = ((!(e.Distance < near)) ? ((e.Distance < mid) ? Plugin.MidResolution.Value : Plugin.FarResolution.Value) : 0);
			if (num <= 0)
			{
				return e.OrigRes;
			}
			return Math.Min(e.OrigRes, num);
		}

		private static void ApplyRes(Entry e, int res)
		{
			e.CurRes = res;
			if (res == e.OrigRes)
			{
				e.Hd.SetShadowResolutionOverride(e.OrigUseOverride);
				e.Hd.SetShadowResolution(e.OrigOverride);
			}
			else
			{
				e.Hd.SetShadowResolutionOverride(true);
				e.Hd.SetShadowResolution(res);
			}
		}

		private void Promote(Entry e)
		{
			IntScalableSettingValue shadowResolution = e.Hd.shadowResolution;
			e.OrigUseOverride = ((ScalableSettingValue<int>)(object)shadowResolution).useOverride;
			e.OrigOverride = ((ScalableSettingValue<int>)(object)shadowResolution).@override;
			e.OrigRes = AtlasSetup.EffectiveResolution(e.Hd);
			e.CurRes = e.OrigRes;
			int num = WantedRes(e, Plugin.NearDistance.Value, Plugin.MidDistance.Value);
			if (num != e.OrigRes)
			{
				ApplyRes(e, num);
			}
			e.Hd.shadowUpdateMode = (ShadowUpdateMode)2;
			e.Cached = true;
			e.Placed = false;
			e.UnplacedFrames = 0;
			e.WasVisible = false;
			_cachedCount++;
			e.Hd.RequestShadowMapRendering();
			if (Plugin.DebugLog.Value)
			{
				Plugin.Log.LogInfo((object)$"cache + {((Object)e.Light).name} ({e.Distance:F0} m, res {e.CurRes}/{e.OrigRes}), cached={_cachedCount}");
			}
		}

		private void Demote(Entry e, string why)
		{
			if ((Object)(object)e.Hd != (Object)null)
			{
				e.Hd.shadowUpdateMode = (ShadowUpdateMode)0;
				if (e.CurRes != e.OrigRes)
				{
					ApplyRes(e, e.OrigRes);
				}
			}
			e.Cached = false;
			e.Placed = false;
			_cachedCount--;
			if (Plugin.DebugLog.Value && (Object)(object)e.Light != (Object)null)
			{
				Plugin.Log.LogInfo((object)$"cache - {((Object)e.Light).name} ({why}), cached={_cachedCount}");
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void ShowTip(string body)
		{
			if ((Object)(object)HUDManager.Instance != (Object)null)
			{
				HUDManager.Instance.DisplayTip("ShadowThrottle", body, false, false, "LC_Tip1");
			}
		}

		private static Camera GetCamera()
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)instance.activeCamera != (Object)null && ((Behaviour)instance.activeCamera).isActiveAndEnabled)
			{
				return instance.activeCamera;
			}
			return Camera.main;
		}

		private void Rescan()
		{
			for (int num = _list.Count - 1; num >= 0; num--)
			{
				Entry entry = _list[num];
				if (!((Object)(object)entry.Hd != (Object)null))
				{
					if (entry.Cached)
					{
						entry.Cached = false;
						_cachedCount--;
					}
					_list.RemoveAt(num);
				}
			}
			if (_entries.Count != _list.Count)
			{
				_entries.Clear();
				foreach (Entry item in _list)
				{
					_entries[item.Hd] = item;
				}
			}
			HDAdditionalLightData[] array = Object.FindObjectsOfType<HDAdditionalLightData>();
			foreach (HDAdditionalLightData hd in array)
			{
				Register(hd);
			}
		}

		private void Register(HDAdditionalLightData hd)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			if (!_entries.ContainsKey(hd))
			{
				Light component = ((Component)hd).GetComponent<Light>();
				if (!((Object)(object)component == (Object)null) && ((int)component.type == 0 || (int)component.type == 2) && (int)hd.shadowUpdateMode == 0)
				{
					Entry entry = new Entry
					{
						Hd = hd,
						Light = component,
						T = ((Component)hd).transform,
						Phase = _list.Count * 7
					};
					((Component)hd).transform.hasChanged = false;
					_entries[hd] = entry;
					_list.Add(entry);
				}
			}
		}
	}
	internal static class ShipItemLights
	{
		public static bool On;

		private static readonly Dictionary<Light, GrabbableObject> Disabled = new Dictionary<Light, GrabbableObject>();

		private static readonly List<Light> Buffer = new List<Light>();

		private static readonly List<Light> ToRestore = new List<Light>();

		private static float _next;

		public static int Count => Disabled.Count;

		public static void Tick()
		{
			if (!On)
			{
				Off();
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < _next)
			{
				return;
			}
			_next = unscaledTime + 1f;
			ToRestore.Clear();
			foreach (KeyValuePair<Light, GrabbableObject> item in Disabled)
			{
				if ((Object)(object)item.Key == (Object)null || (Object)(object)item.Value == (Object)null || !item.Value.isInShipRoom)
				{
					ToRestore.Add(item.Key);
				}
			}
			foreach (Light item2 in ToRestore)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					((Behaviour)item2).enabled = true;
				}
				Disabled.Remove(item2);
			}
			GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
			foreach (GrabbableObject val in array)
			{
				if (!val.isInShipRoom || val is FlashlightItem)
				{
					continue;
				}
				Buffer.Clear();
				((Component)val).GetComponentsInChildren<Light>(false, Buffer);
				foreach (Light item3 in Buffer)
				{
					if (((Behaviour)item3).enabled && !Disabled.ContainsKey(item3))
					{
						((Behaviour)item3).enabled = false;
						Disabled[item3] = val;
					}
				}
			}
		}

		public static void Off()
		{
			if (Disabled.Count == 0)
			{
				return;
			}
			foreach (Light key in Disabled.Keys)
			{
				if ((Object)(object)key != (Object)null)
				{
					((Behaviour)key).enabled = true;
				}
			}
			Disabled.Clear();
		}
	}
	internal static class SunCache
	{
		private class Sun
		{
			public HDAdditionalLightData Hd;

			public Light L;

			public ShadowUpdateMode Orig;

			public bool Cached;

			public float[] LastTime = new float[4];

			public Vector3[] LastPos = (Vector3[])(object)new Vector3[4];

			public Quaternion LastRot;

			public bool OrigUseOverride;

			public int OrigOverride;

			public bool ResChanged;
		}

		public static bool On;

		private static readonly List<Sun> Suns = new List<Sun>();

		private static Vector3 _lastCamPos;

		private static Vector3 _lastShipPos;

		private static Quaternion _lastShipRot;

		private static float _shipBoostUntil;

		private static Transform _ship;

		private static GameObject _volGo;

		private static string _volKey;

		private static float _nextScan;

		private static int[] _intervals = new int[4] { 2, 4, 12, 40 };

		private static float[] _moveLimit = new float[4] { 1f, 3f, 8f, 20f };

		private static string _parsed;

		public static void Rescan()
		{
			_nextScan = 0f;
		}

		public static void Tick(Camera cam, int frame)
		{
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Invalid comparison between Unknown and I4
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Invalid comparison between Unknown and I4
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_042e: Unknown result type (might be due to invalid IL or missing references)
			if (!On)
			{
				Off();
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime >= _nextScan)
			{
				_nextScan = unscaledTime + 5f;
				Suns.RemoveAll((Sun s) => (Object)(object)s.Hd == (Object)null || (Object)(object)s.L == (Object)null);
				Light[] array = Object.FindObjectsOfType<Light>();
				foreach (Light l in array)
				{
					if ((int)l.type == 1 && !Suns.Any((Sun s) => (Object)(object)s.L == (Object)(object)l))
					{
						HDAdditionalLightData component = ((Component)l).GetComponent<HDAdditionalLightData>();
						if ((Object)(object)component != (Object)null)
						{
							Suns.Add(new Sun
							{
								Hd = component,
								L = l,
								Orig = component.shadowUpdateMode
							});
						}
					}
				}
			}
			ParseConfig();
			ApplyVolume(cam);
			Vector3 position = ((Component)cam).transform.position;
			Vector3 val = position - _lastCamPos;
			bool flag = ((Vector3)(ref val)).sqrMagnitude > 0.0004f;
			_lastCamPos = position;
			if ((Object)(object)_ship == (Object)null)
			{
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.elevatorTransform != (Object)null)
				{
					_ship = instance.elevatorTransform;
				}
			}
			if ((Object)(object)_ship != (Object)null && Plugin.SunShipRefresh.Value)
			{
				val = _ship.position - _lastShipPos;
				if (((Vector3)(ref val)).sqrMagnitude > 1E-06f || Quaternion.Angle(_ship.rotation, _lastShipRot) > 0.01f)
				{
					_shipBoostUntil = unscaledTime + 0.5f;
				}
				_lastShipPos = _ship.position;
				_lastShipRot = _ship.rotation;
			}
			bool flag2 = unscaledTime < _shipBoostUntil;
			int num2 = (flag ? Plugin.SunBoostCascades.Value : 0);
			int num3 = 4;
			try
			{
				HDShadowSettings component2 = VolumeManager.instance.stack.GetComponent<HDShadowSettings>();
				if ((Object)(object)component2 != (Object)null)
				{
					num3 = Mathf.Clamp(((VolumeParameter<int>)(object)component2.cascadeShadowSplitCount).value, 1, 4);
				}
			}
			catch
			{
			}
			Vector3 position2 = ((Component)cam).transform.position;
			foreach (Sun sun in Suns)
			{
				if (!((Behaviour)sun.L).isActiveAndEnabled || (int)sun.L.shadows == 0 || (int)sun.Orig != 0)
				{
					Restore(sun);
					continue;
				}
				ApplyResolution(sun);
				if (!sun.Cached)
				{
					sun.Hd.shadowUpdateMode = (ShadowUpdateMode)2;
					sun.Cached = true;
					sun.Hd.RequestShadowMapRendering();
					for (int num4 = 0; num4 < 4; num4++)
					{
						sun.LastTime[num4] = unscaledTime;
						sun.LastPos[num4] = position2;
					}
					sun.LastRot = ((Component)sun.L).transform.rotation;
					continue;
				}
				if (Quaternion.Angle(sun.LastRot, ((Component)sun.L).transform.rotation) > Plugin.SunAngleRefresh.Value)
				{
					sun.Hd.RequestShadowMapRendering();
					sun.LastRot = ((Component)sun.L).transform.rotation;
					for (int num5 = 0; num5 < 4; num5++)
					{
						sun.LastTime[num5] = unscaledTime;
						sun.LastPos[num5] = position2;
					}
					continue;
				}
				for (int num6 = 0; num6 < num3; num6++)
				{
					int num7 = _intervals[Mathf.Min(num6, _intervals.Length - 1)];
					float num8 = _moveLimit[Mathf.Min(num6, _moveLimit.Length - 1)];
					bool num9 = flag2 || num6 < num2 || (frame + num6) % num7 == 0;
					val = position2 - sun.LastPos[num6];
					bool flag3 = ((Vector3)(ref val)).sqrMagnitude > num8 * num8;
					if (num9 || flag3)
					{
						sun.Hd.RequestSubShadowMapRendering(num6);
						sun.LastTime[num6] = unscaledTime;
						sun.LastPos[num6] = position2;
					}
				}
			}
		}

		public static void Off()
		{
			foreach (Sun sun in Suns)
			{
				Restore(sun);
			}
			RemoveVolume();
		}

		private static void ApplyVolume(Camera cam)
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			int value = Plugin.SunCascadeCount.Value;
			float value2 = Plugin.SunMaxShadowDistance.Value;
			string text = Plugin.SunCascadeSplits.Value.Trim();
			string text2 = $"{value}|{value2}|{text}";
			if (value <= 0 && value2 <= 0f && text.Length == 0)
			{
				RemoveVolume();
				_volKey = text2;
			}
			else
			{
				if ((Object)(object)_volGo != (Object)null && text2 == _volKey)
				{
					return;
				}
				RemoveVolume();
				_volKey = text2;
				_volGo = new GameObject("ShadowThrottle_ShadowSettings");
				Object.DontDestroyOnLoad((Object)(object)_volGo);
				HDAdditionalCameraData component = ((Component)cam).GetComponent<HDAdditionalCameraData>();
				int num = ((!((Object)(object)component != (Object)null)) ? 1 : LayerMask.op_Implicit(component.volumeLayerMask));
				for (int i = 0; i < 32; i++)
				{
					if ((num & (1 << i)) != 0)
					{
						_volGo.layer = i;
						break;
					}
				}
				Volume obj = _volGo.AddComponent<Volume>();
				obj.isGlobal = true;
				obj.priority = 10000f;
				VolumeProfile val = ScriptableObject.CreateInstance<VolumeProfile>();
				HDShadowSettings val2 = val.Add<HDShadowSettings>(true);
				if (value > 0)
				{
					((VolumeParameter<int>)(object)val2.cascadeShadowSplitCount).Override(Mathf.Clamp(value, 1, 4));
				}
				if (value2 > 0f)
				{
					((VolumeParameter<float>)(object)val2.maxShadowDistance).Override(value2);
				}
				if (text.Length > 0)
				{
					float[] array = (from x in text.Split(',')
						select float.Parse(x.Trim(), CultureInfo.InvariantCulture)).ToArray();
					if (array.Length != 0)
					{
						((VolumeParameter<float>)(object)val2.cascadeShadowSplit0).Override(array[0]);
					}
					if (array.Length > 1)
					{
						((VolumeParameter<float>)(object)val2.cascadeShadowSplit1).Override(array[1]);
					}
					if (array.Length > 2)
					{
						((VolumeParameter<float>)(object)val2.cascadeShadowSplit2).Override(array[2]);
					}
				}
				obj.sharedProfile = val;
				Plugin.Log.LogInfo((object)("Sun cascades override: count=" + ((value > 0) ? value.ToString() : "game") + ", distance=" + ((value2 > 0f) ? value2.ToString() : "game") + ", splits=" + ((text.Length > 0) ? text : "game")));
				foreach (Sun sun in Suns)
				{
					if (sun.Cached && (Object)(object)sun.Hd != (Object)null)
					{
						sun.Hd.RequestShadowMapRendering();
					}
				}
			}
		}

		private static void RemoveVolume()
		{
			if ((Object)(object)_volGo != (Object)null)
			{
				Object.Destroy((Object)(object)_volGo);
			}
			_volGo = null;
		}

		private static void ApplyResolution(Sun s)
		{
			int value = Plugin.SunResolution.Value;
			if (value <= 0)
			{
				RestoreResolution(s);
				return;
			}
			if (!s.ResChanged)
			{
				IntScalableSettingValue shadowResolution = s.Hd.shadowResolution;
				s.OrigUseOverride = ((ScalableSettingValue<int>)(object)shadowResolution).useOverride;
				s.OrigOverride = ((ScalableSettingValue<int>)(object)shadowResolution).@override;
				int num = AtlasSetup.EffectiveDirectionalResolution(s.Hd);
				if (value >= num)
				{
					return;
				}
				Plugin.Log.LogInfo((object)$"Sun shadow resolution {num} -> {value}");
				s.ResChanged = true;
			}
			if (((ScalableSettingValue<int>)(object)s.Hd.shadowResolution).@override != value || !((ScalableSettingValue<int>)(object)s.Hd.shadowResolution).useOverride)
			{
				s.Hd.SetShadowResolutionOverride(true);
				s.Hd.SetShadowResolution(value);
			}
		}

		private static void RestoreResolution(Sun s)
		{
			if (s.ResChanged && !((Object)(object)s.Hd == (Object)null))
			{
				s.Hd.SetShadowResolutionOverride(s.OrigUseOverride);
				s.Hd.SetShadowResolution(s.OrigOverride);
				s.ResChanged = false;
			}
		}

		private static void Restore(Sun s)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			RestoreResolution(s);
			if (s.Cached && !((Object)(object)s.Hd == (Object)null))
			{
				s.Hd.shadowUpdateMode = s.Orig;
				s.Cached = false;
			}
		}

		private static void ParseConfig()
		{
			string text = Plugin.SunCascadeIntervals.Value + "|" + Plugin.SunCascadeMoveLimits.Value;
			if (text == _parsed)
			{
				return;
			}
			_parsed = text;
			try
			{
				_intervals = (from x in Plugin.SunCascadeIntervals.Value.Split(',')
					select Mathf.Max(1, int.Parse(x.Trim()))).ToArray();
			}
			catch
			{
			}
			try
			{
				_moveLimit = (from x in Plugin.SunCascadeMoveLimits.Value.Split(',')
					select float.Parse(x.Trim(), CultureInfo.InvariantCulture)).ToArray();
			}
			catch
			{
			}
		}
	}
}