Decompiled source of GapCloser v1.3.7

GapCloser.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GapCloser.Fixes;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("GapCloser")]
[assembly: AssemblyDescription("Fixes for the game and for other mods, each only where the code it relies on is the checked code, and fast teleports")]
[assembly: AssemblyFileVersion("1.3.7.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.3.7.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace GapCloser
{
	internal static class CodeCheck
	{
		internal static string Of(MethodBase method)
		{
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			if (method == null)
			{
				return null;
			}
			List<CodeInstruction> originalInstructions;
			try
			{
				originalInstructions = PatchProcessor.GetOriginalInstructions(method, (ILGenerator)null);
			}
			catch
			{
				return null;
			}
			Dictionary<Label, int> dictionary = new Dictionary<Label, int>();
			for (int i = 0; i < originalInstructions.Count; i++)
			{
				foreach (Label label in originalInstructions[i].labels)
				{
					dictionary[label] = i;
				}
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (CodeInstruction item in originalInstructions)
			{
				stringBuilder.Append(item.opcode.Name).Append(' ').Append(Operand(item.operand, dictionary));
				foreach (ExceptionBlock block in item.blocks)
				{
					stringBuilder.Append(" [").Append(block.blockType).Append(']');
				}
				stringBuilder.Append('\n');
			}
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString())), 0, 4).Replace("-", "");
		}

		private static string Operand(object operand, Dictionary<Label, int> at)
		{
			if (operand != null)
			{
				if (!(operand is Label label))
				{
					if (!(operand is Label[] array))
					{
						if (!(operand is LocalBuilder localBuilder))
						{
							if (!(operand is MethodBase methodBase))
							{
								if (!(operand is FieldInfo fieldInfo))
								{
									if (!(operand is Type type))
									{
										if (operand is IConvertible convertible)
										{
											return Convert.ToString(convertible, CultureInfo.InvariantCulture);
										}
										return operand.ToString();
									}
									return type.ToString();
								}
								return fieldInfo.DeclaringType?.ToString() + "::" + fieldInfo.Name;
							}
							ParameterInfo[] parameters = methodBase.GetParameters();
							string[] array2 = new string[parameters.Length];
							for (int i = 0; i < parameters.Length; i++)
							{
								array2[i] = parameters[i].ParameterType.ToString();
							}
							return methodBase.DeclaringType?.ToString() + "::" + methodBase.Name + "(" + string.Join(",", array2) + ")";
						}
						return "loc" + localBuilder.LocalIndex + ":" + localBuilder.LocalType;
					}
					string[] array3 = new string[array.Length];
					for (int j = 0; j < array.Length; j++)
					{
						array3[j] = Target(array[j], at);
					}
					return string.Join(",", array3);
				}
				return Target(label, at);
			}
			return "";
		}

		private static string Target(Label label, Dictionary<Label, int> at)
		{
			if (!at.TryGetValue(label, out var value))
			{
				return "@?";
			}
			return "@" + value;
		}
	}
	internal static class ConflictScan
	{
		private const string Name = "ConflictScan";

		private static int _stage;

		private static readonly HashSet<string> Seen = new HashSet<string>();

		private static readonly (string mod, string method, string kind, string text)[] Known = new(string, string, string, string)[6]
		{
			("ValheimCommunityPatch", "ZNetScene.CreateObjectsSorted", "prefix", "its spawn queue replaces this loop, ObjectLoadBudget's own line says whether its budget is inside the queue"),
			("ValheimCommunityPatch", "ZNetScene.CreateObjectsSorted", "transpiler", "it swaps the missing prefab log line, another place than ObjectLoadBudget's, no conflict"),
			("ValheimCommunityPatch", "ZNetScene.CreateDistantObjects", "transpiler", "it swaps the missing prefab log line, another place than ObjectLoadBudget's, no conflict"),
			("ValheimOptimized", "ZNetScene.CreateObjectsSorted", "prefix", "it runs its own budgeted loop in game, so ObjectLoadBudget only works on the loading screen there (no error)"),
			("ValheimOptimized", "ZNetScene.CreateDistantObjects", "prefix", "it runs its own budgeted loop when over its budget, ObjectLoadBudget only works where it lets the game's loop run (no error)"),
			("BalrondCoreOptimizer", "LightFlicker.CustomUpdate", "prefix", "both only skip flicker work of distant or unseen lights, no conflict")
		};

		internal static void Frame()
		{
			if (_stage == 2)
			{
				return;
			}
			try
			{
				if (_stage == 0 && (Object)(object)FejdStartup.instance != (Object)null)
				{
					_stage = 1;
					Run("at the main menu");
				}
				else if (_stage == 1 && (Object)(object)Player.m_localPlayer != (Object)null)
				{
					_stage = 2;
					Run("after spawning");
				}
			}
			catch (Exception ex)
			{
				_stage = 2;
				Plugin.Log.LogWarning((object)("ConflictScan: could not read the patches (" + ex.GetType().Name + ": " + ex.Message + "), nothing changed"));
			}
		}

		private static void Run(string when)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			foreach (MethodBase item in Harmony.GetAllPatchedMethods().ToList())
			{
				Patches patchInfo = Harmony.GetPatchInfo(item);
				if (patchInfo == null)
				{
					continue;
				}
				List<Patch> list = (from p in All(patchInfo)
					where p.owner == "onononoki.GapCloser"
					select p).ToList();
				if (list.Count == 0)
				{
					continue;
				}
				num++;
				List<Patch> list2 = (from p in All(patchInfo)
					where p.owner != "onononoki.GapCloser"
					select p).ToList();
				if (list2.Count == 0)
				{
					continue;
				}
				num2++;
				string target = item.DeclaringType?.Name + "." + item.Name;
				string text = string.Join(", ", list.Select((Patch p) => p.PatchMethod.DeclaringType?.Name).Distinct());
				bool flag = patchInfo.Transpilers.Any((Patch p) => p.owner == "onononoki.GapCloser");
				foreach (Patch item2 in list2)
				{
					string text2 = ModName(item2);
					string assembly = item2.PatchMethod.DeclaringType?.Assembly.GetName().Name ?? "";
					string kind = (patchInfo.Prefixes.Contains(item2) ? "prefix" : (patchInfo.Transpilers.Contains(item2) ? "transpiler" : null));
					if (kind != null && Seen.Add(target + "|" + item2.owner + "|" + item2.PatchMethod.Name + "|" + kind))
					{
						(string, string, string, string) tuple = Known.FirstOrDefault(((string mod, string method, string kind, string text) k) => assembly.IndexOf(k.mod, StringComparison.OrdinalIgnoreCase) >= 0 && k.method == target && k.kind == kind);
						if (tuple.Item4 != null)
						{
							Plugin.Log.LogInfo((object)("ConflictScan: " + text2 + " " + kind + " on " + target + " (" + text + "): " + tuple.Item4));
							num4++;
						}
						else if (flag && kind == "prefix" && item2.PatchMethod?.ReturnType == typeof(bool))
						{
							Plugin.Log.LogWarning((object)("ConflictScan: " + text2 + " has a prefix on " + target + " that can skip it, " + text + " edits inside it and does not run while it is skipped"));
							num3++;
							num4++;
						}
						else if (flag && kind == "transpiler")
						{
							Plugin.Log.LogInfo((object)("ConflictScan: " + text2 + " also edits " + target + ", " + text + " edits it too (its own line says whether it found its places)"));
							num3++;
							num4++;
						}
					}
				}
			}
			Plugin.Log.LogInfo((object)(string.Format("{0} ({1}): GapCloser patches {2} methods, other mods patch {3} of them too, ", "ConflictScan", when, num, num2) + string.Format("{0} can skip or also edit code GapCloser edits{1}", num3, (num4 > 0) ? ", see the lines above" : "")));
		}

		private static IEnumerable<Patch> All(Patches info)
		{
			return info.Prefixes.Concat(info.Postfixes).Concat(info.Transpilers).Concat(info.Finalizers);
		}

		private static string ModName(Patch p)
		{
			if (Chainloader.PluginInfos.TryGetValue(p.owner, out var value))
			{
				return value.Metadata.Name;
			}
			return p.PatchMethod.DeclaringType?.Assembly.GetName().Name ?? p.owner;
		}
	}
	[BepInPlugin("onononoki.GapCloser", "GapCloser", "1.3.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[DefaultExecutionOrder(30000)]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGuid = "onononoki.GapCloser";

		public const string ModName = "GapCloser";

		public const string ModVersion = "1.3.7";

		private static readonly string[] CheckedGameVersions = new string[2] { "1.0.20", "1.0.21" };

		internal static ManualLogSource Log;

		private static ConfigEntry<bool> _force;

		private Harmony _harmony;

		private static readonly Dictionary<string, string> OldSections = new Dictionary<string, string>
		{
			{ "General", "1 - General" },
			{ "Options", "2 - Options" },
			{ "Fixes", "3 - Fixes" },
			{ "RockSupport", "4 - Rock Support" },
			{ "Debug", "9 - Debug" }
		};

		private static readonly Dictionary<string, string> ToDebug = new Dictionary<string, string>
		{
			{ "Fixes.OcclusionCullingKey", "OcclusionCullingKey" },
			{ "Fixes.OcclusionCullingBenchmarkKey", "OcclusionCullingBenchmarkKey" },
			{ "Fixes.OcclusionCullingLogLines", "OcclusionCullingLogLines" },
			{ "Fixes.BenchmarkKey", "BenchmarkKey" },
			{ "Fixes.ChestReloadSkipSelfCheck", "ChestReloadSkipSelfCheck" },
			{ "Fixes.AzuCraftyBoxesBuildCountsSelfCheck", "AzuCraftyBoxesBuildCountsSelfCheck" },
			{ "RockSupport.SelfCheck", "RockSupportSelfCheck" },
			{ "RockSupport.LogChecks", "RockSupportLogChecks" }
		};

		private static readonly HashSet<string> Dropped = new HashSet<string> { "Fixes.SmoothPacing", "Fixes.SmoothPacingKey", "Fixes.OpenSkySmoke", "Fixes.ShadowBenchmarkKey" };

		internal static bool ForceOnUntested => _force.Value;

		private void Awake()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			MoveOldSettings();
			_force = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "ForceOnUntestedVersions", false, "Turns the fixes on also where the game's or another mod's code they rely on changed. At your own risk, the log names each one.");
			_harmony = new Harmony("onononoki.GapCloser");
			ApplyFix("AzuCraftyBoxesForgeRecipes", AzuCraftyBoxesForgeRecipes.Apply);
			ApplyFix("ValheimPlusProcreation", ValheimPlusProcreation.Apply);
			ApplyFix("TriggerWarningSpam", TriggerWarningSpam.Apply);
			ApplyFix("RecipeChecks", RecipeChecks.Apply);
			ApplyFix("WishboneForgeWarning", WishboneForgeWarning.Apply);
			ApplyFix("RecipeCleanup", RecipeCleanup.Apply);
			ApplyFix("ErrorGuards", ErrorGuards.Apply);
			ApplyFix("AzuCraftyBoxesCraftingList", AzuCraftyBoxesCraftingList.Apply);
			ApplyFix("PieceParticleCulling", PieceParticleCulling.Apply);
			ApplyFix("ValheimPlusChestCounts", ValheimPlusChestCounts.Apply);
			ApplyFix("ValheimPlusSpawnArea", ValheimPlusSpawnArea.Apply);
			ApplyFix("ExtraSlotsFindSlot", ExtraSlotsFindSlot.Apply);
			ApplyFix("ExtraSlotsCountItems", ExtraSlotsCountItems.Apply);
			ApplyFix("AzuCraftyBoxesChestNames", AzuCraftyBoxesChestNames.Apply);
			ApplyFix("SunShadows", SunShadows.Apply);
			ApplyFix("OtherMerger", OtherMerger.Apply);
			ApplyFix("OcclusionCulling", OcclusionCulling.Apply);
			ApplyFix("RockSupport", RockSupport.Apply);
			ApplyFix("ObjectLoadBudget", ObjectLoadBudget.Apply);
			ApplyFix("HiddenLights", HiddenLights.Apply);
			ApplyFix("PieceBatching", PieceBatching.Apply);
			ApplyFix("ChestReloadSkip", ChestReloadSkip.Apply);
			ApplyFix("SmokeOption", SmokeOption.Apply);
			ApplyFix("LightFlickerOffscreen", LightFlickerOffscreen.Apply);
			ApplyFix("AzuCraftyBoxesBuildCounts", AzuCraftyBoxesBuildCounts.Apply);
			ApplyFix("BenchmarkAll", BenchmarkAll.Apply);
		}

		private void Start()
		{
			ApplyFix("FastTeleport", FastTeleport.Apply);
		}

		private void MoveOldSettings()
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Expected O, but got Unknown
			if (!(AccessTools.Property(typeof(ConfigFile), "OrphanedEntries")?.GetValue(((BaseUnityPlugin)this).Config, null) is Dictionary<ConfigDefinition, string> dictionary))
			{
				Log.LogWarning((object)"the settings of an older version could not be read, they are back at their defaults");
				return;
			}
			int num = 0;
			int num2 = 0;
			foreach (ConfigDefinition item in dictionary.Keys.ToList())
			{
				if (!OldSections.TryGetValue(item.Section, out var value))
				{
					continue;
				}
				string text = item.Section + "." + item.Key;
				string value2 = dictionary[item];
				dictionary.Remove(item);
				if (Dropped.Contains(text))
				{
					num2++;
					continue;
				}
				string value3;
				ConfigDefinition key = (ToDebug.TryGetValue(text, out value3) ? new ConfigDefinition("9 - Debug", value3) : new ConfigDefinition(value, item.Key));
				if (!dictionary.ContainsKey(key))
				{
					dictionary[key] = value2;
				}
				num++;
			}
			if (num + num2 > 0)
			{
				Log.LogInfo((object)$"settings moved to the new sections: {num} with their values, {num2} of removed test tools dropped");
			}
		}

		private void ApplyFix(string name, Action<Harmony, ConfigFile> apply)
		{
			try
			{
				apply(_harmony, ((BaseUnityPlugin)this).Config);
			}
			catch (Exception ex)
			{
				Log.LogError((object)(name + ": could not be applied (" + ex.GetType().Name + ": " + ex.Message + "), the other fixes still work"));
			}
		}

		private void LateUpdate()
		{
			RecipeChecks.Flush();
			FastTeleport.Frame();
			Benchmark.Frame();
			PieceBatching.Frame();
			OcclusionCulling.Frame();
			HiddenLights.Frame();
			RockSupport.Frame();
			ChestReloadSkip.Frame();
			ConflictScan.Frame();
			BenchmarkAll.Frame();
		}

		internal static bool TargetMatches(string fix, string guid, string[] versions)
		{
			if (!Chainloader.PluginInfos.TryGetValue(guid, out var value))
			{
				Log.LogInfo((object)(fix + ": " + guid + " is not installed, not needed"));
				return false;
			}
			string text = value.Metadata.Version.ToString();
			if (Array.IndexOf(versions, text) < 0)
			{
				Log.LogInfo((object)(fix + ": " + guid + " " + text + " is not a checked version (" + string.Join(", ", versions) + "), the code the fix relies on decides"));
			}
			return true;
		}

		internal static bool CodeMatches(string fix, MethodBase method, params string[] known)
		{
			string text = CodeCheck.Of(method);
			if (text != null && Array.IndexOf(known, text) >= 0)
			{
				return true;
			}
			string text2 = ((method == null) ? "a method" : $"{method.DeclaringType}.{method.Name}");
			if (_force.Value)
			{
				Log.LogWarning((object)(fix + ": " + text2 + " is not the checked code (" + (text ?? "unreadable") + ", checked " + string.Join(", ", known) + "), forced on by ForceOnUntestedVersions"));
				return true;
			}
			Log.LogWarning((object)(fix + ": " + text2 + " is not the checked code (" + (text ?? "unreadable") + ", checked " + string.Join(", ", known) + "), the fix stays off (ForceOnUntestedVersions turns it on)"));
			return false;
		}

		internal static bool GameMatches(string fix)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			string text = ((object)Version.CurrentVersion/*cast due to .constrained prefix*/).ToString();
			if (Array.IndexOf(CheckedGameVersions, text) < 0)
			{
				Log.LogInfo((object)(fix + ": Valheim " + text + " is not a checked version (" + string.Join(", ", CheckedGameVersions) + "), the game code the fix relies on decides"));
			}
			return true;
		}
	}
	internal static class Sections
	{
		internal const string General = "1 - General";

		internal const string Options = "2 - Options";

		internal const string Fixes = "3 - Fixes";

		internal const string RockSupport = "4 - Rock Support";

		internal const string Debug = "9 - Debug";
	}
}
namespace GapCloser.Fixes
{
	internal static class AzuCraftyBoxesBuildCounts
	{
		private sealed class SameItem : IEqualityComparer<ItemDrop>
		{
			public bool Equals(ItemDrop a, ItemDrop b)
			{
				return a == b;
			}

