Decompiled source of balrond core optimizer v0.2.7

plugins/BalrondCoreOptimizer.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BalrondVisualOptimizer.Compatibility;
using BalrondVisualOptimizer.Config;
using BalrondVisualOptimizer.Core;
using BalrondVisualOptimizer.Networking;
using BalrondVisualOptimizer.Patches;
using BalrondVisualOptimizer.Patches.ArmorStandOptimizations;
using BalrondVisualOptimizer.Patches.CookingStationOptimizations;
using BalrondVisualOptimizer.Patches.CraftingStationOptimizations;
using BalrondVisualOptimizer.Patches.EffectFadeOptimizations;
using BalrondVisualOptimizer.Patches.FireplaceOptimizations;
using BalrondVisualOptimizer.Patches.ItemStandOptimizations;
using BalrondVisualOptimizer.Patches.LightFlickerOptimizations;
using BalrondVisualOptimizer.Patches.LightLodOptimizations;
using BalrondVisualOptimizer.Patches.LineConnectOptimizations;
using BalrondVisualOptimizer.Patches.MaterialFaderOptimizations;
using BalrondVisualOptimizer.Patches.PieceOptimizations;
using BalrondVisualOptimizer.Patches.PrivateAreaOptimizations;
using BalrondVisualOptimizer.Patches.SmelterOptimizations;
using BalrondVisualOptimizer.Patches.SmokeRendererOptimizations;
using BalrondVisualOptimizer.Patches.StationExtensionOptimizations;
using BalrondVisualOptimizer.Patches.TeleportWorldOptimizations;
using BalrondVisualOptimizer.Patches.VagonOptimizations;
using BalrondVisualOptimizer.Patches.VisEquipmentOptimizations;
using BalrondVisualOptimizer.Patches.WindmillOptimizations;
using BalrondVisualOptimizer.Patches.ZSFXOptimizations;
using BalrondVisualOptimizer.Services;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("BalrondCoreOptimizer")]
[assembly: AssemblyDescription("Valheim client-side visual optimization with required, bundled server-side configuration synchronization.")]
[assembly: AssemblyCompany("Balrond")]
[assembly: AssemblyProduct("BalrondCoreOptimizer")]
[assembly: ComVisible(false)]
[assembly: Guid("f03f328f-fc3d-43b7-b051-c689bc12310d")]
[assembly: AssemblyFileVersion("0.2.7.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.2.7.0")]
[module: UnverifiableCode]
namespace BalrondVisualOptimizer
{
	[BepInPlugin("balrond.astafaraios.BalrondCoreOptimizer", "BalrondCoreOptimizer", "0.2.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Launch : BaseUnityPlugin
	{
		public const string PluginGuid = "balrond.astafaraios.BalrondCoreOptimizer";

		public const string PluginName = "BalrondCoreOptimizer";

		public const string PluginVersion = "0.2.7";

		internal static Launch Instance;

		internal static OptimizerConfig Settings;

		private Harmony harmony;

		private PatchInstaller patchInstaller;

		private float nextCompatibilityCheck;

		private float nextStatsLog;

		private bool refreshRequested;

		private bool lastDiagnostics;

		private bool initialized;

		private float nextDiagCommandRegister;

		private void Awake()
		{
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Expected O, but got Unknown
			Instance = this;
			try
			{
				Settings = new OptimizerConfig(((BaseUnityPlugin)this).Config, ServerConfigBridge.Initialize());
				RuntimeTuning.Refresh(Settings);
				RuntimeStats.Enabled = Settings.Diagnostics.Value;
				RuntimeStats.ResetBaseline();
				PerformanceSampler.Reset();
				lastDiagnostics = RuntimeStats.Enabled;
				((BaseUnityPlugin)this).Config.SettingChanged += OnSettingChanged;
				LogInfo("BalrondCoreOptimizer 0.2.7 starting (publicized fast-path build).");
				LogInfo("assembly_valheim runtime MVID: " + RuntimeAssemblyInfo.CurrentValheimMvid.ToString() + ", identity: " + RuntimeAssemblyInfo.AssemblyIdentity + " (diagnostic only; patch compatibility is not MVID/version-gated).");
				LogInfo("Conservative Mode=" + Settings.ConservativeMode.Value + ". Non-equivalent scheduling/throttling/full-render-loop optimizations are " + (Settings.ConservativeMode.Value ? "disabled" : "allowed by their individual toggles") + ".");
				if (Application.isBatchMode)
				{
					LogInfo("Dedicated/batch mode detected. Client presentation patches are not installed.");
					initialized = true;
					return;
				}
				LogInfo("[graphics] api=" + ((object)SystemInfo.graphicsDeviceType/*cast due to .constrained prefix*/).ToString() + ", instancing=" + SystemInfo.supportsInstancing + ", unity=" + Application.unityVersion);
				LogInfo("Compatibility: VCP=" + ModCompatibility.ValheimCommunityPatchInstalled + ", RuneRails=" + ModCompatibility.RuneRailsInstalled + ", CharacterCustomization=" + ModCompatibility.CharacterCustomizationInstalled + ", BAO=" + ModCompatibility.AbsoluteOverhaulInstalled + ", MonsterMayhem=" + ModCompatibility.MonsterMayhemInstalled + ", BetterBuild=" + ModCompatibility.BetterBuildInstalled + ", FiresGhettoNetworking=" + ModCompatibility.FiresGhettoNetworkingInstalled + ".");
				harmony = new Harmony("balrond.astafaraios.BalrondCoreOptimizer");
				patchInstaller = new PatchInstaller(harmony, Settings);
				VanillaCollectionRegistry.Initialize();
				ArmorStandPatches.Install(patchInstaller);
				ItemStandPatches.Install(patchInstaller);
				PrivateAreaPatches.Install(patchInstaller);
				TeleportWorldPatches.Install(patchInstaller);
				VisEquipmentPatches.Install(patchInstaller);
				SmelterPatches.Install(patchInstaller);
				FireplacePatches.Install(patchInstaller);
				CookingStationPatches.Install(patchInstaller);
				CraftingStationDormancyPatches.Install(patchInstaller);
				LightFlickerPatches.Install(patchInstaller);
				LightLodPatches.Install(patchInstaller);
				SmokeRendererPatches.Install(patchInstaller);
				WindmillPatches.Install(patchInstaller);
				VagonPatches.Install(patchInstaller);
				EffectFadePatches.Install(patchInstaller);
				MaterialFaderPatches.Install(patchInstaller);
				ZSFXPatches.Install(patchInstaller);
				LineConnectPatches.Install(patchInstaller);
				PiecePatches.Install(patchInstaller);
				CraftingStationPatches.Install(patchInstaller);
				StationExtensionPatches.Install(patchInstaller);
				GroundLootPatches.Install(patchInstaller);
				SkyAlphaPatches.Install(patchInstaller);
				RefreshSubsystemOwnership();
				nextCompatibilityCheck = Time.unscaledTime + Settings.CompatibilityRecheckSeconds.Value;
				nextStatsLog = Time.unscaledTime + Settings.DiagnosticsIntervalSeconds.Value;
				LogInfo("[patches] " + patchInstaller.BuildStatusSummary());
				initialized = true;
				DiagnosticConsole.TryRegister();
				LogInfo("BalrondCoreOptimizer initialization complete.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Fatal initialization error. Rolling back BVO and restoring vanilla dispatch: " + ex));
				ShutdownSubsystems();
				try
				{
					if (harmony != null)
					{
						harmony.UnpatchSelf();
					}
				}
				catch (Exception ex2)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Rollback failed: " + ex2.Message));
				}
				patchInstaller = null;
				initialized = false;
			}
		}

		private void OnSettingChanged(object sender, SettingChangedEventArgs args)
		{
			refreshRequested = true;
		}

		private void Update()
		{
			if (!initialized || Settings == null || Application.isBatchMode)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (!DiagnosticConsole.Registered && unscaledTime >= nextDiagCommandRegister)
			{
				nextDiagCommandRegister = unscaledTime + 2f;
				DiagnosticConsole.TryRegister();
			}
			DiagnosticConsole.Tick(unscaledTime);
			if (patchInstaller != null && (refreshRequested || unscaledTime >= nextCompatibilityCheck))
			{
				refreshRequested = false;
				if (DiagnosticBcoTiming.Active)
				{
					long start = DiagnosticBcoTiming.Start();
					try
					{
						RuntimeTuning.Refresh(Settings);
						patchInstaller.RefreshAll();
						RefreshSubsystemOwnership();
					}
					finally
					{
						DiagnosticBcoTiming.End(0, start);
					}
				}
				else
				{
					RuntimeTuning.Refresh(Settings);
					patchInstaller.RefreshAll();
					RefreshSubsystemOwnership();
				}
				nextCompatibilityCheck = unscaledTime + Mathf.Max(2f, Settings.CompatibilityRecheckSeconds.Value);
			}
			if (DiagnosticBcoTiming.Active)
			{
				long start2 = DiagnosticBcoTiming.Start();
				try
				{
					LightLodScheduler.Tick(Time.deltaTime);
				}
				finally
				{
					DiagnosticBcoTiming.End(1, start2);
				}
				long start3 = DiagnosticBcoTiming.Start();
				try
				{
					ZSFXPatches.Tick(unscaledTime);
				}
				finally
				{
					DiagnosticBcoTiming.End(2, start3);
				}
				long start4 = DiagnosticBcoTiming.Start();
				try
				{
					GpuInstancingService.Tick(Settings);
				}
				finally
				{
					DiagnosticBcoTiming.End(3, start4);
				}
			}
			else
			{
				LightLodScheduler.Tick(Time.deltaTime);
				ZSFXPatches.Tick(unscaledTime);
				GpuInstancingService.Tick(Settings);
			}
			bool flag = Settings.Diagnostics.Value || DiagnosticConsole.SessionActive;
			if (DiagnosticConsole.SessionActive || (Settings.Diagnostics.Value && Settings.DiagnosticsPerformanceSamples.Value))
			{
				PerformanceSampler.Tick(DiagnosticConsole.SessionActive ? 60 : Settings.DiagnosticsSampleEveryFrames.Value);
			}
			if (flag != lastDiagnostics)
			{
				lastDiagnostics = flag;
				RuntimeStats.Enabled = flag;
				RuntimeStats.ResetBaseline();
				PerformanceSampler.Reset();
				nextStatsLog = unscaledTime + Mathf.Max(10f, Settings.DiagnosticsIntervalSeconds.Value);
			}
			if (Settings.Diagnostics.Value && !DiagnosticConsole.SessionActive && unscaledTime >= nextStatsLog)
			{
				float num = Mathf.Max(10f, Settings.DiagnosticsIntervalSeconds.Value);
				nextStatsLog = unscaledTime + num;
				LogInfo("[stats] " + RuntimeStats.BuildDeltaSummary(num));
				if (Settings.DiagnosticsPerformanceSamples.Value)
				{
					LogInfo("[performance] " + PerformanceSampler.Drain());
				}
				else
				{
					PerformanceSampler.Reset();
				}
				if (patchInstaller != null)
				{
					LogInfo("[patches] " + patchInstaller.BuildStatusSummary());
				}
				LogInfo("[balrond] " + ModCompatibility.BuildBalrondInventory());
			}
		}

		internal string BuildDiagnosticPatchReport()
		{
			return (patchInstaller == null) ? "Patch installer unavailable (batch mode or initialization failure)" : patchInstaller.BuildDetailedStatusReport();
		}

		private static void RefreshSubsystemOwnership()
		{
			CraftingStationDormancyPatches.RefreshDormancy();
			EffectFadePatches.RefreshDormancy();
			MaterialFaderPatches.RefreshDormancy();
			ZSFXPatches.RefreshDormancy();
			LightLodPatches.RefreshScheduler();
		}

		private static void ShutdownSubsystems()
		{
			try
			{
				LightLodScheduler.RestoreVanilla();
			}
			catch
			{
			}
			try
			{
				GroundLootPatches.Shutdown();
			}
			catch
			{
			}
			try
			{
				SkyAlphaPatches.Reset();
			}
			catch
			{
			}
			try
			{
				GpuInstancingService.Restore();
			}
			catch
			{
			}
			FrameCameraSnapshot.Invalidate();
			CacheVerification.Reset();
			ReusableBufferPool<string>.Clear();
			try
			{
				CraftingStationDormancyPatches.Shutdown();
			}
			catch
			{
			}
			try
			{
				EffectFadePatches.Shutdown();
			}
			catch
			{
			}
			try
			{
				MaterialFaderPatches.Shutdown();
			}
			catch
			{
			}
			try
			{
				ZSFXPatches.Shutdown();
			}
			catch
			{
			}
		}

		private void OnDestroy()
		{
			initialized = false;
			if (((BaseUnityPlugin)this).Config != null)
			{
				((BaseUnityPlugin)this).Config.SettingChanged -= OnSettingChanged;
			}
			DiagnosticConsole.Shutdown();
			ShutdownSubsystems();
			try
			{
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Failed to unpatch cleanly: " + ex.Message));
			}
			Instance = null;
		}

		internal static void LogInfo(object message)
		{
			if ((Object)(object)Instance != (Object)null && Settings != null && Settings.Diagnostics != null && Settings.Diagnostics.Value)
			{
				((BaseUnityPlugin)Instance).Logger.LogDebug(message);
			}
		}

		internal static void LogDiagnostic(object message)
		{
			if ((Object)(object)Instance != (Object)null && Settings != null && Settings.Diagnostics != null && Settings.Diagnostics.Value)
			{
				((BaseUnityPlugin)Instance).Logger.LogDebug(message);
			}
		}

		internal static void LogWarning(object message)
		{
			if ((Object)(object)Instance != (Object)null)
			{
				((BaseUnityPlugin)Instance).Logger.LogWarning(message);
			}
		}

		internal static void LogError(object message)
		{
			if ((Object)(object)Instance != (Object)null)
			{
				((BaseUnityPlugin)Instance).Logger.LogError(message);
			}
		}
	}
}
namespace BalrondVisualOptimizer.Networking
{
	internal static class ServerConfigBridge
	{
		private static ConfigSync sync;

