Decompiled source of Path of Valheiman Performance Boosts v1.0.0

plugins/PathOfValheimanPerformanceBoosts.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using SoftReferenceableAssets;
using TMPro;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.EventSystems;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: AssemblyProduct("PovPerformanceBoosts")]
[assembly: AssemblyCompany("Robin")]
[assembly: AssemblyDescription("Pure performance boosts for Path of Valheiman with zero changes to gameplay, balance, or design.")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyTitle("Path of Valheiman Performance Boosts")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace PovPerformanceBoosts;

internal static class AvxCooperationManager
{
	private static Assembly _avxAssembly;

	private static bool _avxDetected;

	private static bool _reflectionResolved;

	private static Type _avxSceneRemovalType;

	private static Type _avxSceneCreationType;

	private static FieldInfo _avxSceneCreationCurrentField;

	private static FieldInfo _avxSceneCreationMaxField;

	private static FieldInfo _avxSceneCreationBudgetField;

	private static Func<object> _getAvxSceneCreationCurrent;

	private static Action<object, int> _setAvxSceneCreationMax;

	private static Action<object, long> _setAvxSceneCreationBudget;

	internal static bool IsAvxLoaded => _avxDetected;

	internal static bool IsSceneCreationCoopEnabled
	{
		get
		{
			if (_avxDetected && Plugin.ConfigEnableAvxSceneCreationCoop != null)
			{
				return Plugin.ConfigEnableAvxSceneCreationCoop.Value;
			}
			return false;
		}
	}

	internal static bool IsSceneRemovalCoopEnabled
	{
		get
		{
			if (_avxDetected && Plugin.ConfigEnableAvxSceneRemovalCoop != null)
			{
				return Plugin.ConfigEnableAvxSceneRemovalCoop.Value;
			}
			return false;
		}
	}

	internal static bool AnyCoopToggleEnabled()
	{
		if ((Plugin.ConfigEnableAvxSceneCreationCoop == null || !Plugin.ConfigEnableAvxSceneCreationCoop.Value) && (Plugin.ConfigEnableAvxSceneRemovalCoop == null || !Plugin.ConfigEnableAvxSceneRemovalCoop.Value) && (Plugin.ConfigEnableAvxTerrainCoop == null || !Plugin.ConfigEnableAvxTerrainCoop.Value) && (Plugin.ConfigEnableAvxDungeonStreamingCoop == null || !Plugin.ConfigEnableAvxDungeonStreamingCoop.Value) && (Plugin.ConfigEnableAvxDungeonRoomCoop == null || !Plugin.ConfigEnableAvxDungeonRoomCoop.Value) && (Plugin.ConfigEnableAvxAiSenseCoop == null || !Plugin.ConfigEnableAvxAiSenseCoop.Value) && (Plugin.ConfigEnableAvxMinimapFogCoop == null || !Plugin.ConfigEnableAvxMinimapFogCoop.Value))
		{
			if (Plugin.ConfigEnableAvxGrassGroundCoop != null)
			{
				return Plugin.ConfigEnableAvxGrassGroundCoop.Value;
			}
			return false;
		}
		return true;
	}

	internal static bool AnyAvxToggleEnabled()
	{
		if (!AnyCoopToggleEnabled())
		{
			if (Plugin.ConfigEnableAvxProfilerCrashShield != null)
			{
				return Plugin.ConfigEnableAvxProfilerCrashShield.Value;
			}
			return false;
		}
		return true;
	}

	internal static void InitializeDetection()
	{
		_avxAssembly = Plugin.FindLoadedAssembly("ValheimAccel.Managed");
		_avxDetected = _avxAssembly != null || Chainloader.PluginInfos.ContainsKey("com.kewb.valheimavx");
	}

	private static void ResolveAvxReflection()
	{
		if (_reflectionResolved || _avxAssembly == null)
		{
			return;
		}
		_reflectionResolved = true;
		try
		{
			_avxSceneRemovalType = _avxAssembly.GetType("ValheimAccel.Managed.SceneRemovalBudget");
			_avxSceneCreationType = _avxAssembly.GetType("ValheimAccel.Managed.SceneCreationBudget");
			if (_avxSceneCreationType != null)
			{
				_avxSceneCreationCurrentField = AccessTools.Field(_avxSceneCreationType, "current");
				_avxSceneCreationMaxField = AccessTools.Field(_avxSceneCreationType, "maximum");
				_avxSceneCreationBudgetField = AccessTools.Field(_avxSceneCreationType, "budget");
				_getAvxSceneCreationCurrent = FastFieldAccess.CreateStaticGetter<object>(_avxSceneCreationCurrentField);
				_setAvxSceneCreationMax = FastFieldAccess.CreateSetter<object, int>(_avxSceneCreationMaxField);
				_setAvxSceneCreationBudget = FastFieldAccess.CreateSetter<object, long>(_avxSceneCreationBudgetField);
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogDebug((object)$"[AvxCooperation] Reflection notice: {ex.Message}");
			}
		}
	}

	internal static void ApplyDynamicPatches(Harmony harmony)
	{
		if (harmony == null)
		{
			return;
		}
		if (!_avxDetected || _avxAssembly == null)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)"[AvxCooperation] Valheim AVX not detected; optional AVX cooperation skipped.");
			}
			return;
		}
		bool flag = AnyCoopToggleEnabled();
		bool flag2 = Plugin.ConfigEnableAvxProfilerCrashShield != null && Plugin.ConfigEnableAvxProfilerCrashShield.Value;
		if (!flag && !flag2)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)"[AvxCooperation] Valheim AVX detected. All optional AVX cooperation settings are Off (0 AVX hooks installed; configure in Section 05 if desired).");
			}
			return;
		}
		try
		{
			if (flag)
			{
				ResolveAvxReflection();
				AttachAvxPolicyCoordination(_avxAssembly, harmony);
				DeclareCooperativeCoordinationFallback();
				if (Plugin.ConfigEnableAvxSceneRemovalCoop != null && Plugin.ConfigEnableAvxSceneRemovalCoop.Value)
				{
					AttachCompatibilityPostfix(harmony, _avxAssembly, "ValheimAccel.Managed.SceneRemovalBudget", "Refresh", typeof(AvxGenericCooperationPatch), "Postfix", "SceneRemovalBudget.Refresh");
				}
				if (Plugin.ConfigEnableAvxSceneCreationCoop != null && Plugin.ConfigEnableAvxSceneCreationCoop.Value)
				{
					AttachCompatibilityPostfix(harmony, _avxAssembly, "ValheimAccel.Managed.SceneCreationBudget", "Refresh", typeof(AvxGenericCooperationPatch), "Postfix", "SceneCreationBudget.Refresh");
				}
				if (Plugin.ConfigEnableAvxDungeonStreamingCoop != null && Plugin.ConfigEnableAvxDungeonStreamingCoop.Value)
				{
					AttachCompatibilityPostfix(harmony, _avxAssembly, "ValheimAccel.Managed.DungeonSpawnBudget", "RefreshCompatibility", typeof(AvxDungeonCooperationPatch), "Postfix", "DungeonSpawnBudget.RefreshCompatibility");
				}
				if (Plugin.ConfigEnableAvxAiSenseCoop != null && Plugin.ConfigEnableAvxAiSenseCoop.Value)
				{
					AttachCompatibilityPostfix(harmony, _avxAssembly, "ValheimAccel.Managed.AiSenseFilter", "Refresh", typeof(AvxGenericCooperationPatch), "Postfix", "AiSenseFilter.Refresh");
				}
				if (Plugin.ConfigEnableAvxMinimapFogCoop != null && Plugin.ConfigEnableAvxMinimapFogCoop.Value)
				{
					AttachCompatibilityPostfix(harmony, _avxAssembly, "ValheimAccel.Managed.MinimapFog", "Refresh", typeof(AvxGenericCooperationPatch), "Postfix", "MinimapFog.Refresh");
				}
				AvxScopedCooperationBridge.ApplyDynamicPatches(_avxAssembly, harmony);
			}
			if (flag2)
			{
				AttachAvxProfilerGuard(_avxAssembly, harmony);
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogWarning((object)$"[AvxCooperation] Initialization notice: {ex.Message}");
			}
		}
	}

	internal static void OnAllPluginsStarted()
	{
		if (_avxDetected && !(_avxAssembly == null) && AnyCoopToggleEnabled())
		{
			DeclareCooperativeCoordinationFallback();
			AvxScopedCooperationBridge.OnAllPluginsStarted();
		}
	}

	internal static void ReassertSceneRemovalCooperation()
	{
		if (IsSceneRemovalCoopEnabled && _avxSceneRemovalType != null)
		{
			AvxGenericCooperationPatch.ApplyTo(_avxSceneRemovalType);
		}
	}

	internal static void SyncAvxCreationLimits(int maxObjects, float budgetMs)
	{
		if (!IsSceneCreationCoopEnabled)
		{
			return;
		}
		try
		{
			object obj = null;
			if (_getAvxSceneCreationCurrent != null)
			{
				obj = _getAvxSceneCreationCurrent();
			}
			else if (_avxSceneCreationCurrentField != null)
			{
				obj = _avxSceneCreationCurrentField.GetValue(null);
			}
			if (obj != null)
			{
				if (_setAvxSceneCreationMax != null)
				{
					_setAvxSceneCreationMax(obj, maxObjects);
				}
				else if (_avxSceneCreationMaxField != null)
				{
					_avxSceneCreationMaxField.SetValue(obj, maxObjects);
				}
				long num = (long)((double)budgetMs * (double)Stopwatch.Frequency / 1000.0);
				if (_setAvxSceneCreationBudget != null)
				{
					_setAvxSceneCreationBudget(obj, num);
				}
				else if (_avxSceneCreationBudgetField != null)
				{
					_avxSceneCreationBudgetField.SetValue(obj, num);
				}
			}
		}
		catch
		{
		}
	}

	private static void AttachAvxPolicyCoordination(Assembly avxAssembly, Harmony harmony)
	{
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Expected O, but got Unknown
		try
		{
			Type type = avxAssembly.GetType("ValheimAccel.Managed.ModCompatibilityPolicy");
			if (type == null)
			{
				return;
			}
			ConstructorInfo constructorInfo = null;
			ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			for (int i = 0; i < constructors.Length; i++)
			{
				ParameterInfo[] parameters = constructors[i].GetParameters();
				if (parameters.Length == 4 && parameters[0].ParameterType == typeof(bool) && parameters[1].ParameterType == typeof(string) && parameters[2].ParameterType == typeof(string))
				{
					constructorInfo = constructors[i];
					break;
				}
			}
			if (!(constructorInfo != null))
			{
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(AvxModCompatibilityPolicyPatch), "Prefix", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				ConstructorInfo constructorInfo2 = constructorInfo;
				HarmonyMethod val = new HarmonyMethod(methodInfo);
				val.priority = 600;
				harmony.Patch((MethodBase)constructorInfo2, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				if (Plugin.Log != null)
				{
					Plugin.Log.LogInfo((object)"[AvxCooperation] Attached Valheim AVX ModCompatibilityPolicy coordination hook.");
				}
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogDebug((object)$"[AvxCooperation] ModCompatibilityPolicy hook notice: {ex.Message}");
			}
		}
	}

	private static void DeclareCooperativeCoordinationFallback()
	{
		try
		{
			if (_avxAssembly == null)
			{
				return;
			}
			Type type = _avxAssembly.GetType("ValheimAccel.Managed.OptimizationPatchGuard");
			if (type == null)
			{
				return;
			}
			FieldInfo field = type.GetField("current", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (field == null)
			{
				return;
			}
			object value = field.GetValue(null);
			if (value == null)
			{
				return;
			}
			FieldInfo field2 = type.GetField("policy", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field2 == null)
			{
				return;
			}
			object value2 = field2.GetValue(value);
			if (value2 == null)
			{
				return;
			}
			FieldInfo field3 = value2.GetType().GetField("cooperate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (!(field3 != null) || !(field3.FieldType == typeof(string[])))
			{
				return;
			}
			string[] array = field3.GetValue(value2) as string[];
			List<string> list = new List<string>();
			if (array != null)
			{
				for (int i = 0; i < array.Length; i++)
				{
					string text = ((array[i] != null) ? array[i].Trim() : null);
					if (!string.IsNullOrEmpty(text) && !ContainsIgnoreCase(list, text))
					{
						list.Add(text);
					}
				}
			}
			bool flag = false;
			string[] cooperativePeers = AvxModCompatibilityPolicyPatch.GetCooperativePeers();
			for (int j = 0; j < cooperativePeers.Length; j++)
			{
				if (!ContainsIgnoreCase(list, cooperativePeers[j]))
				{
					list.Add(cooperativePeers[j]);
					flag = true;
				}
			}
			if (flag)
			{
				field3.SetValue(value2, list.ToArray());
				if (Plugin.Log != null)
				{
					Plugin.Log.LogInfo((object)"[AvxCooperation] Registered active cooperative peers in Valheim AVX compatibility policy.");
				}
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogDebug((object)$"[AvxCooperation] Policy fallback notice: {ex.Message}");
			}
		}
	}

	private static void AttachCompatibilityPostfix(Harmony harmony, Assembly avxAssembly, string typeName, string methodName, Type patchClass, string patchMethodName, string label)
	{
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Expected O, but got Unknown
		try
		{
			Type type = avxAssembly.GetType(typeName);
			if (type == null)
			{
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
			if (methodInfo == null && !methodName.EndsWith("Compatibility"))
			{
				methodInfo = AccessTools.Method(type, methodName + "Compatibility", (Type[])null, (Type[])null);
			}
			if (methodInfo == null && methodName.EndsWith("Compatibility"))
			{
				methodInfo = AccessTools.Method(type, methodName.Substring(0, methodName.Length - "Compatibility".Length), (Type[])null, (Type[])null);
			}
			if (!(methodInfo != null))
			{
				return;
			}
			MethodInfo methodInfo2 = AccessTools.Method(patchClass, patchMethodName, (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				if (Plugin.Log != null)
				{
					Plugin.Log.LogInfo((object)$"[AvxCooperation] Attached cooperation hook on Valheim AVX {label}.");
				}
				MethodInfo methodInfo3 = AccessTools.Method(patchClass, "ApplyTo", new Type[1] { typeof(Type) }, (Type[])null);
				if (methodInfo3 != null)
				{
					methodInfo3.Invoke(null, new object[1] { type });
				}
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogWarning((object)$"[AvxCooperation] Failed to attach hook on {label}: {ex.Message}");
			}
		}
	}

	private static void AttachAvxProfilerGuard(Assembly avxAssembly, Harmony harmony)
	{
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Expected O, but got Unknown
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Expected O, but got Unknown
		try
		{
			Type type = avxAssembly.GetType("ValheimAccel.Managed.BenchmarkBehaviourProfiler");
			if (type == null)
			{
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(AvxBenchmarkProfilerGuardPatch), "Prefix", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				return;
			}
			int num = 0;
			foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(type))
			{
				if (declaredMethod.Name != null && declaredMethod.Name.Contains("g__Add|"))
				{
					ParameterInfo[] parameters = declaredMethod.GetParameters();
					if (parameters.Length >= 1 && typeof(MethodBase).IsAssignableFrom(parameters[0].ParameterType))
					{
						HarmonyMethod val = new HarmonyMethod(methodInfo);
						val.priority = 600;
						harmony.Patch((MethodBase)declaredMethod, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						num++;
					}
				}
			}
			MethodInfo methodInfo2 = AccessTools.Method(type, "Patch", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				HarmonyMethod val2 = new HarmonyMethod(methodInfo);
				val2.priority = 600;
				harmony.Patch((MethodBase)methodInfo2, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num++;
			}
			if (num > 0 && Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)"[AvxCooperation] Attached AVX profiler crash shield to BenchmarkBehaviourProfiler.");
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogDebug((object)$"[AvxCooperation] Profiler shield notice: {ex.Message}");
			}
		}
	}

	private static bool ContainsIgnoreCase(List<string> list, string value)
	{
		for (int i = 0; i < list.Count; i++)
		{
			if (string.Equals(list[i], value, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
		}
		return false;
	}
}
public static class AvxModCompatibilityPolicyPatch
{
	internal static string[] GetCooperativePeers()
	{
		List<string> list = new List<string>(8);
		if (Plugin.IsPovLoaded)
		{
			list.Add("treextr.pathofvalheiman");
		}
		list.Add("robin.valheim.pov_performance_boosts");
		bool flag = Plugin.ConfigEnableAvxSceneCreationCoop != null && Plugin.ConfigEnableAvxSceneCreationCoop.Value;
		bool flag2 = Plugin.ConfigEnableAvxTerrainCoop != null && Plugin.ConfigEnableAvxTerrainCoop.Value;
		bool flag3 = Plugin.ConfigEnableAvxGrassGroundCoop != null && Plugin.ConfigEnableAvxGrassGroundCoop.Value;
		bool flag4 = Plugin.ConfigEnableAvxDungeonRoomCoop != null && Plugin.ConfigEnableAvxDungeonRoomCoop.Value;
		bool flag5 = Plugin.IsAssemblyLoaded("FarLands");
		bool flag6 = Plugin.IsAssemblyLoaded("ValheimHDTerrain");
		bool flag7 = Plugin.IsAssemblyLoaded("HDValheimTextures");
		bool flag8 = Plugin.IsAssemblyLoaded("WiresAcoustics");
		if (flag && flag5)
		{
			list.Add("ru.ivest.farlands.pieces");
		}
		if (flag2 || flag3)
		{
			if (flag5)
			{
				list.Add("ValheimMods.Shared.GpuGrass");
				list.Add("ValheimMods.Shared.GrassPatches");
			}
			if (flag6)
			{
				list.Add("Badgers.ValheimHDTerrain");
			}
		}
		if (flag4)
		{
			if (flag7)
			{
				list.Add("Badgers.HDValheimTextures");
			}
			if (flag8)
			{
				list.Add("wire.valheim.acoustics");
			}
		}
		return list.ToArray();
	}

	public static void Prefix(ref string __2)
	{
		try
		{
			List<string> list = new List<string>();
			if (!string.IsNullOrEmpty(__2))
			{
				string[] array = __2.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (!string.IsNullOrEmpty(text) && !ContainsIgnoreCase(list, text))
					{
						list.Add(text);
					}
				}
			}
			bool flag = false;
			string[] cooperativePeers = GetCooperativePeers();
			for (int j = 0; j < cooperativePeers.Length; j++)
			{
				if (!ContainsIgnoreCase(list, cooperativePeers[j]))
				{
					list.Add(cooperativePeers[j]);
					flag = true;
				}
			}
			if (flag)
			{
				__2 = string.Join(", ", list.ToArray());
				if (Plugin.Log != null)
				{
					Plugin.Log.LogInfo((object)$"[AvxCooperation] Declared cooperative peers in Valheim AVX ModCompatibilityPolicy: {__2}");
				}
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogDebug((object)$"[AvxCooperation] Policy prefix notice: {ex.Message}");
			}
		}
	}

	private static bool ContainsIgnoreCase(List<string> list, string value)
	{
		for (int i = 0; i < list.Count; i++)
		{
			if (string.Equals(list[i], value, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
		}
		return false;
	}
}
internal sealed class AvxCoopFieldCache
{
	internal readonly Func<object> GetCurrent;

	internal readonly Action<object, bool> SetCompatible;

	internal readonly Action<object, bool> SetGenCompatible;

	internal readonly Action<object, bool> SetExploreCompatible;

	internal readonly Action<object, bool> SetResetCompatible;

	internal readonly Action<object, long> SetNextCheck;

	internal readonly FieldInfo CurrentField;

	internal readonly FieldInfo CompatibleField;

	internal readonly FieldInfo GenCompatibleField;

	internal readonly FieldInfo ExploreCompatibleField;

	internal readonly FieldInfo ResetCompatibleField;

	internal readonly FieldInfo NextCheckField;

	private static readonly Dictionary<Type, AvxCoopFieldCache> _cache = new Dictionary<Type, AvxCoopFieldCache>();

	private AvxCoopFieldCache(Type type, bool includeGenCompatible)
	{
		CurrentField = AccessTools.Field(type, "current");
		CompatibleField = AccessTools.Field(type, "compatible");
		GenCompatibleField = (includeGenCompatible ? AccessTools.Field(type, "generationCompatible") : null);
		ExploreCompatibleField = AccessTools.Field(type, "exploreCompatible");
		ResetCompatibleField = AccessTools.Field(type, "resetCompatible");
		FieldInfo fieldInfo = AccessTools.Field(type, "nextCheck");
		NextCheckField = ((fieldInfo != null && fieldInfo.FieldType == typeof(long)) ? fieldInfo : null);
		GetCurrent = FastFieldAccess.CreateStaticGetter<object>(CurrentField);
		SetCompatible = FastFieldAccess.CreateSetter<object, bool>(CompatibleField);
		SetGenCompatible = FastFieldAccess.CreateSetter<object, bool>(GenCompatibleField);
		SetExploreCompatible = FastFieldAccess.CreateSetter<object, bool>(ExploreCompatibleField);
		SetResetCompatible = FastFieldAccess.CreateSetter<object, bool>(ResetCompatibleField);
		SetNextCheck = FastFieldAccess.CreateSetter<object, long>(NextCheckField);
	}

	internal static AvxCoopFieldCache For(Type type, bool includeGenCompatible)
	{
		if (type == null)
		{
			return null;
		}
		if (!_cache.TryGetValue(type, out var value))
		{
			value = new AvxCoopFieldCache(type, includeGenCompatible);
			_cache[type] = value;
		}
		return value;
	}

	internal void ApplyInstance(object instance, bool includeGenCompatible)
	{
		if (instance == null)
		{
			return;
		}
		if (SetCompatible != null)
		{
			SetCompatible(instance, arg2: true);
		}
		else if (CompatibleField != null)
		{
			CompatibleField.SetValue(instance, true);
		}
		if (SetExploreCompatible != null)
		{
			SetExploreCompatible(instance, arg2: true);
		}
		else if (ExploreCompatibleField != null)
		{
			ExploreCompatibleField.SetValue(instance, true);
		}
		if (SetResetCompatible != null)
		{
			SetResetCompatible(instance, arg2: true);
		}
		else if (ResetCompatibleField != null)
		{
			ResetCompatibleField.SetValue(instance, true);
		}
		if (includeGenCompatible)
		{
			if (SetGenCompatible != null)
			{
				SetGenCompatible(instance, arg2: true);
			}
			else if (GenCompatibleField != null)
			{
				GenCompatibleField.SetValue(instance, true);
			}
		}
		if (Plugin.ConfigEnableMinimapSpikeGuard == null || Plugin.ConfigEnableMinimapSpikeGuard.Value)
		{
			long num = Stopwatch.GetTimestamp() + Stopwatch.Frequency * 30;
			if (SetNextCheck != null)
			{
				SetNextCheck(instance, num);
			}
			else if (NextCheckField != null)
			{
				NextCheckField.SetValue(instance, num);
			}
		}
	}
}
public static class AvxGenericCooperationPatch
{
	public static void ApplyTo(Type type)
	{
		if (type == null)
		{
			return;
		}
		try
		{
			AvxCoopFieldCache avxCoopFieldCache = AvxCoopFieldCache.For(type, includeGenCompatible: false);
			if (avxCoopFieldCache != null)
			{
				object obj = ((avxCoopFieldCache.GetCurrent != null) ? avxCoopFieldCache.GetCurrent() : ((avxCoopFieldCache.CurrentField != null) ? avxCoopFieldCache.CurrentField.GetValue(null) : null));
				if (obj != null)
				{
					avxCoopFieldCache.ApplyInstance(obj, includeGenCompatible: false);
				}
			}
		}
		catch
		{
		}
	}

	public static void Postfix(MethodBase __originalMethod, object __instance)
	{
		Type type = ((__originalMethod != null) ? __originalMethod.DeclaringType : null);
		if (type == null && __instance != null)
		{
			type = __instance.GetType();
		}
		if (type == null)
		{
			return;
		}
		if (__instance != null)
		{
			try
			{
				AvxCoopFieldCache.For(type, includeGenCompatible: false)?.ApplyInstance(__instance, includeGenCompatible: false);
				return;
			}
			catch
			{
				return;
			}
		}
		ApplyTo(type);
	}
}
public static class AvxDungeonCooperationPatch
{
	public static void ApplyTo(Type type)
	{
		if (type == null)
		{
			return;
		}
		try
		{
			AvxCoopFieldCache avxCoopFieldCache = AvxCoopFieldCache.For(type, includeGenCompatible: true);
			if (avxCoopFieldCache != null)
			{
				object obj = ((avxCoopFieldCache.GetCurrent != null) ? avxCoopFieldCache.GetCurrent() : ((avxCoopFieldCache.CurrentField != null) ? avxCoopFieldCache.CurrentField.GetValue(null) : null));
				if (obj != null)
				{
					avxCoopFieldCache.ApplyInstance(obj, includeGenCompatible: true);
				}
			}
		}
		catch
		{
		}
	}

	public static void Postfix(MethodBase __originalMethod, object __instance)
	{
		Type type = ((__originalMethod != null) ? __originalMethod.DeclaringType : null);
		if (type == null && __instance != null)
		{
			type = __instance.GetType();
		}
		if (type == null)
		{
			return;
		}
		if (__instance != null)
		{
			try
			{
				AvxCoopFieldCache.For(type, includeGenCompatible: true)?.ApplyInstance(__instance, includeGenCompatible: true);
				return;
			}
			catch
			{
				return;
			}
		}
		ApplyTo(type);
	}
}
public static class AvxBenchmarkProfilerGuardPatch
{
	[HarmonyPriority(600)]
	public static bool Prefix(MethodBase __0)
	{
		if (Plugin.ConfigEnableAvxProfilerCrashShield != null && !Plugin.ConfigEnableAvxProfilerCrashShield.Value)
		{
			return true;
		}
		if (__0 == null)
		{
			return true;
		}
		try
		{
			Type declaringType = __0.DeclaringType;
			if (declaringType == null)
			{
				return true;
			}
			string fullName = declaringType.FullName;
			if (!string.IsNullOrEmpty(fullName) && fullName.IndexOf("SelfTest", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return false;
			}
			string name = __0.Name;
			if (name != null && (name == "MoveNext" || name.EndsWith(".MoveNext", StringComparison.Ordinal)) && typeof(IEnumerable).IsAssignableFrom(declaringType))
			{
				return false;
			}
		}
		catch
		{
		}
		return true;
	}
}
public static class AvxScopedCooperationBridge
{
	private sealed class FallbackTypeInfo
	{
		public FieldInfo CompatibleField;

		public FieldInfo GroundCompatibleField;

		public FieldInfo MaskCompatibleField;

		public FieldInfo GroundFailedField;

		public FieldInfo MaskFailedField;

		public FieldInfo MethodsDictField;

		public FieldInfo WatchedArrayField;

		public FieldInfo PinsArrayField;

		public FieldInfo MethodsArrayField;
	}

	private const int ScopeTerrain = 1;

	private const int ScopeGrassGround = 2;

	private const int ScopeDungeonRooms = 4;

	private const int ScopeSceneCreation = 8;

	private const int ScopeSceneRemoval = 16;

	private const string OwnerGpuGrass = "ValheimMods.Shared.GpuGrass";

	private const string OwnerHdTerrain = "Badgers.ValheimHDTerrain";

	private const string OwnerHdTextures = "Badgers.HDValheimTextures";

	private const string OwnerWiresAcoustics = "wire.valheim.acoustics";

	private const string OwnerFarLandsPieces = "ru.ivest.farlands.pieces";

	private const string OwnerSelf = "robin.valheim.pov_performance_boosts";

	[ThreadStatic]
	private static int _activeScopeMask;

	[ThreadStatic]
	private static bool _inspectHitDuringRefresh;

	private static bool _terrainModifierBatchAllowed = true;

	private static bool _dungeonIlVerified;

	private static bool _gpuGrassPaintCaseAVerified;

	private static bool _gpuGrassBuildReturnsVoid;

	private static bool _gpuGrassFound;

	private static bool _farLandsPiecesFound;

	private static bool _hdTerrainFound;

	private static bool _wiresAcousticsFound;

	private static MethodBase _hmOnDisable;

	private static MethodBase _hmRegenerate;

	private static MethodBase _hmPaintCleared;

	private static MethodBase _hmAwake;

	private static MethodBase _hmInitialize;

	private static MethodBase _clutterGenerateVegPatch;

	private static MethodBase _dungeonPlaceRoom5;

	private static MethodBase _znsCreateObject;

	private static MethodBase _znsCreateObjectsSorted;

	private static MethodBase _znsRemoveObjects;

	private static readonly List<MethodInfo> _verifiedTerrainObserverMethods = new List<MethodInfo>(6);

	private static bool _observerMethodsResolved;

	private static FieldInfo _nearTerrainObserversField;

	private static readonly Dictionary<Type, FallbackTypeInfo> _fallbackCache = new Dictionary<Type, FallbackTypeInfo>();

	internal static void ApplyDynamicPatches(Assembly avxAssembly, Harmony harmony)
	{
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: Expected O, but got Unknown
		//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f7: Expected O, but got Unknown
		if (avxAssembly == null || harmony == null)
		{
			return;
		}
		try
		{
			bool flag = Plugin.ConfigEnableAvxTerrainCoop != null && Plugin.ConfigEnableAvxTerrainCoop.Value;
			bool flag2 = Plugin.ConfigEnableAvxGrassGroundCoop != null && Plugin.ConfigEnableAvxGrassGroundCoop.Value;
			bool flag3 = Plugin.ConfigEnableAvxDungeonRoomCoop != null && Plugin.ConfigEnableAvxDungeonRoomCoop.Value;
			bool flag4 = Plugin.ConfigEnableAvxDungeonStreamingCoop != null && Plugin.ConfigEnableAvxDungeonStreamingCoop.Value;
			bool flag5 = Plugin.ConfigEnableAvxSceneCreationCoop != null && Plugin.ConfigEnableAvxSceneCreationCoop.Value;
			bool flag6 = Plugin.ConfigEnableAvxSceneRemovalCoop != null && Plugin.ConfigEnableAvxSceneRemovalCoop.Value;
			if (!flag && !flag2 && !flag3 && !flag5 && !flag6)
			{
				return;
			}
			ResolveGameTargetMethods();
			ResolvePassiveObserverMethods();
			VerifyGpuGrassPaintMaskSync();
			VerifyGpuGrassBuildPrefix();
			if (flag3)
			{
				_dungeonIlVerified = VerifyDungeonPlaceRoomIlCoexistence();
				if (!_dungeonIlVerified && Plugin.Log != null)
				{
					Plugin.Log.LogWarning((object)"[AvxCooperation] DungeonGenerator.PlaceRoom IL verification failed; standing down DungeonRoomComponents cooperation.");
				}
			}
			if (!flag && (!flag2 || (_gpuGrassFound && !_gpuGrassBuildReturnsVoid)) && (!flag3 || !_dungeonIlVerified) && !flag5 && !flag6)
			{
				return;
			}
			MethodInfo methodInfo = FindPatchCompatibilityAllowedMethod(avxAssembly);
			string arg;
			if (methodInfo != null)
			{
				MethodInfo method = typeof(AvxScopedCooperationBridge).GetMethod("AllowedPostfix", BindingFlags.Static | BindingFlags.NonPublic);
				HarmonyMethod val = new HarmonyMethod(method);
				val.priority = 0;
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				arg = "PatchCompatibility.Allowed (AVX 1.1.27+)";
			}
			else
			{
				Type type = avxAssembly.GetType("ValheimAccel.Managed.OptimizationPatchGuard");
				MethodInfo methodInfo2 = ((type != null) ? type.GetMethod("Inspect", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(MethodBase) }, null) : null);
				if (methodInfo2 == null)
				{
					if (Plugin.Log != null)
					{
						Plugin.Log.LogWarning((object)"[AvxCooperation] Neither PatchCompatibility.Allowed nor OptimizationPatchGuard.Inspect found; standing down scoped cooperation.");
					}
					return;
				}
				MethodInfo method2 = typeof(AvxScopedCooperationBridge).GetMethod("InspectPostfix", BindingFlags.Static | BindingFlags.NonPublic);
				HarmonyMethod val2 = new HarmonyMethod(method2);
				val2.priority = 0;
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				arg = "OptimizationPatchGuard.Inspect (legacy AVX)";
			}
			if (flag)
			{
				List<string> list = new List<string>(5);
				if (HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.NearTerrainRebuilds", "RefreshCompatibility", 1, isNearTerrain: true))
				{
					list.Add("NearTerrainRebuilds");
				}
				if (HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.TerrainModifierCache", "RefreshCompatibility", 1, isNearTerrain: false))
				{
					list.Add("TerrainModifierCache");
				}
				if (_terrainModifierBatchAllowed && HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.TerrainModifierBatch", "Refresh", 1, isNearTerrain: false))
				{
					list.Add("TerrainModifierBatch");
				}
				if (HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.FastSupportCallbacks", "Refresh", 1, isNearTerrain: false))
				{
					list.Add("FastSupportCallbacks");
				}
				if (HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.TerrainNotificationBounds", "Refresh", 1, isNearTerrain: false))
				{
					list.Add("TerrainNotificationBounds");
				}
				if (list.Count > 0 && Plugin.Log != null)
				{
					string arg2 = ((!_gpuGrassFound) ? "" : (_gpuGrassPaintCaseAVerified ? " (GpuGrass Forget sync verified)" : " (TerrainModifierBatch conservative)"));
					Plugin.Log.LogInfo((object)string.Format("[AvxCooperation] Enabled terrain cooperation ({0}) via {1}{2}.", string.Join(", ", list.ToArray()), arg, arg2));
				}
			}
			if (flag2 && (!_gpuGrassFound || _gpuGrassBuildReturnsVoid) && HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.GrassGroundSampling", "Refresh", 2, isNearTerrain: false) && Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)"[AvxCooperation] Enabled GrassGroundSampling cooperation.");
			}
			if (flag3 && _dungeonIlVerified && HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.DungeonRoomComponents", "Refresh", 4, isNearTerrain: false))
			{
				if (flag4)
				{
					HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.DungeonSpawnBudget", "RefreshCompatibility", 4, isNearTerrain: false);
				}
				if (Plugin.Log != null)
				{
					Plugin.Log.LogInfo((object)"[AvxCooperation] Enabled DungeonRoomComponents cooperation (disjoint PlaceRoom IL verified).");
				}
			}
			List<string> list2 = new List<string>(2);
			if (flag5 && HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.SceneCreationBudget", "Refresh", 8, isNearTerrain: false))
			{
				list2.Add("SceneCreationBudget");
			}
			if (flag6 && HookScopedRefresh(avxAssembly, harmony, "ValheimAccel.Managed.SceneRemovalBudget", "Refresh", 16, isNearTerrain: false))
			{
				list2.Add("SceneRemovalBudget");
			}
			if (list2.Count > 0 && Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)string.Format("[AvxCooperation] Enabled scoped streaming cooperation ({0}) via {1} (farLandsDetected={2}).", string.Join(", ", list2.ToArray()), arg, _farLandsPiecesFound));
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogWarning((object)$"[AvxCooperation] Scoped cooperation notice: {ex.Message}");
			}
		}
	}

	private static MethodInfo FindPatchCompatibilityAllowedMethod(Assembly avxAssembly)
	{
		if (avxAssembly == null)
		{
			return null;
		}
		Type type = avxAssembly.GetType("ValheimAccel.Managed.PatchCompatibility");
		if (type == null)
		{
			return null;
		}
		MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		foreach (MethodInfo methodInfo in methods)
		{
			if (!(methodInfo.Name != "Allowed") && !(methodInfo.ReturnType != typeof(bool)))
			{
				ParameterInfo[] parameters = methodInfo.GetParameters();
				if (parameters.Length >= 3 && parameters[0].ParameterType == typeof(MethodBase) && parameters[1].ParameterType == typeof(Patch) && parameters[2].ParameterType == typeof(HarmonyPatchType))
				{
					return methodInfo;
				}
			}
		}
		return null;
	}

	internal static void OnAllPluginsStarted()
	{
		try
		{
			if (!_observerMethodsResolved)
			{
				ResolvePassiveObserverMethods();
			}
			if (!_gpuGrassFound)
			{
				VerifyGpuGrassPaintMaskSync();
				VerifyGpuGrassBuildPrefix();
			}
		}
		catch
		{
		}
	}

	private static void ResolveGameTargetMethods()
	{
		BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
		Type typeFromHandle = typeof(Heightmap);
		_hmOnDisable = typeFromHandle.GetMethod("OnDisable", bindingAttr, null, Type.EmptyTypes, null);
		_hmRegenerate = typeFromHandle.GetMethod("Regenerate", bindingAttr, null, Type.EmptyTypes, null);
		_hmPaintCleared = typeFromHandle.GetMethod("PaintCleared", bindingAttr, null, new Type[6]
		{
			typeof(Vector3),
			typeof(float),
			typeof(PaintType),
			typeof(bool),
			typeof(bool),
			typeof(float)
		}, null);
		_hmAwake = typeFromHandle.GetMethod("Awake", bindingAttr, null, Type.EmptyTypes, null);
		_hmInitialize = typeFromHandle.GetMethod("Initialize", bindingAttr, null, Type.EmptyTypes, null);
		_clutterGenerateVegPatch = typeof(ClutterSystem).GetMethod("GenerateVegPatch", bindingAttr, null, new Type[2]
		{
			typeof(Vector2Int),
			typeof(float)
		}, null);
		_dungeonPlaceRoom5 = typeof(DungeonGenerator).GetMethod("PlaceRoom", bindingAttr, null, new Type[5]
		{
			typeof(RoomData),
			typeof(Vector3),
			typeof(Quaternion),
			typeof(RoomConnection),
			typeof(SpawnMode)
		}, null);
		Type typeFromHandle2 = typeof(ZNetScene);
		_znsCreateObject = typeFromHandle2.GetMethod("CreateObject", bindingAttr, null, new Type[1] { typeof(ZDO) }, null);
		_znsCreateObjectsSorted = typeFromHandle2.GetMethod("CreateObjectsSorted", bindingAttr, null, new Type[3]
		{
			typeof(List<ZDO>),
			typeof(int),
			typeof(int).MakeByRefType()
		}, null);
		_znsRemoveObjects = typeFromHandle2.GetMethod("RemoveObjects", bindingAttr, null, new Type[2]
		{
			typeof(List<ZDO>),
			typeof(List<ZDO>)
		}, null);
	}

	private static void ResolvePassiveObserverMethods()
	{
		_verifiedTerrainObserverMethods.Clear();
		BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			switch (assembly.GetName().Name)
			{
			case "FarLands":
			{
				Type type = assembly.GetType("ValheimMods.Shared.GpuGrass");
				if (type != null)
				{
					_gpuGrassFound = true;
					AddNestedMethod(type, "Patch_HeightmapOff", "Postfix", flags);
					AddNestedMethod(type, "Patch_Regenerate", "Postfix", flags);
					AddNestedMethod(type, "Patch_PaintCleared", "Postfix", flags);
				}
				if (assembly.GetType("FarLands.InstanceCreated") != null)
				{
					_farLandsPiecesFound = true;
				}
				break;
			}
			case "ValheimHDTerrain":
			{
				Type type2 = assembly.GetType("ValheimHDTerrain.HarmonyPatches");
				if (type2 != null)
				{
					_hdTerrainFound = true;
					AddNestedMethod(type2, "HeightMap_Awake", "Prefix", flags);
					AddNestedMethod(type2, "Heightmap_Initialize", "Postfix", flags);
				}
				break;
			}
			case "WiresAcoustics":
				if (assembly.GetType("WiresAcoustics.Spawned") != null)
				{
					_wiresAcousticsFound = true;
				}
				break;
			}
		}
		if (_gpuGrassFound && _hdTerrainFound)
		{
			_observerMethodsResolved = true;
		}
	}

	private static MethodInfo FindFirstMethodByName(Type type, string methodName, BindingFlags flags)
	{
		if (type == null || string.IsNullOrEmpty(methodName))
		{
			return null;
		}
		MethodInfo[] methods = type.GetMethods(flags);
		for (int i = 0; i < methods.Length; i++)
		{
			if (methods[i].Name == methodName)
			{
				return methods[i];
			}
		}
		return null;
	}

	private static bool SameMethod(MethodBase a, MethodBase b)
	{
		if (object.ReferenceEquals(a, b))
		{
			return true;
		}
		if (a == null || b == null)
		{
			return false;
		}
		if (a.Equals(b))
		{
			return true;
		}
		if (a.Module == b.Module)
		{
			return a.MetadataToken == b.MetadataToken;
		}
		return false;
	}

	private static void AddNestedMethod(Type parentType, string nestedName, string methodName, BindingFlags flags)
	{
		if (parentType == null)
		{
			return;
		}
		Type nestedType = parentType.GetNestedType(nestedName, BindingFlags.Public | BindingFlags.NonPublic);
		if (!(nestedType == null))
		{
			MethodInfo methodInfo = FindFirstMethodByName(nestedType, methodName, flags);
			if (methodInfo != null && !_verifiedTerrainObserverMethods.Contains(methodInfo))
			{
				_verifiedTerrainObserverMethods.Add(methodInfo);
			}
		}
	}

	private static void VerifyGpuGrassPaintMaskSync()
	{
		_gpuGrassPaintCaseAVerified = false;
		_terrainModifierBatchAllowed = true;
		Type type = FindTypeInLoadedAssemblies("ValheimMods.Shared.GpuGrass");
		if (type == null)
		{
			return;
		}
		_gpuGrassFound = true;
		BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
		Type nestedType = type.GetNestedType("Patch_PaintCleared", BindingFlags.Public | BindingFlags.NonPublic);
		Type nestedType2 = type.GetNestedType("Patch_Regenerate", BindingFlags.Public | BindingFlags.NonPublic);
		MethodInfo methodInfo = FindFirstMethodByName(nestedType, "Postfix", bindingFlags);
		MethodInfo methodInfo2 = FindFirstMethodByName(nestedType2, "Postfix", bindingFlags);
		MethodInfo method = type.GetMethod("Forget", bindingFlags, null, new Type[1] { typeof(Heightmap) }, null);
		if (!(methodInfo == null) && !(methodInfo2 == null) && !(method == null))
		{
			if (CallsOnlyTargetMethod(methodInfo, method) && CallsOnlyTargetMethod(methodInfo2, method))
			{
				_gpuGrassPaintCaseAVerified = true;
				_terrainModifierBatchAllowed = true;
			}
			else
			{
				_gpuGrassPaintCaseAVerified = false;
				_terrainModifierBatchAllowed = false;
			}
		}
	}

	private static bool CallsOnlyTargetMethod(MethodInfo caller, MethodInfo expectedCallee)
	{
		try
		{
			List<CodeInstruction> originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)caller, (ILGenerator)null);
			if (originalInstructions == null || originalInstructions.Count == 0)
			{
				return false;
			}
			int num = 0;
			for (int i = 0; i < originalInstructions.Count; i++)
			{
				OpCode opcode = originalInstructions[i].opcode;
				if (opcode == OpCodes.Call || opcode == OpCodes.Callvirt)
				{
					MethodBase a = originalInstructions[i].operand as MethodBase;
					if (!SameMethod(a, expectedCallee))
					{
						return false;
					}
					num++;
				}
			}
			return num == 1;
		}
		catch
		{
			return false;
		}
	}

	private static void VerifyGpuGrassBuildPrefix()
	{
		_gpuGrassBuildReturnsVoid = false;
		Type type = FindTypeInLoadedAssemblies("ValheimMods.Shared.GpuGrass");
		if (!(type == null))
		{
			_gpuGrassFound = true;
			Type nestedType = type.GetNestedType("Patch_Build", BindingFlags.Public | BindingFlags.NonPublic);
			if (nestedType == null)
			{
				_gpuGrassBuildReturnsVoid = true;
				return;
			}
			MethodInfo methodInfo = FindFirstMethodByName(nestedType, "Prefix", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			_gpuGrassBuildReturnsVoid = methodInfo == null || methodInfo.ReturnType == typeof(void);
		}
	}

	private static bool VerifyDungeonPlaceRoomIlCoexistence()
	{
		try
		{
			if (_dungeonPlaceRoom5 == null)
			{
				return false;
			}
			List<CodeInstruction> originalInstructions = PatchProcessor.GetOriginalInstructions(_dungeonPlaceRoom5, (ILGenerator)null);
			if (originalInstructions == null || originalInstructions.Count < 10)
			{
				return false;
			}
			int num = 0;
			int num2 = -1;
			for (int i = 0; i <= originalInstructions.Count - 5; i++)
			{
				if (originalInstructions[i].opcode == OpCodes.Ldarg_1 && originalInstructions[i + 1].opcode == OpCodes.Ldflda && originalInstructions[i + 2].opcode == OpCodes.Call && originalInstructions[i + 3].opcode == OpCodes.Callvirt && originalInstructions[i + 4].opcode == OpCodes.Stloc_0)
				{
					num++;
					num2 = i + 4;
				}
			}
			if (num != 1)
			{
				return false;
			}
			int num3 = 0;
			for (int j = 0; j < originalInstructions.Count; j++)
			{
				if (!(originalInstructions[j].opcode == OpCodes.Call))
				{
					continue;
				}
				MethodInfo methodInfo = originalInstructions[j].operand as MethodInfo;
				if (methodInfo != null && methodInfo.IsGenericMethod && methodInfo.DeclaringType == typeof(Utils) && methodInfo.Name == "GetEnabledComponentsInChildren")
				{
					if (j <= num2)
					{
						return false;
					}
					num3++;
				}
			}
			if (num3 != 3)
			{
				return false;
			}
			if (_wiresAcousticsFound)
			{
				Type type = FindTypeInLoadedAssemblies("WiresAcoustics.Spawned");
				if (type != null)
				{
					Type nestedType = type.GetNestedType("AtDungeonRoom", BindingFlags.Public | BindingFlags.NonPublic);
					if (nestedType != null)
					{
						BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
						if (FindFirstMethodByName(nestedType, "Prefix", flags) != null || FindFirstMethodByName(nestedType, "Transpiler", flags) != null)
						{
							return false;
						}
					}
				}
			}
			return true;
		}
		catch
		{
			return false;
		}
	}

	private static bool HookScopedRefresh(Assembly avxAssembly, Harmony harmony, string typeName, string methodName, int scopeFlag, bool isNearTerrain)
	{
		//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Expected O, but got Unknown
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Expected O, but got Unknown
		Type type = avxAssembly.GetType(typeName);
		if (type == null)
		{
			return false;
		}
		BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
		MethodInfo method = type.GetMethod(methodName, bindingAttr, null, Type.EmptyTypes, null);
		if (method == null)
		{
			return false;
		}
		if (isNearTerrain)
		{
			_nearTerrainObserversField = type.GetField("upscalerObservers", bindingAttr);
		}
		FallbackTypeInfo fallbackTypeInfo = new FallbackTypeInfo();
		fallbackTypeInfo.CompatibleField = type.GetField("compatible", bindingAttr);
		fallbackTypeInfo.GroundCompatibleField = type.GetField("groundCompatible", bindingAttr);
		fallbackTypeInfo.MaskCompatibleField = type.GetField("maskCompatible", bindingAttr);
		fallbackTypeInfo.GroundFailedField = type.GetField("groundFailed", bindingAttr);
		fallbackTypeInfo.MaskFailedField = type.GetField("maskFailed", bindingAttr);
		fallbackTypeInfo.MethodsDictField = type.GetField("methods", bindingAttr);
		fallbackTypeInfo.WatchedArrayField = type.GetField("watched", bindingAttr);
		fallbackTypeInfo.PinsArrayField = type.GetField("pins", bindingAttr);
		fallbackTypeInfo.MethodsArrayField = ((fallbackTypeInfo.MethodsDictField != null && fallbackTypeInfo.MethodsDictField.FieldType == typeof(MethodInfo[])) ? fallbackTypeInfo.MethodsDictField : null);
		if (fallbackTypeInfo.MethodsArrayField != null)
		{
			fallbackTypeInfo.MethodsDictField = null;
		}
		_fallbackCache[type] = fallbackTypeInfo;
		string name;
		string name2;
		switch (scopeFlag)
		{
		case 1:
			name = (isNearTerrain ? "NearTerrainRefreshPrefix" : "TerrainRefreshPrefix");
			name2 = "TerrainRefreshFinalizer";
			break;
		case 2:
			name = "GrassGroundRefreshPrefix";
			name2 = "GrassGroundRefreshFinalizer";
			break;
		case 8:
			name = "SceneCreationRefreshPrefix";
			name2 = "SceneCreationRefreshFinalizer";
			break;
		case 16:
			name = "SceneRemovalRefreshPrefix";
			name2 = "SceneRemovalRefreshFinalizer";
			break;
		default:
			name = "DungeonRoomsRefreshPrefix";
			name2 = "DungeonRoomsRefreshFinalizer";
			break;
		}
		MethodInfo method2 = typeof(AvxScopedCooperationBridge).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic);
		MethodInfo method3 = typeof(AvxScopedCooperationBridge).GetMethod(name2, BindingFlags.Static | BindingFlags.NonPublic);
		if (method2 == null || method3 == null)
		{
			return false;
		}
		HarmonyMethod val = new HarmonyMethod(method2);
		val.priority = 800;
		HarmonyMethod val2 = new HarmonyMethod(method3);
		val2.priority = 0;
		harmony.Patch((MethodBase)method, val, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null);
		return true;
	}

	private static void NearTerrainRefreshPrefix(object __instance, out int __state)
	{
		if (__instance != null && _nearTerrainObserversField != null)
		{
			try
			{
				if (!_observerMethodsResolved)
				{
					ResolvePassiveObserverMethods();
				}
				if (_nearTerrainObserversField.GetValue(__instance) is HashSet<MethodInfo> hashSet)
				{
					for (int i = 0; i < _verifiedTerrainObserverMethods.Count; i++)
					{
						hashSet.Add(_verifiedTerrainObserverMethods[i]);
					}
				}
			}
			catch
			{
			}
		}
		__state = _activeScopeMask;
		_inspectHitDuringRefresh = false;
		_activeScopeMask = __state | 1;
	}

	private static void TerrainRefreshPrefix(out int __state)
	{
		__state = _activeScopeMask;
		_inspectHitDuringRefresh = false;
		_activeScopeMask = __state | 1;
	}

	private static Exception TerrainRefreshFinalizer(Exception __exception, object __instance, MethodBase __originalMethod, int __state)
	{
		_activeScopeMask = __state;
		if (__exception == null && !_inspectHitDuringRefresh && __instance != null && __originalMethod != null)
		{
			RunInlinedInspectFallback(__instance, __originalMethod.DeclaringType, 1);
		}
		return __exception;
	}

	private static void GrassGroundRefreshPrefix(out int __state)
	{
		__state = _activeScopeMask;
		_inspectHitDuringRefresh = false;
		_activeScopeMask = __state | 2;
	}

	private static Exception GrassGroundRefreshFinalizer(Exception __exception, object __instance, MethodBase __originalMethod, int __state)
	{
		_activeScopeMask = __state;
		if (__exception == null && !_inspectHitDuringRefresh && __instance != null && __originalMethod != null)
		{
			RunInlinedInspectFallback(__instance, __originalMethod.DeclaringType, 2);
		}
		return __exception;
	}

	private static void DungeonRoomsRefreshPrefix(out int __state)
	{
		__state = _activeScopeMask;
		_inspectHitDuringRefresh = false;
		_activeScopeMask = __state | 4;
	}

	private static Exception DungeonRoomsRefreshFinalizer(Exception __exception, object __instance, MethodBase __originalMethod, int __state)
	{
		_activeScopeMask = __state;
		if (__exception == null && !_inspectHitDuringRefresh && __instance != null && __originalMethod != null)
		{
			RunInlinedInspectFallback(__instance, __originalMethod.DeclaringType, 4);
		}
		return __exception;
	}

	private static void SceneCreationRefreshPrefix(out int __state)
	{
		__state = _activeScopeMask;
		_inspectHitDuringRefresh = false;
		_activeScopeMask = __state | 8;
	}

	private static Exception SceneCreationRefreshFinalizer(Exception __exception, int __state)
	{
		_activeScopeMask = __state;
		return __exception;
	}

	private static void SceneRemovalRefreshPrefix(out int __state)
	{
		__state = _activeScopeMask;
		_inspectHitDuringRefresh = false;
		_activeScopeMask = __state | 0x10;
	}

	private static Exception SceneRemovalRefreshFinalizer(Exception __exception, int __state)
	{
		_activeScopeMask = __state;
		return __exception;
	}

	private static void AllowedPostfix(MethodBase __0, Patch __1, HarmonyPatchType __2, ref bool __result)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		int activeScopeMask = _activeScopeMask;
		if (activeScopeMask == 0)
		{
			return;
		}
		_inspectHitDuringRefresh = true;
		if (!__result && !(__0 == null) && __1 != null && IsMethodEligibleForScope(activeScopeMask, __0))
		{
			string text = PatchTypeToKind(__2);
			if (text != null && IsWhitelistedPatch(activeScopeMask, __0, text, __1))
			{
				__result = true;
			}
		}
	}

	private static string PatchTypeToKind(HarmonyPatchType kind)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected I4, but got Unknown
		return (kind - 1) switch
		{
			0 => "prefix", 
			1 => "postfix", 
			2 => "transpiler", 
			3 => "finalizer", 
			5 => "ilmanipulator", 
			_ => null, 
		};
	}

	private static void InspectPostfix(MethodBase __0, ref Patches __result)
	{
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		int activeScopeMask = _activeScopeMask;
		if (activeScopeMask == 0)
		{
			return;
		}
		_inspectHitDuringRefresh = true;
		if (__result != null && !(__0 == null) && IsMethodEligibleForScope(activeScopeMask, __0))
		{
			bool anyRemoved = false;
			Patch[] array = FilterPatchList(__result.Prefixes, activeScopeMask, __0, "prefix", ref anyRemoved);
			Patch[] array2 = FilterPatchList(__result.Postfixes, activeScopeMask, __0, "postfix", ref anyRemoved);
			Patch[] array3 = FilterPatchList(__result.Transpilers, activeScopeMask, __0, "transpiler", ref anyRemoved);
			Patch[] array4 = FilterPatchList(__result.Finalizers, activeScopeMask, __0, "finalizer", ref anyRemoved);
			Patch[] array5 = FilterPatchList(__result.ILManipulators, activeScopeMask, __0, "ilmanipulator", ref anyRemoved);
			if (anyRemoved)
			{
				__result = new Patches(array, array2, array3, array4, array5);
			}
		}
	}

	private static bool IsMethodEligibleForScope(int scope, MethodBase method)
	{
		if ((scope & 1) != 0 && (SameMethod(method, _hmOnDisable) || SameMethod(method, _hmRegenerate) || SameMethod(method, _hmPaintCleared) || SameMethod(method, _hmAwake) || SameMethod(method, _hmInitialize)))
		{
			return true;
		}
		if ((scope & 2) != 0 && SameMethod(method, _clutterGenerateVegPatch))
		{
			return true;
		}
		if ((scope & 4) != 0 && _dungeonIlVerified && SameMethod(method, _dungeonPlaceRoom5))
		{
			return true;
		}
		if ((scope & 8) != 0 && (SameMethod(method, _znsCreateObject) || SameMethod(method, _znsCreateObjectsSorted)))
		{
			return true;
		}
		if ((scope & 0x10) != 0 && SameMethod(method, _znsRemoveObjects))
		{
			return true;
		}
		return false;
	}

	private static Patch[] FilterPatchList(ReadOnlyCollection<Patch> source, int scope, MethodBase targetMethod, string kind, ref bool anyRemoved)
	{
		if (source == null || source.Count == 0)
		{
			return (Patch[])(object)new Patch[0];
		}
		List<Patch> list = null;
		int count = source.Count;
		for (int i = 0; i < count; i++)
		{
			Patch val = source[i];
			if (IsWhitelistedPatch(scope, targetMethod, kind, val))
			{
				if (list == null)
				{
					list = new List<Patch>(count - 1);
					for (int j = 0; j < i; j++)
					{
						list.Add(source[j]);
					}
				}
				anyRemoved = true;
			}
			else
			{
				list?.Add(val);
			}
		}
		if (list != null)
		{
			return list.ToArray();
		}
		Patch[] array = (Patch[])(object)new Patch[count];
		for (int k = 0; k < count; k++)
		{
			array[k] = source[k];
		}
		return array;
	}

	private static bool IsWhitelistedPatch(int scope, MethodBase targetMethod, string kind, Patch p)
	{
		if (p == null)
		{
			return false;
		}
		string owner = p.owner;
		MethodInfo patchMethod = p.PatchMethod;
		if (string.IsNullOrEmpty(owner) || patchMethod == null || patchMethod.DeclaringType == null)
		{
			return false;
		}
		string fullName = patchMethod.DeclaringType.FullName;
		if ((scope & 1) != 0)
		{
			if (SameMethod(targetMethod, _hmOnDisable) && kind == "postfix" && owner == "ValheimMods.Shared.GpuGrass" && patchMethod.Name == "Postfix" && fullName == "ValheimMods.Shared.GpuGrass+Patch_HeightmapOff")
			{
				return true;
			}
			if (SameMethod(targetMethod, _hmRegenerate) && kind == "postfix" && owner == "ValheimMods.Shared.GpuGrass" && patchMethod.Name == "Postfix" && fullName == "ValheimMods.Shared.GpuGrass+Patch_Regenerate")
			{
				return true;
			}
			if (SameMethod(targetMethod, _hmPaintCleared) && kind == "postfix" && owner == "ValheimMods.Shared.GpuGrass" && patchMethod.Name == "Postfix" && fullName == "ValheimMods.Shared.GpuGrass+Patch_PaintCleared")
			{
				return true;
			}
			if (SameMethod(targetMethod, _hmAwake) && kind == "prefix" && owner == "Badgers.ValheimHDTerrain" && patchMethod.Name == "Prefix" && fullName == "ValheimHDTerrain.HarmonyPatches+HeightMap_Awake")
			{
				return true;
			}
			if (SameMethod(targetMethod, _hmInitialize) && kind == "postfix" && owner == "Badgers.ValheimHDTerrain" && patchMethod.Name == "Postfix" && fullName == "ValheimHDTerrain.HarmonyPatches+Heightmap_Initialize")
			{
				return true;
			}
		}
		if ((scope & 2) != 0 && SameMethod(targetMethod, _clutterGenerateVegPatch) && owner == "ValheimMods.Shared.GpuGrass" && fullName == "ValheimMods.Shared.GpuGrass+Patch_Build")
		{
			if (kind == "prefix" && patchMethod.Name == "Prefix")
			{
				return patchMethod.ReturnType == typeof(void);
			}
			if (kind == "postfix" && patchMethod.Name == "Postfix")
			{
				return true;
			}
			if (kind == "finalizer" && patchMethod.Name == "Finalizer")
			{
				return true;
			}
		}
		if ((scope & 4) != 0 && _dungeonIlVerified && SameMethod(targetMethod, _dungeonPlaceRoom5))
		{
			if (kind == "transpiler" && owner == "Badgers.HDValheimTextures" && patchMethod.Name == "Transpiler" && fullName == "NS_HDValheimTextures.HarmonyPatches+DungeonGenerator_PlaceRoom")
			{
				return true;
			}
			if (kind == "postfix" && owner == "wire.valheim.acoustics" && patchMethod.Name == "Postfix" && fullName == "WiresAcoustics.Spawned+AtDungeonRoom")
			{
				return true;
			}
		}
		if ((scope & 8) != 0)
		{
			if (SameMethod(targetMethod, _znsCreateObject) && kind == "postfix" && owner == "ru.ivest.farlands.pieces" && patchMethod.Name == "Postfix" && fullName == "FarLands.InstanceCreated" && patchMethod.ReturnType == typeof(void))
			{
				return true;
			}
			if (SameMethod(targetMethod, _znsCreateObjectsSorted) && kind == "transpiler" && owner == "robin.valheim.pov_performance_boosts" && patchMethod.Name == "Transpiler" && fullName == "PovPerformanceBoosts.ZNetSceneCreateObjectsSortedBridge")
			{
				return true;
			}
		}
		if ((scope & 0x10) != 0 && SameMethod(targetMethod, _znsRemoveObjects) && kind == "prefix" && owner == "robin.valheim.pov_performance_boosts" && patchMethod.Name == "ZNetSceneRemoveObjectsPrefix" && fullName == "PovPerformanceBoosts.ZNetSceneEvenOddSplitBridge")
		{
			return true;
		}
		return false;
	}

	private static void RunInlinedInspectFallback(object instance, Type type, int scope)
	{
		if (instance == null || type == null || !_fallbackCache.TryGetValue(type, out var value))
		{
			return;
		}
		bool flag = value.CompatibleField != null;
		bool flag2 = value.GroundCompatibleField != null || value.MaskCompatibleField != null;
		if (!flag && !flag2)
		{
			return;
		}
		try
		{
			if (flag)
			{
				if ((bool)value.CompatibleField.GetValue(instance))
				{
					return;
				}
			}
			else
			{
				bool flag3 = value.GroundCompatibleField == null || (bool)value.GroundCompatibleField.GetValue(instance);
				bool flag4 = value.MaskCompatibleField == null || (bool)value.MaskCompatibleField.GetValue(instance);
				if (flag3 && flag4)
				{
					return;
				}
			}
			List<MethodBase> list = new List<MethodBase>(16);
			if (value.MethodsDictField != null)
			{
				if (value.MethodsDictField.GetValue(instance) is Dictionary<string, MethodInfo> dictionary)
				{
					foreach (MethodInfo value2 in dictionary.Values)
					{
						if (value2 != null)
						{
							list.Add(value2);
						}
					}
				}
			}
			else if (value.WatchedArrayField != null)
			{
				if (value.WatchedArrayField.GetValue(instance) is MethodInfo[] array)
				{
					for (int i = 0; i < array.Length; i++)
					{
						if (array[i] != null)
						{
							list.Add(array[i]);
						}
					}
				}
			}
			else if (value.PinsArrayField != null)
			{
				if (value.PinsArrayField.GetValue(instance) is MethodInfo[] array2)
				{
					for (int j = 0; j < array2.Length; j++)
					{
						if (array2[j] != null)
						{
							list.Add(array2[j]);
						}
					}
				}
			}
			else if (value.MethodsArrayField != null && value.MethodsArrayField.GetValue(instance) is MethodInfo[] array3)
			{
				for (int k = 0; k < array3.Length; k++)
				{
					if (array3[k] != null)
					{
						list.Add(array3[k]);
					}
				}
			}
			if (type.Name == "TerrainNotificationBounds")
			{
				if (_hmRegenerate != null)
				{
					list.Add(_hmRegenerate);
				}
				MethodInfo method = typeof(Heightmap).GetMethod("GetAllHeightmaps", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
				if (method != null)
				{
					list.Add(method);
				}
				MethodInfo method2 = typeof(TerrainModifier).GetMethod("GetAllInstances", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
				if (method2 != null)
				{
					list.Add(method2);
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			for (int l = 0; l < list.Count; l++)
			{
				if (HasUnwhitelistedForeignPatch(scope, list[l]))
				{
					return;
				}
			}
			if (flag)
			{
				value.CompatibleField.SetValue(instance, true);
				return;
			}
			bool flag5 = value.GroundFailedField != null && (bool)value.GroundFailedField.GetValue(instance);
			bool flag6 = value.MaskFailedField != null && (bool)value.MaskFailedField.GetValue(instance);
			if (!flag5 && value.GroundCompatibleField != null)
			{
				value.GroundCompatibleField.SetValue(instance, true);
			}
			if (!flag6 && value.MaskCompatibleField != null)
			{
				value.MaskCompatibleField.SetValue(instance, true);
			}
		}
		catch
		{
		}
	}

	private static bool HasUnwhitelistedForeignPatch(int scope, MethodBase method)
	{
		Patches patchInfo = Harmony.GetPatchInfo(method);
		if (patchInfo == null)
		{
			return false;
		}
		if (ListHasUnwhitelistedForeign(patchInfo.Prefixes, scope, method, "prefix"))
		{
			return true;
		}
		if (ListHasUnwhitelistedForeign(patchInfo.Postfixes, scope, method, "postfix"))
		{
			return true;
		}
		if (ListHasUnwhitelistedForeign(patchInfo.Transpilers, scope, method, "transpiler"))
		{
			return true;
		}
		if (ListHasUnwhitelistedForeign(patchInfo.Finalizers, scope, method, "finalizer"))
		{
			return true;
		}
		if (ListHasUnwhitelistedForeign(patchInfo.ILManipulators, scope, method, "ilmanipulator"))
		{
			return true;
		}
		return false;
	}

	private static bool ListHasUnwhitelistedForeign(ReadOnlyCollection<Patch> list, int scope, MethodBase method, string kind)
	{
		if (list == null)
		{
			return false;
		}
		for (int i = 0; i < list.Count; i++)
		{
			Patch val = list[i];
			if (val != null && !string.IsNullOrEmpty(val.owner) && !val.owner.StartsWith("com.kewb.valheimavx", StringComparison.Ordinal) && !IsWhitelistedPatch(scope, method, kind, val))
			{
				return true;
			}
		}
		return false;
	}

	private static Type FindTypeInLoadedAssemblies(string fullTypeName)
	{
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		for (int i = 0; i < assemblies.Length; i++)
		{
			Type type = assemblies[i].GetType(fullTypeName, throwOnError: false);
			if (type != null)
			{
				return type;
			}
		}
		return null;
	}
}
[Flags]
internal enum BuildCapability : ulong
{
	None = 0uL,
	Bow = 1uL,
	Crossbow = 2uL,
	Staff = 4uL,
	Shield = 8uL,
	ThrownOrSpear = 0x10uL,
	Bomb = 0x20uL,
	MeleeOneHand = 0x40uL,
	MeleeTwoHand = 0x80uL,
	Sceptre = 0x100uL,
	Unarmed = 0x200uL,
	FishingRod = 0x400uL,
	Bell = 0x800uL,
	LinkStaff = 0x1000uL,
	CompanionHorn = 0x2000uL,
	Pickaxe = 0x4000uL,
	JotunHeir = 0x10000uL,
	Berserker = 0x20000uL,
	MeadReaver = 0x40000uL,
	ForgeMaster = 0x80000uL,
	Marksman = 0x100000uL,
	VenomKeeper = 0x200000uL,
	StormLord = 0x400000uL,
	Elementalist = 0x800000uL,
	Gladiator = 0x1000000uL,
	Phantom = 0x2000000uL,
	BallistaMaster = 0x4000000uL,
	LinkWarden = 0x8000000uL,
	HasEnergyShield = 0x100000000uL,
	HasChainLightning = 0x200000000uL,
	HasImmobilize = 0x400000000uL,
	HasProvoke = 0x800000000uL,
	HasWaterMelee = 0x1000000000uL,
	HasFistDash = 0x2000000000uL,
	HasSoulVessel = 0x4000000000uL,
	HasSpores = 0x10000000000uL,
	HasGroundEffects = 0x20000000000uL,
	HasInfusion = 0x40000000000uL,
	HasShieldThrow = 0x80000000000uL,
	HasBehindTheGuard = 0x100000000000uL,
	HasReturningBombs = 0x200000000000uL,
	HasSlamMastery = 0x400000000000uL,
	HasRecoupOrConversion = 0x1000000000000uL,
	HasStaffCurse = 0x2000000000000uL,
	HasMovementAttackOps = 0x4000000000000uL,
	HasMedicOrCompanions = 0x8000000000000uL,
	HasArrowRange = 0x10000000000000uL,
	HasBossSigilHit = 0x20000000000000uL,
	HasGemBoardNodes = 0x40000000000000uL
}
internal static class BuildCapabilityGate
{
	private struct GatedHookSpec
	{
		public readonly string TypeName;

		public readonly string MethodName;

		public readonly ulong RequiredMask;

		public readonly bool ReturnsBool;

		public readonly string GateMethodName;

		public GatedHookSpec(string typeName, string methodName, ulong requiredMask, bool returnsBool, string gateMethodName)
		{
			TypeName = typeName;
			MethodName = methodName;
			RequiredMask = requiredMask;
			ReturnsBool = returnsBool;
			GateMethodName = gateMethodName;
		}
	}

	private struct StatBitGroup
	{
		public readonly BuildCapability Bit;

		public readonly string AscId;

		public readonly string[] StatNames;

		public object[] ResolvedStats;

		public StatBitGroup(BuildCapability bit, string ascId, string[] statNames)
		{
			Bit = bit;
			AscId = ascId;
			StatNames = statNames;
			ResolvedStats = null;
		}
	}

	private const float GraceLatchSeconds = 10f;

	private const ulong MaskJotunOrTwoHand = 65664uL;

	private const ulong MaskBowOrCrossbow = 3uL;

	private const ulong MaskMelee = 192uL;

	private const ulong MaskSlamOrJotun = 70368744243200uL;

	private const ulong MaskGroundOrInfusion = 6597069766656uL;

	internal static Func<bool> IsEnabled = () => true;

	internal static Action<string> LogInfo;

	internal static Action<string> LogWarning;

	private static ulong _activeCapabilities = ulong.MaxValue;

	private static ulong _rawCapabilities = ulong.MaxValue;

	private static ulong _lastLoggedMask = ulong.MaxValue;

	private static long _skippedCalls;

	private static int _gatedHookCount;

	private static bool _hasValidBaseline;

	private static bool _patchesInstalled;

	private static bool _sessionHadActivity;

	private static bool _gemBoardDirty;

	private static int _lastRecomputeCount = -1;

	private static uint _pairRan_MarksmanSetup;

	private static uint _pairRan_MarksmanRelease;

	private static uint _pairRan_StormLordWardProbe;

	private static uint _pairRan_StarterStavesInput;

	private static uint _pairRan_ShieldOpsAnchor;

	private static uint _pairRan_CrossbowGate;

	private static uint _pairRan_BehindTheGuardStart;

	private static uint _pairRan_SlamsArea;

	private static uint _pairRan_LightningChainHit;

	private static uint _pairRan_SporesSwing;

	private static uint _pairRan_GroundEffectsSpellImpact;

	private static uint _pairRan_UniqueOpsTaken;

	private static readonly float[] _bitGraceUntil = new float[64];

	private static int _activeGraceCount;

	private static float _earliestGraceExpiry = float.MaxValue;

	private static readonly List<ulong> _installedHookMasks = new List<ulong>(128);

	private static bool _reflectionReady;

	private static Func<int> _getRecomputeCount;

	private static MethodInfo _mProgressCurrent;

	private static FieldInfo _fProgressStats;

	private static MethodInfo _mStatSetMentions;

	private static MethodInfo _mClassTreesChosen;

	private static MethodInfo _mWeaponAffixesFor;

	private static FieldInfo _fWeaponProfileKind;

	private static FieldInfo _fWeaponProfileGroups;

	private static MethodInfo _mThrownWeaponsThrows;

	private static MethodInfo _mSceptresIs;

	private static MethodInfo _mLinkStavesIs;

	private static MethodInfo _mBellsMine;

	private static MethodInfo _mCompanionsIsWhistle;

	private static MethodInfo _mGemPlayerScheme;

	private static FieldInfo _fGemSchemeNodes;

	private static FieldInfo _fEnergyShieldCurrent;

	private static PropertyInfo _pEnergyShieldMax;

	private static FieldInfo[] _fHumanoidEquipSlots;

	private static Type _tStatEnum;

	private static readonly GatedHookSpec[] HookCatalog = new GatedHookSpec[117]
	{
		new GatedHookSpec("PassiveTree.JotunHeir+Begin", "Postfix", 65536uL, returnsBool: false, "GateVoid_JotunHeir"),
		new GatedHookSpec("PassiveTree.JotunHeir+CatchUp", "Postfix", 65536uL, returnsBool: false, "GateVoid_JotunHeir"),
		new GatedHookSpec("PassiveTree.JotunHeir+Impact", "Prefix", 65536uL, returnsBool: false, "GateVoid_JotunHeir"),
		new GatedHookSpec("PassiveTree.JotunHeir+Landing", "Prefix", 65536uL, returnsBool: false, "GateVoid_JotunHeir"),
		new GatedHookSpec("PassiveTree.JotunHeir+AfterSlam", "Postfix", 65536uL, returnsBool: false, "GateVoid_JotunHeir"),
		new GatedHookSpec("PassiveTree.JotunHeir+RememberWait", "Postfix", 65536uL, returnsBool: false, "GateVoid_JotunHeir"),
		new GatedHookSpec("PassiveTree.JotunHeir+StanceCue", "Postfix", 65664uL, returnsBool: false, "GateVoid_JotunOrTwoHand"),
		new GatedHookSpec("PassiveTree.Marksman+FarHit", "Prefix", 1048576uL, returnsBool: false, "GateVoid_Marksman"),
		new GatedHookSpec("PassiveTree.Marksman+OneArrow", "Postfix", 1048576uL, returnsBool: false, "GateVoid_Marksman"),
		new GatedHookSpec("PassiveTree.Marksman+Setup", "Prefix", 1048576uL, returnsBool: false, "GatePairPreVoid_MarksmanSetup"),
		new GatedHookSpec("PassiveTree.Marksman+Setup", "Postfix", 1048576uL, returnsBool: false, "GatePairPost_MarksmanSetup"),
		new GatedHookSpec("PassiveTree.Marksman+Release", "Prefix", 1048576uL, returnsBool: false, "GatePairPreVoid_MarksmanRelease"),
		new GatedHookSpec("PassiveTree.Marksman+Release", "Postfix", 1048576uL, returnsBool: false, "GatePairPost_MarksmanRelease"),
		new GatedHookSpec("PassiveTree.ElementWeaver+Start", "Postfix", 8388608uL, returnsBool: false, "GateVoid_Elementalist"),
		new GatedHookSpec("PassiveTree.ElementWeaver+Burst", "Prefix", 8388608uL, returnsBool: false, "GateVoid_Elementalist"),
		new GatedHookSpec("PassiveTree.ElementWeaver+Made", "Postfix", 8388608uL, returnsBool: false, "GateVoid_Elementalist"),
		new GatedHookSpec("PassiveTree.ElementWeaver+Lands", "Prefix", 8388608uL, returnsBool: false, "GateVoid_Elementalist"),
		new GatedHookSpec("PassiveTree.ElementWeaver+AreaCast", "Prefix", 8388608uL, returnsBool: false, "GateVoid_Elementalist"),
		new GatedHookSpec("PassiveTree.ElementWeaver+Outgoing", "Prefix", 8388608uL, returnsBool: false, "GateVoid_Elementalist"),
		new GatedHookSpec("PassiveTree.ElementWeaver+Tick", "Postfix", 8388608uL, returnsBool: false, "GateVoid_Elementalist"),
		new GatedHookSpec("PassiveTree.ForgeMaster+Outgoing", "Prefix", 524288uL, returnsBool: false, "GateVoid_ForgeMaster"),
		new GatedHookSpec("PassiveTree.ForgeMaster+OwnLast", "Prefix", 524288uL, returnsBool: false, "GateVoid_ForgeMaster"),
		new GatedHookSpec("PassiveTree.ForgeHost+Catch", "Prefix", 524288uL, returnsBool: false, "GateVoid_ForgeMaster"),
		new GatedHookSpec("PassiveTree.SiegeMaster+Tick", "Postfix", 67108864uL, returnsBool: false, "GateVoid_BallistaMaster"),
		new GatedHookSpec("PassiveTree.SiegeHead+Tick", "Postfix", 67108864uL, returnsBool: false, "GateVoid_BallistaMaster"),
		new GatedHookSpec("PassiveTree.SerpentKeeper+Outgoing", "Prefix", 2097152uL, returnsBool: false, "GateVoid_VenomKeeper"),
		new GatedHookSpec("PassiveTree.StormLord+Outgoing", "Prefix", 4194304uL, returnsBool: false, "GateVoid_StormLord"),
		new GatedHookSpec("PassiveTree.StormLord+WardProbe", "Prefix", 4194304uL, returnsBool: false, "GatePairPreVoid_StormLordWardProbe"),
		new GatedHookSpec("PassiveTree.StormLord+WardProbe", "Postfix", 4194304uL, returnsBool: false, "GatePairPost_StormLordWardProbe"),
		new GatedHookSpec("PassiveTree.StormLord+WardShown", "Postfix", 4194304uL, returnsBool: false, "GateVoid_StormLord"),
		new GatedHookSpec("PassiveTree.MeadJarl+Attack", "Prefix", 262144uL, returnsBool: true, "GateBool_MeadReaver"),
		new GatedHookSpec("PassiveTree.MeadJarl+BrewMark", "Prefix", 262144uL, returnsBool: false, "GateVoid_MeadReaver"),
		new GatedHookSpec("PassiveTree.MeadJarl+Tick", "Postfix", 262144uL, returnsBool: false, "GateVoid_MeadReaver"),
		new GatedHookSpec("PassiveTree.MeadJarlBarrel+Tick", "Postfix", 262144uL, returnsBool: false, "GateVoid_MeadReaver"),
		new GatedHookSpec("PassiveTree.ArenaSpearman+Tick", "Postfix", 16777216uL, returnsBool: false, "GateVoid_Gladiator"),
		new GatedHookSpec("PassiveTree.ArenaSpearman+StepIn", "Postfix", 16777216uL, returnsBool: false, "GateVoid_Gladiator"),
		new GatedHookSpec("PassiveTree.Berserker+Outgoing", "Prefix", 131072uL, returnsBool: false, "GateVoid_Berserker"),
		new GatedHookSpec("PassiveTree.Berserker+OutgoingLate", "Prefix", 131072uL, returnsBool: false, "GateVoid_Berserker"),
		new GatedHookSpec("PassiveTree.PhantomAsc+Outgoing", "Prefix", 33554432uL, returnsBool: false, "GateVoid_Phantom"),
		new GatedHookSpec("PassiveTree.PhantomAsc+Tick", "Postfix", 33554432uL, returnsBool: false, "GateVoid_Phantom"),
		new GatedHookSpec("PassiveTree.Phantoms+Tick", "Postfix", 33554432uL, returnsBool: false, "GateVoid_Phantom"),
		new GatedHookSpec("PassiveTree.LinkWardenSpectral+Tick", "Postfix", 134217728uL, returnsBool: false, "GateVoid_LinkWarden"),
		new GatedHookSpec("PassiveTree.ThrownWeapons+KnifeThrow", "Prefix", 16uL, returnsBool: false, "GateVoid_ThrownOrSpear"),
		new GatedHookSpec("PassiveTree.ThrownWeapons+ClassifyThrowBeforeBonuses", "Prefix", 16uL, returnsBool: false, "GateVoid_ThrownOrSpear"),
		new GatedHookSpec("PassiveTree.ThrownWeapons+OwnThrownItem", "Postfix", 16uL, returnsBool: false, "GateVoid_ThrownOrSpear"),
		new GatedHookSpec("PassiveTree.ThrownImpact+OnLanding", "Postfix", 16uL, returnsBool: false, "GateVoid_ThrownOrSpear"),
		new GatedHookSpec("PassiveTree.StarterStaves+Cast_Start", "Postfix", 4uL, returnsBool: false, "GateVoid_Staff"),
		new GatedHookSpec("PassiveTree.StarterStaves+Staff_Input", "Prefix", 4uL, returnsBool: false, "GatePairPreVoid_StarterStavesInput"),
		new GatedHookSpec("PassiveTree.StarterStaves+Staff_Input", "Postfix", 4uL, returnsBool: false, "GatePairPost_StarterStavesInput"),
		new GatedHookSpec("PassiveTree.StarterStaves+Summon_Gate", "Prefix", 4uL, returnsBool: true, "GateBool_Staff"),
		new GatedHookSpec("PassiveTree.StarterStaves+Vanilla_Gate", "Prefix", 4uL, returnsBool: true, "GateBool_Staff"),
		new GatedHookSpec("PassiveTree.LinkStaves+Gate", "Prefix", 4096uL, returnsBool: true, "GateBool_LinkStaff"),
		new GatedHookSpec("PassiveTree.ShieldOps+Sealed", "Prefix", 8uL, returnsBool: false, "GateVoid_Shield"),
		new GatedHookSpec("PassiveTree.ShieldOps+Arm", "Postfix", 8uL, returnsBool: false, "GateVoid_Shield"),
		new GatedHookSpec("PassiveTree.ShieldOps+Bash", "Prefix", 8uL, returnsBool: true, "GateBool_Shield"),
		new GatedHookSpec("PassiveTree.ShieldOps+BashHits", "Prefix", 8uL, returnsBool: true, "GateBool_Shield"),
		new GatedHookSpec("PassiveTree.ShieldOps+RamNoDamage", "Prefix", 8uL, returnsBool: false, "GateVoid_Shield"),
		new GatedHookSpec("PassiveTree.ShieldOps+RamNoApply", "Prefix", 8uL, returnsBool: true, "GateBool_Shield"),
		new GatedHookSpec("PassiveTree.ShieldOps+Anchor", "Prefix", 8uL, returnsBool: false, "GatePairPreVoid_ShieldOpsAnchor"),
		new GatedHookSpec("PassiveTree.ShieldOps+Anchor", "Postfix", 8uL, returnsBool: false, "GatePairPost_ShieldOpsAnchor"),
		new GatedHookSpec("PassiveTree.CrossbowMagazine+Gate", "Prefix", 2uL, returnsBool: true, "GatePairPreBool_CrossbowGate"),
		new GatedHookSpec("PassiveTree.CrossbowMagazine+Gate", "Postfix", 2uL, returnsBool: false, "GatePairPost_CrossbowGate"),
		new GatedHookSpec("PassiveTree.CrossbowMagazine+ReloadKey", "Postfix", 2uL, returnsBool: false, "GateVoid_Crossbow"),
		new GatedHookSpec("PassiveTree.CrossbowRecoil+Burst", "Postfix", 2uL, returnsBool: false, "GateVoid_Crossbow"),
		new GatedHookSpec("PassiveTree.AmmoRotation+PerProjectile", "Prefix", 3uL, returnsBool: false, "GateVoid_BowOrCrossbow"),
		new GatedHookSpec("PassiveTree.AmmoRotation+Model", "Prefix", 3uL, returnsBool: true, "GateBool_BowOrCrossbow"),
		new GatedHookSpec("PassiveTree.AmmoVariety+Fired", "Postfix", 3uL, returnsBool: false, "GateVoid_BowOrCrossbow"),
		new GatedHookSpec("PassiveTree.Sceptres+Swing", "Prefix", 256uL, returnsBool: false, "GateVoid_Sceptre"),
		new GatedHookSpec("PassiveTree.Sceptres+Collect", "Prefix", 256uL, returnsBool: false, "GateVoid_Sceptre"),
		new GatedHookSpec("PassiveTree.Bells+Press", "Prefix", 2048uL, returnsBool: true, "GateBool_Bell"),
		new GatedHookSpec("PassiveTree.Bells+Clock", "Postfix", 2048uL, returnsBool: false, "GateVoid_Bell"),
		new GatedHookSpec("PassiveTree.Grips+PairSwing", "Prefix", 192uL, returnsBool: false, "GateVoid_Melee"),
		new GatedHookSpec("PassiveTree.Companions+Command", "Postfix", 8192uL, returnsBool: false, "GateVoid_CompanionHorn"),
		new GatedHookSpec("PassiveTree.ShieldThrow+Throw", "Prefix", 8796093022208uL, returnsBool: true, "GateBool_HasShieldThrow"),
		new GatedHookSpec("PassiveTree.ShieldThrow+Flight", "Postfix", 8796093022208uL, returnsBool: false, "GateVoid_HasShieldThrow"),
		new GatedHookSpec("PassiveTree.BehindTheGuard+Start", "Prefix", 17592186044416uL, returnsBool: false, "GatePairPreVoid_BehindTheGuardStart"),
		new GatedHookSpec("PassiveTree.BehindTheGuard+Start", "Postfix", 17592186044416uL, returnsBool: false, "GatePairPost_BehindTheGuardStart"),
		new GatedHookSpec("PassiveTree.ReturningBombs+TrackBomb", "Postfix", 35184372088832uL, returnsBool: false, "GateVoid_HasReturningBombs"),
		new GatedHookSpec("PassiveTree.Slams+Area", "Prefix", 70368744243200uL, returnsBool: true, "GatePairPreBool_SlamsArea"),
		new GatedHookSpec("PassiveTree.Slams+Area", "Postfix", 70368744243200uL, returnsBool: false, "GatePairPost_SlamsArea"),
		new GatedHookSpec("PassiveTree.FistDash+Humanoid_StartAttack", "Postfix", 137438953472uL, returnsBool: false, "GateVoid_HasFistDash"),
		new GatedHookSpec("PassiveTree.CraftFisher+Attack_Fire", "Prefix", 1024uL, returnsBool: false, "GateVoid_FishingRod"),
		new GatedHookSpec("PassiveTree.OreDetector+Player_Update_Detector", "Postfix", 16384uL, returnsBool: false, "GateVoid_Pickaxe"),
		new GatedHookSpec("PassiveTree.EnergyShield+Character_ApplyDamage_Shield", "Prefix", 4294967296uL, returnsBool: false, "GateVoid_HasEnergyShield"),
		new GatedHookSpec("PassiveTree.ChainLightning+OnHit", "Postfix", 8589934592uL, returnsBool: false, "GateVoid_HasChainLightning"),
		new GatedHookSpec("PassiveTree.LightningChain+Hit", "Prefix", 8589934592uL, returnsBool: false, "GatePairPreVoid_LightningChainHit"),
		new GatedHookSpec("PassiveTree.LightningChain+Hit", "Postfix", 8589934592uL, returnsBool: false, "GatePairPost_LightningChainHit"),
		new GatedHookSpec("PassiveTree.Immobilize+OnHit", "Postfix", 17179869184uL, returnsBool: false, "GateVoid_HasImmobilize"),
		new GatedHookSpec("PassiveTree.Provoke+Hit", "Postfix", 34359738368uL, returnsBool: false, "GateVoid_HasProvoke"),
		new GatedHookSpec("PassiveTree.WaterCombat+OnlyMeleeAttack", "Prefix", 68719476736uL, returnsBool: true, "GateBool_HasWaterMelee"),
		new GatedHookSpec("PassiveTree.Keystones+SpiritImmunity", "Prefix", 274877906944uL, returnsBool: false, "GateVoid_HasSoulVessel"),
		new GatedHookSpec("PassiveTree.Spores+Shot", "Postfix", 1099511627776uL, returnsBool: false, "GateVoid_HasSpores"),
		new GatedHookSpec("PassiveTree.Spores+Swing", "Prefix", 1099511627776uL, returnsBool: false, "GatePairPreVoid_SporesSwing"),
		new GatedHookSpec("PassiveTree.Spores+Swing", "Postfix", 1099511627776uL, returnsBool: false, "GatePairPost_SporesSwing"),
		new GatedHookSpec("PassiveTree.Spores+Slam", "Postfix", 1099511627776uL, returnsBool: false, "GateVoid_HasSpores"),
		new GatedHookSpec("PassiveTree.SpellGround+Area", "Postfix", 2199023255552uL, returnsBool: false, "GateVoid_HasGroundEffects"),
		new GatedHookSpec("PassiveTree.GroundEffects+SpellImpact", "Prefix", 6597069766656uL, returnsBool: false, "GatePairPreVoid_GroundEffectsSpellImpact"),
		new GatedHookSpec("PassiveTree.GroundEffects+SpellImpact", "Postfix", 6597069766656uL, returnsBool: false, "GatePairPost_GroundEffectsSpellImpact"),
		new GatedHookSpec("PassiveTree.Infusion+Driver", "Postfix", 4398046511104uL, returnsBool: false, "GateVoid_HasInfusion"),
		new GatedHookSpec("PassiveTree.Infusion+Burst", "Prefix", 4398046511104uL, returnsBool: false, "GateVoid_HasInfusion"),
		new GatedHookSpec("PassiveTree.Infusion+AreaHit", "Prefix", 4398046511104uL, returnsBool: false, "GateVoid_HasInfusion"),
		new GatedHookSpec("PassiveTree.Infusion+AreaCast", "Prefix", 4398046511104uL, returnsBool: false, "GateVoid_HasInfusion"),
		new GatedHookSpec("PassiveTree.Infusion+Shot", "Postfix", 4398046511104uL, returnsBool: false, "GateVoid_HasInfusion"),
		new GatedHookSpec("PassiveTree.MovementOps+Draw", "Postfix", 1125899906842624uL, returnsBool: false, "GateVoid_HasMovementAttackOps"),
		new GatedHookSpec("PassiveTree.MovementOps+Steps", "Postfix", 1125899906842624uL, returnsBool: false, "GateVoid_HasMovementAttackOps"),
		new GatedHookSpec("PassiveTree.ResourceOps+Medic", "Postfix", 2251799813685248uL, returnsBool: false, "GateVoid_HasMedicOrCompanions"),
		new GatedHookSpec("PassiveTree.ResourceOps+MedicNoHarm", "Prefix", 2251799813685248uL, returnsBool: true, "GateBool_HasMedicOrCompanions"),
		new GatedHookSpec("PassiveTree.ResourceOps+Mark", "Prefix", 2251799813685248uL, returnsBool: false, "GateVoid_HasMedicOrCompanions"),
		new GatedHookSpec("PassiveTree.UniqueOps+Incoming", "Prefix", 281474976710656uL, returnsBool: false, "GateVoid_HasRecoupOrConversion"),
		new GatedHookSpec("PassiveTree.UniqueOps+Clock", "Postfix", 281474976710656uL, returnsBool: false, "GateVoid_HasRecoupOrConversion"),
		new GatedHookSpec("PassiveTree.UniqueOps+Taken", "Prefix", 281474976710656uL, returnsBool: false, "GatePairPreVoid_UniqueOpsTaken"),
		new GatedHookSpec("PassiveTree.UniqueOps+Taken", "Postfix", 281474976710656uL, returnsBool: false, "GatePairPost_UniqueOpsTaken"),
		new GatedHookSpec("PassiveTree.BossSigilPowers+OnHit", "Postfix", 9007199254740992uL, returnsBool: false, "GateVoid_HasBossSigilHit"),
		new GatedHookSpec("PassiveTree.Gems.StaffCurse+Start", "Prefix", 562949953421312uL, returnsBool: true, "GateBool_HasStaffCurse"),
		new GatedHookSpec("PassiveTree.Gems.GemRuntime+OnHit", "Postfix", 18014398509481984uL, returnsBool: false, "GateVoid_HasGemBoardNodes"),
		new GatedHookSpec("PassiveTree.TamingHunting+Attack_Start", "Postfix", 4503599627370496uL, returnsBool: false, "GateVoid_HasArrowRange"),
		new GatedHookSpec("PassiveTree.TamingHunting+Projectile_Setup", "Postfix", 4503599627370496uL, returnsBool: false, "GateVoid_HasArrowRange")
	};

	private static readonly StatBitGroup[] StatGroups = new StatBitGroup[33]
	{
		new StatBitGroup(BuildCapability.JotunHeir, "jotun", new string[3] { "EarthMemory", "GroundFissure", "HeavyLanding" }),
		new StatBitGroup(BuildCapability.Berserker, "berserker", new string[11]
		{
			"BloodForFear", "FirstTaste", "FrenzyUnbound", "OpenWound", "PastTheLastLine", "RedCovenant", "TearTheIron", "TemperedOnFoe", "TwinFangs", "UnbowedHead",
			"UnfinishedFight"
		}),
		new StatBitGroup(BuildCapability.MeadReaver, "mead", new string[11]
		{
			"BackCellar", "BottleInHand", "CaskAging", "Coupage", "EndlessFeast", "FeastDebt", "GiftThrow", "LastDrop", "PassingCup", "ShatterVenom",
			"TipsyCourage"
		}),
		new StatBitGroup(BuildCapability.ForgeMaster, "forge", new string[9] { "ForgeGuard", "ForgeHost", "ForgeInherit", "ForgeKinship", "ForgeMasterwork", "ForgeMend", "ForgeOrder", "ForgeQuench", "ForgeRally" }),
		new StatBitGroup(BuildCapability.Marksman, "marksman", new string[10] { "AimAloft", "AutoRelease", "FarShot", "Overdraw", "ReturnVolley", "ShotStride", "SingleShot", "SkyVolley", "SpectralArcher", "SpectreDescends" }),
		new StatBitGroup(BuildCapability.VenomKeeper, "venom", new string[5] { "GatherBitterness", "QuietFever", "ShedSkin", "TwoFangs", "VenomSqueeze" }),
		new StatBitGroup(BuildCapability.StormLord, "storm", new string[8] { "ConductiveFlesh", "RainWard", "SkyReach", "SkySplit", "StormEcho", "StormRide", "ThunderVictory", "ThunderWill" }),
		new StatBitGroup(BuildCapability.Elementalist, "weaver", new string[7] { "ElementAttunement", "FlameMemory", "PatternShift", "QuietStorm", "ResonanceCharges", "ResonanceConcord", "ResonantMantle" }),
		new StatBitGroup(BuildCapability.Gladiator, "spear", new string[7] { "EchoAnchor", "EchoRetarget", "EchoRush", "GuardStepIn", "MeasuredThrust", "ParryEcho", "ThrustRetreat" }),
		new StatBitGroup(BuildCapability.Phantom, "phantom", new string[10] { "DenseReflection", "DoubleMarked", "ManifestedForm", "MuspelheimReflection", "NiflheimReflection", "PartialPresence", "PhantomStrikeChain", "PhantomStrikeChance", "ShadeReturn", "StepBeyond" }),
		new StatBitGroup(BuildCapability.BallistaMaster, "siege", new string[7] { "FieldForge", "FrameRunes", "IronFooting", "RatchetBlow", "SiegeOrder", "SiegeSalvo", "TautCharge" }),
		new StatBitGroup(BuildCapability.LinkWarden, "warden", new string[11]
		{
			"LinkAimAreaPct", "LinkCeiling", "LinkDamageTransferPct", "LinkGraceSeconds", "LinkNearby", "LinkPersistence", "LinkRangePct", "LinkSpectralWeapon", "LinkTransferPct", "LinkUnbroken",
			"MasteryLink2"
		}),
		new StatBitGroup(BuildCapability.HasEnergyShield, null, new string[6] { "HealthToShieldPct", "RegenToShield", "ShieldDelayPct", "ShieldFlat", "ShieldPct", "ShieldRegenPct" }),
		new StatBitGroup(BuildCapability.HasChainLightning, null, new string[4] { "EikthyrChainChance", "ProjectileChainChance", "LightningChainRadiusFlat", "LightningWetChainChance" }),
		new StatBitGroup(BuildCapability.HasImmobilize, null, new string[2] { "ImmobilizeChance", "ImmobilizeDeathBurst" }),
		new StatBitGroup(BuildCapability.HasProvoke, null, new string[1] { "ProvokeOnHit" }),
		new StatBitGroup(BuildCapability.HasWaterMelee, null, new string[1] { "WaterMelee" }),
		new StatBitGroup(BuildCapability.HasFistDash, null, new string[1] { "FistDash" }),
		new StatBitGroup(BuildCapability.HasSoulVessel, null, new string[1] { "SoulVessel" }),
		new StatBitGroup(BuildCapability.HasSpores, null, new string[1] { "SporeOnImpact" }),
		new StatBitGroup(BuildCapability.HasGroundEffects, null, new string[1] { "CreateGround" }),
		new StatBitGroup(BuildCapability.HasInfusion, null, new string[1] { "AbsorbGround" }),
		new StatBitGroup(BuildCapability.HasShieldThrow, null, new string[1] { "ShieldThrow" }),
		new StatBitGroup(BuildCapability.HasBehindTheGuard, null, new string[1] { "GuardAttackTeleportBehind" }),
		new StatBitGroup(BuildCapability.HasReturningBombs, null, new string[1] { "BombReturnBlast" }),
		new StatBitGroup(BuildCapability.HasSlamMastery, null, new string[3] { "MasterySlam2", "MasterySlam3", "MasteryAftershock1" }),
		new StatBitGroup(BuildCapability.HasRecoupOrConversion, null, new string[3] { "Conversion", "Recoup", "RestoreOverTime" }),
		new StatBitGroup(BuildCapability.HasStaffCurse, null, new string[1] { "Hex" }),
		new StatBitGroup(BuildCapability.HasMovementAttackOps, null, new string[2] { "DrawStoredAim", "MasteryOnehand2" }),
		new StatBitGroup(BuildCapability.HasMedicOrCompanions, null, new string[2] { "MasteryHealing2", "MasteryCompanions1" }),
		new StatBitGroup(BuildCapability.HasArrowRange, null, new string[1] { "ArrowRangePct" }),
		new StatBitGroup(BuildCapability.HasBossSigilHit, null, new string[2] { "MaxHealthHitChance", "MaxHealthHitShare" }),
		new StatBitGroup(BuildCapability.Bell, null, new string[2] { "HitRelay", "AlternateOverride" })
	};

	internal static void ApplyDynamicPatches(Harmony harmony)
	{
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ab: Expected O, but got Unknown
		if (harmony == null || _patchesInstalled)
		{
			return;
		}
		try
		{
			if (!InitializeReflection())
			{
				return;
			}
			PatchTrigger(harmony, AccessTools.Method(typeof(Player), "OnSpawned", new Type[1] { typeof(bool) }, (Type[])null), "PlayerOnSpawnedPostfix");
			PatchTrigger(harmony, AccessTools.Method(typeof(Player), "Update", Type.EmptyTypes, (Type[])null), "PlayerUpdatePostfix");
			PatchTrigger(harmony, AccessTools.Method(typeof(Humanoid), "EquipItem", new Type[2]
			{
				typeof(ItemData),
				typeof(bool)
			}, (Type[])null), "HumanoidEquipItemPostfix");
			PatchTrigger(harmony, AccessTools.Method(typeof(Humanoid), "UnequipItem", new Type[2]
			{
				typeof(ItemData),
				typeof(bool)
			}, (Type[])null), "HumanoidUnequipItemPostfix");
			Type type = AccessTools.TypeByName("PassiveTree.Progress");
			if (type != null)
			{
				MethodInfo target = AccessTools.Method(type, "RecomputeStats", Type.EmptyTypes, (Type[])null);
				PatchTrigger(harmony, target, "ProgressRecomputeStatsPostfix");
			}
			Type type2 = AccessTools.TypeByName("PassiveTree.ClassTrees");
			if (type2 != null)
			{
				MethodInfo target2 = AccessTools.Method(type2, "Choose", new Type[2]
				{
					typeof(Player),
					typeof(string)
				}, (Type[])null);
				PatchTrigger(harmony, target2, "ClassTreesChoosePostfix");
			}
			Type type3 = AccessTools.TypeByName("PassiveTree.Gems.GemPlayer");
			if (type3 != null)
			{
				MethodInfo target3 = AccessTools.Method(type3, "Invalidate", Type.EmptyTypes, (Type[])null);
				PatchTrigger(harmony, target3, "GemPlayerInvalidatePostfix");
			}
			int num = CountLivePovHotPathHooks();
			_installedHookMasks.Clear();
			int num2 = 0;
			for (int i = 0; i < HookCatalog.Length; i++)
			{
				GatedHookSpec gatedHookSpec = HookCatalog[i];
				Type type4 = AccessTools.TypeByName(gatedHookSpec.TypeName);
				if (type4 == null)
				{
					continue;
				}
				MethodInfo method = type4.GetMethod(gatedHookSpec.MethodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (method == null || method.ContainsGenericParameters)
				{
					continue;
				}
				bool flag = method.ReturnType == typeof(bool);
				bool flag2 = method.ReturnType == typeof(void);
				if ((gatedHookSpec.ReturnsBool && !flag) || (!gatedHookSpec.ReturnsBool && !flag2))
				{
					continue;
				}
				MethodInfo method2 = typeof(BuildCapabilityGate).GetMethod(gatedHookSpec.GateMethodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (!(method2 == null))
				{
					try
					{
						HarmonyMethod val = new HarmonyMethod(method2);
						val.priority = 800;
						harmony.Patch((MethodBase)method, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						_installedHookMasks.Add(gatedHookSpec.RequiredMask);
						num2++;
					}
					catch
					{
					}
				}
			}
			_gatedHookCount = num2;
			_patchesInstalled = true;
			if (LogInfo != null)
			{
				int num3 = ((num > 0) ? num : num2);
				LogInfo($"[PovBuildGate] Audited {num3} PoV hot-path hooks -> gated {num2} verified local-player build-scoped hooks (0 AVX/automation overlap; fail-open default).");
			}
		}
		catch (Exception ex)
		{
			_activeCapabilities = ulong.MaxValue;
			if (LogWarning != null)
			{
				LogWarning($"[PovBuildGate] Setup notice (fail-open active): {ex.Message}");
			}
		}
	}

	private static void PatchTrigger(Harmony harmony, MethodInfo target, string postfixName)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		if (harmony == null || target == null)
		{
			return;
		}
		MethodInfo method = typeof(BuildCapabilityGate).GetMethod(postfixName, BindingFlags.Static | BindingFlags.NonPublic);
		if (method == null)
		{
			return;
		}
		try
		{
			HarmonyMethod val = new HarmonyMethod(method);
			val.priority = 0;
			harmony.Patch((MethodBase)target, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch
		{
		}
	}

	private static int CountLivePovHotPathHooks()
	{
		int num = 0;
		try
		{
			MethodBase[] array = new MethodBase[13]
			{
				AccessTools.Method(typeof(Player), "Update", Type.EmptyTypes, (Type[])null),
				AccessTools.Method(typeof(Attack), "FireProjectileBurst", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Attack), "Start", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Attack), "DoMeleeAttack", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Attack), "DoAreaAttack", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Humanoid), "StartAttack", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Projectile), "Setup", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Projectile), "OnHit", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Projectile), "FixedUpdate", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Character), "RPC_Damage", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Character), "ApplyDamage", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Character), "Damage", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(SEMan), "ModifyAttack", (Type[])null, (Type[])null)
			};
			for (int i = 0; i < array.Length; i++)
			{
				if (!(array[i] == null))
				{
					Patches patchInfo = Harmony.GetPatchInfo(array[i]);
					if (patchInfo != null)
					{
						num += CountPovInList(patchInfo.Prefixes);
						num += CountPovInList(patchInfo.Postfixes);
						num += CountPovInList(patchInfo.Transpilers);
						num += CountPovInList(patchInfo.Finalizers);
					}
				}
			}
		}
		catch
		{
		}
		return num;
	}

	private static int CountPovInList(IList<Patch> patches)
	{
		if (patches == null)
		{
			return 0;
		}
		int num = 0;
		for (int i = 0; i < patches.Count; i++)
		{
			Patch val = patches[i];
			if (val != null && val.PatchMethod != null && val.PatchMethod.DeclaringType != null)
			{
				string text = val.PatchMethod.DeclaringType.Namespace;
				if (!string.IsNullOrEmpty(text) && text.StartsWith("PassiveTree", StringComparison.Ordinal))
				{
					num++;
				}
			}
		}
		return num;
	}

	private static Func<int> CreateStaticIntGetter(FieldInfo field)
	{
		if (field == null || !field.IsStatic || field.FieldType != typeof(int))
		{
			return null;
		}
		try
		{
			DynamicMethod dynamicMethod = new DynamicMethod("PBCG_StaticGet_" + field.DeclaringType.Name + "_" + field.Name, typeof(int), Type.EmptyTypes, field.DeclaringType, skipVisibility: true);
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldsfld, field);
			iLGenerator.Emit(OpCodes.Ret);
			return (Func<int>)dynamicMethod.CreateDelegate(typeof(Func<int>));
		}
		catch
		{
			return null;
		}
	}

	private static bool InitializeReflection()
	{
		if (_reflectionReady)
		{
			return _mProgressCurrent != null;
		}
		_reflectionReady = true;
		Type type = AccessTools.TypeByName("PassiveTree.Progress");
		if (type == null)
		{
			return false;
		}
		_mProgressCurrent = type.GetMethod("get_Current", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
		_fProgressStats = type.GetField("Stats", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		_getRecomputeCount = CreateStaticIntGetter(type.GetField("RecomputeCount", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
		_tStatEnum = AccessTools.TypeByName("PassiveTree.Stat");
		Type type2 = AccessTools.TypeByName("PassiveTree.StatSet");
		if (type2 != null && _tStatEnum != null)
		{
			_mStatSetMentions = type2.GetMethod("Mentions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { _tStatEnum }, null);
		}
		if (_mProgressCurrent == null || _fProgressStats == null || _mStatSetMentions == null || _tStatEnum == null)
		{
			return false;
		}
		for (int i = 0; i < StatGroups.Length; i++)
		{
			string[] statNames = StatGroups[i].StatNames;
			List<object> list = new List<object>(statNames.Length);
			for (int j = 0; j < statNames.Length; j++)
			{
				try
				{
					if (Enum.IsDefined(_tStatEnum, statNames[j]))
					{
						list.Add(Enum.Parse(_tStatEnum, statNames[j], ignoreCase: false));
					}
				}
				catch
				{
				}
			}
			StatGroups[i].ResolvedStats = list.ToArray();
		}
		Type type3 = AccessTools.TypeByName("PassiveTree.ClassTrees");
		if (type3 != null)
		{
			_mClassTreesChosen = type3.GetMethod("Chosen", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Player) }, null);
		}
		Type type4 = AccessTools.TypeByName("PassiveTree.WeaponAffixes");
		if (type4 != null)
		{
			_mWeaponAffixesFor = type4.GetMethod("For", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[4]
			{
				typeof(ItemData),
				typeof(bool),
				typeof(bool),
				typeof(Humanoid)
			}, null);
		}
		Type type5 = AccessTools.TypeByName("PassiveTree.WeaponProfile");
		if (type5 != null)
		{
			_fWeaponProfileKind = type5.GetField("Kind", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_fWeaponProfileGroups = type5.GetField("Groups", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		}
		Type type6 = AccessTools.TypeByName("PassiveTree.ThrownWeapons");
		if (type6 != null)
		{
			_mThrownWeaponsThrows = type6.GetMethod("Throws", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(ItemData) }, null);
		}
		Type type7 = AccessTools.TypeByName("PassiveTree.Sceptres");
		if (type7 != null)
		{
			_mSceptresIs = type7.GetMethod("Is", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(ItemData) }, null);
		}
		Type type8 = AccessTools.TypeByName("PassiveTree.LinkStaves");
		if (type8 != null)
		{
			_mLinkStavesIs = type8.GetMethod("Is", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(ItemData) }, null);
		}
		Type type9 = AccessTools.TypeByName("PassiveTree.Bells");
		if (type9 != null)
		{
			_mBellsMine = type9.GetMethod("Mine_", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2]
			{
				typeof(Player),
				typeof(ItemData)
			}, null);
		}
		Type type10 = AccessTools.TypeByName("PassiveTree.Companions");
		if (type10 != null)
		{
			_mCompanionsIsWhistle = type10.GetMethod("IsWhistle", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(ItemData) }, null);
		}
		Type type11 = AccessTools.TypeByName("PassiveTree.Gems.GemPlayer");
		if (type11 != null)
		{
			_mGemPlayerScheme = type11.GetMethod("get_Scheme", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
		}
		Type type12 = AccessTools.TypeByName("PassiveTree.Gems.Scheme");
		if (type12 != null)
		{
			_fGemSchemeNodes = type12.GetField("Nodes", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		}
		Type type13 = AccessTools.TypeByName("PassiveTree.EnergyShield");
		if (type13 != null)
		{
			_fEnergyShieldCurrent = type13.GetField("Current", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			_pEnergyShieldMax = type13.GetProperty("Max", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		}
		string[] array = new string[4] { "m_rightItem", "m_leftItem", "m_hiddenRightItem", "m_hiddenLeftItem" };
		List<FieldInfo> list2 = new List<FieldInfo>(array.Length);
		for (int k = 0; k < array.Length; k++)
		{
			FieldInfo field = typeof(Humanoid).GetField(array[k], BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				list2.Add(field);
			}
		}
		_fHumanoidEquipSlots = list2.ToArray();
		return true;
	}

	internal static void OnConfigChanged()
	{
		if (IsEnabled != null && !IsEnabled())
		{
			FailOpen();
		}
		else
		{
			RefreshCapabilities(allowGraceLatch: false);
		}
	}

	internal static void OnWorldUnload()
	{
		if (_sessionHadActivity && _gatedHookCount > 0 && LogInfo != null)
		{
			LogInfo($"[PovBuildGate] Session summary: skipped {_skippedCalls} dead PoV hook invocations across {_gatedHookCount} gated hooks.");
		}
		_activeCapabilities = ulong.MaxValue;
		_rawCapabilities = ulong.MaxValue;
		_lastLoggedMask = ulong.MaxValue;
		_skippedCalls = 0L;
		_hasValidBaseline = false;
		_sessionHadActivity = false;
		_gemBoardDirty = false;
		_lastRecomputeCount = -1;
		_activeGraceCount = 0;
		_earliestGraceExpiry = float.MaxValue;
		Array.Clear(_bitGraceUntil, 0, _bitGraceUntil.Length);
		ResetPairStacks();
	}

	private static void ResetPairStacks()
	{
		_pairRan_MarksmanSetup = 0u;
		_pairRan_MarksmanRelease = 0u;
		_pairRan_StormLordWardProbe = 0u;
		_pairRan_StarterStavesInput = 0u;
		_pairRan_ShieldOpsAnchor = 0u;
		_pairRan_CrossbowGate = 0u;
		_pairRan_BehindTheGuardStart = 0u;
		_pairRan_SlamsArea = 0u;
		_pairRan_LightningChainHit = 0u;
		_pairRan_SporesSwing = 0u;
		_pairRan_GroundEffectsSpellImpact = 0u;
		_pairRan_UniqueOpsTaken = 0u;
	}

	private static void FailOpen()
	{
		_activeCapabilities = ulong.MaxValue;
		_rawCapabilities = ulong.MaxValue;
		_hasValidBaseline = false;
		_activeGraceCount = 0;
		_earliestGraceExpiry = float.MaxValue;
		Array.Clear(_bitGraceUntil, 0, _bitGraceUntil.Length);
	}

	private static void PlayerOnSpawnedPostfix(Player __instance)
	{
		if (!((Object)(object)__instance == (Object)null) && object.ReferenceEquals(__instance, Player.m_localPlayer))
		{
			_sessionHadActivity = true;
			RefreshCapabilities(allowGraceLatch: false);
		}
	}

	private static void HumanoidEquipItemPostfix(Humanoid __instance, bool __result)
	{
		if (__result && !((Object)(object)__instance == (Object)null) && object.ReferenceEquals(__instance, Player.m_localPlayer))
		{
			RefreshCapabilities(allowGraceLatch: true);
		}
	}

	private static void HumanoidUnequipItemPostfix(Humanoid __instance)
	{
		if (!((Object)(object)__instance == (Object)null) && object.ReferenceEquals(__instance, Player.m_localPlayer))
		{
			RefreshCapabilities(allowGraceLatch: true);
		}
	}

	private static void ProgressRecomputeStatsPostfix()
	{
		if (!((Object)(object)Player.m_localPlayer == (Object)null))
		{
			RefreshCapabilities(allowGraceLatch: true);
		}
	}

	private static void ClassTreesChoosePostfix(Player __0, bool __result)
	{
		if (__result && !((Object)(object)__0 == (Object)null) && object.ReferenceEquals(__0, Player.m_localPlayer))
		{
			RefreshCapabilities(allowGraceLatch: true);
		}
	}

	private static void GemPlayerInvalidatePostfix()
	{
		if (!((Object)(object)Player.m_localPlayer == (Object)null))
		{
			_gemBoardDirty = true;
		}
	}

	private static void PlayerUpdatePostfix(Player __instance)
	{
		if (!object.ReferenceEquals(__instance, Player.m_localPlayer))
		{
			return;
		}
		if ((_pairRan_MarksmanSetup | _pairRan_MarksmanRelease | _pairRan_StormLordWardProbe | _pairRan_StarterStavesInput | _pairRan_ShieldOpsAnchor | _pairRan_CrossbowGate | _pairRan_BehindTheGuardStart | _pairRan_SlamsArea | _pairRan_LightningChainHit | _pairRan_SporesSwing | _pai