			public int GetHashCode(ItemDrop d)
			{
				return RuntimeHelpers.GetHashCode(d);
			}
		}

		private const string Name = "AzuCraftyBoxesBuildCounts";

		private const string PatchType = "AzuCraftyBoxes.Patches.HaveRequirementsPatch2";

		private static readonly string[] CheckedCode = new string[1] { "40B333A6" };

		private const float StatSeconds = 60f;

		private const int SelfCheckEvery = 20;

		private const int DifferencesLogged = 5;

		private static readonly string[] CheckedVersions = new string[1] { "1.8.19" };

		private static Func<bool> _shouldPrevent;

		private static Func<bool> _skip;

		private static Func<ItemDrop, bool> _integrity;

		private static Func<Player, float, IList> _nearby;

		private static ConfigEntry<float> _range;

		private static Func<object, string> _chestPrefab;

		private static Func<string, string, string, bool> _canPull;

		private static Func<object, string, int> _count;

		private static Func<int, int> _decrement;

		private static ConfigEntry<bool> _selfCheck;

		private static readonly Dictionary<ItemDrop, int> Totals = new Dictionary<ItemDrop, int>(new SameItem());

		private static readonly Dictionary<ItemDrop, bool> Founds = new Dictionary<ItemDrop, bool>(new SameItem());

		private static int _frame = -1;

		private static int _taking;

		private static IList _list;

		private static bool _changed;

		private static bool _loggedFirst;

		private static bool _loggedError;

		private static int _answered;

		private static int _walks;

		private static int _counts;

		private static int _match;

		private static int _different;