		internal static ConfigSync Initialize()
		{
			if (sync != null)
			{
				return sync;
			}
			return sync = new ConfigSync("balrond.astafaraios.BalrondCoreOptimizer")
			{
				DisplayName = "BalrondCoreOptimizer",
				CurrentVersion = "0.2.7",
				MinimumRequiredVersion = "0.2.7",
				ModRequired = true
			};
		}

		internal static void ReportRegistered(int count)
		{
			if (sync == null)
			{
				throw new InvalidOperationException("ServerSync not initialized");
			}
			Launch.LogInfo("Bundled ServerSync: " + count + " BVO settings registered (including server lock), ModRequired=true, minimum version=0.2.7.");
		}
	}
}
namespace BalrondVisualOptimizer.Services
{
	internal static class FrameCameraSnapshot
	{
		private static int sampledFrame = -1;

		private static Camera sampledCamera;

		private static int hits;

		private static int misses;

		internal static bool TryGetLightReferencePoint(out Vector3 point)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			Camera val = ResolveCamera();
			if ((Object)(object)val == (Object)null)
			{
				point = Vector3.zero;
				return false;
			}
			Player localPlayer = Player.m_localPlayer;
			point = ((GameCamera.InFreeFly() || (Object)(object)localPlayer == (Object)null) ? ((Component)val).transform.position : ((Component)localPlayer).transform.position);
			return true;
		}

		private static Camera ResolveCamera()
		{
			int frameCount = Time.frameCount;
			bool flag = CacheVerification.CameraCacheAllowed && !ExternalVisualModCatalog.CameraOwnerDetected;
			if (!flag)
			{
				Invalidate();
			}
			if (flag && sampledFrame == frameCount && (Object)(object)sampledCamera != (Object)null && ((Behaviour)sampledCamera).enabled && ((Component)sampledCamera).gameObject.activeInHierarchy)
			{
				if (CacheVerification.ShouldCheckCamera())
				{
					Camera mainCamera = Utils.GetMainCamera();
					if (!CacheVerification.VerifyCamera(sampledCamera, mainCamera))
					{
						sampledCamera = null;
						sampledFrame = -1;
						return mainCamera;
					}
				}
				hits++;
				return sampledCamera;
			}
			misses++;
			Camera mainCamera2 = Utils.GetMainCamera();
			if (flag && (Object)(object)mainCamera2 != (Object)null && ((Behaviour)mainCamera2).enabled && ((Component)mainCamera2).gameObject.activeInHierarchy)
			{
				sampledCamera = mainCamera2;
				sampledFrame = frameCount;
			}
			else
			{
				sampledCamera = null;
				sampledFrame = -1;
			}
			return mainCamera2;
		}

		internal static void Invalidate()
		{
			sampledCamera = null;
			sampledFrame = -1;
		}

		internal static string BuildDiagnosticReport()
		{
			return "scope=BCO_LIGHTLOD_ONLY\nreferencePoint=LIVE_TRANSFORM_EACH_ACCESS\ncameraFrameHits=" + hits + "\ncameraFrameMisses=" + misses + "\ncacheWindow=SAME_UNITY_FRAME\n";
		}
	}
	internal struct OwnedStateGuard<T>
	{
		private readonly T before;

		private readonly T expected;

		private bool owned;

		internal OwnedStateGuard(T before, T expected)
		{
			this.before = before;
			this.expected = expected;
			owned = true;
		}

		internal bool TryGetPrevious(T observed, out T previous)
		{
			previous = before;
			return owned && EqualityComparer<T>.Default.Equals(expected, observed);
		}

		internal void Disown()
		{
			owned = false;
		}
	}
	internal static class ReusableBufferPool<T>
	{
		private const int MaximumPooledLength = 256;

		private const int MaximumRetainedArrays = 4;

		private static readonly Stack<T[]> free = new Stack<T[]>(4);

		private static int reused;

		private static int created;

		internal static T[] Rent(int minimumLength)
		{
			if (minimumLength <= 0)
			{
				return new T[0];
			}
			if (minimumLength > 256)
			{
				created++;
				return new T[minimumLength];
			}
			int num;
			for (num = 1; num < minimumLength; num <<= 1)
			{
			}
			lock (free)
			{
				if (free.Count != 0 && free.Peek().Length >= num)
				{
					reused++;
					return free.Pop();
				}
			}
			created++;
			return new T[num];
		}

		internal static void Return(T[] buffer)
		{
			if (buffer == null)
			{
				return;
			}
			Array.Clear(buffer, 0, buffer.Length);
			if (buffer.Length == 0 || buffer.Length > 256)
			{
				return;
			}
			lock (free)
			{
				if (free.Count < 4)
				{
					free.Push(buffer);
				}
			}
		}

		internal static string BuildDiagnosticReport()
		{
			lock (free)
			{
				return "pool=" + typeof(T).Name + " retained=" + free.Count + " reused=" + reused + " created=" + created + " maxArrays=" + 4 + " maxLength=" + 256;
			}
		}

		internal static void Clear()
		{
			lock (free)
			{
				free.Clear();
			}
		}
	}
	internal static class GpuInstancingService
	{
		private struct OwnedMaterialState
		{
			internal OwnedStateGuard<bool> Instancing;

			internal Shader ShaderAtWrite;
		}

		private static readonly Dictionary<Material, OwnedMaterialState> changed = new Dictionary<Material, OwnedMaterialState>();

		private static int deferredRestoreCount;

		private static readonly HashSet<string> processed = new HashSet<string>(StringComparer.Ordinal);

		private static string lastPrefabList = "";

		private static string lastMaterialList = "";

		private static string[] prefabs = new string[0];

		private static readonly HashSet<string> materials = new HashSet<string>(StringComparer.Ordinal);

		private static float nextScan;

		private static int cursor;

		internal static void Tick(OptimizerConfig config)
		{
			if (config == null || !config.Enabled.Value || config.ConservativeMode.Value || !config.GpuInstancing.Value || Application.isBatchMode || ModCompatibility.AbsoluteOverhaulInstalled || ExternalVisualModCatalog.CompetingSharedRendererInstalled)
			{
				if (changed.Count != 0 || processed.Count != 0)
				{
					Restore();
				}
				return;
			}
			string text = config.GpuInstancingPrefabs.Value ?? "";
			string text2 = config.GpuInstancingMaterials.Value ?? "";
			if (text != lastPrefabList || text2 != lastMaterialList)
			{
				Restore();
				lastPrefabList = text;
				lastMaterialList = text2;
				prefabs = Parse(text);
				materials.Clear();
				string[] array = Parse(text2);
				foreach (string item in array)
				{
					materials.Add(item);
				}
				cursor = 0;
			}
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				Restore();
			}
			else
			{
				if (prefabs.Length == 0 || materials.Count == 0 || Time.unscaledTime < nextScan)
				{
					return;
				}
				nextScan = Time.unscaledTime + 0.05f;
				int num = Mathf.Clamp(config.GpuInstancingPrefabsPerTick.Value, 1, 8);
				while (num-- > 0 && cursor < prefabs.Length)
				{
					string text3 = prefabs[cursor++];
					if (processed.Contains(text3))
					{
						continue;
					}
					try
					{
						GameObject prefab = ZNetScene.instance.GetPrefab(text3);
						if ((Object)(object)prefab == (Object)null)
						{
							continue;
						}
						MeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren<MeshRenderer>(true);
						MeshRenderer[] array2 = componentsInChildren;
						foreach (MeshRenderer val in array2)
						{
							if ((Object)(object)val == (Object)null)
							{
								continue;
							}
							Material[] sharedMaterials = ((Renderer)val).sharedMaterials;
							foreach (Material val2 in sharedMaterials)
							{
								if (!((Object)(object)val2 == (Object)null) && materials.Contains(((Object)val2).name) && val2.renderQueue <= 2500 && !((Object)(object)val2.shader == (Object)null) && SystemInfo.supportsInstancing && val2.shader.isSupported && !changed.ContainsKey(val2) && !val2.enableInstancing)
								{
									changed.Add(val2, new OwnedMaterialState
									{
										Instancing = new OwnedStateGuard<bool>(val2.enableInstancing, expected: true),
										ShaderAtWrite = val2.shader
									});
									val2.enableInstancing = true;
								}
							}
						}
						processed.Add(text3);
					}
					catch (Exception ex)
					{
						Launch.LogWarning("GPU Instancing skipped prefab '" + text3 + "': " + ex.Message);
						processed.Add(text3);
					}
				}
				if (cursor >= prefabs.Length)
				{
					cursor = 0;
					nextScan = Time.unscaledTime + 10f;
				}
			}
		}

		internal static string BuildOwnershipReport()
		{
			return "scope=BCO_EXPLICIT_MATERIAL_ALLOWLIST_ONLY\ntrackedMaterials=" + changed.Count + "\nrestoreSkippedForeignState=" + deferredRestoreCount + "\n";
		}

		private static string[] Parse(string input)
		{
			string[] array = input.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			List<string> list = new List<string>(array.Length);
			string[] array2 = array;
			foreach (string text in array2)
			{
				string text2 = text.Trim();
				if (text2.Length > 0 && !list.Contains(text2))
				{
					list.Add(text2);
				}
			}
			return list.ToArray();
		}

		internal static void Restore()
		{
			foreach (KeyValuePair<Material, OwnedMaterialState> item in changed)
			{
				Material key = item.Key;
				if ((Object)(object)key == (Object)null)
				{
					continue;
				}
				try
				{
					if (key.shader == item.Value.ShaderAtWrite && item.Value.Instancing.TryGetPrevious(key.enableInstancing, out var previous))
					{
						key.enableInstancing = previous;
					}
					else
					{
						deferredRestoreCount++;
					}
				}
				catch (Exception ex)
				{
					deferredRestoreCount++;
					Launch.LogWarning("GPU Instancing ownership restore failed: " + ex.GetType().Name);
				}
			}
			changed.Clear();
			processed.Clear();
			nextScan = 0f;
			cursor = 0;
		}
	}
	internal static class LightLodScheduler
	{
		private sealed class Entry
		{
			internal LightLod Lod;

			internal int Id;

			internal int Index;

			internal bool TargetLight;

			internal bool TargetShadow;

			internal bool Fading;

			internal int FadingIndex = -1;
		}

		private static readonly List<Entry> Entries = new List<Entry>();

		private static readonly Dictionary<int, Entry> Map = new Dictionary<int, Entry>();

		private static readonly List<Entry> Fading = new List<Entry>();

		private static int cursor;

		private static bool enabled;

		private static float fractionalChecks;

		private static bool lastFractionalMode;

		internal static void SetEnabled(bool value)
		{
			if (enabled != value)
			{
				enabled = value;
				if (enabled)
				{
					TakeOwnershipOfExisting();
				}
				else
				{
					RestoreVanilla();
				}
			}
		}

		internal static void Register(LightLod lod)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (!enabled || (Object)(object)lod == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)lod).GetInstanceID();
			if (Map.TryGetValue(instanceID, out var value))
			{
				if (value.Lod == lod)
				{
					return;
				}
				RemoveEntry(value);
			}
			Vector3 point;
			bool hasPoint = TryGetReferencePoint(out point);
			AddEntry(lod, instanceID, hasPoint, point);
		}

		private static void AddEntry(LightLod lod, int id, bool hasPoint, Vector3 point)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			Entry entry = new Entry
			{
				Lod = lod,
				Id = id,
				Index = Entries.Count
			};
			Entries.Add(entry);
			Map[id] = entry;
			if (hasPoint)
			{
				Evaluate(entry, point);
			}
		}

		internal static void Unregister(LightLod lod)
		{
			if (!((Object)(object)lod == (Object)null) && Map.TryGetValue(((Object)lod).GetInstanceID(), out var value) && value.Lod == lod)
			{
				RemoveEntry(value);
			}
		}

		internal static void Tick(float dt)
		{
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			if (!enabled || Entries.Count == 0)
			{
				return;
			}
			if (TryGetReferencePoint(out var point))
			{
				float num = Mathf.Max(0.25f, RuntimeTuning.LightLodDecisionInterval);
				bool flag = Launch.Settings != null && Launch.Settings.LightLodFractionalBudget.Value;
				if (flag != lastFractionalMode)
				{
					fractionalChecks = 0f;
					lastFractionalMode = flag;
				}
				int num2;
				if (flag)
				{
					fractionalChecks = Mathf.Min((float)Entries.Count, fractionalChecks + (float)Entries.Count * Mathf.Min(0.25f, Mathf.Max(0f, dt)) / num);
					num2 = Mathf.FloorToInt(fractionalChecks);
				}
				else
				{
					num2 = Mathf.Max(1, Mathf.CeilToInt((float)Entries.Count * Mathf.Min(0.25f, Mathf.Max(0f, dt)) / num));
				}
				int num3 = Mathf.Min(Entries.Count, Mathf.Min(RuntimeTuning.LightLodChecksPerFrame, num2));
				if (flag)
				{
					fractionalChecks -= num3;
				}
				for (int i = 0; i < num3; i++)
				{
					if (Entries.Count <= 0)
					{
						break;
					}
					if (cursor >= Entries.Count)
					{
						cursor = 0;
					}
					Entry entry = Entries[cursor++];
					if ((Object)(object)entry.Lod == (Object)null || !((Behaviour)entry.Lod).enabled || !((Component)entry.Lod).gameObject.activeInHierarchy)
					{
						RemoveEntry(entry);
						continue;
					}
					Evaluate(entry, point);
					RuntimeStats.Inc(ref RuntimeStats.LightLodDecisionChecks);
				}
			}
			for (int num4 = Fading.Count - 1; num4 >= 0; num4--)
			{
				Entry entry2 = Fading[num4];
				if (!entry2.Fading)
				{
					RemoveFadingAt(num4);
				}
				else if ((Object)(object)entry2.Lod == (Object)null || !((Behaviour)entry2.Lod).enabled || !((Component)entry2.Lod).gameObject.activeInHierarchy)
				{
					RemoveFadingAt(num4);
				}
				else if (AdvanceFade(entry2, dt))
				{
					RemoveFadingAt(num4);
				}
			}
		}

		internal static void RestoreVanilla()
		{
			int num = 0;
			string text = null;
			try
			{
				for (int i = 0; i < Entries.Count; i++)
				{
					try
					{
						LightLod lod = Entries[i].Lod;
						if ((Object)(object)lod != (Object)null && ((Behaviour)lod).enabled && ((Component)lod).gameObject.activeInHierarchy)
						{
							((MonoBehaviour)lod).StopCoroutine("UpdateLoop");
							((MonoBehaviour)lod).StartCoroutine("UpdateLoop");
						}
					}
					catch (Exception ex)
					{
						num++;
						if (text == null)
						{
							text = ex.GetType().Name + ": " + ex.Message;
						}
					}
				}
			}
			finally
			{
				Entries.Clear();
				Map.Clear();
				Fading.Clear();
				cursor = 0;
				fractionalChecks = 0f;
				lastFractionalMode = false;
				FrameCameraSnapshot.Invalidate();
			}
			if (num != 0)
			{
				Launch.LogWarning("LightLod rollback: " + num + " component(s) could not restart vanilla UpdateLoop. First error: " + text);
			}
		}

		private static void TakeOwnershipOfExisting()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			Vector3 point = Vector3.zero;
			bool hasPoint = false;
			bool flag = false;
			foreach (LightLod light in LightLod.m_lights)
			{
				if ((Object)(object)light == (Object)null || !((Behaviour)light).enabled || !((Component)light).gameObject.activeInHierarchy)
				{
					continue;
				}
				((MonoBehaviour)light).StopCoroutine("UpdateLoop");
				int instanceID = ((Object)light).GetInstanceID();
				if (Map.TryGetValue(instanceID, out var value))
				{
					if (value.Lod == light)
					{
						continue;
					}
					RemoveEntry(value);
				}
				if (!flag)
				{
					hasPoint = TryGetReferencePoint(out point);
					flag = true;
				}
				AddEntry(light, instanceID, hasPoint, point);
			}
		}

		private static bool TryGetReferencePoint(out Vector3 point)
		{
			return FrameCameraSnapshot.TryGetLightReferencePoint(out point);
		}

		private static void Evaluate(Entry e, Vector3 reference)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			LightLod lod = e.Lod;
			if (!((Object)(object)lod == (Object)null) && !((Object)(object)lod.m_light == (Object)null))
			{
				Vector3 val = ((Component)lod).transform.position - reference;
				float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
				bool flag = !lod.m_lightLod || (sqrMagnitude < lod.m_lightDistance * lod.m_lightDistance && (lod.m_lightPrio < LightLod.m_lightLimit || LightLod.m_lightLimit < 0));
				bool flag2 = !lod.m_shadowLod || (sqrMagnitude < lod.m_shadowDistance * lod.m_shadowDistance && (lod.m_lightPrio < LightLod.m_shadowLimit || LightLod.m_shadowLimit < 0));
				bool flag3 = e.TargetLight != flag || e.TargetShadow != flag2;
				e.TargetLight = flag;
				e.TargetShadow = flag2;
				if (flag3 || !IsSettled(e))
				{
					AddFading(e);
				}
			}
		}

		private static bool AdvanceFade(Entry e, float dt)
		{
			LightLod lod = e.Lod;
			Light light = lod.m_light;
			if ((Object)(object)light == (Object)null)
			{
				return true;
			}
			if (lod.m_lightLod)
			{
				if (e.TargetLight)
				{
					((Behaviour)light).enabled = true;
					light.range = Mathf.Min(lod.m_baseRange, light.range + dt * lod.m_baseRange);
				}
				else
				{
					light.range = Mathf.Max(0f, light.range - dt * lod.m_baseRange);
					if (light.range <= 0f)
					{
						((Behaviour)light).enabled = false;
					}
				}
			}
			if (lod.m_shadowLod)
			{
				if (e.TargetShadow)
				{
					light.shadows = (LightShadows)2;
					light.shadowStrength = Mathf.Min(lod.m_baseShadowStrength, light.shadowStrength + dt * lod.m_baseShadowStrength);
				}
				else
				{
					light.shadowStrength = Mathf.Max(0f, light.shadowStrength - dt * lod.m_baseShadowStrength);
					if (light.shadowStrength <= 0f)
					{
						light.shadows = (LightShadows)0;
					}
				}
			}
			return IsSettled(e);
		}

		private static bool IsSettled(Entry e)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			LightLod lod = e.Lod;
			Light val = (((Object)(object)lod == (Object)null) ? null : lod.m_light);
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			bool flag = true;
			if (lod.m_lightLod)
			{
				flag = ((!e.TargetLight) ? (!((Behaviour)val).enabled && val.range <= 0f) : (((Behaviour)val).enabled && val.range >= lod.m_baseRange));
			}
			bool flag2 = true;
			if (lod.m_shadowLod)
			{
				flag2 = ((!e.TargetShadow) ? ((int)val.shadows == 0 && val.shadowStrength <= 0f) : ((int)val.shadows != 0 && val.shadowStrength >= lod.m_baseShadowStrength));
			}
			return flag && flag2;
		}

		private static void AddFading(Entry e)
		{
			if (!e.Fading)
			{
				e.Fading = true;
				e.FadingIndex = Fading.Count;
				Fading.Add(e);
			}
		}

		private static void RemoveFadingAt(int index)
		{
			int num = Fading.Count - 1;
			Entry entry = Fading[index];
			if (index != num)
			{
				Entry entry2 = Fading[num];
				Fading[index] = entry2;
				entry2.FadingIndex = index;
			}
			Fading.RemoveAt(num);
			entry.Fading = false;
			entry.FadingIndex = -1;
		}

		private static void RemoveEntry(Entry e)
		{
			if (e != null && e.Index >= 0 && e.Index < Entries.Count)
			{
				if (e.FadingIndex >= 0 && e.FadingIndex < Fading.Count && Fading[e.FadingIndex] == e)
				{
					RemoveFadingAt(e.FadingIndex);
				}
				int id = e.Id;
				int index = Entries.Count - 1;
				Entry entry = Entries[index];
				Entries[e.Index] = entry;
				entry.Index = e.Index;
				Entries.RemoveAt(index);
				Map.Remove(id);
				e.Index = -1;
				e.Fading = false;
				e.FadingIndex = -1;
				if (cursor > Entries.Count)
				{
					cursor = Entries.Count;
				}
			}
		}
	}
	internal static class RuntimeTuning
	{
		internal static float VisualSafety;

		internal static float StaticVisualSafety;

		internal static float ArmorClothInterval;

		internal static float LightNearSqr;

		internal static float LightMidSqr;

		internal static float LightFarSqr;

		internal static float LightMidInterval;

		internal static float LightFarInterval;

		internal static float LightDistantInterval;

		internal static float LightDistanceCheckInterval;

		internal static float LightLodDecisionInterval;

		internal static int LightLodChecksPerFrame;

		internal static float SmokeRendererInterval;

		internal static float WindmillAudioInterval;

		internal static float VagonAudioInterval;

		internal static void Refresh(OptimizerConfig c)
		{
			VisualSafety = Mathf.Max(5f, c.VisualSafetyRefreshSeconds.Value);
			StaticVisualSafety = Mathf.Max(10f, c.StaticVisualSafetyRefreshSeconds.Value);
			if (c.ConservativeMode.Value)
			{
				VisualSafety = Mathf.Min(VisualSafety, 5f);
				StaticVisualSafety = Mathf.Min(StaticVisualSafety, 10f);
			}
			ArmorClothInterval = UpdateRateLimiter.IntervalFromRate(c.ArmorStandClothRate.Value);
			float num = Mathf.Max(0f, c.LightFlickerNearDistance.Value);
			float num2 = Mathf.Max(num, c.LightFlickerMidDistance.Value);
			float num3 = Mathf.Max(num2, c.LightFlickerFarDistance.Value);
			LightNearSqr = num * num;
			LightMidSqr = num2 * num2;
			LightFarSqr = num3 * num3;
			LightMidInterval = UpdateRateLimiter.IntervalFromRate(c.LightFlickerMidRate.Value);
			LightFarInterval = UpdateRateLimiter.IntervalFromRate(c.LightFlickerFarRate.Value);
			LightDistantInterval = UpdateRateLimiter.IntervalFromRate(c.LightFlickerDistantRate.Value);
			LightDistanceCheckInterval = UpdateRateLimiter.IntervalFromRate(c.LightFlickerDistanceCheckRate.Value);
			LightLodDecisionInterval = UpdateRateLimiter.IntervalFromRate(c.LightLodDistanceCheckRate.Value);
			LightLodChecksPerFrame = Mathf.Clamp(c.LightLodChecksPerFrame.Value, 32, 4096);
			SmokeRendererInterval = UpdateRateLimiter.IntervalFromRate(c.SmokeRendererRate.Value);
			WindmillAudioInterval = UpdateRateLimiter.IntervalFromRate(c.WindmillAudioRate.Value);
			VagonAudioInterval = UpdateRateLimiter.IntervalFromRate(c.VagonAudioRate.Value);
		}
	}
	internal static class UpdateRateLimiter
	{
		internal static float IntervalFromRate(float updatesPerSecond)
		{
			return 1f / Mathf.Max(0.01f, updatesPerSecond);
		}

		internal static bool IsDue(ref float nextTime, float interval, float now, int phaseSeed)
		{
			if (interval <= 0f)
			{
				nextTime = now;
				return true;
			}
			if (nextTime <= 0f)
			{
				nextTime = now + interval * Phase01(phaseSeed);
				return true;
			}
			if (now < nextTime)
			{
				return false;
			}
			nextTime = now + interval;
			return true;
		}

		internal static float StaggeredSafetyDeadline(float now, float maximumInterval, int phaseSeed)
		{
			if (maximumInterval <= 0f)
			{
				return now;
			}
			float num = 0.75f + 0.25f * Phase01(phaseSeed);
			return now + maximumInterval * num;
		}

		internal static bool IsDiscontinuous(ref float lastSeenTime, float now, float maximumGap)
		{
			bool result = lastSeenTime > 0f && (now < lastSeenTime || now - lastSeenTime > maximumGap);
			lastSeenTime = now;
			return result;
		}

		internal static float Phase01Public(int seed)
		{
			return Phase01(seed);
		}

		private static float Phase01(int seed)
		{
			uint num = (uint)seed;
			num ^= num >> 16;
			num *= 2146121005;
			num ^= num >> 15;
			num *= 2221713035u;
			num ^= num >> 16;
			return (float)(num & 0xFFFFFF) / 16777215f;
		}
	}
	internal static class VanillaCollectionRegistry
	{
		internal static List<Piece> Pieces => Piece.s_allPieces;

		internal static HashSet<Piece> ComfortPieces => Piece.s_allComfortPieces;

		internal static List<CraftingStation> CraftingStations => CraftingStation.m_allStations;

		internal static List<StationExtension> StationExtensions => StationExtension.m_allExtensions;

		internal static int GhostLayer { get; private set; }

		internal static void Initialize()
		{
			GhostLayer = LayerMask.NameToLayer("ghost");
		}
	}
	internal static class WeakStateStore<TKey, TState> where TKey : class where TState : class, new()
	{
		private static readonly ConditionalWeakTable<TKey, TState> States = new ConditionalWeakTable<TKey, TState>();

		private static readonly ConditionalWeakTable<TKey, TState>.CreateValueCallback CreateCallback = Create;

		internal static TState Get(TKey key)
		{
			return States.GetValue(key, CreateCallback);
		}

		internal static bool TryGet(TKey key, out TState state)
		{
			state = null;
			return key != null && States.TryGetValue(key, out state);
		}

		private static TState Create(TKey key)
		{
			return new TState();
		}

		internal static void Remove(TKey key)
		{
			if (key != null)
			{
				States.Remove(key);
			}
		}
	}
	internal sealed class WeakUnityRegistry<T> where T : Object
	{
		private readonly Dictionary<int, WeakReference> entries = new Dictionary<int, WeakReference>();

		private readonly List<int> dead = new List<int>();

		private int addsUntilPrune = 64;

		internal int Count => entries.Count;

		internal void Add(T value)
		{
			if ((Object)(object)value == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)value).GetInstanceID();
			if (entries.TryGetValue(instanceID, out var value2))
			{
				if (value2.Target != (object)value)
				{
					value2.Target = value;
				}
				return;
			}
			entries.Add(instanceID, new WeakReference(value));
			if (--addsUntilPrune <= 0)
			{
				addsUntilPrune = 64;
				PruneDead();
			}
		}

		internal void Remove(T value)
		{
			if (!((Object)(object)value == (Object)null))
			{
				int instanceID = ((Object)value).GetInstanceID();
				if (entries.TryGetValue(instanceID, out var value2) && value2.Target == (object)value)
				{
					entries.Remove(instanceID);
				}
			}
		}

		internal void PruneDead()
		{
			if (entries.Count == 0)
			{
				return;
			}
			dead.Clear();
			foreach (KeyValuePair<int, WeakReference> entry in entries)
			{
				object? target = entry.Value.Target;
				T val = (T)((target is T) ? target : null);
				if ((Object)(object)val == (Object)null)
				{
					dead.Add(entry.Key);
				}
			}
			for (int i = 0; i < dead.Count; i++)
			{
				entries.Remove(dead[i]);
			}
			dead.Clear();
		}

		internal void ForEachAlive(Action<T> action)
		{
			dead.Clear();
			foreach (KeyValuePair<int, WeakReference> entry in entries)
			{
				object? target = entry.Value.Target;
				T val = (T)((target is T) ? target : null);
				if ((Object)(object)val == (Object)null)
				{
					dead.Add(entry.Key);
				}
				else
				{
					action(val);
				}
			}
			for (int i = 0; i < dead.Count; i++)
			{
				entries.Remove(dead[i]);
			}
			dead.Clear();
		}

		internal void Clear()
		{
			entries.Clear();
			dead.Clear();
			addsUntilPrune = 64;
		}
	}
}
namespace BalrondVisualOptimizer.Patches
{
	internal static class GroundLootPatches
	{
		private static PatchRuntimeGate gate;

		private static readonly Collider[] Empty = (Collider[])(object)new Collider[0];

		private static Collider[] queryBuffer = (Collider[])(object)new Collider[64];

		private static readonly Dictionary<int, Collider[]> resultArrays = new Dictionary<int, Collider[]>();

		private static Collider[] activeResult;

		private static int nestingDepth;

		private const int MaxNonAllocCount = 1024;

		private const int MaxCachedSizes = 32;

		internal static void Install(PatchInstaller installer)
		{
			MethodInfo target = AccessTools.Method(typeof(ItemDrop), "AutoStackItems", Type.EmptyTypes, (Type[])null);
			gate = installer.Install("ItemDrop.AutoStackItems NonAlloc physics query", target, AccessTools.Method(typeof(GroundLootPatches), "BeforeAutoStack", (Type[])null, (Type[])null), AccessTools.Method(typeof(GroundLootPatches), "AfterAutoStack", (Type[])null, (Type[])null), Launch.Settings.GroundLootNonAlloc, strictForeignPatchCheck: true, disabledByConservativeMode: false, AccessTools.Method(typeof(GroundLootPatches), "ReplaceQuery", (Type[])null, (Type[])null));
		}

		private static IEnumerable<CodeInstruction> ReplaceQuery(IEnumerable<CodeInstruction> source)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(source);
			MethodInfo methodInfo = AccessTools.Method(typeof(Physics), "OverlapSphere", new Type[3]
			{
				typeof(Vector3),
				typeof(float),
				typeof(int)
			}, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(GroundLootPatches), "CachedOverlapSphere", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				throw new InvalidOperationException("Physics overload or replacement method unavailable");
			}
			int num = 0;
			for (int i = 0; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(list[i], methodInfo))
				{
					num++;
				}
			}
			if (num != 1)
			{
				throw new InvalidOperationException("AutoStackItems query IL is not the audited 3-argument OverlapSphere pattern (matches=" + num + ")");
			}
			for (int j = 0; j < list.Count; j++)
			{
				if (CodeInstructionExtensions.Calls(list[j], methodInfo))
				{
					list[j].opcode = OpCodes.Call;
					list[j].operand = methodInfo2;
				}
			}
			return list;
		}

		private static void BeforeAutoStack()
		{
			nestingDepth++;
		}

		private static Collider[] CachedOverlapSphere(Vector3 position, float radius, int mask)
		{
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			if (gate == null || !gate.Enabled || nestingDepth != 1 || activeResult != null)
			{
				return Physics.OverlapSphere(position, radius, mask);
			}
			try
			{
				int num;
				while (true)
				{
					num = Physics.OverlapSphereNonAlloc(position, radius, queryBuffer, mask);
					if (num < queryBuffer.Length)
					{
						break;
					}
					if (queryBuffer.Length >= 1024)
					{
						Array.Clear(queryBuffer, 0, num);
						return Physics.OverlapSphere(position, radius, mask);
					}
					queryBuffer = (Collider[])(object)new Collider[Math.Min(queryBuffer.Length * 2, 1024)];
				}
				if (num == 0)
				{
					return Empty;
				}
				if (!resultArrays.TryGetValue(num, out var value))
				{
					if (resultArrays.Count >= 32)
					{
						Array.Clear(queryBuffer, 0, num);
						return Physics.OverlapSphere(position, radius, mask);
					}
					value = (Collider[])(object)new Collider[num];
					resultArrays.Add(num, value);
				}
				Array.Copy(queryBuffer, value, num);
				Array.Clear(queryBuffer, 0, num);
				activeResult = value;
				RuntimeStats.Inc(ref RuntimeStats.GroundLootQueriesReused);
				return value;
			}
			catch
			{
				if (activeResult != null)
				{
					Array.Clear(activeResult, 0, activeResult.Length);
					activeResult = null;
				}
				return Physics.OverlapSphere(position, radius, mask);
			}
		}

		private static void AfterAutoStack()
		{
			if (nestingDepth > 0)
			{
				if (nestingDepth == 1 && activeResult != null)
				{
					Array.Clear(activeResult, 0, activeResult.Length);
					activeResult = null;
				}
				nestingDepth--;
			}
		}

		internal static void Shutdown()
		{
			if (activeResult != null)
			{
				Array.Clear(activeResult, 0, activeResult.Length);
				activeResult = null;
			}
			nestingDepth = 0;
			resultArrays.Clear();
			queryBuffer = (Collider[])(object)new Collider[64];
		}
	}
	internal static class SkyAlphaPatches
	{
		private static PatchRuntimeGate skyGate;

		private static PatchRuntimeGate pieceCreatedGate;

		private static PatchRuntimeGate pieceRemovedGate;

		private static PatchRuntimeGate doorChangedGate;

		private static bool dirty = true;

		private static bool valid;

		private static Vector3 previousPosition;

		private static float lastUpdate;

		private static int previousPlayerId;

		internal static void Install(PatchInstaller installer)
		{
			MethodInfo target = FindSkyMethod();
			skyGate = installer.Install("SkyAlpha bounded presentation cache", target, AccessTools.Method(typeof(SkyAlphaPatches), "BeforeSkyAlpha", (Type[])null, (Type[])null), null, Launch.Settings.SkyAlphaCache, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			if (skyGate != null && !skyGate.PermanentlyBlocked)
			{
				pieceCreatedGate = installer.Install("SkyAlpha invalidate on Piece.Awake", AccessTools.Method(typeof(Piece), "Awake", Type.EmptyTypes, (Type[])null), null, AccessTools.Method(typeof(SkyAlphaPatches), "PieceChanged", (Type[])null, (Type[])null), Launch.Settings.SkyAlphaCache, strictForeignPatchCheck: true, disabledByConservativeMode: true);
				pieceRemovedGate = installer.Install("SkyAlpha invalidate on Piece.OnDestroy", AccessTools.Method(typeof(Piece), "OnDestroy", Type.EmptyTypes, (Type[])null), null, AccessTools.Method(typeof(SkyAlphaPatches), "PieceChanged", (Type[])null, (Type[])null), Launch.Settings.SkyAlphaCache, strictForeignPatchCheck: true, disabledByConservativeMode: true);
				doorChangedGate = installer.Install("SkyAlpha invalidate on Door.Interact", AccessTools.Method(typeof(Door), "Interact", new Type[3]
				{
					typeof(Humanoid),
					typeof(bool),
					typeof(bool)
				}, (Type[])null), null, AccessTools.Method(typeof(SkyAlphaPatches), "DoorChanged", (Type[])null, (Type[])null), Launch.Settings.SkyAlphaCache, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			}
		}

		private static MethodInfo FindSkyMethod()
		{
			MethodInfo methodInfo = null;
			try
			{
				Type[] types = typeof(Player).Assembly.GetTypes();
				foreach (Type type in types)
				{
					MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					foreach (MethodInfo methodInfo2 in methods)
					{
						if ((!(methodInfo2.Name != "SkyAlpha") || !(methodInfo2.Name != "UpdateSkyAlpha")) && !methodInfo2.IsAbstract && !methodInfo2.IsGenericMethod && !(methodInfo2.ReturnType != typeof(void)) && methodInfo2.GetParameters().Length == 0 && typeof(MonoBehaviour).IsAssignableFrom(type))
						{
							if (methodInfo != null)
							{
								return null;
							}
							methodInfo = methodInfo2;
						}
					}
				}
			}
			catch (ReflectionTypeLoadException)
			{
				return null;
			}
			return methodInfo;
		}

		private static bool BeforeSkyAlpha()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: 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_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			if (skyGate == null || !skyGate.Enabled)
			{
				return true;
			}
			if (pieceCreatedGate == null || !pieceCreatedGate.Enabled || pieceRemovedGate == null || !pieceRemovedGate.Enabled || doorChangedGate == null || !doorChangedGate.Enabled)
			{
				return true;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsTeleporting())
			{
				valid = false;
				return true;
			}
			Vector3 position = ((Component)localPlayer).transform.position;
			float unscaledTime = Time.unscaledTime;
			float num = Mathf.Clamp(Launch.Settings.SkyAlphaMaxAge.Value, 1f, 5f);
			float value = Launch.Settings.SkyAlphaMovementTolerance.Value;
			if (valid && !dirty && previousPlayerId == ((Object)localPlayer).GetInstanceID())
			{
				Vector3 val = position - previousPosition;
				if (!(((Vector3)(ref val)).sqrMagnitude >= value * value) && !(unscaledTime < lastUpdate) && !(unscaledTime - lastUpdate >= num))
				{
					RuntimeStats.Inc(ref RuntimeStats.SkyAlphaReused);
					return false;
				}
			}
			previousPosition = position;
			previousPlayerId = ((Object)localPlayer).GetInstanceID();
			lastUpdate = unscaledTime;
			valid = true;
			dirty = false;
			return true;
		}

		private static void PieceChanged(Piece __instance)
		{
			//IL_004f: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (skyGate == null || !skyGate.Enabled)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)__instance == (Object)null)
			{
				dirty = true;
				return;
			}
			Vector3 val = ((Component)__instance).transform.position - ((Component)localPlayer).transform.position;
			float value = Launch.Settings.SkyAlphaInvalidationRadius.Value;
			if (val.x * val.x + val.z * val.z <= value * value)
			{
				dirty = true;
			}
		}

		private static void DoorChanged()
		{
			dirty = true;
		}

		internal static void Invalidate()
		{
			dirty = true;
		}

		internal static void Reset()
		{
			valid = false;
			dirty = true;
			previousPlayerId = 0;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.ZSFXOptimizations
{
	internal static class ZSFXPatches
	{
		private static PatchRuntimeGate updateGate;

		internal static void Install(PatchInstaller installer)
		{
			updateGate = installer.Install("ZSFX.CustomUpdate idle fast gate", AccessTools.Method(typeof(ZSFX), "CustomUpdate", new Type[2]
			{
				typeof(float),
				typeof(float)
			}, (Type[])null), AccessTools.Method(typeof(ZSFXPatches), "UpdatePrefix", (Type[])null, (Type[])null), null, Launch.Settings.ZsfxDormancy, strictForeignPatchCheck: true);
		}

		private static bool UpdatePrefix(ZSFX __instance)
		{
			if (updateGate == null || !updateGate.Enabled || (Object)(object)__instance == (Object)null || (Object)(object)__instance.m_audioSource == (Object)null)
			{
				return true;
			}
			if (__instance.m_audioSource.loop || __instance.m_audioSource.isPlaying)
			{
				return true;
			}
			if ((__instance.m_playOnAwake && __instance.m_delay >= 0f) || __instance.m_fadeOutTimer >= 0f || __instance.m_fadeInTimer >= 0f)
			{
				return true;
			}
			RuntimeStats.Inc(ref RuntimeStats.ZsfxDormantFrames);
			return false;
		}

		internal static void Tick(float now)
		{
		}

		internal static void RefreshDormancy()
		{
		}

		internal static void Shutdown()
		{
		}
	}
}
namespace BalrondVisualOptimizer.Patches.WindmillOptimizations
{
	internal static class WindmillPatches
	{
		private sealed class State
		{
			internal int Epoch;

			internal float NextUpdate;

			internal float AccumulatedDelta;

			internal float LastSeenTime;
		}

		private static PatchRuntimeGate gate;

		internal static void Install(PatchInstaller installer)
		{
			gate = installer.Install("Windmill.UpdateAudio throttle", AccessTools.Method(typeof(Windmill), "UpdateAudio", new Type[1] { typeof(float) }, (Type[])null), AccessTools.Method(typeof(WindmillPatches), "Prefix", (Type[])null, (Type[])null), null, Launch.Settings.WindmillAudio, strictForeignPatchCheck: true, disabledByConservativeMode: true);
		}

		private static bool Prefix(Windmill __instance, ref float dt)
		{
			if (gate == null || !gate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			State state = WeakStateStore<Windmill, State>.Get(__instance);
			if (state.Epoch != gate.Epoch)
			{
				Reset(state, gate.Epoch);
			}
			float windmillAudioInterval = RuntimeTuning.WindmillAudioInterval;
			float time = Time.time;
			if (UpdateRateLimiter.IsDiscontinuous(ref state.LastSeenTime, time, Mathf.Max(1f, windmillAudioInterval * 3f)))
			{
				state.NextUpdate = 0f;
				state.AccumulatedDelta = 0f;
			}
			if (UpdateRateLimiter.IsDue(ref state.NextUpdate, windmillAudioInterval, time, ((Object)__instance).GetInstanceID()))
			{
				if (state.AccumulatedDelta > 0f)
				{
					dt += state.AccumulatedDelta;
					state.AccumulatedDelta = 0f;
				}
				return true;
			}
			state.AccumulatedDelta += dt;
			RuntimeStats.Inc(ref RuntimeStats.WindmillAudioSkips);
			return false;
		}

		private static void Reset(State state, int epoch)
		{
			state.Epoch = epoch;
			state.NextUpdate = 0f;
			state.AccumulatedDelta = 0f;
			state.LastSeenTime = 0f;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.VisEquipmentOptimizations
{
	internal static class VisEquipmentPatches
	{
		private struct EquipmentSignature
		{
			internal int Left;

			internal int Right;

			internal int Chest;

			internal int Legs;

			internal int Helmet;

			internal int Shoulder;

			internal int Utility;

			internal int Trinket;

			internal int Beard;

			internal int Hair;

			internal int LeftBack;

			internal int RightBack;

			internal int ShoulderVariant;

			internal int LeftVariant;

			internal int LeftBackVariant;

			internal int RightQuality;

			internal int RightBackQuality;

			internal int ShoulderQuality;

			internal int LeftQuality;

			internal int LeftBackQuality;

			internal bool SameAs(EquipmentSignature other)
			{
				return Left == other.Left && Right == other.Right && Chest == other.Chest && Legs == other.Legs && Helmet == other.Helmet && Shoulder == other.Shoulder && Utility == other.Utility && Trinket == other.Trinket && Beard == other.Beard && Hair == other.Hair && LeftBack == other.LeftBack && RightBack == other.RightBack && ShoulderVariant == other.ShoulderVariant && LeftVariant == other.LeftVariant && LeftBackVariant == other.LeftBackVariant && RightQuality == other.RightQuality && RightBackQuality == other.RightBackQuality && ShoulderQuality == other.ShoulderQuality && LeftQuality == other.LeftQuality && LeftBackQuality == other.LeftBackQuality;
			}
		}

		private sealed class State
		{
			internal int WholeEpoch;

			internal uint WholeRevision = uint.MaxValue;

			internal bool HasWhole;

			internal float WholeSafetyRefresh;

			internal int EquipmentEpoch;

			internal uint EquipmentRevision = uint.MaxValue;

			internal EquipmentSignature Equipment;

			internal bool HasEquipment;

			internal float EquipmentSafetyRefresh;

			internal int ColorEpoch;

			internal Vector3 SkinColor;

			internal Vector3 HairColor;

			internal bool HasColors;

			internal float ColorSafetyRefresh;

			internal uint ColorRevision = uint.MaxValue;

			internal int BeardInstanceId;

			internal int HairInstanceId;

			internal int ModelIndex = int.MinValue;
		}

		private static PatchRuntimeGate wholeGate;

		private static PatchRuntimeGate equipmentGate;

		private static PatchRuntimeGate colorGate;

		internal static void Install(PatchInstaller installer)
		{
			wholeGate = installer.Install("VisEquipment.UpdateVisuals whole-player revision gate", AccessTools.Method(typeof(VisEquipment), "UpdateVisuals", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(VisEquipmentPatches), "WholeVisualsPrefix", (Type[])null, (Type[])null), null, Launch.Settings.VisEquipmentWholeUpdate, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			equipmentGate = installer.Install("VisEquipment.UpdateEquipmentVisuals signature gate", AccessTools.Method(typeof(VisEquipment), "UpdateEquipmentVisuals", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(VisEquipmentPatches), "EquipmentPrefix", (Type[])null, (Type[])null), null, Launch.Settings.VisEquipmentEquipment, strictForeignPatchCheck: true);
			colorGate = installer.Install("VisEquipment.UpdateColors signature gate", AccessTools.Method(typeof(VisEquipment), "UpdateColors", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(VisEquipmentPatches), "ColorPrefix", (Type[])null, (Type[])null), null, Launch.Settings.VisEquipmentColors, strictForeignPatchCheck: true);
		}

		private static bool WholeVisualsPrefix(VisEquipment __instance)
		{
			if (wholeGate == null || !wholeGate.Enabled || (Object)(object)__instance == (Object)null || !__instance.m_isPlayer)
			{
				return true;
			}
			if ((Object)(object)__instance.m_nview == (Object)null)
			{
				return true;
			}
			ZDO zDO = __instance.m_nview.GetZDO();
			if (zDO == null)
			{
				return true;
			}
			State state = WeakStateStore<VisEquipment, State>.Get(__instance);
			if (state.WholeEpoch != wholeGate.Epoch)
			{
				state.WholeEpoch = wholeGate.Epoch;
				state.HasWhole = false;
				state.WholeRevision = uint.MaxValue;
				state.WholeSafetyRefresh = 0f;
			}
			float unscaledTime = Time.unscaledTime;
			uint dataRevision = zDO.DataRevision;
			if (state.HasWhole && state.WholeRevision == dataRevision && unscaledTime < state.WholeSafetyRefresh)
			{
				RuntimeStats.Inc(ref RuntimeStats.VisEquipmentWholeUpdateSkips);
				return false;
			}
			state.WholeRevision = dataRevision;
			state.HasWhole = true;
			state.WholeSafetyRefresh = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, RuntimeTuning.VisualSafety, ((Object)__instance).GetInstanceID() ^ 0x3A71);
			return true;
		}

		private static bool EquipmentPrefix(VisEquipment __instance)
		{
			if (equipmentGate == null || !equipmentGate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (__instance.m_isPlayer && wholeGate != null && wholeGate.Enabled)
			{
				return true;
			}
			if ((Object)(object)__instance.m_nview == (Object)null)
			{
				return true;
			}
			ZDO zDO = __instance.m_nview.GetZDO();
			if (zDO == null)
			{
				return true;
			}
			State state = WeakStateStore<VisEquipment, State>.Get(__instance);
			if (state.EquipmentEpoch != equipmentGate.Epoch)
			{
				state.EquipmentEpoch = equipmentGate.Epoch;
				state.HasEquipment = false;
				state.EquipmentRevision = uint.MaxValue;
				state.EquipmentSafetyRefresh = 0f;
			}
			float unscaledTime = Time.unscaledTime;
			uint dataRevision = zDO.DataRevision;
			if (__instance.m_isPlayer && state.HasEquipment && dataRevision == state.EquipmentRevision && unscaledTime < state.EquipmentSafetyRefresh)
			{
				RuntimeStats.Inc(ref RuntimeStats.VisEquipmentEquipmentSkips);
				return false;
			}
			int num = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_shoulderItemVariant, 0) : __instance.m_shoulderItemVariant);
			int num2 = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_leftItemVariant, 0) : __instance.m_leftItemVariant);
			int num3 = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_leftBackItemVariant, 0) : __instance.m_leftBackItemVariant);
			int num4 = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_rightItemQuality, 0) : __instance.m_rightItemQuality);
			int num5 = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_rightBackItemQuality, 0) : __instance.m_rightBackItemQuality);
			int num6 = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_shoulderItemQuality, 0) : __instance.m_shoulderItemQuality);
			int num7 = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_leftItemQuality, 0) : __instance.m_leftItemQuality);
			int num8 = (__instance.m_isPlayer ? zDO.GetInt(ZDOVars.s_leftBackItemQuality, 0) : __instance.m_leftBackItemQuality);
			if (state.HasEquipment && dataRevision == state.EquipmentRevision && state.Equipment.ShoulderVariant == num && state.Equipment.LeftVariant == num2 && state.Equipment.LeftBackVariant == num3 && state.Equipment.RightQuality == num4 && state.Equipment.RightBackQuality == num5 && state.Equipment.ShoulderQuality == num6 && state.Equipment.LeftQuality == num7 && state.Equipment.LeftBackQuality == num8 && unscaledTime < state.EquipmentSafetyRefresh)
			{
				RuntimeStats.Inc(ref RuntimeStats.VisEquipmentEquipmentSkips);
				return false;
			}
			EquipmentSignature equipmentSignature = ReadEquipmentSignature(__instance, zDO, num, num2, num3, num4, num5, num6, num7, num8);
			bool flag = !state.HasEquipment || !state.Equipment.SameAs(equipmentSignature);
			state.EquipmentRevision = dataRevision;
			if (!flag && unscaledTime < state.EquipmentSafetyRefresh)
			{
				RuntimeStats.Inc(ref RuntimeStats.VisEquipmentEquipmentSkips);
				return false;
			}
			state.Equipment = equipmentSignature;
			state.HasEquipment = true;
			state.EquipmentSafetyRefresh = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, RuntimeTuning.VisualSafety, ((Object)__instance).GetInstanceID());
			return true;
		}

		private static EquipmentSignature ReadEquipmentSignature(VisEquipment instance, ZDO zdo, int shoulderVariant, int leftVariant, int leftBackVariant, int rightQuality, int rightBackQuality, int shoulderQuality, int leftQuality, int leftBackQuality)
		{
			EquipmentSignature result = new EquipmentSignature
			{
				Left = zdo.GetInt(ZDOVars.s_leftItem, 0),
				Right = zdo.GetInt(ZDOVars.s_rightItem, 0),
				Chest = zdo.GetInt(ZDOVars.s_chestItem, 0),
				Legs = zdo.GetInt(ZDOVars.s_legItem, 0),
				Helmet = zdo.GetInt(ZDOVars.s_helmetItem, 0),
				Shoulder = zdo.GetInt(ZDOVars.s_shoulderItem, 0),
				Utility = zdo.GetInt(ZDOVars.s_utilityItem, 0),
				Trinket = zdo.GetInt(ZDOVars.s_trinketItem, 0),
				ShoulderVariant = shoulderVariant,
				LeftVariant = leftVariant,
				LeftBackVariant = leftBackVariant,
				RightQuality = rightQuality,
				RightBackQuality = rightBackQuality,
				ShoulderQuality = shoulderQuality,
				LeftQuality = leftQuality,
				LeftBackQuality = leftBackQuality
			};
			if (instance.m_isPlayer)
			{
				if (!instance.m_isArmorStand)
				{
					result.Beard = zdo.GetInt(ZDOVars.s_beardItem, 0);
					result.Hair = zdo.GetInt(ZDOVars.s_hairItem, 0);
				}
				result.LeftBack = zdo.GetInt(ZDOVars.s_leftBackItem, 0);
				result.RightBack = zdo.GetInt(ZDOVars.s_rightBackItem, 0);
			}
			return result;
		}

		private static bool ColorPrefix(VisEquipment __instance)
		{
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			if (colorGate == null || !colorGate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (__instance.m_isPlayer && wholeGate != null && wholeGate.Enabled)
			{
				return true;
			}
			if ((Object)(object)__instance.m_nview == (Object)null)
			{
				return true;
			}
			ZDO zDO = __instance.m_nview.GetZDO();
			if (zDO == null)
			{
				return true;
			}
			State state = WeakStateStore<VisEquipment, State>.Get(__instance);
			if (state.ColorEpoch != colorGate.Epoch)
			{
				state.ColorEpoch = colorGate.Epoch;
				state.HasColors = false;
				state.ColorRevision = uint.MaxValue;
				state.ColorSafetyRefresh = 0f;
				state.BeardInstanceId = 0;
				state.HairInstanceId = 0;
			}
			float unscaledTime = Time.unscaledTime;
			uint dataRevision = zDO.DataRevision;
			int num = ((!((Object)(object)__instance.m_beardItemInstance == (Object)null)) ? ((Object)__instance.m_beardItemInstance).GetInstanceID() : 0);
			int num2 = ((!((Object)(object)__instance.m_hairItemInstance == (Object)null)) ? ((Object)__instance.m_hairItemInstance).GetInstanceID() : 0);
			int num3 = zDO.GetInt(ZDOVars.s_modelIndex, __instance.m_modelIndex);
			bool flag = state.BeardInstanceId == num && state.HairInstanceId == num2 && state.ModelIndex == num3;
			if (state.HasColors && state.ColorRevision == dataRevision && flag && unscaledTime < state.ColorSafetyRefresh)
			{
				RuntimeStats.Inc(ref RuntimeStats.VisEquipmentColorSkips);
				return false;
			}
			Vector3 vec = zDO.GetVec3(ZDOVars.s_skinColor, Vector3.one);
			Vector3 vec2 = zDO.GetVec3(ZDOVars.s_hairColor, Vector3.one);
			if (state.HasColors && flag && state.SkinColor == vec && state.HairColor == vec2 && unscaledTime < state.ColorSafetyRefresh)
			{
				state.ColorRevision = dataRevision;
				RuntimeStats.Inc(ref RuntimeStats.VisEquipmentColorSkips);
				return false;
			}
			state.SkinColor = vec;
			state.HairColor = vec2;
			state.ColorRevision = dataRevision;
			state.BeardInstanceId = num;
			state.HairInstanceId = num2;
			state.ModelIndex = num3;
			state.HasColors = true;
			state.ColorSafetyRefresh = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, RuntimeTuning.VisualSafety, ((Object)__instance).GetInstanceID() ^ 0x51C0);
			return true;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.VagonOptimizations
{
	internal static class VagonPatches
	{
		private sealed class AudioState
		{
			internal int Epoch;

			internal float NextUpdate;

			internal float AccumulatedDelta;

			internal float LastSeenTime;
		}

		private sealed class TetherState
		{
			internal int Epoch;

			internal float NextSafetyRefresh;
		}

		private sealed class EligibilityState
		{
			internal bool Evaluated;

			internal bool RequiresVanillaFlow;
		}

		private static PatchRuntimeGate audioGate;

		private static PatchRuntimeGate tetherGate;

		internal static void Install(PatchInstaller installer)
		{
			audioGate = installer.Install("Vagon.UpdateAudio throttle", AccessTools.Method(typeof(Vagon), "UpdateAudio", new Type[1] { typeof(float) }, (Type[])null), AccessTools.Method(typeof(VagonPatches), "AudioPrefix", (Type[])null, (Type[])null), null, Launch.Settings.VagonAudio, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			tetherGate = installer.Install("Vagon.LateUpdate parked tether no-op gate", AccessTools.Method(typeof(Vagon), "LateUpdate", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(VagonPatches), "LateUpdatePrefix", (Type[])null, (Type[])null), null, Launch.Settings.VagonIdleTether, strictForeignPatchCheck: true, disabledByConservativeMode: true);
		}

		private static bool AudioPrefix(Vagon __instance, ref float dt)
		{
			if (audioGate == null || !audioGate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (RequiresVanillaVehicleFlow(__instance))
			{
				return true;
			}
			AudioState audioState = WeakStateStore<Vagon, AudioState>.Get(__instance);
			if (audioState.Epoch != audioGate.Epoch)
			{
				Reset(audioState, audioGate.Epoch);
			}
			float vagonAudioInterval = RuntimeTuning.VagonAudioInterval;
			float time = Time.time;
			if (UpdateRateLimiter.IsDiscontinuous(ref audioState.LastSeenTime, time, Mathf.Max(1f, vagonAudioInterval * 3f)))
			{
				audioState.NextUpdate = 0f;
				audioState.AccumulatedDelta = 0f;
			}
			if (UpdateRateLimiter.IsDue(ref audioState.NextUpdate, vagonAudioInterval, time, ((Object)__instance).GetInstanceID()))
			{
				if (audioState.AccumulatedDelta > 0f)
				{
					dt += audioState.AccumulatedDelta;
					audioState.AccumulatedDelta = 0f;
				}
				return true;
			}
			audioState.AccumulatedDelta += dt;
			RuntimeStats.Inc(ref RuntimeStats.VagonAudioSkips);
			return false;
		}

		private static bool LateUpdatePrefix(Vagon __instance)
		{
			if (tetherGate == null || !tetherGate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (RequiresVanillaVehicleFlow(__instance))
			{
				return true;
			}
			if ((Object)(object)__instance.m_attachJoin == (Object)null && (Object)(object)__instance.m_lineRenderer != (Object)null && !((Renderer)__instance.m_lineRenderer).enabled)
			{
				TetherState tetherState = WeakStateStore<Vagon, TetherState>.Get(__instance);
				if (tetherState.Epoch != tetherGate.Epoch)
				{
					tetherState.Epoch = tetherGate.Epoch;
					tetherState.NextSafetyRefresh = 0f;
				}
				float unscaledTime = Time.unscaledTime;
				if (tetherState.NextSafetyRefresh > 0f && unscaledTime < tetherState.NextSafetyRefresh)
				{
					RuntimeStats.Inc(ref RuntimeStats.VagonTetherSkips);
					return false;
				}
				tetherState.NextSafetyRefresh = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, 1f, ((Object)__instance).GetInstanceID() ^ 0x6A21);
			}
			return true;
		}

		private static bool RequiresVanillaVehicleFlow(Vagon instance)
		{
			EligibilityState eligibilityState = WeakStateStore<Vagon, EligibilityState>.Get(instance);
			if (!eligibilityState.Evaluated)
			{
				eligibilityState.Evaluated = true;
				eligibilityState.RequiresVanillaFlow = (Object)(object)((Component)instance).GetComponent<Catapult>() != (Object)null || (Object)(object)((Component)instance).GetComponent<SiegeMachine>() != (Object)null;
			}
			return eligibilityState.RequiresVanillaFlow;
		}

		private static void Reset(AudioState state, int epoch)
		{
			state.Epoch = epoch;
			state.NextUpdate = 0f;
			state.AccumulatedDelta = 0f;
			state.LastSeenTime = 0f;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.TeleportWorldOptimizations
{
	internal static class TeleportWorldPatches
	{
		private sealed class State
		{
			internal int Epoch;

			internal bool HasTarget;

			internal float NextSafety;
		}

		private static PatchRuntimeGate gate;

		internal static void Install(PatchInstaller installer)
		{
			gate = installer.Install("TeleportWorld.Update stable emission gate", AccessTools.Method(typeof(TeleportWorld), "Update", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(TeleportWorldPatches), "Prefix", (Type[])null, (Type[])null), null, Launch.Settings.PortalStableEmission, strictForeignPatchCheck: true);
		}

		private static bool Prefix(TeleportWorld __instance)
		{
			if (gate == null || !gate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			float num = (__instance.m_hadTarget ? 1f : 0f);
			if (!Mathf.Approximately(__instance.m_colorAlpha, num))
			{
				return true;
			}
			State state = WeakStateStore<TeleportWorld, State>.Get(__instance);
			if (state.Epoch != gate.Epoch)
			{
				state.Epoch = gate.Epoch;
				state.HasTarget = !__instance.m_hadTarget;
				state.NextSafety = 0f;
			}
			float unscaledTime = Time.unscaledTime;
			if (state.HasTarget == __instance.m_hadTarget && unscaledTime < state.NextSafety)
			{
				RuntimeStats.Inc(ref RuntimeStats.PortalVisualSkips);
				return false;
			}
			state.HasTarget = __instance.m_hadTarget;
			state.NextSafety = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, RuntimeTuning.StaticVisualSafety, ((Object)__instance).GetInstanceID());
			return true;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.StationExtensionOptimizations
{
	internal static class StationExtensionPatches
	{
		private static PatchRuntimeGate gate;

		internal static void Install(PatchInstaller installer)
		{
			gate = installer.Install("StationExtension.OtherExtensionInRange squared-distance query", AccessTools.Method(typeof(StationExtension), "OtherExtensionInRange", new Type[1] { typeof(float) }, (Type[])null), AccessTools.Method(typeof(StationExtensionPatches), "Prefix", (Type[])null, (Type[])null), null, Launch.Settings.StationExtensionSquaredDistanceQuery, strictForeignPatchCheck: true);
		}

		private static bool Prefix(StationExtension __instance, float radius, ref bool __result)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			List<StationExtension> stationExtensions = VanillaCollectionRegistry.StationExtensions;
			if (gate == null || !gate.Enabled || stationExtensions == null || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (!(radius > 0f) || float.IsNaN(radius))
			{
				__result = false;
				return false;
			}
			float num = radius * radius;
			Vector3 position = ((Component)__instance).transform.position;
			for (int i = 0; i < stationExtensions.Count; i++)
			{
				StationExtension val = stationExtensions[i];
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)__instance))
				{
					Vector3 val2 = ((Component)val).transform.position - position;
					if (((Vector3)(ref val2)).sqrMagnitude < num)
					{
						__result = true;
						RuntimeStats.Inc(ref RuntimeStats.StationExtensionQueryReplacements);
						return false;
					}
				}
			}
			__result = false;
			RuntimeStats.Inc(ref RuntimeStats.StationExtensionQueryReplacements);
			return false;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.SmokeRendererOptimizations
{
	internal static class SmokeRendererPatches
	{
		private struct SmokeMove
		{
			internal Vector3Int From;

			internal Vector3Int To;

			internal Smoke Smoke;
		}

		private sealed class State
		{
			internal int Epoch;

			internal float NextUpdate;
		}

		private const int VanillaChunkParticleCapacity = 100;

		private static readonly List<SmokeMove> Moves = new List<SmokeMove>(32);

		private static PatchRuntimeGate lateGate;

		private static PatchRuntimeGate addGate;

		private static PatchRuntimeGate transferGate;

		internal static void Install(PatchInstaller installer)
		{
			lateGate = installer.Install("SmokeRenderer.LateUpdate presentation/memory optimizer", AccessTools.Method(typeof(SmokeRenderer), "LateUpdate", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(SmokeRendererPatches), "LateUpdatePrefix", (Type[])null, (Type[])null), null, Launch.Settings.SmokeRenderer, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			addGate = installer.Install("SmokeRenderer.AddSmokeToChunk adaptive particle buffer", AccessTools.Method(typeof(SmokeRenderer), "AddSmokeToChunk", new Type[2]
			{
				typeof(Vector3Int),
				typeof(Smoke)
			}, (Type[])null), AccessTools.Method(typeof(SmokeRendererPatches), "AddSmokeToChunkPrefix", (Type[])null, (Type[])null), null, Launch.Settings.SmokeAdaptiveChunkBuffers, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			transferGate = installer.Install("SmokeRenderer.TransferSmokeBetweenChunks no-allocation replacement", AccessTools.Method(typeof(SmokeRenderer), "TransferSmokeBetweenChunks", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(SmokeRendererPatches), "TransferSmokeBetweenChunksPrefix", (Type[])null, (Type[])null), null, Launch.Settings.SmokeNoAllocChunkTransfers, strictForeignPatchCheck: true, disabledByConservativeMode: true);
		}

		private static bool LateUpdatePrefix(SmokeRenderer __instance)
		{
			if (lateGate == null || !lateGate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			State state = WeakStateStore<SmokeRenderer, State>.Get(__instance);
			if (state.Epoch != lateGate.Epoch)
			{
				state.Epoch = lateGate.Epoch;
				state.NextUpdate = 0f;
			}
			if (!UpdateRateLimiter.IsDue(ref state.NextUpdate, RuntimeTuning.SmokeRendererInterval, Time.time, ((Object)__instance).GetInstanceID()))
			{
				if (__instance.m_chunkedSmoke != null && __instance.m_chunkedSmoke.Count > 0)
				{
					RuntimeStats.Inc(ref RuntimeStats.SmokeRendererSkips);
				}
				return false;
			}
			if (!Launch.Settings.SmokeAdaptiveChunkBuffers.Value)
			{
				return true;
			}
			OptimizedLateUpdate(__instance);
			return false;
		}

		private static bool AddSmokeToChunkPrefix(SmokeRenderer __instance, Vector3Int chunk, Smoke smoke)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
			if (addGate == null || !addGate.Enabled || (Object)(object)__instance == (Object)null || !Launch.Settings.SmokeAdaptiveChunkBuffers.Value)
			{
				return true;
			}
			if (!__instance.m_chunkedSmoke.ContainsKey(chunk))
			{
				__instance.m_chunkedSmoke.Add(chunk, new List<Smoke>());
				__instance.m_chunkedParticleSystems.Add(chunk, Object.Instantiate<ParticleSystem>(__instance._particleSystemPrefab, __instance.ChunkToWorld(chunk), Quaternion.identity));
				int num = Mathf.Clamp(Launch.Settings.SmokeInitialChunkParticleCapacity.Value, 1, 100);
				__instance.m_chunkedParticles.Add(chunk, (Particle[])(object)new Particle[num]);
				RuntimeStats.Add(ref RuntimeStats.SmokeParticleSlotsAvoided, 100 - num);
			}
			List<Smoke> list = __instance.m_chunkedSmoke[chunk];
			if (!list.Contains(smoke))
			{
				list.Add(smoke);
			}
			smoke.RenderChunk = chunk;
			return false;
		}

		private static bool TransferSmokeBetweenChunksPrefix(SmokeRenderer __instance)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: 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_014b: Unknown result type (might be due to invalid IL or missing references)
			if (transferGate == null || !transferGate.Enabled || (Object)(object)__instance == (Object)null || !Launch.Settings.SmokeNoAllocChunkTransfers.Value)
			{
				return true;
			}
			Moves.Clear();
			foreach (KeyValuePair<Vector3Int, List<Smoke>> item in __instance.m_chunkedSmoke)
			{
				Vector3Int key = item.Key;
				List<Smoke> value = item.Value;
				for (int i = 0; i < value.Count; i++)
				{
					Smoke val = value[i];
					Vector3Int val2 = __instance.PositionToChunk(((Component)val).transform.position);
					if (val2 != key)
					{
						Moves.Add(new SmokeMove
						{
							From = key,
							To = val2,
							Smoke = val
						});
						RuntimeStats.Inc(ref RuntimeStats.SmokeMoveAllocationsAvoided);
					}
				}
			}
			for (int j = 0; j < Moves.Count; j++)
			{
				SmokeMove smokeMove = Moves[j];
				__instance.RemoveSmokeFromChunk(smokeMove.From, smokeMove.Smoke);
				__instance.AddSmokeToChunk(smokeMove.To, smokeMove.Smoke);
			}
			Moves.Clear();
			return false;
		}

		private static void OptimizedLateUpdate(SmokeRenderer instance)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			instance.TransferSmokeBetweenChunks();
			foreach (Vector3Int key in instance.m_chunkedParticleSystems.Keys)
			{
				ParticleSystem val = instance.m_chunkedParticleSystems[key];
				List<Smoke> list = instance.m_chunkedSmoke[key];
				Particle[] array = instance.m_chunkedParticles[key];
				int count = list.Count;
				int particleCount = val.particleCount;
				int num = Mathf.Max(count, particleCount);
				if (array == null || array.Length < num)
				{
					int num2 = ((array != null) ? array.Length : 0);
					int num3 = Mathf.Max(1, num2);
					while (num3 < num && num3 < 100)
					{
						num3 = Mathf.Min(100, num3 * 2);
					}
					if (num3 < num)
					{
						num3 = num;
					}
					array = (Particle[])(object)new Particle[num3];
					instance.m_chunkedParticles[key] = array;
					RuntimeStats.Inc(ref RuntimeStats.SmokeChunkBufferGrows);
				}
				if (count > particleCount)
				{
					val.Emit(count - particleCount);
				}
				for (int i = 0; i < count; i++)
				{
					Smoke val2 = list[i];
					array[i] = val2.GetParticleValues();
					((Particle)(ref array[i])).startColor = Color32.op_Implicit(instance.m_smokeColor * new Color(1f, 1f, 1f, val2.GetAlpha()));
					((Particle)(ref array[i])).startSize = instance.m_smokeBallSize;
				}
				particleCount = val.particleCount;
				if (array.Length < particleCount)
				{
					array = (Particle[])(object)new Particle[particleCount];
					instance.m_chunkedParticles[key] = array;
					RuntimeStats.Inc(ref RuntimeStats.SmokeChunkBufferGrows);
					for (int j = 0; j < count; j++)
					{
						Smoke val3 = list[j];
						array[j] = val3.GetParticleValues();
						((Particle)(ref array[j])).startColor = Color32.op_Implicit(instance.m_smokeColor * new Color(1f, 1f, 1f, val3.GetAlpha()));
						((Particle)(ref array[j])).startSize = instance.m_smokeBallSize;
					}
				}
				for (int k = count; k < particleCount; k++)
				{
					((Particle)(ref array[k])).remainingLifetime = -1f;
				}
				val.SetParticles(array, particleCount);
			}
		}
	}
}
namespace BalrondVisualOptimizer.Patches.SmelterOptimizations
{
	internal static class SmelterPatches
	{
		private struct Signature
		{
			internal bool Active;

			internal bool HasFuel;

			internal bool HasOre;

			internal bool AnimationActive;

			internal bool SameAs(Signature other)
			{
				return Active == other.Active && HasFuel == other.HasFuel && HasOre == other.HasOre && AnimationActive == other.AnimationActive;
			}
		}

		private sealed class State
		{
			internal int Epoch;

			internal bool HasValue;

			internal uint Revision = uint.MaxValue;

			internal bool HaveRoof;

			internal bool BlockedSmoke;

			internal bool AnimationWindow;

			internal float MaxFuel;

			internal float MaxOre;

			internal bool RequiresRoof;

			internal Signature Value;

			internal float NextSafetyRefresh;
		}

		private static PatchRuntimeGate gate;

		internal static void Install(PatchInstaller installer)
		{
			gate = installer.Install("Smelter.UpdateState visual signature gate", AccessTools.Method(typeof(Smelter), "UpdateState", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(SmelterPatches), "Prefix", (Type[])null, (Type[])null), null, Launch.Settings.SmelterVisualState, strictForeignPatchCheck: true);
		}

		private static bool Prefix(Smelter __instance)
		{
			if (gate == null || !gate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if ((Object)(object)__instance.m_nview == (Object)null || !__instance.m_nview.IsValid())
			{
				return true;
			}
			ZDO zDO = __instance.m_nview.GetZDO();
			if (zDO == null)
			{
				return true;
			}
			State state = WeakStateStore<Smelter, State>.Get(__instance);
			if (state.Epoch != gate.Epoch)
			{
				state.Epoch = gate.Epoch;
				state.HasValue = false;
				state.Revision = uint.MaxValue;
				state.NextSafetyRefresh = 0f;
			}
			float unscaledTime = Time.unscaledTime;
			bool flag = __instance.m_addOreAnimationDuration > 0f && Time.time - __instance.m_addedOreTime < __instance.m_addOreAnimationDuration;
			uint dataRevision = zDO.DataRevision;
			if (state.HasValue && dataRevision == state.Revision && state.HaveRoof == __instance.m_haveRoof && state.BlockedSmoke == __instance.m_blockedSmoke && state.AnimationWindow == flag && state.MaxFuel == (float)__instance.m_maxFuel && state.MaxOre == (float)__instance.m_maxOre && state.RequiresRoof == __instance.m_requiresRoof && unscaledTime < state.NextSafetyRefresh)
			{
				RuntimeStats.Inc(ref RuntimeStats.SmelterStateSkips);
				return false;
			}
			float num = zDO.GetFloat(ZDOVars.s_fuel, 0f);
			int num2 = zDO.GetInt(ZDOVars.s_queued, 0);
			bool flag2 = num > 0f;
			bool flag3 = num2 > 0;
			bool flag4 = (__instance.m_maxFuel == 0 || flag2) && (__instance.m_maxOre == 0 || flag3) && (!__instance.m_requiresRoof || __instance.m_haveRoof) && !__instance.m_blockedSmoke;
			Signature signature = new Signature
			{
				Active = flag4,
				HasFuel = flag2,
				HasOre = flag3,
				AnimationActive = (flag4 || flag)
			};
			if (state.HasValue && state.Value.SameAs(signature) && unscaledTime < state.NextSafetyRefresh)
			{
				state.Revision = dataRevision;
				state.HaveRoof = __instance.m_haveRoof;
				state.BlockedSmoke = __instance.m_blockedSmoke;
				state.AnimationWindow = flag;
				state.MaxFuel = __instance.m_maxFuel;
				state.MaxOre = __instance.m_maxOre;
				state.RequiresRoof = __instance.m_requiresRoof;
				RuntimeStats.Inc(ref RuntimeStats.SmelterStateSkips);
				return false;
			}
			state.Value = signature;
			state.HasValue = true;
			state.Revision = dataRevision;
			state.HaveRoof = __instance.m_haveRoof;
			state.BlockedSmoke = __instance.m_blockedSmoke;
			state.AnimationWindow = flag;
			state.MaxFuel = __instance.m_maxFuel;
			state.MaxOre = __instance.m_maxOre;
			state.RequiresRoof = __instance.m_requiresRoof;
			state.NextSafetyRefresh = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, RuntimeTuning.VisualSafety, ((Object)__instance).GetInstanceID());
			return true;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.PrivateAreaOptimizations
{
	internal static class PrivateAreaPatches
	{
		private sealed class State
		{
			internal int Epoch;

			internal bool HasValue;

			internal bool Enabled;

			internal float NextSafety;
		}

		private static PatchRuntimeGate gate;

		internal static void Install(PatchInstaller installer)
		{
			gate = installer.Install("PrivateArea.UpdateStatus stable visual gate", AccessTools.Method(typeof(PrivateArea), "UpdateStatus", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(PrivateAreaPatches), "Prefix", (Type[])null, (Type[])null), null, Launch.Settings.PrivateAreaStatusVisual, strictForeignPatchCheck: true);
		}

		private static bool Prefix(PrivateArea __instance)
		{
			if (gate == null || !gate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			__instance.m_flashAvailable = true;
			bool flag = __instance.IsEnabled();
			State state = WeakStateStore<PrivateArea, State>.Get(__instance);
			if (state.Epoch != gate.Epoch)
			{
				state.Epoch = gate.Epoch;
				state.HasValue = false;
				state.NextSafety = 0f;
			}
			float unscaledTime = Time.unscaledTime;
			if (state.HasValue && state.Enabled == flag && unscaledTime < state.NextSafety)
			{
				RuntimeStats.Inc(ref RuntimeStats.PrivateAreaVisualSkips);
				return false;
			}
			state.HasValue = true;
			state.Enabled = flag;
			state.NextSafety = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, RuntimeTuning.StaticVisualSafety, ((Object)__instance).GetInstanceID());
			return true;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.PieceOptimizations
{
	internal static class PiecePatches
	{
		private static PatchRuntimeGate allPiecesGate;

		private static PatchRuntimeGate comfortPiecesGate;

		internal static void Install(PatchInstaller installer)
		{
			allPiecesGate = installer.Install("Piece.GetAllPiecesInRadius squared-distance query", AccessTools.Method(typeof(Piece), "GetAllPiecesInRadius", new Type[3]
			{
				typeof(Vector3),
				typeof(float),
				typeof(List<Piece>)
			}, (Type[])null), AccessTools.Method(typeof(PiecePatches), "AllPiecesPrefix", (Type[])null, (Type[])null), null, Launch.Settings.PieceSquaredDistanceQueries, strictForeignPatchCheck: true);
			comfortPiecesGate = installer.Install("Piece.GetAllComfortPiecesInRadius squared-distance query", AccessTools.Method(typeof(Piece), "GetAllComfortPiecesInRadius", new Type[3]
			{
				typeof(Vector3),
				typeof(float),
				typeof(List<Piece>)
			}, (Type[])null), AccessTools.Method(typeof(PiecePatches), "ComfortPiecesPrefix", (Type[])null, (Type[])null), null, Launch.Settings.PieceSquaredDistanceQueries, strictForeignPatchCheck: true);
		}

		private static bool AllPiecesPrefix(Vector3 p, float radius, List<Piece> pieces)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			List<Piece> pieces2 = VanillaCollectionRegistry.Pieces;
			if (allPiecesGate == null || !allPiecesGate.Enabled || pieces2 == null || pieces == null)
			{
				return true;
			}
			if (!(radius > 0f) || float.IsNaN(radius))
			{
				return false;
			}
			float num = radius * radius;
			int ghostLayer = VanillaCollectionRegistry.GhostLayer;
			for (int i = 0; i < pieces2.Count; i++)
			{
				Piece val = pieces2[i];
				if (!((Object)(object)val == (Object)null) && ((Component)val).gameObject.layer != ghostLayer)
				{
					Vector3 val2 = ((Component)val).transform.position - p;
					if (((Vector3)(ref val2)).sqrMagnitude < num)
					{
						pieces.Add(val);
					}
				}
			}
			RuntimeStats.Inc(ref RuntimeStats.PieceQueryReplacements);
			return false;
		}

		private static bool ComfortPiecesPrefix(Vector3 p, float radius, List<Piece> pieces)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			HashSet<Piece> comfortPieces = VanillaCollectionRegistry.ComfortPieces;
			if (comfortPiecesGate == null || !comfortPiecesGate.Enabled || comfortPieces == null || pieces == null)
			{
				return true;
			}
			if (!(radius > 0f) || float.IsNaN(radius))
			{
				return false;
			}
			float num = radius * radius;
			int ghostLayer = VanillaCollectionRegistry.GhostLayer;
			foreach (Piece item in comfortPieces)
			{
				if (!((Object)(object)item == (Object)null) && ((Component)item).gameObject.layer != ghostLayer)
				{
					Vector3 val = ((Component)item).transform.position - p;
					if (((Vector3)(ref val)).sqrMagnitude < num)
					{
						pieces.Add(item);
					}
				}
			}
			RuntimeStats.Inc(ref RuntimeStats.PieceQueryReplacements);
			return false;
		}
	}
}
namespace BalrondVisualOptimizer.Patches.MaterialFaderOptimizations
{
	internal static class MaterialFaderPatches
	{
		private sealed class State
		{
			internal int Epoch;

			internal float NextSafetyRefresh;
		}

		private static PatchRuntimeGate updateGate;

		internal static void Install(PatchInstaller installer)
		{
			updateGate = installer.Install("MaterialFader.Update stable-endpoint gate", AccessTools.Method(typeof(MaterialFader), "Update", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(MaterialFaderPatches), "UpdatePrefix", (Type[])null, (Type[])null), null, Launch.Settings.MaterialFaderDormancy, strictForeignPatchCheck: true);
		}

		private static bool UpdatePrefix(MaterialFader __instance)
		{
			if (updateGate == null || !updateGate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			bool flag = !__instance.m_started;
			if (!flag)
			{
				flag = __instance.m_fadeProperties != null;
				if (flag)
				{
					for (int i = 0; i < __instance.m_fadeProperties.Count; i++)
					{
						if (!__instance.m_fadeProperties[i].m_finished)
						{
							flag = false;
							break;
						}
					}
				}
			}
			if (!flag)
			{
				return true;
			}
			State state = WeakStateStore<MaterialFader, State>.Get(__instance);
			if (state.Epoch != updateGate.Epoch)
			{
				state.Epoch = updateGate.Epoch;
				state.NextSafetyRefresh = 0f;
			}
			float unscaledTime = Time.unscaledTime;
			if (state.NextSafetyRefresh <= 0f || unscaledTime >= state.NextSafetyRefresh)
			{
				state.NextSafetyRefresh = UpdateRateLimiter.StaggeredSafetyDeadline(unscaledTime, RuntimeTuning.VisualSafety, ((Object)__instance).GetInstanceID());
				return true;
			}
			RuntimeStats.Inc(ref RuntimeStats.MaterialFaderDormantFrames);
			return false;
		}

		internal static void RefreshDormancy()
		{
		}

		internal static void Shutdown()
		{
		}
	}
}
namespace BalrondVisualOptimizer.Patches.LineConnectOptimizations
{
	internal static class LineConnectPatches
	{
		private sealed class State
		{
			internal int Epoch;

			internal bool HiddenNoConnection;

			internal uint Revision = uint.MaxValue;

			internal float NextSafety;
		}

		private static PatchRuntimeGate gate;

		internal static void Install(PatchInstaller installer)
		{
			gate = installer.Install("LineConnect.LateUpdate stable no-connection gate", AccessTools.Method(typeof(LineConnect), "LateUpdate", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(LineConnectPatches), "Prefix", (Type[])null, (Type[])null), AccessTools.Method(typeof(LineConnectPatches), "Postfix", (Type[])null, (Type[])null), Launch.Settings.LineConnectStableNoConnection, strictForeignPatchCheck: true);
		}

		private static bool Prefix(LineConnect __instance)
		{
			if (gate == null || !gate.Enabled || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if ((Object)(object)__instance.m_nview == (Object)null || !__instance.m_nview.IsValid())
			{
				if ((Object)(object)__instance.m_lineRenderer != (Object)null && !((Renderer)__instance.m_lineRenderer).enabled)
				{
					RuntimeStats.Inc(ref RuntimeStats.LineConnectSkips);
					return false;
				}
				return true;
			}
			ZDO zDO = __instance.m_nview.GetZDO();
			if (zDO == null)
			{
				return true;
			}
			State state = WeakStateStore<LineConnect, State>.Get(__instance);
			if (state.Epoch != gate.Epoch)
			{
				state.Epoch = gate.Epoch;
				state.HiddenNoConnection = false;
				state.Revision = uint.MaxValue;
				state.NextSafety = 0f;
			}
			float unscaledTime = Time.unscaledTime;
			if (state.HiddenNoConnection && state.Revision == zDO.DataRevision && unscaledTime < state.NextSafety)
			{
				RuntimeStats.Inc(ref RuntimeStats.LineConnectSkips);
				return false;
			}
			return true;
		}

		private static void Postfix(LineConnect __instance)
		{
			if (gate != null && gate.Enabled && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.m_nview == (Object)null) && __instance.m_nview.IsValid())
			{
				ZDO zDO = __instance.m_nview.GetZDO();
				if (zDO != null)
				{
					State state = WeakStateStore<LineConnect, State>.Get(__instance);
					state.HiddenNoConnection = __instance.m_hideIfNoConnection && (Object)(object)__instance.m_lineRenderer != (Object)null && !((Renderer)__instance.m_lineRenderer).enabled;
					state.Revision = zDO.DataRevision;
					state.NextSafety = Time.unscaledTime + 1f * (0.75f + 0.25f * UpdateRateLimiter.Phase01Public(((Object)__instance).GetInstanceID()));
				}
			}
		}
	}
}
namespace BalrondVisualOptimizer.Patches.LightLodOptimizations
{
	internal static class LightLodPatches
	{
		private static PatchRuntimeGate enableGate;

		private static PatchRuntimeGate disableGate;

		private static PatchRuntimeGate destroyGate;

		internal static bool CanManage
		{
			get
			{
				if (enableGate == null || disableGate == null || !enableGate.Enabled || !disableGate.Enabled)
				{
					return false;
				}
				if (Launch.Settings != null && Launch.Settings.DisableOnForeignHarmonyPatches.Value && HarmonyConflictService.TryGetFirstForeignOwner(AccessTools.Method(typeof(LightLod), "UpdateLoop", Type.EmptyTypes, (Type[])null), out var _))
				{
					return false;
				}
				return true;
			}
		}

		internal static void Install(PatchInstaller installer)
		{
			enableGate = installer.Install("LightLod.OnEnable central scheduler hook", AccessTools.Method(typeof(LightLod), "OnEnable", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(LightLodPatches), "OnEnablePrefix", (Type[])null, (Type[])null), null, Launch.Settings.LightLodCentralScheduler, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			disableGate = installer.Install("LightLod.OnDisable central scheduler hook", AccessTools.Method(typeof(LightLod), "OnDisable", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(LightLodPatches), "OnDisablePrefix", (Type[])null, (Type[])null), null, Launch.Settings.LightLodCentralScheduler, strictForeignPatchCheck: true, disabledByConservativeMode: true);
			destroyGate = installer.Install("LightLod.OnDestroy scheduler cleanup hook", AccessTools.Method(typeof(LightLod), "OnDestroy", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(LightLodPatches), "OnDestroyPrefix", (Type[])null, (Type[])null), null, Launch.Settings.LightLodCentralScheduler, strictForeignPatchCheck: tr