		private static float _nextStat;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Expected O, but got Unknown
			ConfigEntry<bool> obj = config.Bind<bool>("3 - Fixes", "AzuCraftyBoxesBuildCounts", true, "AzuCraftyBoxes 1.8.19: the hammer's build list counts each material in the chests once a frame instead of again for every piece. Same answers, much less work near many chests.");
			_selfCheck = config.Bind<bool>("9 - Debug", "AzuCraftyBoxesBuildCountsSelfCheck", false, "Test: every 20th hammer build check AzuCraftyBoxes answers too, the log counts MATCH and DIFFERENT.");
			if (!obj.Value || !Plugin.TargetMatches("AzuCraftyBoxesBuildCounts", "Azumatt.AzuCraftyBoxes", CheckedVersions))
			{
				return;
			}
			Type type = AccessTools.TypeByName("AzuCraftyBoxes.Patches.HaveRequirementsPatch2");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Postfix", (Type[])null, (Type[])null));
			if (methodInfo == null || !SameShape(methodInfo))
			{
				Plugin.Log.LogWarning((object)"AzuCraftyBoxesBuildCounts: AzuCraftyBoxes' build check is not the one this was written for, the fix stays off");
			}
			else if (Plugin.CodeMatches("AzuCraftyBoxesBuildCounts", methodInfo, CheckedCode))
			{
				if (!Resolve())
				{
					Plugin.Log.LogWarning((object)"AzuCraftyBoxesBuildCounts: a method or setting AzuCraftyBoxes' build check uses was not found, the fix stays off");
					return;
				}
				harmony.Patch((MethodBase)methodInfo, Method("Prefix"), Method("Compare"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null), (HarmonyMethod)null, Method("Changed"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(AzuCraftyBoxesBuildCounts), "TakeStart", (Type[])null, (Type[])null))
				{
					priority = 800
				};
				HarmonyMethod val2 = Method("TakeEnd");
				harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "ConsumeResources", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "DoCrafting", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null);
				Plugin.Log.LogInfo((object)("AzuCraftyBoxesBuildCounts: on for AzuCraftyBoxes 1.8.19" + (_selfCheck.Value ? ", self-check on" : "")));
			}
		}

		private static HarmonyMethod Method(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.Method(typeof(AzuCraftyBoxesBuildCounts), name, (Type[])null, (Type[])null));
		}

		private static bool SameShape(MethodInfo postfix)
		{
			ParameterInfo[] parameters = postfix.GetParameters();
			if (parameters.Length == 6 && parameters[0].ParameterType == typeof(Player) && parameters[1].ParameterType == typeof(bool).MakeByRefType() && parameters[2].ParameterType == typeof(Piece) && parameters[3].ParameterType == typeof(RequirementMode) && parameters[4].ParameterType == typeof(HashSet<string>))
			{
				return parameters[5].ParameterType == typeof(Dictionary<string, int>);
			}
			return false;
		}

		private static bool Resolve()
		{
			Type type = AccessTools.TypeByName("AzuCraftyBoxes.Util.Functions.MiscFunctions");
			Type type2 = AccessTools.TypeByName("AzuCraftyBoxes.AzuCraftyBoxesPlugin");
			Type type3 = AccessTools.TypeByName("AzuCraftyBoxes.Util.Functions.Boxes");
			Type type4 = ((type3 == null) ? null : AccessTools.Inner(type3, "QueryFrame"));
			Type type5 = AccessTools.TypeByName("AzuCraftyBoxes.IContainers.IContainer");
			Type type6 = AccessTools.TypeByName("AzuCraftyBoxes.IContainers.IContainerExtensions");
			if (type == null || type2 == null || type3 == null || type4 == null || type5 == null || type6 == null)
			{
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "ShouldPrevent", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(type, "CheckItemDropIntegrity", new Type[1] { typeof(ItemDrop) }, (Type[])null);
			FieldInfo fieldInfo = AccessTools.Field(type2, "skip");
			FieldInfo fieldInfo2 = AccessTools.Field(type2, "mRange");
			MethodInfo methodInfo3 = AccessTools.Method(type4, "Get", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(type3, "CanItemBePulled", new Type[3]
			{
				typeof(string),
				typeof(string),
				typeof(string)
			}, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(type3, "CheckAndDecrement", new Type[1] { typeof(int) }, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(type5, "GetPrefabName", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(type6, "ContainsItem", new Type[4]
			{
				type5,
				typeof(string),
				typeof(int),
				typeof(int).MakeByRefType()
			}, (Type[])null);
			if (methodInfo == null || methodInfo2 == null || fieldInfo == null || fieldInfo.FieldType != typeof(bool) || !fieldInfo.IsStatic || fieldInfo2 == null || !fieldInfo2.IsStatic || methodInfo3 == null || !methodInfo3.IsGenericMethodDefinition || methodInfo4 == null || methodInfo5 == null || methodInfo6 == null || methodInfo7 == null)
			{
				return false;
			}
			_range = fieldInfo2.GetValue(null) as ConfigEntry<float>;
			if (_range == null)
			{
				return false;
			}
			_shouldPrevent = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo);
			_integrity = (Func<ItemDrop, bool>)Delegate.CreateDelegate(typeof(Func<ItemDrop, bool>), methodInfo2);
			_canPull = (Func<string, string, string, bool>)Delegate.CreateDelegate(typeof(Func<string, string, string, bool>), methodInfo4);
			_decrement = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), methodInfo5);
			_skip = ReadStatic(fieldInfo);
			_nearby = NearbyCall(methodInfo3.MakeGenericMethod(typeof(Player)));
			_chestPrefab = PrefabCall(type5, methodInfo6);
			_count = CountCall(type5, methodInfo7);
			return true;
		}

		private static Func<bool> ReadStatic(FieldInfo field)
		{
			DynamicMethod dynamicMethod = new DynamicMethod("GapCloser_" + field.Name, typeof(bool), Type.EmptyTypes, typeof(AzuCraftyBoxesBuildCounts).Module, skipVisibility: true);
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldsfld, field);
			iLGenerator.Emit(OpCodes.Ret);
			return (Func<bool>)dynamicMethod.CreateDelegate(typeof(Func<bool>));
		}

		private static Func<Player, float, IList> NearbyCall(MethodInfo get)
		{
			DynamicMethod dynamicMethod = new DynamicMethod("GapCloser_NearbyChests", typeof(IList), new Type[2]
			{
				typeof(Player),
				typeof(float)
			}, typeof(AzuCraftyBoxesBuildCounts).Module, skipVisibility: true);
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, get);
			iLGenerator.Emit(OpCodes.Ret);
			return (Func<Player, float, IList>)dynamicMethod.CreateDelegate(typeof(Func<Player, float, IList>));
		}

		private static Func<object, string> PrefabCall(Type container, MethodInfo prefabName)
		{
			DynamicMethod dynamicMethod = new DynamicMethod("GapCloser_ChestPrefab", typeof(string), new Type[1] { typeof(object) }, typeof(AzuCraftyBoxesBuildCounts).Module, skipVisibility: true);
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Castclass, container);
			iLGenerator.Emit(OpCodes.Callvirt, prefabName);
			iLGenerator.Emit(OpCodes.Ret);
			return (Func<object, string>)dynamicMethod.CreateDelegate(typeof(Func<object, string>));
		}

		private static Func<object, string, int> CountCall(Type container, MethodInfo contains)
		{
			DynamicMethod dynamicMethod = new DynamicMethod("GapCloser_ChestCount", typeof(int), new Type[2]
			{
				typeof(object),
				typeof(string)
			}, typeof(AzuCraftyBoxesBuildCounts).Module, skipVisibility: true);
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			LocalBuilder local = iLGenerator.DeclareLocal(typeof(int));
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Castclass, container);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Ldc_I4_1);
			iLGenerator.Emit(OpCodes.Ldloca_S, local);
			iLGenerator.Emit(OpCodes.Call, contains);
			iLGenerator.Emit(OpCodes.Pop);
			iLGenerator.Emit(OpCodes.Ldloc, local);
			iLGenerator.Emit(OpCodes.Ret);
			return (Func<object, string, int>)dynamicMethod.CreateDelegate(typeof(Func<object, string, int>));
		}

		private static void TakeStart()
		{
			_taking++;
		}

		private static void TakeEnd()
		{
			if (--_taking < 0)
			{
				_taking = 0;
			}
			_changed = true;
		}

		private static void Changed()
		{
			_changed = true;
		}

		private static bool Prefix(Player __0, ref bool __1, Piece __2, RequirementMode __3, HashSet<string> __4, Dictionary<string, int> __5, out int __state)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			__state = -1;
			if (_taking > 0)
			{
				return true;
			}
			bool result = __1;
			try
			{
				Answer(__0, ref result, __2, __3, __4, __5);
			}
			catch (Exception ex)
			{
				if (!_loggedError)
				{
					_loggedError = true;
					Plugin.Log.LogWarning((object)("AzuCraftyBoxesBuildCounts: a build check failed here (" + ex.GetType().Name + ": " + ex.Message + "), AzuCraftyBoxes answers it, first time this session"));
				}
				return true;
			}
			_answered++;
			Stat();
			if (!_loggedFirst)
			{
				_loggedFirst = true;
				Plugin.Log.LogInfo((object)"AzuCraftyBoxesBuildCounts: answered a build check from the material totals, first time this session");
			}
			if (_selfCheck.Value && _answered % 20 == 0)
			{
				__state = (result ? 1 : 0);
				return true;
			}
			__1 = result;
			return false;
		}

		private static void Compare(ref bool __1, Piece __2, RequirementMode __3, int __state)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if (__state < 0)
			{
				return;
			}
			bool flag = __state == 1;
			if (flag == __1)
			{
				_match++;
				return;
			}
			_different++;
			if (_different <= 5)
			{
				Plugin.Log.LogWarning((object)string.Format("{0}: self-check DIFFERENT for {1} ({2}): here {3}, AzuCraftyBoxes {4}", "AzuCraftyBoxesBuildCounts", ((Object)(object)__2 != (Object)null) ? ((Object)__2).name : "?", __3, flag, __1));
			}
		}

		private static void Answer(Player player, ref bool result, Piece piece, RequirementMode mode, HashSet<string> knownMaterial, Dictionary<string, int> knownStations)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Expected I4, but got Unknown
			if ((_shouldPrevent() | result) || _skip() || player == null || ((Component)player).transform == null || (Object)(object)piece == (Object)null)
			{
				return;
			}
			CraftingStation craftingStation = piece.m_craftingStation;
			if (Object.op_Implicit((Object)(object)craftingStation))
			{
				if (mode - 1 <= 1)
				{
					if (!knownStations.ContainsKey(craftingStation.m_name))
					{
						return;
					}
				}
				else if (!Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(craftingStation.m_name, ((Component)player).transform.position)))
				{
					return;
				}
			}
			if (piece.m_dlc.Length > 0 && !DLCMan.instance.IsDLCInstalled(piece.m_dlc))
			{
				return;
			}
			IList chests = _nearby(player, _range.Value);
			Fresh(chests);
			Requirement[] resources = piece.m_resources;
			foreach (Requirement val in resources)
			{
				ItemDrop resItem = val.m_resItem;
				if ((Object)(object)resItem == (Object)null || val.m_amount <= 0 || !_integrity(resItem))
				{
					continue;
				}
				resItem.m_itemData.m_dropPrefab = ((Component)resItem).gameObject;
				if ((Object)(object)resItem.m_itemData.m_dropPrefab == (Object)null)
				{
					continue;
				}
				string name = resItem.m_itemData.m_shared.m_name;
				switch ((int)mode)
				{
				case 0:
				{
					int num = ((Humanoid)player).GetInventory().CountItems(name, -1, true);
					if (num < val.m_amount && num + Total(resItem, name, chests) < val.m_amount)
					{
						return;
					}
					break;
				}
				case 1:
					if (!knownMaterial.Contains(name))
					{
						return;
					}
					break;
				case 2:
					if (!((Humanoid)player).GetInventory().HaveItem(name, true) && !Found(resItem, name, chests))
					{
						return;
					}
					break;
				}
			}
			result = true;
		}

		private static void Fresh(IList chests)
		{
			int frameCount = Time.frameCount;
			if (frameCount != _frame || chests != _list || _changed)
			{
				_frame = frameCount;
				_list = chests;
				_changed = false;
				Totals.Clear();
				Founds.Clear();
			}
		}

		private static int Total(ItemDrop item, string name, IList chests)
		{
			if (Totals.TryGetValue(item, out var value))
			{
				return value;
			}
			_walks++;
			string prefab = ((Object)item).name;
			value = TotalOf(chests, (object chest) => _canPull(_chestPrefab(chest), prefab, ""), (object chest) => _count(chest, name), _decrement);
			Totals[item] = value;
			return value;
		}

		private static bool Found(ItemDrop item, string name, IList chests)
		{
			if (Founds.TryGetValue(item, out var value))
			{
				return value;
			}
			_walks++;
			string prefab = Utils.GetPrefabName(item.m_itemData.m_dropPrefab);
			value = AnyOf(chests, (object chest) => _canPull(_chestPrefab(chest), prefab, ""), (object chest) => _count(chest, name));
			Founds[item] = value;
			return value;
		}

		internal static int TotalOf(IList chests, Func<object, bool> pull, Func<object, int> count, Func<int, int> decrement)
		{
			int num = 0;
			for (int i = 0; i < chests.Count; i++)
			{
				object arg = chests[i];
				bool flag;
				try
				{
					flag = pull(arg);
				}
				catch (Exception)
				{
					break;
				}
				if (flag)
				{
					_counts++;
					try
					{
						num += decrement(count(arg));
					}
					catch (Exception)
					{
					}
				}
			}
			return num;
		}

		internal static bool AnyOf(IList chests, Func<object, bool> pull, Func<object, int> count)
		{
			try
			{
				for (int i = 0; i < chests.Count; i++)
				{
					object arg = chests[i];
					if (pull(arg))
					{
						_counts++;
						if (count(arg) >= 1)
						{
							return true;
						}
					}
				}
			}
			catch (Exception)
			{
			}
			return false;
		}

		private static void Stat()
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!(realtimeSinceStartup < _nextStat))
			{
				if (_nextStat > 0f)
				{
					Plugin.Log.LogInfo((object)(string.Format("{0} {1:0} s: {2} build checks answered, {3} material walks, {4} chest counts", "AzuCraftyBoxesBuildCounts", 60f, _answered, _walks, _counts) + (_selfCheck.Value ? $"; self-check {_match} MATCH, {_different} DIFFERENT" : "")));
				}
				_nextStat = realtimeSinceStartup + 60f;
				_answered = (_walks = (_counts = 0));
			}
		}
	}
	internal static class AzuCraftyBoxesChestNames
	{
		private sealed class SameObject : IEqualityComparer<Container>
		{
			public bool Equals(Container a, Container b)
			{
				return a == b;
			}

			public int GetHashCode(Container c)
			{
				return RuntimeHelpers.GetHashCode(c);
			}
		}

		private const string Name = "AzuCraftyBoxesChestNames";

		private const string ContainerType = "AzuCraftyBoxes.IContainers.VanillaContainer";

		private const int MaxNames = 4096;

		private static readonly string[] CheckedVersions = new string[1] { "1.8.19" };

		private static readonly string[] CheckedCode = new string[1] { "CA53C12B" };

		private static readonly Dictionary<Container, string> Names = new Dictionary<Container, string>(new SameObject());

		private static FieldRef<object, Container> _containerOf;

		private static bool _logged;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Expected O, but got Unknown
			if (config.Bind<bool>("3 - Fixes", "AzuCraftyBoxesChestNames", true, "AzuCraftyBoxes 1.8.19: keeps each chest's name instead of building it again for every check (less garbage).").Value && Plugin.TargetMatches("AzuCraftyBoxesChestNames", "Azumatt.AzuCraftyBoxes", CheckedVersions))
			{
				Type type = AccessTools.TypeByName("AzuCraftyBoxes.IContainers.VanillaContainer");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "GetPrefabName", new Type[0], (Type[])null));
				FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "<_container>P"));
				if (methodInfo == null || methodInfo.ReturnType != typeof(string) || fieldInfo == null || fieldInfo.FieldType != typeof(Container))
				{
					Plugin.Log.LogWarning((object)"AzuCraftyBoxesChestNames: AzuCraftyBoxes' chest prefab name or its chest not found, the fix stays off");
				}
				else if (Plugin.CodeMatches("AzuCraftyBoxesChestNames", methodInfo, CheckedCode))
				{
					_containerOf = AccessTools.FieldRefAccess<Container>(type, fieldInfo.Name);
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(AzuCraftyBoxesChestNames), "Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)"AzuCraftyBoxesChestNames: on for AzuCraftyBoxes 1.8.19");
				}
			}
		}

		private static bool Prefix(object __instance, ref string __result)
		{
			Container val = _containerOf.Invoke(__instance);
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			if (!Names.TryGetValue(val, out var value))
			{
				value = Utils.GetPrefabName(((Component)val).gameObject);
				if (Names.Count >= 4096)
				{
					Names.Clear();
				}
				Names[val] = value;
				if (!_logged)
				{
					_logged = true;
					Plugin.Log.LogInfo((object)("AzuCraftyBoxesChestNames: kept the prefab name " + value + " of a chest, first time this session"));
				}
			}
			__result = value;
			return false;
		}
	}
	internal static class AzuCraftyBoxesCraftingList
	{
		private const string Name = "AzuCraftyBoxesCraftingList";

		private const string ContainerType = "AzuCraftyBoxes.IContainers.VanillaContainer";

		private const string CheckType = "AzuCraftyBoxes.Patches.PlayerHaveRequirementsPatchRBoolInt";

		private const string BoxesType = "AzuCraftyBoxes.Util.Functions.Boxes";

		private const float CountSeconds = 2f;

		private const float RuleSeconds = 5f;

		private static readonly string[] CheckedVersions = new string[1] { "1.8.19" };

		private static readonly string[] CheckedCountCode = new string[1] { "FF0CDAB5" };

		private static readonly string[] CheckedRuleCode = new string[1] { "4C98F8A3" };

		private static readonly Dictionary<(Inventory, string), int> Counts = new Dictionary<(Inventory, string), int>();

		private static readonly Dictionary<(string, string, string), bool> Rules = new Dictionary<(string, string, string), bool>();

		private static FieldRef<object, Container> _containerOf;

		private static ConfigEntryBase _debugLog;

		private static float _countsSince;

		private static float _rulesSince;

		private static int _taking;

		private static int _reused;

		private static bool _loggedReuse;

		private static bool _loggedText;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			if (config.Bind<bool>("3 - Fixes", "AzuCraftyBoxesCraftingList", true, "AzuCraftyBoxes 1.8.19: faster inventory and crafting near many chests (chest counts kept until a chest changes).").Value && Plugin.TargetMatches("AzuCraftyBoxesCraftingList", "Azumatt.AzuCraftyBoxes", CheckedVersions))
			{
				Type type = AccessTools.TypeByName("AzuCraftyBoxes.IContainers.VanillaContainer");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "ItemCount", new Type[1] { typeof(string) }, (Type[])null));
				FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "<_container>P"));
				Type type2 = AccessTools.TypeByName("AzuCraftyBoxes.Patches.PlayerHaveRequirementsPatchRBoolInt");
				MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.Method(type2, "HaveRequirementItems", (Type[])null, (Type[])null));
				Type type3 = AccessTools.TypeByName("AzuCraftyBoxes.Util.Functions.Boxes");
				MethodInfo methodInfo3 = ((type3 == null) ? null : AccessTools.Method(type3, "CanItemBePulled", new Type[3]
				{
					typeof(string),
					typeof(string),
					typeof(string)
				}, (Type[])null));
				Type type4 = AccessTools.TypeByName("AzuCraftyBoxes.AzuCraftyBoxesPlugin");
				_debugLog = (ConfigEntryBase)((type4 == null) ? null : /*isinst with value type is only supported in some contexts*/);
				if (methodInfo == null || fieldInfo == null || fieldInfo.FieldType != typeof(Container) || methodInfo2 == null || methodInfo3 == null || _debugLog == null)
				{
					Plugin.Log.LogWarning((object)"AzuCraftyBoxesCraftingList: AzuCraftyBoxes' chest count, its chest, requirement check, pull rules or debug setting not found, the fix stays off");
				}
				else if (Plugin.CodeMatches("AzuCraftyBoxesCraftingList", methodInfo, CheckedCountCode) && Plugin.CodeMatches("AzuCraftyBoxesCraftingList", methodInfo3, CheckedRuleCode))
				{
					_containerOf = AccessTools.FieldRefAccess<Container>(type, fieldInfo.Name);
					harmony.Patch((MethodBase)methodInfo, Method("CountPrefix"), Method("CountPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					harmony.Patch((MethodBase)methodInfo3, Method("RulePrefix"), Method("RulePostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					harmony.Patch((MethodBase)AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null), (HarmonyMethod)null, Method("Changed"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(AzuCraftyBoxesCraftingList), "TakeStart", (Type[])null, (Type[])null))
					{
						priority = 800
					};
					HarmonyMethod val2 = Method("TakeEnd");
					harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "ConsumeResources", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null);
					harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "DoCrafting", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null);
					harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, Method("Transpiler"), (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)"AzuCraftyBoxesCraftingList: on for AzuCraftyBoxes 1.8.19");
				}
			}
		}

		private static HarmonyMethod Method(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.Method(typeof(AzuCraftyBoxesCraftingList), name, (Type[])null, (Type[])null));
		}

		private static void TakeStart()
		{
			_taking++;
			Counts.Clear();
		}

		private static void TakeEnd()
		{
			if (--_taking < 0)
			{
				_taking = 0;
			}
			Counts.Clear();
		}

		private static void Changed()
		{
			if (Counts.Count > 0)
			{
				Counts.Clear();
			}
		}

		private static bool CountPrefix(object __instance, string __0, ref int __result, out (Inventory, string) __state)
		{
			__state = default((Inventory, string));
			if (_taking > 0 || __0 == null)
			{
				return true;
			}
			Container obj = _containerOf.Invoke(__instance);
			Inventory val = ((obj != null) ? obj.GetInventory() : null);
			if (val == null)
			{
				return true;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup - _countsSince > 2f)
			{
				Counts.Clear();
				_countsSince = realtimeSinceStartup;
			}
			if (Counts.TryGetValue((val, __0), out var value))
			{
				__result = value;
				if (++_reused == 1000 && !_loggedReuse)
				{
					_loggedReuse = true;
					Plugin.Log.LogInfo((object)string.Format("{0}: reused kept chest counts 1000 times ({1} kept now), first time this session", "AzuCraftyBoxesCraftingList", Counts.Count));
				}
				return false;
			}
			__state = (val, __0);
			return true;
		}

		private static void CountPostfix(int __result, (Inventory, string) __state)
		{
			if (__state.Item1 != null && _taking == 0)
			{
				Counts[__state] = __result;
			}
		}

		private static bool RulePrefix(string __0, string __1, string __2, ref bool __result, out bool __state)
		{
			__state = false;
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup - _rulesSince > 5f)
			{
				Rules.Clear();
				_rulesSince = realtimeSinceStartup;
			}
			if (__0 != null && __1 != null && __2 != null && Rules.TryGetValue((__0, __1, __2), out var value))
			{
				__result = value;
				return false;
			}
			__state = __0 != null && __1 != null && __2 != null;
			return true;
		}

		private static void RulePostfix(string __0, string __1, string __2, bool __result, bool __state)
		{
			if (__state)
			{
				Rules[(__0, __1, __2)] = __result;
			}
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(string), "Format", new Type[2]
			{
				typeof(string),
				typeof(object[])
			}, (Type[])null);
			MethodInfo operand = AccessTools.Method(typeof(AzuCraftyBoxesCraftingList), "FormatIfDebug", (Type[])null, (Type[])null);
			List<CodeInstruction> list = instructions.ToList();
			int num = 0;
			for (int i = 0; i + 1 < list.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(list[i], methodInfo) && !(list[i + 1].opcode != OpCodes.Call) && !((list[i + 1].operand as MethodInfo)?.Name != "LogIfReleaseAndDebugEnable"))
				{
					list[i].operand = operand;
					num++;
				}
			}
			Plugin.Log.LogInfo((object)string.Format("{0}: {1} debug text built only with AzuCraftyBoxes' debug log on", "AzuCraftyBoxesCraftingList", num));
			return list;
		}

		private static string FormatIfDebug(string format, object[] args)
		{
			if (string.Equals(_debugLog.BoxedValue?.ToString(), "On", StringComparison.Ordinal))
			{
				return string.Format(format, args);
			}
			if (!_loggedText)
			{
				_loggedText = true;
				Plugin.Log.LogInfo((object)"AzuCraftyBoxesCraftingList: skipped a debug text while AzuCraftyBoxes' debug log is off, first time this session");
			}
			return string.Empty;
		}
	}
	internal static class AzuCraftyBoxesForgeRecipes
	{
		public const string TargetGuid = "Azumatt.AzuCraftyBoxes";

		private const string Name = "AzuCraftyBoxesForgeRecipes";

		private const string TargetType = "AzuCraftyBoxes.Patches.PlayerHaveRequirementsPatchRBoolInt";

		private static readonly string[] CheckedVersions = new string[1] { "1.8.19" };

		private static readonly string[] CheckedCode = new string[1] { "4A726BA5" };

		private static bool _actedOnce;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			if (!config.Bind<bool>("3 - Fixes", "AzuCraftyBoxesForgeRecipes", true, "AzuCraftyBoxes 1.8.19: the Forge of Potential no longer teaches every recipe.").Value || !Plugin.TargetMatches("AzuCraftyBoxesForgeRecipes", "Azumatt.AzuCraftyBoxes", CheckedVersions))
			{
				return;
			}
			Type type = AccessTools.TypeByName("AzuCraftyBoxes.Patches.PlayerHaveRequirementsPatchRBoolInt");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Postfix", (Type[])null, (Type[])null));
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"AzuCraftyBoxesForgeRecipes: AzuCraftyBoxes.Patches.PlayerHaveRequirementsPatchRBoolInt.Postfix not found, the fix stays off");
			}
			else if (Plugin.CodeMatches("AzuCraftyBoxesForgeRecipes", methodInfo, CheckedCode))
			{
				try
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(AzuCraftyBoxesForgeRecipes), "Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)("AzuCraftyBoxesForgeRecipes: on for AzuCraftyBoxes " + string.Join(", ", CheckedVersions)));
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("AzuCraftyBoxesForgeRecipes: could not patch AzuCraftyBoxes.Patches.PlayerHaveRequirementsPatchRBoolInt.Postfix, the fix stays off: " + ex.Message));
				}
			}
		}

		private static bool Prefix(Player __0, bool discover)
		{
			if (!discover || (Object)(object)__0 == (Object)null)
			{
				return true;
			}
			CraftingStation currentCraftingStation = __0.GetCurrentCraftingStation();
			if ((Object)(object)currentCraftingStation == (Object)null || !currentCraftingStation.m_upgrader)
			{
				return true;
			}
			if (!_actedOnce)
			{
				_actedOnce = true;
				Plugin.Log.LogInfo((object)("AzuCraftyBoxesForgeRecipes: skipped AzuCraftyBoxes' learn check at " + currentCraftingStation.m_name + ", first time this session"));
			}
			return false;
		}
	}
	internal static class Benchmark
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static CameraCallback <0>__OnPreCull;

			public static CameraCallback <1>__OnPostRender;
		}

		private const float PhaseSeconds = 2f;

		private const float SettleSeconds = 0.6f;

		private const int Phases = 10;

		private const float LongPhaseSeconds = 5f;

		private const int LongPhases = 4;

		private const float TotalSeconds = 40f;

		private const string FileName = "GapCloser_benchmarks.txt";

		private static bool _started;

		private static readonly Stopwatch FrameClock = Stopwatch.StartNew();

		private static readonly Stopwatch RenderClock = new Stopwatch();

		private static double _lastFrameAt = -1.0;

		private static ProfilerRecorder _drawCalls;

		private static ProfilerRecorder _setPass;

		private static ProfilerRecorder _triangles;

		private static string _name;

		private static string _onLabel;

		private static string _offLabel;

		private static string _extraLabel;

		private static Action<bool> _set;

		private static Func<double> _extra;

		private static bool _wasOn;

		private static float _start = -1f;

		private static float _moved;

		private static float _turned;

		private static int _phase = -1;

		private static Vector3 _pos;

		private static Quaternion _rot;

		private static readonly List<float>[] Ms = new List<float>[2]
		{
			new List<float>(),
			new List<float>()
		};

		private static readonly List<float>[] Render = new List<float>[2]
		{
			new List<float>(),
			new List<float>()
		};

		private static readonly double[] Draw = new double[2];

		private static readonly double[] Pass = new double[2];

		private static readonly double[] Tris = new double[2];

		private static readonly double[] Extra = new double[2];

		private static readonly double[] Jump = new double[2];

		private static readonly int[] Jumps = new int[2];

		private static float _lastMs = -1f;

		private static readonly List<float>[] Long = new List<float>[2]
		{
			new List<float>(),
			new List<float>()
		};

		private static readonly double[] LongJump = new double[2];

		private static readonly int[] LongJumps = new int[2];

		internal static string StepText;

		public static float FrameMs { get; private set; }

		public static double RenderMs { get; private set; }

		public static long DrawCalls => Counter(_drawCalls);

		public static long SetPass => Counter(_setPass);

		public static long Triangles => Counter(_triangles);

		public static bool Running => _start >= 0f;

		public static void Start()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			if (!_started)
			{
				_started = true;
				_drawCalls = ProfilerRecorder.StartNew(ProfilerCategory.Render, "Draw Calls Count", 1, (ProfilerRecorderOptions)24);
				_setPass = ProfilerRecorder.StartNew(ProfilerCategory.Render, "SetPass Calls Count", 1, (ProfilerRecorderOptions)24);
				_triangles = ProfilerRecorder.StartNew(ProfilerCategory.Render, "Triangles Count", 1, (ProfilerRecorderOptions)24);
				CameraCallback onPreCull = Camera.onPreCull;
				object obj = <>O.<0>__OnPreCull;
				if (obj == null)
				{
					CameraCallback val = OnPreCull;
					<>O.<0>__OnPreCull = val;
					obj = (object)val;
				}
				Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)onPreCull, (Delegate?)obj);
				CameraCallback onPostRender = Camera.onPostRender;
				object obj2 = <>O.<1>__OnPostRender;
				if (obj2 == null)
				{
					CameraCallback val2 = OnPostRender;
					<>O.<1>__OnPostRender = val2;
					obj2 = (object)val2;
				}
				Camera.onPostRender = (CameraCallback)Delegate.Combine((Delegate?)(object)onPostRender, (Delegate?)obj2);
			}
		}

		private static long Counter(ProfilerRecorder recorder)
		{
			if (!((ProfilerRecorder)(ref recorder)).Valid)
			{
				return -1L;
			}
			return ((ProfilerRecorder)(ref recorder)).LastValue;
		}

		internal static void Record(string line)
		{
			Plugin.Log.LogInfo((object)line);
			try
			{
				File.AppendAllText(Path.Combine(Paths.BepInExRootPath, "GapCloser_benchmarks.txt"), string.Format("{0:yyyy-MM-dd HH:mm:ss} GapCloser {1}: {2}{3}", DateTime.Now, "1.3.7", line, Environment.NewLine));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("the benchmark file could not be written (" + ex.GetType().Name + ": " + ex.Message + ")"));
			}
		}

		private static void OnPreCull(Camera cam)
		{
			if ((Object)(object)cam == (Object)(object)Utils.GetMainCamera())
			{
				RenderClock.Restart();
			}
		}

		private static void OnPostRender(Camera cam)
		{
			if (RenderClock.IsRunning && !((Object)(object)cam != (Object)(object)Utils.GetMainCamera()))
			{
				RenderMs = RenderClock.Elapsed.TotalMilliseconds;
				RenderClock.Stop();
			}
		}

		internal static void Frame()
		{
			if (_started)
			{
				double totalMilliseconds = FrameClock.Elapsed.TotalMilliseconds;
				FrameMs = ((_lastFrameAt < 0.0) ? 0f : ((float)(totalMilliseconds - _lastFrameAt)));
				_lastFrameAt = totalMilliseconds;
				if (Running)
				{
					Step();
				}
			}
		}

		public static bool Begin(string name, string onLabel, string offLabel, Action<bool> set, bool wasOn, Func<double> extra = null, string extraLabel = null)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (!_started || Running)
			{
				return false;
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera == (Object)null)
			{
				return false;
			}
			_name = name;
			_onLabel = onLabel;
			_offLabel = offLabel;
			_set = set;
			_wasOn = wasOn;
			_extra = extra;
			_extraLabel = extraLabel;
			_start = Time.realtimeSinceStartup;
			_phase = -1;
			_pos = ((Component)mainCamera).transform.position;
			_rot = ((Component)mainCamera).transform.rotation;
			_moved = (_turned = 0f);
			for (int i = 0; i < 2; i++)
			{
				Ms[i].Clear();
				Render[i].Clear();
				Draw[i] = (Pass[i] = (Tris[i] = (Extra[i] = (Jump[i] = (LongJump[i] = 0.0)))));
				Jumps[i] = (LongJumps[i] = 0);
				Long[i].Clear();
			}
			Plugin.Log.LogInfo((object)$"{_name}: benchmark started at {DateTime.Now:HH:mm:ss}, ({_pos.x:0}, {_pos.z:0})");
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)2, (StepText != null) ? $"GapCloser benchmark {StepText}: stand still {40f:0} s" : $"GapCloser {_name} benchmark: stand still {40f:0} s", 0, (Sprite)null, false, true);
			}
			return true;
		}

		private static void Step()
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			float num = Time.realtimeSinceStartup - _start;
			int num2;
			float num3;
			if (num < 20f)
			{
				num2 = (int)(num / 2f);
				num3 = (float)num2 * 2f;
			}
			else
			{
				int num4 = (int)((num - 20f) / 5f);
				if (num4 >= 4)
				{
					Finish();
					return;
				}
				num2 = 10 + num4;
				num3 = 20f + (float)num4 * 5f;
			}
			bool flag = num2 % 2 == 0;
			if (num2 != _phase)
			{
				_phase = num2;
				_lastMs = -1f;
				_set(flag);
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera != (Object)null)
			{
				_moved = Mathf.Max(_moved, Vector3.Distance(((Component)mainCamera).transform.position, _pos));
				_turned = Mathf.Max(_turned, Quaternion.Angle(((Component)mainCamera).transform.rotation, _rot));
			}
			if (num - num3 < 0.6f)
			{
				return;
			}
			int num5 = (flag ? 1 : 0);
			bool flag2 = num2 >= 10;
			if (_lastMs >= 0f)
			{
				if (flag2)
				{
					LongJump[num5] += Math.Abs(FrameMs - _lastMs);
					LongJumps[num5]++;
				}
				else
				{
					Jump[num5] += Math.Abs(FrameMs - _lastMs);
					Jumps[num5]++;
				}
			}
			_lastMs = FrameMs;
			if (flag2)
			{
				Long[num5].Add(FrameMs);
				return;
			}
			Ms[num5].Add(FrameMs);
			Render[num5].Add((float)RenderMs);
			Draw[num5] += DrawCalls;
			Pass[num5] += SetPass;
			Tris[num5] += Triangles;
			if (_extra != null)
			{
				Extra[num5] += _extra();
			}
		}

		private static void Finish()
		{
			_start = -1f;
			_set(_wasOn);
			int count = Ms[0].Count;
			int count2 = Ms[1].Count;
			if (count == 0 || count2 == 0)
			{
				Plugin.Log.LogInfo((object)(_name + ": benchmark ended without frames to compare"));
				return;
			}
			double num = MeanOf(Ms[0]);
			double num2 = MeanOf(Ms[1]);
			float num3 = Median(Render[0]);
			float num4 = Median(Render[1]);
			float num5 = Median(Ms[0]);
			float num6 = Median(Ms[1]);
			string text = ((_extra != null) ? $", {Extra[1] / (double)count2:0} {_extraLabel}" : "");
			string text2 = "";
			if (Long[0].Count > 0 && Long[1].Count > 0)
			{
				float num7 = Median(Long[1]);
				float num8 = Median(Long[0]);
				text2 = $"; {5f:0} s phases: {_onLabel} {num7:0.00} ms median ({Long[1].Count} frames), {_offLabel} {num8:0.00} ({Long[0].Count} frames), " + $"{_onLabel} minus {_offLabel} {num7 - num8:+0.00;-0.00} ms, jump {((LongJumps[1] > 0) ? (LongJump[1] / (double)LongJumps[1]) : 0.0):0.00} ms {_onLabel}, {((LongJumps[0] > 0) ? (LongJump[0] / (double)LongJumps[0]) : 0.0):0.00} {_offLabel}";
			}
			Record($"{_name}: BENCHMARK at ({_pos.x:0}, {_pos.z:0}), moved {_moved:0.0} m, turned {_turned:0} deg: " + $"{_onLabel} {num6:0.00} ms median ({num2:0.00} mean, {P(Ms[1]):0.0} p95, {Ms[1][count2 - 1]:0.0} worst, {count2} frames{text}), " + $"{_offLabel} {num5:0.00} ms median ({num:0.00} mean, {P(Ms[0]):0.0} p95, {Ms[0][count - 1]:0.0} worst, {count} frames); " + $"{_onLabel} minus {_offLabel}: {num6 - num5:+0.00;-0.00} ms median, {num2 - num:+0.00;-0.00} ms mean, " + $"draw calls {Draw[1] / (double)count2 - Draw[0] / (double)count:+0;-0} (of {Draw[0] / (double)count:0}), set pass {Pass[1] / (double)count2 - Pass[0] / (double)count:+0;-0} (of {Pass[0] / (double)count:0}), " + $"triangles {(Tris[1] / (double)count2 - Tris[0] / (double)count) / 1000.0:+0;-0}k; " + $"main camera render {num4:0.00} ms median {_onLabel}, {num3:0.00} {_offLabel} ({num4 - num3:+0.00;-0.00}); " + $"frame to frame jump {((Jumps[1] > 0) ? (Jump[1] / (double)Jumps[1]) : 0.0):0.00} ms {_onLabel}, {((Jumps[0] > 0) ? (Jump[0] / (double)Jumps[0]) : 0.0):0.00} {_offLabel}" + text2);
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)2, (StepText != null) ? $"GapCloser benchmark {StepText} done: {_onLabel} {num6:0.0} ms, {_offLabel} {num5:0.0} ms" : $"{_name} benchmark done: {_onLabel} {num6:0.0} ms, {_offLabel} {num5:0.0} ms", 0, (Sprite)null, false, true);
			}
			static double MeanOf(List<float> list)
			{
				double num9 = 0.0;
				foreach (float item in list)
				{
					num9 += (double)item;
				}
				return num9 / (double)list.Count;
			}
			static float Median(List<float> list)
			{
				list.Sort();
				return list[list.Count / 2];
			}
			static float P(List<float> list)
			{
				return list[Math.Min(list.Count - 1, (int)((float)list.Count * 0.95f))];
			}
		}
	}
	internal static class BenchmarkAll
	{
		private sealed class Part
		{
			public string Label;

			public Func<bool> Available;

			public Func<bool> Get;

			public Action<bool> Set;
		}

		private sealed class Step
		{
			public string Label;

			public Func<bool> Start;
		}

		private const string Name = "Benchmarks";

		private const float GapSeconds = 1f;

		private static readonly Part[] Parts = new Part[4]
		{
			new Part
			{
				Label = "camera hiding",
				Available = () => OcclusionCulling.CameraPartAvailable,
				Get = () => OcclusionCulling.CameraPart,
				Set = OcclusionCulling.SetCameraPart
			},
			new Part
			{
				Label = "sun shadows",
				Available = () => OcclusionCulling.SunPartAvailable,
				Get = () => OcclusionCulling.SunPart,
				Set = OcclusionCulling.SetSunPart
			},
			new Part
			{
				Label = "hidden lights",
				Available = () => HiddenLights.PartAvailable,
				Get = () => HiddenLights.PartOn,
				Set = HiddenLights.SetPart
			},
			new Part
			{
				Label = "merged areas",
				Available = () => PieceBatching.PartAvailable,
				Get = () => PieceBatching.PartOn,
				Set = PieceBatching.SetPart
			}
		};

		private static ConfigEntry<KeyboardShortcut> _key;

		private static readonly List<Step> Steps = new List<Step>();

		private static readonly List<Part> Here = new List<Part>();

		private static readonly bool[] Saved = new bool[Parts.Length];

		private static readonly List<string> Ran = new List<string>();

		private static readonly List<string> LeftOut = new List<string>();

		private static bool _running;

		private static bool _stopAfter;

		private static bool _savedHiding;

		private static int _step;

		private static float _nextAt;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			_key = config.Bind<KeyboardShortcut>("9 - Debug", "BenchmarkKey", new KeyboardShortcut((KeyCode)279, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Stand still and press it: GapCloser's parts are measured against all of them off, a few minutes, the results in the log and in BepInEx/GapCloser_benchmarks.txt. Press again to stop.");
			Benchmark.Start();
			Plugin.Log.LogInfo((object)string.Format("{0}: {1} runs every benchmark one after another", "Benchmarks", _key.Value));
		}

		internal static void Frame()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (_key == null)
			{
				return;
			}
			KeyboardShortcut value = _key.Value;
			bool flag = ((KeyboardShortcut)(ref value)).IsDown() && !OcclusionCulling.Typing();
			if (!_running)
			{
				if (flag && !Benchmark.Running)
				{
					Begin();
				}
				return;
			}
			if (flag && !_stopAfter)
			{
				_stopAfter = true;
				if ((Object)(object)MessageHud.instance != (Object)null)
				{
					MessageHud.instance.ShowMessage((MessageType)2, "GapCloser benchmarks: stopping after this one", 0, (Sprite)null, false, true);
				}
			}
			if (Benchmark.Running)
			{
				_nextAt = Time.realtimeSinceStartup + 1f;
			}
			else if (!(Time.realtimeSinceStartup < _nextAt))
			{
				if (_stopAfter)
				{
					End("stopped");
				}
				else
				{
					Next();
				}
			}
		}

		private static void Begin()
		{
			Here.Clear();
			for (int i = 0; i < Parts.Length; i++)
			{
				Saved[i] = Parts[i].Get();
				if (Parts[i].Available())
				{
					Here.Add(Parts[i]);
				}
			}
			_savedHiding = OcclusionCulling.Hiding;
			Steps.Clear();
			if (Here.Count > 0)
			{
				Steps.Add(new Step
				{
					Label = "everything",
					Start = () => PartsRun("everything", Here)
				});
				if (Here.Count > 1)
				{
					foreach (Part part in Here)
					{
						List<Part> alone = new List<Part> { part };
						Steps.Add(new Step
						{
							Label = part.Label + " alone",
							Start = () => PartsRun(part.Label + " alone", alone)
						});
					}
				}
			}
			Ran.Clear();
			LeftOut.Clear();
			_running = true;
			_stopAfter = false;
			_step = -1;
			Plugin.Log.LogInfo((object)string.Format("{0}: run started at {1:HH:mm:ss}, {2} steps, parts here: {3}", "Benchmarks", DateTime.Now, Steps.Count, (Here.Count > 0) ? string.Join(", ", Here.ConvertAll((Part p) => p.Label)) : "none"));
			Next();
		}

		private static bool PartsRun(string label, List<Part> chosen)
		{
			OcclusionCulling.SetHidingForRun(on: true);
			return Benchmark.Begin("Benchmark " + label, "on", "baseline", delegate(bool on)
			{
				foreach (Part item in Here)
				{
					item.Set(on && chosen.Contains(item));
				}
			}, wasOn: false);
		}

		private static void Next()
		{
			while (++_step < Steps.Count)
			{
				Step step = Steps[_step];
				Benchmark.StepText = $"{_step + 1} of {Steps.Count}: {step.Label}";
				if (step.Start())
				{
					Ran.Add(step.Label);
					return;
				}
				LeftOut.Add(step.Label);
			}
			End(null);
		}

		private static void Restore()
		{
			for (int i = 0; i < Parts.Length; i++)
			{
				if (Parts[i].Get() != Saved[i])
				{
					Parts[i].Set(Saved[i]);
				}
			}
			OcclusionCulling.SetHidingForRun(_savedHiding);
		}

		private static void End(string reason)
		{
			Restore();
			_running = false;
			Benchmark.StepText = null;
			Benchmark.Record("Benchmarks: run " + (reason ?? "done") + ", ran " + ((Ran.Count > 0) ? string.Join(", ", Ran) : "nothing") + ((LeftOut.Count > 0) ? (", left out here: " + string.Join(", ", LeftOut)) : ""));
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)2, (reason == null) ? $"GapCloser benchmarks: all {Ran.Count} done, results in GapCloser_benchmarks.txt" : $"GapCloser benchmarks stopped after {Ran.Count}", 0, (Sprite)null, false, true);
			}
		}
	}
	internal static class ChestReloadSkip
	{
		private const string Name = "ChestReloadSkip";

		private const float StatSeconds = 60f;

		private static readonly string[] CheckedCode = new string[1] { "225C0DE7" };

		private static ConfigEntry<bool> _enabled;

		private static ConfigEntry<bool> _selfCheck;

		private static FieldRef<Container, ZNetView> _nview;

		private static FieldRef<Container, Inventory> _inventory;

		private static FieldRef<Container, uint> _lastRevision;

		private static FieldRef<Container, bool> _inUse;

		private static int _itemsKey;

		private static readonly ZPackage Package = new ZPackage();

		private static float _nextStat;

		private static int _skipped;

		private static int _loaded;

		private static int _match;

		private static int _different;

		private static int _checkFailed;

		private static bool _loggedSkip;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Expected O, but got Unknown
			_enabled = config.Bind<bool>("3 - Fixes", "ChestReloadSkip", true, "A chest whose stored items did not change is not rebuilt when its open flag changes or the ship or cart under it moves.");
			_selfCheck = config.Bind<bool>("9 - Debug", "ChestReloadSkipSelfCheck", false, "Test: each skipped chest rebuild is also checked item by item, the log gets MATCH or DIFFERENT.");
			if (_enabled.Value && Plugin.GameMatches("ChestReloadSkip"))
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Container), "Load", (Type[])null, (Type[])null);
				FieldInfo fieldInfo = AccessTools.Field(typeof(Container), "m_nview");
				FieldInfo fieldInfo2 = AccessTools.Field(typeof(Container), "m_inventory");
				FieldInfo fieldInfo3 = AccessTools.Field(typeof(Container), "m_lastRevision");
				FieldInfo fieldInfo4 = AccessTools.Field(typeof(Container), "m_inUse");
				FieldInfo fieldInfo5 = AccessTools.Field(typeof(ZDOVars), "s_items");
				if (methodInfo == null || methodInfo.ReturnType != typeof(bool) || methodInfo.GetParameters().Length != 0 || fieldInfo?.FieldType != typeof(ZNetView) || fieldInfo2?.FieldType != typeof(Inventory) || fieldInfo3?.FieldType != typeof(uint) || fieldInfo4?.FieldType != typeof(bool) || fieldInfo5 == null || fieldInfo5.FieldType != typeof(int))
				{
					Plugin.Log.LogWarning((object)"ChestReloadSkip: the game's chest load did not look as checked, off");
				}
				else if (Plugin.CodeMatches("ChestReloadSkip", methodInfo, CheckedCode))
				{
					_nview = AccessTools.FieldRefAccess<Container, ZNetView>(fieldInfo);
					_inventory = AccessTools.FieldRefAccess<Container, Inventory>(fieldInfo2);
					_lastRevision = AccessTools.FieldRefAccess<Container, uint>(fieldInfo3);
					_inUse = AccessTools.FieldRefAccess<Container, bool>(fieldInfo4);
					_itemsKey = (int)fieldInfo5.GetValue(null);
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(ChestReloadSkip), "Before", (Type[])null, (Type[])null))
					{
						priority = 0
					}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)("ChestReloadSkip: on" + (_selfCheck.Value ? ", self-check on (every left out rebuild is checked)" : "")));
				}
			}
		}

		private static bool Before(Container __instance, ref bool __result)
		{
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ZNetView val = _nview.Invoke(__instance);
				ZDO val2 = (((Object)(object)val != (Object)null) ? val.GetZDO() : null);
				if (val2 == null)
				{
					return true;
				}
				uint dataRevision = val2.DataRevision;
				if (dataRevision == _lastRevision.Invoke(__instance) || _inUse.Invoke(__instance))
				{
					return true;
				}
				byte[] byteArray = val2.GetByteArray(_itemsKey, (byte[])null);
				Inventory val3 = _inventory.Invoke(__instance);
				if (byteArray == null || val3 == null || (Object)(object)((Component)__instance).GetComponent<TombStone>() != (Object)null)
				{
					return true;
				}
				Package.Clear();
				val3.Save(Package);
				if (!Same(Package.GetArray(), byteArray))
				{
					_loaded++;
					return true;
				}
				if (_selfCheck.Value)
				{
					Check(__instance, val3, byteArray);
				}
				_lastRevision.Invoke(__instance) = dataRevision;
				__result = true;
				_skipped++;
				if (!_loggedSkip)
				{
					_loggedSkip = true;
					Plugin.Log.LogInfo((object)string.Format("{0}: left out the rebuild of {1} at {2}, its stored items are what it holds, first time this session", "ChestReloadSkip", ((Object)__instance).name, ((Component)__instance).transform.position));
				}
				return false;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("ChestReloadSkip: " + ex.GetType().Name + " (" + ex.Message + "), the game's load runs"));
				return true;
			}
		}

		private static bool Same(byte[] a, byte[] b)
		{
			if (a.Length != b.Length)
			{
				return false;
			}
			for (int i = 0; i < a.Length; i++)
			{
				if (a[i] != b[i])
				{
					return false;
				}
			}
			return true;
		}

		private static void Check(Container chest, Inventory inventory, byte[] stored)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			string text;
			try
			{
				Inventory val = new Inventory(inventory.GetName(), (Sprite)null, inventory.GetWidth(), inventory.GetHeight());
				val.Load(new ZPackage(stored));
				text = Difference(inventory.GetAllItems(), val.GetAllItems());
			}
			catch (Exception ex)
			{
				_checkFailed++;
				Plugin.Log.LogWarning((object)("ChestReloadSkip: self-check could not load the stored items of " + ((Object)chest).name + " (" + ex.GetType().Name + ": " + ex.Message + ")"));
				return;
			}
			if (text == null)
			{
				_match++;
				return;
			}
			_different++;
			Plugin.Log.LogWarning((object)string.Format("{0}: self-check DIFFERENT for {1} at {2}: {3}", "ChestReloadSkip", ((Object)chest).name, ((Component)chest).transform.position, text));
		}

		private static string Difference(List<ItemData> held, List<ItemData> stored)
		{
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			if (held.Count != stored.Count)
			{
				return $"{held.Count} items held, {stored.Count} stored";
			}
			for (int i = 0; i < held.Count; i++)
			{
				ItemData val = held[i];
				ItemData val2 = stored[i];
				string text = ((val.m_dropPrefab != null) ? ((Object)val.m_dropPrefab).name : val.m_shared?.m_name);
				string text2 = ((val2.m_dropPrefab != null) ? ((Object)val2.m_dropPrefab).name : val2.m_shared?.m_name);
				if (text != text2 || val.m_stack != val2.m_stack || val.m_quality != val2.m_quality || val.m_variant != val2.m_variant || val.m_gridPos.x != val2.m_gridPos.x || val.m_gridPos.y != val2.m_gridPos.y || Math.Abs(val.m_durability - val2.m_durability) > 0.001f || val.m_crafterID != val2.m_crafterID || val.m_crafterName != val2.m_crafterName || val.m_worldLevel != val2.m_worldLevel || val.m_pickedUp != val2.m_pickedUp || !SameData(val.m_customData, val2.m_customData))
				{
					return $"item {i}: held {text} x{val.m_stack} q{val.m_quality} at {val.m_gridPos}, stored {text2} x{val2.m_stack} q{val2.m_quality} at {val2.m_gridPos}";
				}
			}
			return null;
		}

		private static bool SameData(Dictionary<string, string> a, Dictionary<string, string> b)
		{
			int num = a?.Count ?? 0;
			int num2 = b?.Count ?? 0;
			if (num != num2)
			{
				return false;
			}
			if (num == 0)
			{
				return true;
			}
			foreach (KeyValuePair<string, string> item in a)
			{
				if (!b.TryGetValue(item.Key, out var value) || value != item.Value)
				{
					return false;
				}
			}
			return true;
		}

		internal static void Frame()
		{
			if (_inventory != null && !(Time.time < _nextStat))
			{
				_nextStat = Time.time + 60f;
				if (_skipped + _loaded != 0)
				{
					Plugin.Log.LogInfo((object)(string.Format("{0} {1:0} s: {2} rebuilds left out, {3} chests loaded new items", "ChestReloadSkip", 60f, _skipped, _loaded) + (_selfCheck.Value ? $"; self-check {_match} MATCH, {_different} DIFFERENT, {_checkFailed} not checked" : "")));
					_skipped = (_loaded = (_match = (_different = (_checkFailed = 0))));
				}
			}
		}
	}
	internal static class ErrorGuards
	{
		private static readonly FieldRef<Tameable, Character> TameCharacter = AccessTools.FieldRefAccess<Tameable, Character>("m_character");

		private static bool _fermenterOnce;

		private static bool _tameOnce;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			Guard(harmony, config, "AzuCraftyBoxesFermenterError", "Azumatt.AzuCraftyBoxes", new string[1] { "1.8.19" }, new string[1] { "648AD3CD" }, "AzuCraftyBoxes.Patches.SearchContainersAsWell", "Fermenter", "AzuCraftyBoxes 1.8.19: stops its fermenter error while there is no player.");
			Guard(harmony, config, "ValheimPlusTameHoverError", "org.bepinex.plugins.valheim_plus", new string[2] { "0.10.3.0", "10.4.0.0" }, new string[1] { "2294510E" }, "ValheimPlus.GameClasses.Tameable_GetHoverText_Patch", "Tame", "ValheimPlus 0.10.3.0 and 10.4.0.0: stops its tame hover error on objects without a creature.");
		}

		private static void Guard(Harmony harmony, ConfigFile config, string name, string guid, string[] versions, string[] code, string type, string prefix, string description)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			if (!config.Bind<bool>("3 - Fixes", name, true, description).Value || !Plugin.TargetMatches(name, guid, versions))
			{
				return;
			}
			Type type2 = AccessTools.TypeByName(type);
			MethodInfo methodInfo = ((type2 == null) ? null : AccessTools.Method(type2, "Postfix", (Type[])null, (Type[])null));
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)(name + ": " + type + ".Postfix not found, the fix stays off"));
			}
			else if (Plugin.CodeMatches(name, methodInfo, code))
			{
				try
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(ErrorGuards), prefix, (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)(name + ": on for " + guid + " " + string.Join(", ", versions)));
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)(name + ": could not patch " + type + ".Postfix, the fix stays off: " + ex.Message));
				}
			}
		}

		private static bool Fermenter()
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				return true;
			}
			if (!_fermenterOnce)
			{
				_fermenterOnce = true;
				Plugin.Log.LogInfo((object)"AzuCraftyBoxesFermenterError: skipped AzuCraftyBoxes' fermenter postfix, no local player, first time this session");
			}
			return false;
		}

		private static bool Tame(Tameable __0)
		{
			if ((Object)(object)__0 != (Object)null && (Object)(object)TameCharacter.Invoke(__0) != (Object)null)
			{
				return true;
			}
			if (!_tameOnce)
			{
				_tameOnce = true;
				Plugin.Log.LogInfo((object)("ValheimPlusTameHoverError: skipped ValheimPlus' tame hover text on " + (((Object)(object)__0 != (Object)null) ? ((Object)__0).name : "a removed object") + ", no creature, first time this session"));
			}
			return false;
		}
	}
	internal static class ExtraSlotsCountItems
	{
		private const string Name = "ExtraSlotsCountItems";

		private const string PostfixType = "ExtraSlots.Compatibility.BBHCompat+Inventory_CountItems_BBHFix";

		private static readonly string[] CheckedVersions = new string[1] { "1.2.21" };

		private static readonly string[] CheckedCode = new string[1] { "7A843ED5" };

		private static FieldRef<bool> _bbhOn;

		private static bool _logged;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			if (config.Bind<bool>("3 - Fixes", "ExtraSlotsCountItems", true, "ExtraSlots 1.2.21: skips its Bows Before Hoes count while that mod is not installed.").Value && Plugin.TargetMatches("ExtraSlotsCountItems", "shudnal.ExtraSlots", CheckedVersions))
			{
				Type type = AccessTools.TypeByName("ExtraSlots.Compatibility.BBHCompat+Inventory_CountItems_BBHFix");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Postfix", (Type[])null, (Type[])null));
				Type type2 = AccessTools.TypeByName("ExtraSlots.Compatibility.BBHCompat");
				FieldInfo fieldInfo = ((type2 == null) ? null : AccessTools.Field(type2, "isEnabled"));
				if (methodInfo == null || fieldInfo == null || !fieldInfo.IsStatic || fieldInfo.FieldType != typeof(bool))
				{
					Plugin.Log.LogWarning((object)"ExtraSlotsCountItems: ExtraSlots' item count postfix or its BowsBeforeHoes switch not found, the fix stays off");
				}
				else if (Plugin.CodeMatches("ExtraSlotsCountItems", methodInfo, CheckedCode))
				{
					_bbhOn = AccessTools.StaticFieldRefAccess<bool>(fieldInfo);
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(ExtraSlotsCountItems), "Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)("ExtraSlotsCountItems: on for ExtraSlots 1.2.21 (BowsBeforeHoes support " + (_bbhOn.Invoke() ? "on, so the postfix still runs" : "off") + ")"));
				}
			}
		}

		private static bool Prefix()
		{
			if (_bbhOn.Invoke())
			{
				return true;
			}
			if (!_logged)
			{
				_logged = true;
				Plugin.Log.LogInfo((object)"ExtraSlotsCountItems: skipped ExtraSlots' quiver count, BowsBeforeHoes is not there, first time this session");
			}
			return false;
		}
	}
	internal static class ExtraSlotsFindSlot
	{
		public const string TargetGuid = "shudnal.ExtraSlots";

		private const string Name = "ExtraSlotsFindSlot";

		private static readonly string[] CheckedVersions = new string[1] { "1.2.21" };

		private static readonly string[] CheckedCode = new string[1] { "9A10BCD7" };

		private static readonly Dictionary<string, string> CustomIds = new Dictionary<string, string>();

		private static FieldRef<object, string> _idOf;

		private static FieldInfo _slots;

		private static Type _slotType;

		private static bool _logged;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Expected O, but got Unknown
			if (config.Bind<bool>("3 - Fixes", "ExtraSlotsFindSlot", true, "ExtraSlots 1.2.21: finds slots for other mods without garbage.").Value && Plugin.TargetMatches("ExtraSlotsFindSlot", "shudnal.ExtraSlots", CheckedVersions))
			{
				Type type = AccessTools.TypeByName("ExtraSlots.API");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "FindSlot", new Type[1] { typeof(string) }, (Type[])null));
				Type type2 = AccessTools.TypeByName("ExtraSlots.Slots");
				_slotType = AccessTools.TypeByName("ExtraSlots.Slots+Slot");
				_slots = ((type2 == null) ? null : AccessTools.Field(type2, "slots"));
				FieldInfo fieldInfo = ((_slotType == null) ? null : AccessTools.Field(_slotType, "_id"));
				if (methodInfo == null || _slots == null || _slotType == null || fieldInfo == null || _slots.FieldType != _slotType.MakeArrayType() || methodInfo.ReturnType != _slotType || fieldInfo.FieldType != typeof(string))
				{
					Plugin.Log.LogWarning((object)"ExtraSlotsFindSlot: ExtraSlots' FindSlot, its slot list or a slot's id not found as checked, the fix stays off");
				}
				else if (Plugin.CodeMatches("ExtraSlotsFindSlot", methodInfo, CheckedCode))
				{
					_idOf = AccessTools.FieldRefAccess<string>(_slotType, "_id");
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(ExtraSlotsFindSlot), "Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)"ExtraSlotsFindSlot: on for ExtraSlots 1.2.21");
				}
			}
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			yield return new CodeInstruction(OpCodes.Ldsfld, (object)_slots);
			yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
			yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(ExtraSlotsFindSlot), "Find", (Type[])null, (Type[])null));
			yield return new CodeInstruction(OpCodes.Castclass, (object)_slotType);
			yield return new CodeInstruction(OpCodes.Ret, (object)null);
		}

		private static object Find(object[] slots, string id)
		{
			if (slots == null)
			{
				return null;
			}
			string text = null;
			foreach (object obj in slots)
			{
				if (obj != null)
				{
					string text2 = _idOf.Invoke(obj);
					if (text2 == id)
					{
						return Found(obj);
					}
					if (text == null)
					{
						text = CustomId(id);
					}
					if (text2 == text)
					{
						return Found(obj);
					}
				}
			}
			return null;
		}

		private static string CustomId(string id)
		{
			if (id == null)
			{
				return "Custom";
			}
			if (CustomIds.TryGetValue(id, out var value))
			{
				return value;
			}
			value = "Custom" + id;
			if (CustomIds.Count < 1024)
			{
				CustomIds[id] = value;
			}
			return value;
		}

		private static object Found(object slot)
		{
			if (!_logged)
			{
				_logged = true;
				Plugin.Log.LogInfo((object)("ExtraSlotsFindSlot: found slot " + _idOf.Invoke(slot) + " without building texts, first time this session"));
			}
			return slot;
		}
	}
	internal static class FastTeleport
	{
		private class Trip
		{
			public float Start;

			public float Black = -1f;

			public float Moved = -1f;

			public float Ready = -1f;

			public Vector3 From;

			public Vector3 To;

			public bool Portal;

			public bool LoadedAtStart;
		}

		private const string Name = "FastTeleport";

		internal const string KnownTeleportMods = "elg.QuickTeleport,muindor.QuickTeleport";

		private const float PastGameWaits = 8.01f;

		private const float GameCooldown = 2f;

		private const float MovedWithin = 1f;

		private static readonly string[] CheckedUpdateCode = new string[1] { "F2A68A0C" };

		private static readonly string[] CheckedTeleportCode = new string[1] { "A5F320E9" };

		private static readonly FieldRef<Player, float> Timer = AccessTools.FieldRefAccess<Player, float>("m_teleportTimer");

		private static readonly FieldRef<Player, Vector3> FromPos = AccessTools.FieldRefAccess<Player, Vector3>("m_teleportFromPos");

		private static readonly FieldRef<Player, Vector3> TargetPos = AccessTools.FieldRefAccess<Player, Vector3>("m_teleportTargetPos");

		private static readonly FieldRef<Player, bool> Distant = AccessTools.FieldRefAccess<Player, bool>("m_distantTeleport");

		private static readonly FieldRef<Player, float> Cooldown = AccessTools.FieldRefAccess<Player, float>("m_teleportCooldown");

		private static ConfigEntry<float> _fade;

		private static ConfigEntry<float> _cooldown;

		private static ConfigEntry<bool> _log;

		private static ConfigEntry<string> _otherModIDs;

		private static bool _loggedCooldown;

		private static Trip _trip;

		private const float AfterSeconds = 5f;

		private const float SlowFrameMs = 40f;

		private static float _afterUntil = -1f;

		private static float _afterWorst;

		private static int _afterSlow;

		private static int _afterFrames;

		private static double _afterSum;

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			//IL_01cb: Expected O, but got Unknown
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Expected O, but got Unknown
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Expected O, but got Unknown
			ConfigEntry<bool> obj = config.Bind<bool>("3 - Fixes", "FastTeleport", true, "Portals and teleports take only as long as loading the destination needs.");
			_fade = config.Bind<float>("3 - Fixes", "FastTeleportFadeSeconds", 0.25f, new ConfigDescription("Seconds of the fade to black and back (the game uses 1).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>()));
			_cooldown = config.Bind<float>("3 - Fixes", "FastTeleportCooldownSeconds", 0.5f, new ConfigDescription("Seconds after a trip before the next one works (the game uses 2).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			_log = config.Bind<bool>("9 - Debug", "LogTeleports", false, "A log line for each teleport with its timings.");
			_otherModIDs = config.Bind<string>("3 - Fixes", "FastTeleportOtherModIDs", "elg.QuickTeleport,muindor.QuickTeleport", "Comma-separated plugin IDs whose presence disables only GapCloser's FastTeleport. Defaults cover OdinPlus and Muindor QuickTeleport. Add IDs for other dedicated teleport timing mods. Empty disables this automatic check. Restart after changing it.");
			if (!obj.Value || !Plugin.GameMatches("FastTeleport"))
			{
				return;
			}
			string text = OtherTeleportMod(_otherModIDs.Value, Chainloader.PluginInfos.Keys);
			if (text != null)
			{
				Plugin.Log.LogInfo((object)("FastTeleport: off, " + text + " is loaded and takes priority; the saved FastTeleport setting is unchanged"));
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(Player), "UpdateTeleport", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(Player), "TeleportTo", new Type[3]
			{
				typeof(Vector3),
				typeof(Quaternion),
				typeof(bool)
			}, (Type[])null);
			if (Plugin.CodeMatches("FastTeleport", methodInfo, CheckedUpdateCode) && Plugin.CodeMatches("FastTeleport", methodInfo2, CheckedTeleportCode))
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(FastTeleport), "BeforeUpdate", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.Method(typeof(FastTeleport), "AfterUpdate", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(Hud), "GetFadeDuration", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(FastTeleport), "Fade", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(FastTeleport), "BeforeTeleport", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Plugin.Log.LogInfo((object)string.Format("{0}: on, fade {1} s, cooldown {2} s, log {3}", "FastTeleport", _fade.Value, _cooldown.Value, _log.Value));
			}
		}

		private static string OtherTeleportMod(string ids, IEnumerable<string> loaded)
		{
			HashSet<string> hashSet = new HashSet<string>(loaded, StringComparer.OrdinalIgnoreCase);
			string[] array = (ids ?? "").Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0 && !string.Equals(text, "onononoki.GapCloser", StringComparison.OrdinalIgnoreCase) && hashSet.Contains(text))
				{
					return text;
				}
			}
			return null;
		}

		private static void BeforeTeleport(Player __instance)
		{
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			float num = Cooldown.Invoke(__instance);
			if (!(num >= 2f) && !(num < _cooldown.Value))
			{
				Cooldown.Invoke(__instance) = 2f;
				if (!_loggedCooldown)
				{
					_loggedCooldown = true;
					Plugin.Log.LogInfo((object)string.Format("{0}: a teleport {1:0.00} s after the last trip let through (the game waits {2:0} s), first time this session", "FastTeleport", num, 2f));
				}
			}
		}

		private static void BeforeUpdate(Player __instance)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && ((Character)__instance).IsTeleporting())
			{
				if (_trip == null)
				{
					Vector3 val = TargetPos.Invoke(__instance);
					_trip = new Trip
					{
						Start = Time.time,
						From = FromPos.Invoke(__instance),
						To = val,
						Portal = Distant.Invoke(__instance),
						LoadedAtStart = ((Object)(object)ZNetScene.instance != (Object)null && ZNetScene.instance.IsAreaReady(val))
					};
				}
				Hud instance = Hud.instance;
				if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.m_loadingScreen == (Object)null) && !(instance.m_loadingScreen.alpha < 0.99f) && !(Timer.Invoke(__instance) >= 8.01f))
				{
					Timer.Invoke(__instance) = 8.01f;
					_trip.Black = Time.time - _trip.Start;
				}
			}
		}

		private static void AfterUpdate(Player __instance)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || _trip == null)
			{
				return;
			}
			float num = Time.time - _trip.Start;
			Vector3 position = ((Component)__instance).transform.position;
			if (_trip.Moved < 0f)
			{
				Vector2 val = new Vector2(position.x - _trip.To.x, position.z - _trip.To.z);
				if (((Vector2)(ref val)).magnitude < 1f)
				{
					_trip.Moved = num;
				}
			}
			if (_trip.Moved >= 0f && _trip.Ready < 0f && (Object)(object)ZNetScene.instance != (Object)null && ZNetScene.instance.IsAreaReady(_trip.To))
			{
				_trip.Ready = num;
			}
			if (!((Character)__instance).IsTeleporting())
			{
				Trip trip = _trip;
				_trip = null;
				if (_log.Value)
				{
					Plugin.Log.LogInfo((object)(string.Format("{0}: {1} of {2:0} m, destination {3}: ", "FastTeleport", trip.Portal ? "portal" : "teleport", Vector3.Distance(trip.From, trip.To), trip.LoadedAtStart ? "loaded already" : "not loaded") + string.Format("black {0}, moved {1}, area ready {2}, done {3:0.00} s{4}", Seconds(trip.Black), Seconds(trip.Moved), Seconds(trip.Ready), num, (num >= 15f) ? " (the game's 15 s fallback)" : "")));
					_afterUntil = Time.unscaledTime + 5f;
					_afterSlow = (_afterFrames = 0);
					_afterWorst = 0f;
					_afterSum = 0.0;
				}
			}
		}

		internal static void Frame()
		{
			if (!(_afterUntil < 0f))
			{
				float num = Time.unscaledDeltaTime * 1000f;
				_afterFrames++;
				_afterSum += num;
				if (num > 40f)
				{
					_afterSlow++;
				}
				if (num > _afterWorst)
				{
					_afterWorst = num;
				}
				if (!(Time.unscaledTime < _afterUntil))
				{
					_afterUntil = -1f;
					Plugin.Log.LogInfo((object)string.Format("{0}: the {1:0} s after arrival: {2} frames over {3:0} ms, worst {4:0} ms, average {5:0.0} ms", "FastTeleport", 5f, _afterSlow, 40f, _afterWorst, _afterSum / (double)_afterFrames));
				}
			}
		}

		private static string Seconds(float value)
		{
			if (!(value < 0f))
			{
				return $"{value:0.00} s";
			}
			return "never";
		}

		private static void Fade(Player player, ref float __result)
		{
			if ((Object)(object)player != (Object)null && ((Character)player).IsTeleporting() && !((Character)player).IsDead() && !player.IsSleeping())
			{
				__result = _fade.Value;
			}
		}
	}
	internal static class HiddenLights
	{
		private sealed class Entry
		{
			public Piece Piece;

			public Light[] Lights;

			public LightFlicker[] Flickers;

			public ParticleSystem[] Systems;

			public ParticleSystemRenderer[] Flames;

			public Bounds Bounds;

			public bool Hidden;

			public int Streak;

			public int SeenList;

			public readonly List<Light> OffLights = new List<Light>();

			public readonly List<LightFlicker> OffFlickers = new List<LightFlicker>();

			public readonly List<ParticleSystem> Paused = new List<ParticleSystem>();

			public readonly List<ParticleSystemRenderer> OffFlames = new List<ParticleSystemRenderer>();
		}

		private sealed class SameObject : IEqualityComparer<Piece>
		{
			public bool Equals(Piece a, Piece b)
			{
				return a == b;
			}

			public int GetHashCode(Piece p)
			{
				return RuntimeHelpers.GetHashCode(p);
			}
		}

		private const string Name = "HiddenLights";

		private const float Margin = 0.5f;

		private const float MarginScale = 0.02f;

		private const int HideAfter = 3;

		private const int MaxResultAge = 8;

		private const float StaleMeters = 0.75f;

		private const float StaleDegrees = 8f;

		private const float ListSeconds = 1f;

		private static ConfigEntry<bool> _enabled;

		private static readonly FieldRef<LightLod, float> BaseRange = AccessTools.FieldRefAccess<LightLod, float>("m_baseRange");

		private static readonly Dictionary<Piece, Entry> Cache = new Dictionary<Piece, Entry>(new SameObject());

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

		private static readonly List<Vector4> BoundsData = new List<Vector4>();

		private static readonly List<Piece> Stale = new List<Piece>();

		private static ComputeBuffer _bounds;

		private static ComputeBuffer _result;

		private static ComputeBuffer _rect;

		private static int _count;

		private static int _listVersion;

		private static int _sentList;

		private static int _sentFrame;

		private static float _nextList;

		private static bool _pending;

		private static bool _loggedStart;

		private static bool _loggedHide;

		private static Vector3 _sentPos;

		private static Quaternion _sentRot;

		public static int HiddenCount;

		private static bool _partOn = true;

		internal static bool PartOn => _partOn;

		internal static bool PartAvailable
		{
			get
			{
				if (_enabled != null && _enabled.Value)
				{
					return OcclusionCulling.CameraPartAvailable;
				}
				return false;
			}
		}

		internal static void SetPart(bool on)
		{
			_partOn = on;
			if (!on && HiddenCount > 0)
			{
				ShowAll();
			}
		}

		public static void Apply(Harmony harmony, ConfigFile config)
		{
			_enabled = config.Bind<bool>("3 - Fixes", "HiddenLights", true, "With OcclusionCulling On: lights of buildings whose whole light the walls hide go dark until they can be seen.");
			if (_enabled.Value)
			{
				Plugin.Log.LogInfo((object)string.Format("{0}: on, works while OcclusionCulling hides (margin {1} m plus {2:P0} of the distance, after {3} hidden results in a row)", "HiddenLights", 0.5f, 0.02f, 3));
			}
		}

		internal static void Frame()
		{
			if (_enabled == null || !_enabled.Value)
			{
				return;
			}
			if (!OcclusionCulling.HidingNow || !_partOn)
			{
				if (HiddenCount > 0)
				{
					ShowAll();
				}
				return;
			}
			foreach (Entry entry in Entries)
			{
				if (!entry.Hidden)
				{
					continue;
				}
				foreach (Light offLight in entry.OffLights)
				{
					if ((Object)(object)offLight != (Object)null && ((Behaviour)offLight).enabled)
					{
						((Behaviour)offLight).enabled = false;
					}
				}
			}
			if (!(Time.time < _nextList))
			{
				_nextList = Time.time + 1f;
				RebuildList();
			}
		}

		private static void RebuildList()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Expected O, but got Unknown
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknow