Decompiled source of ValPerfPatcher v1.0.32

plugins/ValPerfPatcher.dll

Decompiled 5 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HearthBelow.Digging;
using HearthBelow.VoxelMagic;
using Microsoft.CodeAnalysis;
using SoftReferenceableAssets;
using Splatform;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ValPerfPatcher")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.32.0")]
[assembly: AssemblyInformationalVersion("1.0.32+0748580fd365b77f64b6e7279a486314c4bf5a5d")]
[assembly: AssemblyProduct("ValPerfPatcher")]
[assembly: AssemblyTitle("ValPerfPatcher")]
[assembly: AssemblyVersion("1.0.32.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 ValPerfPatcher
{
	internal static class AdventureBackpacksItemCheckFix
	{
		private const string ItemExtensions = "AdventureBackpacks.Extensions.ItemDataExtensions";

		private const string PlayerExtensions = "AdventureBackpacks.Extensions.PlayerExtensions";

		private static readonly Dictionary<SharedData, bool> Cache = new Dictionary<SharedData, bool>();

		private static Func<ItemData, bool> _isBackpack;

		private static FieldRef<Humanoid, ItemData> _shoulder;

		private const string BackpackData = "AdventureBackpacks#AdventureBackpacks.Components.BackpackComponent";

		private const string OldBackpackData = "JotunnBackpacks#JotunnBackpacks.BackpackComponent";

		public static string Apply(Harmony harmony)
		{
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Expected O, but got Unknown
			//IL_014a: Expected O, but got Unknown
			Type type = Plugin.ModType("vapok.mods.adventurebackpacks", "AdventureBackpacks.Extensions.ItemDataExtensions");
			Type type2 = Plugin.ModType("vapok.mods.adventurebackpacks", "AdventureBackpacks.Extensions.PlayerExtensions");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "IsBackpack", new Type[1] { typeof(ItemData) }, (Type[])null));
			MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.DeclaredMethod(type2, "IsBackpackEquipped", new Type[1] { typeof(Player) }, (Type[])null));
			if (methodInfo == null || methodInfo.ReturnType != typeof(bool) || !methodInfo.IsStatic || methodInfo2 == null || methodInfo2.ReturnType != typeof(bool) || !methodInfo2.IsStatic)
			{
				return "Adventure Backpacks' backpack checks have changed since this fix was written";
			}
			if (AccessTools.Field(typeof(Humanoid), "m_shoulderItem")?.FieldType != typeof(ItemData))
			{
				return "the game's shoulder item slot has changed since this fix was written";
			}
			_shoulder = AccessTools.FieldRefAccess<Humanoid, ItemData>("m_shoulderItem");
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(AdventureBackpacksItemCheckFix), "ItemPrefix", (Type[])null), new HarmonyMethod(typeof(AdventureBackpacksItemCheckFix), "ItemPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_isBackpack = (Func<ItemData, bool>)Delegate.CreateDelegate(typeof(Func<ItemData, bool>), methodInfo);
			bool flag = true;
			MethodInfo methodInfo3 = AccessTools.Method(typeof(Inventory), "GetEquippedItems", Type.EmptyTypes, (Type[])null);
			try
			{
				foreach (CodeInstruction originalInstruction in PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo2, (ILGenerator)null))
				{
					if (CodeInstructionExtensions.Calls(originalInstruction, methodInfo3))
					{
						flag = false;
					}
				}
			}
			catch (Exception)
			{
				flag = false;
			}
			if (!flag)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(AdventureBackpacksItemCheckFix), "EquippedPrefix", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Game), "Shutdown", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AdventureBackpacksItemCheckFix), "Clear", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool ItemPrefix(ItemData item, ref bool __result, out bool __state)
		{
			__state = false;
			SharedData val = item?.m_shared;
			if (val == null)
			{
				return true;
			}
			if (Cache.TryGetValue(val, out var value))
			{
				__result = value || HasBackpackData(item);
				return false;
			}
			__state = !HasBackpackData(item);
			return true;
		}

		private static void ItemPostfix(ItemData item, bool __result, bool __state)
		{
			if (__state && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				if (Cache.Count > 4096)
				{
					Cache.Clear();
				}
				Cache[item.m_shared] = __result;
			}
		}

		private static bool HasBackpackData(ItemData item)
		{
			Dictionary<string, string> customData = item.m_customData;
			if (customData != null && customData.Count > 0)
			{
				if (!customData.ContainsKey("AdventureBackpacks#AdventureBackpacks.Components.BackpackComponent"))
				{
					return customData.ContainsKey("JotunnBackpacks#JotunnBackpacks.BackpackComponent");
				}
				return true;
			}
			return false;
		}

		private static bool EquippedPrefix(Player player, ref bool __result)
		{
			__result = false;
			if ((Object)(object)player == (Object)null)
			{
				return false;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return false;
			}
			ItemData val = _shoulder.Invoke((Humanoid)(object)player);
			if (val != null && _isBackpack(val))
			{
				__result = true;
				return false;
			}
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem != null && allItem.m_equipped && _isBackpack(allItem))
				{
					__result = true;
					return false;
				}
			}
			return false;
		}

		private static void Clear()
		{
			Cache.Clear();
		}
	}
	internal static class AdventureBackpacksProxyFix
	{
		public const string TargetGuid = "vapok.mods.adventurebackpacks";

		private const string Outer = "AdventureBackpacks.Patches.ContainerPatches";

		private const string ProxyName = "AB_BackpackProxy";

		private static readonly string[] Patches = new string[4] { "ZNetViewIsOwnerPatch", "ZNetViewInvokeRpcPatch", "ZNetViewInvokeRpcWithTargetPatch", "ZNetViewAwakePatch" };

		private static readonly Dictionary<int, bool> Cache = new Dictionary<int, bool>();

		private static int _replaced;

		public static string Apply(Harmony harmony)
		{
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			Type type = Plugin.ModType("vapok.mods.adventurebackpacks", "AdventureBackpacks.Patches.ContainerPatches");
			if (type == null)
			{
				return "Adventure Backpacks' container patches were not found";
			}
			int num = 0;
			int num2 = 0;
			string[] patches = Patches;
			foreach (string text in patches)
			{
				Type type2 = AccessTools.Inner(type, text);
				MethodInfo methodInfo = ((type2 == null) ? null : AccessTools.Method(type2, "Prefix", (Type[])null, (Type[])null));
				if (!(methodInfo == null) && !(methodInfo.ReturnType != typeof(bool)))
				{
					num2++;
					int replaced = _replaced;
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(AdventureBackpacksProxyFix), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
					if (_replaced == replaced + 1)
					{
						num++;
					}
					else
					{
						harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)3, harmony.Id);
					}
				}
			}
			if (num == 0)
			{
				return "Adventure Backpacks' backpack check has changed since this fix was written";
			}
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Game), "Shutdown", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AdventureBackpacksProxyFix), "Clear", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (num != num2)
			{
				return $"only {num} of {num2} checks matched; the rest are left as they were";
			}
			return null;
		}

		public static bool IsProxy(GameObject go)
		{
			int instanceID = ((Object)go).GetInstanceID();
			if (!Cache.TryGetValue(instanceID, out var value))
			{
				if (Cache.Count > 200000)
				{
					Cache.Clear();
				}
				value = ((Object)go).name.StartsWith("AB_BackpackProxy", StringComparison.Ordinal);
				Cache[instanceID] = value;
			}
			return value;
		}

		private static void Clear()
		{
			Cache.Clear();
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo objB = AccessTools.PropertyGetter(typeof(Object), "name");
			MethodInfo objB2 = AccessTools.Method(typeof(string), "StartsWith", new Type[1] { typeof(string) }, (Type[])null);
			MethodInfo operand = AccessTools.Method(typeof(AdventureBackpacksProxyFix), "IsProxy", (Type[])null, (Type[])null);
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int num = -1;
			int num2 = 0;
			for (int i = 0; i + 2 < list.Count; i++)
			{
				if ((list[i].opcode == OpCodes.Callvirt || list[i].opcode == OpCodes.Call) && object.Equals(list[i].operand, objB) && list[i + 1].opcode == OpCodes.Ldstr && (string)list[i + 1].operand == "AB_BackpackProxy" && (list[i + 2].opcode == OpCodes.Callvirt || list[i + 2].opcode == OpCodes.Call) && object.Equals(list[i + 2].operand, objB2))
				{
					num = i;
					num2++;
				}
			}
			if (num2 != 1 || list[num + 1].labels.Count > 0 || list[num + 2].labels.Count > 0)
			{
				return list;
			}
			list[num].opcode = OpCodes.Call;
			list[num].operand = operand;
			list.RemoveRange(num + 1, 2);
			_replaced++;
			return list;
		}
	}
	internal static class AnimSyncDeadbandFix
	{
		private const float StepSize = 0.1f;

		private const int Salt = 438569;

		private static int _forwardKey;

		private static int _sidewayKey;

		private static int _turnKey;

		private static readonly ConditionalWeakTable<ZSyncAnimation, object> Players = new ConditionalWeakTable<ZSyncAnimation, object>();

		private static readonly object Yes = new object();

		private static readonly object No = new object();

		private static MethodInfo _zdoSet;

		private static ManualLogSource _log;

		private static int _skipped;

		private static int _sent;

		private static float _nextReport;

		private static bool _reported;

		private static bool _redirected;

		public static string Apply(Harmony harmony, ManualLogSource log)
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			_log = log;
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZSyncAnimation), "SetFloat", new Type[2]
			{
				typeof(int),
				typeof(float)
			}, (Type[])null);
			_zdoSet = AccessTools.Method(typeof(ZDO), "Set", new Type[2]
			{
				typeof(int),
				typeof(float)
			}, (Type[])null);
			if (methodInfo == null || _zdoSet == null)
			{
				return "ZSyncAnimation.SetFloat has changed since this fix was written";
			}
			_forwardKey = 438569 + ZSyncAnimation.GetHash("forward_speed");
			_sidewayKey = 438569 + ZSyncAnimation.GetHash("sideway_speed");
			_turnKey = 438569 + ZSyncAnimation.GetHash("turn_speed");
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(AnimSyncDeadbandFix), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			if (!_redirected)
			{
				return "ZSyncAnimation.SetFloat no longer looks as it did when this fix was written";
			}
			return null;
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int index = -1;
			int num = 0;
			bool flag = false;
			for (int i = 0; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(list[i], _zdoSet))
				{
					index = i;
					num++;
				}
				if (CodeInstructionExtensions.LoadsConstant(list[i], 438569L))
				{
					flag = true;
				}
			}
			if (num != 1 || !flag)
			{
				return list;
			}
			CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
			CodeInstructionExtensions.MoveLabelsTo(list[index], val);
			list[index] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(AnimSyncDeadbandFix), "Write", (Type[])null, (Type[])null));
			list.Insert(index, val);
			_redirected = true;
			return list;
		}

		private static void Write(ZDO zdo, int key, float value, ZSyncAnimation anim)
		{
			if ((key == _forwardKey || key == _sidewayKey || key == _turnKey) && !IsPlayer(anim))
			{
				if (value > -0.1f && value < 0.1f)
				{
					value = 0f;
				}
				float num = zdo.GetFloat(key, 0f);
				bool flag = value != num && value != 0f && Mathf.Abs(value - num) < 0.1f;
				if (!_reported && value != num)
				{
					Count(flag);
				}
				if (flag)
				{
					return;
				}
			}
			zdo.Set(key, value);
		}

		private static void Count(bool skipped)
		{
			if (skipped)
			{
				_skipped++;
			}
			else
			{
				_sent++;
			}
			if (!(Time.time < _nextReport))
			{
				if (_nextReport > 0f)
				{
					_log.LogInfo((object)$"Creature walk and turn speeds: {_sent} sent, {_skipped} skipped in the first minute with creatures nearby.");
					_reported = true;
				}
				_skipped = (_sent = 0);
				_nextReport = Time.time + 60f;
			}
		}

		private static bool IsPlayer(ZSyncAnimation anim)
		{
			if (!Players.TryGetValue(anim, out var value))
			{
				value = (((Object)(object)((Component)anim).GetComponent<Player>() != (Object)null) ? Yes : No);
				Players.Add(anim, value);
			}
			return value == Yes;
		}
	}
	internal static class AutomaticFuelSmelterScanFix
	{
		public const string TargetGuid = "TastyChickenLegs.AutomaticFuel";

		private static readonly List<Smelter> Known = new List<Smelter>();

		private static readonly HashSet<Smelter> KnownSet = new HashSet<Smelter>();

		private static ZNetScene _scannedFor;

		private static MethodInfo _find;

		private static bool _byRef;

		public static string Apply(Harmony harmony)
		{
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			Type type = Plugin.ModType("TastyChickenLegs.AutomaticFuel", "AutomaticFuel.Patches.Smelters+BlastFurnacePatch", fallback: false) ?? Plugin.ModType("TastyChickenLegs.AutomaticFuel", "AutomaticFuel.GameClasses.Smelters+BlastFurnacePatch");
			MethodInfo methodInfo = ((type == null) ? null : (type.GetMethod("Prefix", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Smelter) }, null) ?? type.GetMethod("Prefix", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Smelter).MakeByRefType() }, null)));
			MethodInfo methodInfo2 = AccessTools.Method(typeof(Resources), "FindObjectsOfTypeAll", Type.EmptyTypes, (Type[])null);
			if (methodInfo == null || !methodInfo.IsStatic || methodInfo2 == null || !methodInfo2.IsGenericMethodDefinition)
			{
				return "AutomaticFuel's smelter setup has changed since this fix was written";
			}
			_find = methodInfo2.MakeGenericMethod(typeof(Smelter));
			List<CodeInstruction> originalInstructions;
			try
			{
				originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null);
			}
			catch (Exception ex)
			{
				return "could not read AutomaticFuel's smelter setup (" + ex.Message + ")";
			}
			int num = 0;
			foreach (CodeInstruction item in originalInstructions)
			{
				if (CodeInstructionExtensions.Calls(item, _find))
				{
					num++;
				}
			}
			switch (num)
			{
			case 0:
				return "already done by AutomaticFuel " + Plugin.VersionOf("TastyChickenLegs.AutomaticFuel") + " itself (it no longer searches for smelters)";
			default:
				return $"AutomaticFuel's smelter setup now searches for smelters {num} times instead of once";
			case 1:
				_byRef = methodInfo.GetParameters()[0].ParameterType.IsByRef;
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(AutomaticFuelSmelterScanFix), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				return null;
			}
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo replacement = AccessTools.Method(typeof(AutomaticFuelSmelterScanFix), "Smelters", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, _find))
				{
					yield return CodeInstructionExtensions.MoveBlocksFrom(CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), instruction), instruction);
					if (_byRef)
					{
						yield return new CodeInstruction(OpCodes.Ldind_Ref, (object)null);
					}
					yield return new CodeInstruction(OpCodes.Call, (object)replacement);
				}
				else
				{
					yield return instruction;
				}
			}
		}

		private static Smelter[] Smelters(Smelter self)
		{
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return Resources.FindObjectsOfTypeAll<Smelter>();
			}
			if ((Object)(object)instance != (Object)(object)_scannedFor)
			{
				_scannedFor = instance;
				Known.Clear();
				KnownSet.Clear();
				Smelter[] array = Resources.FindObjectsOfTypeAll<Smelter>();
				foreach (Smelter item in array)
				{
					if (KnownSet.Add(item))
					{
						Known.Add(item);
					}
				}
			}
			else
			{
				for (int num = Known.Count - 1; num >= 0; num--)
				{
					if (!((Object)(object)Known[num] != (Object)null))
					{
						KnownSet.Remove(Known[num]);
						Known.RemoveAt(num);
					}
				}
				if ((Object)(object)self != (Object)null && KnownSet.Add(self))
				{
					Known.Add(self);
				}
			}
			return Known.ToArray();
		}
	}
	internal static class AutomaticFuelTorchSwitchFix
	{
		public static string Apply(Harmony harmony)
		{
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			Type type = Plugin.ModType("TastyChickenLegs.AutomaticFuel", "AutomaticFuel.TastyUtils");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "ToggleFireplaceMode", new Type[1] { typeof(Fireplace) }, (Type[])null));
			if (methodInfo == null || !methodInfo.IsStatic)
			{
				return "AutomaticFuel's torch switch has changed since this fix was written";
			}
			List<CodeInstruction> originalInstructions;
			try
			{
				originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null);
			}
			catch (Exception ex)
			{
				return "could not read AutomaticFuel's torch switch (" + ex.Message + ")";
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ZNetView), "IsOwner", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(ZNetView), "ClaimOwnership", (Type[])null, (Type[])null);
			bool flag = false;
			foreach (CodeInstruction item in originalInstructions)
			{
				if (CodeInstructionExtensions.Calls(item, methodInfo3))
				{
					return "already done by AutomaticFuel " + Plugin.VersionOf("TastyChickenLegs.AutomaticFuel") + " itself (it takes ownership of the fire)";
				}
				if (item.operand is MethodInfo methodInfo4 && methodInfo4.DeclaringType == typeof(ZNetView) && methodInfo4.Name == "InvokeRPC")
				{
					return "already done by AutomaticFuel " + Plugin.VersionOf("TastyChickenLegs.AutomaticFuel") + " itself (it asks the fire's owner to switch it)";
				}
				if (CodeInstructionExtensions.Calls(item, methodInfo2))
				{
					flag = true;
				}
			}
			if (!flag)
			{
				return "already done by AutomaticFuel " + Plugin.VersionOf("TastyChickenLegs.AutomaticFuel") + " itself (it no longer needs ownership to switch a fire)";
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(AutomaticFuelTorchSwitchFix), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static void Prefix(Fireplace fireplace)
		{
			if (!((Object)(object)fireplace == (Object)null))
			{
				ZNetView component = ((Component)fireplace).GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.IsValid() && !component.IsOwner())
				{
					component.ClaimOwnership();
				}
			}
		}
	}
	internal static class AzuEpiBackpackFix
	{
		public const string TargetGuid = "Azumatt.AzuExtendedPlayerInventory";

		private const string TypeName = "AzuEPI.Game.Compatibility.AdvBackpacks.AdvBackpacksCompat";

		private static readonly Dictionary<SharedData, bool> Cache = new Dictionary<SharedData, bool>();

		private const string BackpackData = "AdventureBackpacks#AdventureBackpacks.Components.BackpackComponent";

		private const string OldBackpackData = "JotunnBackpacks#JotunnBackpacks.BackpackComponent";

		public static string Apply(Harmony harmony)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_0097: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Expected O, but got Unknown
			Type type = Plugin.ModType("Azumatt.AzuExtendedPlayerInventory", "AzuEPI.Game.Compatibility.AdvBackpacks.AdvBackpacksCompat");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "IsBackpackItem", new Type[1] { typeof(ItemData) }, (Type[])null));
			if (methodInfo == null || methodInfo.ReturnType != typeof(bool))
			{
				return "AzuExtendedPlayerInventory's backpack check has changed since this fix was written";
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(AzuEpiBackpackFix), "Prefix", (Type[])null), new HarmonyMethod(typeof(AzuEpiBackpackFix), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Game), "Shutdown", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AzuEpiBackpackFix), "Clear", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool Prefix(ItemData item, ref bool __result, out bool __state)
		{
			__state = false;
			SharedData val = item?.m_shared;
			if (val == null)
			{
				return true;
			}
			if (Cache.TryGetValue(val, out var value))
			{
				if (!value && HasBackpackData(item))
				{
					return true;
				}
				__result = value;
				return false;
			}
			__state = !HasBackpackData(item);
			return true;
		}

		private static bool HasBackpackData(ItemData item)
		{
			Dictionary<string, string> customData = item.m_customData;
			if (customData != null && customData.Count > 0)
			{
				if (!customData.ContainsKey("AdventureBackpacks#AdventureBackpacks.Components.BackpackComponent"))
				{
					return customData.ContainsKey("JotunnBackpacks#JotunnBackpacks.BackpackComponent");
				}
				return true;
			}
			return false;
		}

		private static void Postfix(ItemData item, bool __result, bool __state)
		{
			if (__state && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				if (Cache.Count > 4096)
				{
					Cache.Clear();
				}
				Cache[item.m_shared] = __result;
			}
		}

		private static void Clear()
		{
			Cache.Clear();
		}
	}
	internal static class AzuEpiPreviewRefreshFix
	{
		private const string Ns = "AzuEPI.Game.PlayerPreview.";

		private static Action _tryRefresh;

		public static string Apply(Harmony harmony)
		{
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			Type type = Plugin.ModType("Azumatt.AzuExtendedPlayerInventory", "AzuEPI.Game.PlayerPreview.PlayerPreviewManager");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "TryRefresh", Type.EmptyTypes, (Type[])null));
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Humanoid), "EquipItem", new Type[2]
			{
				typeof(ItemData),
				typeof(bool)
			}, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(typeof(Humanoid), "UnequipItem", new Type[2]
			{
				typeof(ItemData),
				typeof(bool)
			}, (Type[])null);
			MethodInfo methodInfo4 = TheirPostfix(methodInfo2, "PreviewInstantRefresh_EquipItem", methodInfo);
			MethodInfo methodInfo5 = TheirPostfix(methodInfo3, "PreviewInstantRefresh_UnequipItem", methodInfo);
			if (methodInfo == null || !methodInfo.IsStatic || methodInfo2 == null || methodInfo3 == null || methodInfo4 == null || methodInfo5 == null)
			{
				return "AzuExtendedPlayerInventory's preview refresh has changed since this fix was written";
			}
			_tryRefresh = AccessTools.MethodDelegate<Action>(methodInfo, (object)null, true);
			HarmonyMethod val = new HarmonyMethod(typeof(AzuEpiPreviewRefreshFix), "Postfix", (Type[])null);
			harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Unpatch((MethodBase)methodInfo2, methodInfo4);
			harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Unpatch((MethodBase)methodInfo3, methodInfo5);
			return null;
		}

		private static MethodInfo TheirPostfix(MethodBase target, string typeName, MethodInfo tryRefresh)
		{
			if (target == null || tryRefresh == null)
			{
				return null;
			}
			Patches patchInfo = Harmony.GetPatchInfo(target);
			object obj;
			if (patchInfo == null)
			{
				obj = null;
			}
			else
			{
				Patch? obj2 = ((IEnumerable<Patch>)patchInfo.Postfixes).FirstOrDefault((Func<Patch, bool>)((Patch p) => p.owner == "Azumatt.AzuExtendedPlayerInventory" && p.PatchMethod.DeclaringType?.FullName == "AzuEPI.Game.PlayerPreview." + typeName));
				obj = ((obj2 != null) ? obj2.PatchMethod : null);
			}
			MethodInfo methodInfo = (MethodInfo)obj;
			if (methodInfo == null || methodInfo.GetParameters().Length != 0)
			{
				return null;
			}
			List<CodeInstruction> list = (from c in PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null)
				where c.opcode != OpCodes.Nop
				select c).ToList();
			if (list.Count != 2 || !CodeInstructionExtensions.Calls(list[0], tryRefresh) || !(list[1].opcode == OpCodes.Ret))
			{
				return null;
			}
			return methodInfo;
		}

		private static void Postfix(Humanoid __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				_tryRefresh();
			}
		}
	}
	internal static class AzuEpiVanityCacheFix
	{
		private const string Ns = "AzuEPI.Game.Panels.Vanity.";

		private const int MaxEntries = 2048;

		private static IDictionary _custom;

		private static IDictionary _weapon;

		public static string Apply(Harmony harmony)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			Type type = Plugin.ModType("Azumatt.AzuExtendedPlayerInventory", "AzuEPI.Game.Panels.Vanity.CustomSlotVanity");
			Type type2 = Plugin.ModType("Azumatt.AzuExtendedPlayerInventory", "AzuEPI.Game.Panels.Vanity.WeaponVanity");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "ForItem", new Type[1] { typeof(ItemData) }, (Type[])null));
			MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.DeclaredMethod(type2, "GetOrAdd", new Type[1] { typeof(SharedData) }, (Type[])null));
			_custom = Table(type);
			_weapon = Table(type2);
			if (methodInfo == null || methodInfo2 == null || _custom == null || _weapon == null)
			{
				return "AzuExtendedPlayerInventory's vanity lookups have changed since this fix was written";
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(AzuEpiVanityCacheFix), "CustomPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(AzuEpiVanityCacheFix), "WeaponPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static IDictionary Table(Type type)
		{
			FieldInfo fieldInfo = ((type == null) ? null : AccessTools.DeclaredField(type, "_byShared"));
			if (fieldInfo == null || !fieldInfo.IsStatic || !fieldInfo.FieldType.IsGenericType || fieldInfo.FieldType.GetGenericArguments()[0] != typeof(SharedData))
			{
				return null;
			}
			return fieldInfo.GetValue(null) as IDictionary;
		}

		private static void CustomPrefix()
		{
			if (_custom.Count > 2048)
			{
				_custom.Clear();
			}
		}

		private static void WeaponPrefix()
		{
			if (_weapon.Count > 2048)
			{
				_weapon.Clear();
			}
		}
	}
	internal static class BetterMapLocationPinsFix
	{
		public const string TargetGuid = "xtav1m.BetterMap";

		private const float GameInterval = 5f;

		private static FieldRef<Minimap, float> _timer;

		public static string Apply(Harmony harmony)
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			Type type = Plugin.ModType("xtav1m.BetterMap", "BetterMap.Scripts.Pins.NamedPinPatches");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "Minimap_UpdateLocationPins_Postfix", Type.EmptyTypes, (Type[])null));
			Type type2 = Plugin.ModType("xtav1m.BetterMap", "BetterMap.Scripts.Pins.NamedPins");
			FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(Minimap), "m_updateLocationsTimer");
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Minimap), "UpdateLocationPins", new Type[1] { typeof(float) }, (Type[])null);
			if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(void) || type2 == null || AccessTools.DeclaredMethod(type2, "NameLocationPins", Type.EmptyTypes, (Type[])null) == null)
			{
				return "BetterMap's trader pin naming has changed since this fix was written";
			}
			if (fieldInfo == null || fieldInfo.FieldType != typeof(float) || methodInfo2 == null)
			{
				return "the game's location pin update has changed since this fix was written";
			}
			if (!HasTimerReset(methodInfo2))
			{
				return "the game's location pin update no longer resets its timer to 5 seconds";
			}
			_timer = AccessTools.FieldRefAccess<Minimap, float>(fieldInfo);
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BetterMapLocationPinsFix), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool HasTimerReset(MethodInfo update)
		{
			List<CodeInstruction> originalInstructions;
			try
			{
				originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)update, (ILGenerator)null);
			}
			catch
			{
				return false;
			}
			for (int i = 0; i + 1 < originalInstructions.Count; i++)
			{
				if (originalInstructions[i].opcode == OpCodes.Ldc_R4 && originalInstructions[i].operand is float num && num == 5f && originalInstructions[i + 1].opcode == OpCodes.Stfld && originalInstructions[i + 1].operand is FieldInfo { Name: "m_updateLocationsTimer" })
				{
					return true;
				}
			}
			return false;
		}

		private static bool Prefix()
		{
			Minimap instance = Minimap.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return true;
			}
			return _timer.Invoke(instance) >= 5f;
		}
	}
	internal static class BetterMapVehicleResetFix
	{
		private static IDictionary _tracked;

		private static IDictionary _wanted;

		public static string Apply(Harmony harmony)
		{
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			Type type = Plugin.ModType("xtav1m.BetterMap", "BetterMap.Scripts.Vehicles.VehicleTracker");
			FieldInfo fieldInfo = ((type == null) ? null : AccessTools.DeclaredField(type, "_tracked"));
			FieldInfo fieldInfo2 = ((type == null) ? null : AccessTools.DeclaredField(type, "_wanted"));
			if (fieldInfo == null || fieldInfo2 == null || !fieldInfo.IsStatic || !fieldInfo2.IsStatic || !(fieldInfo.GetValue(null) is IDictionary tracked) || !(fieldInfo2.GetValue(null) is IDictionary wanted) || fieldInfo.FieldType.GetGenericArguments().Length != 2 || fieldInfo.FieldType.GetGenericArguments()[0] != typeof(ZDOID))
			{
				return "BetterMap's boat tracker has changed since this fix was written";
			}
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Game), "Start", Type.EmptyTypes, (Type[])null);
			if (methodInfo == null)
			{
				return "the game's world start has changed since this fix was written";
			}
			_tracked = tracked;
			_wanted = wanted;
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(BetterMapVehicleResetFix), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static void Postfix()
		{
			_tracked.Clear();
			_wanted.Clear();
		}
	}
	internal static class BiomeMapParallelFix
	{
		private delegate Biome BiomeAt(float wx, float wy);

		private delegate float HeightAt(Biome biome, float wx, float wy);

		private delegate float StateHeightAt(Biome biome, float wx, float wy, out Color mask);

		private static ManualLogSource _log;

		private static MethodInfo _getBiome;

		private static MethodInfo _getBiomeHeight;

		private static MethodInfo _generatePoints;

		private static MethodInfo _stateBiome;

		private static MethodInfo _stateHeight;

		private static FieldRef<AltBiomeWorldData, World> _dataWorld;

		private static string _reportedStandDown;

		public static string Apply(Harmony harmony, ManualLogSource log)
		{
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Expected O, but got Unknown
			_log = log;
			_generatePoints = AccessTools.DeclaredMethod(typeof(AltBiomeWorldData), "GenerateBiomePoints", new Type[1] { typeof(World) }, (Type[])null);
			_getBiome = AccessTools.DeclaredMethod(typeof(WorldGenerator), "GetBiome", new Type[4]
			{
				typeof(float),
				typeof(float),
				typeof(float),
				typeof(bool)
			}, (Type[])null);
			_getBiomeHeight = AccessTools.DeclaredMethod(typeof(WorldGenerator), "GetBiomeHeight", new Type[6]
			{
				typeof(Biome),
				typeof(float),
				typeof(float),
				typeof(Color).MakeByRefType(),
				typeof(bool),
				typeof(bool)
			}, (Type[])null);
			FieldInfo fieldInfo = AccessTools.Field(typeof(AltBiomeWorldData), "m_world");
			int num = _generatePoints?.GetMethodBody()?.GetILAsByteArray()?.Length ?? (-1);
			if (_generatePoints == null || _getBiome == null || _getBiomeHeight == null || fieldInfo?.FieldType != typeof(World) || num != 294)
			{
				return $"the game's biome map code has changed since this fix was written (size {num})";
			}
			_dataWorld = AccessTools.FieldRefAccess<AltBiomeWorldData, World>("m_world");
			if (RiverheimLoadFix.Resolve())
			{
				Type stateType = RiverheimLoadFix._stateType;
				_stateBiome = stateType.GetMethod("GetBiome", BindingFlags.Instance | BindingFlags.Public, null, new Type[2]
				{
					typeof(float),
					typeof(float)
				}, null);
				_stateHeight = stateType.GetMethod("GetHeight", BindingFlags.Instance | BindingFlags.Public, null, new Type[4]
				{
					typeof(Biome),
					typeof(float),
					typeof(float),
					typeof(Color).MakeByRefType()
				}, null);
				if (_stateBiome?.ReturnType != typeof(Biome) || _stateHeight?.ReturnType != typeof(float))
				{
					_stateBiome = (_stateHeight = null);
					log.LogWarning((object)"Biome map: Worldhalla's map lookups have changed since this fix was written; Worldhalla worlds (Riverheim) are filled the usual way.");
				}
			}
			else if (RiverheimLoadFix._worldhalla != null)
			{
				log.LogWarning((object)"Biome map: Worldhalla's code has changed since this fix was written; Worldhalla worlds (Riverheim) are filled the usual way.");
			}
			harmony.Patch((MethodBase)_generatePoints, new HarmonyMethod(typeof(BiomeMapParallelFix), "GeneratePointsPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static string ParallelBlocker(WorldGenerator gen, out object worldState)
		{
			worldState = null;
			if (gen == null)
			{
				return "no world generator";
			}
			if (RiverheimLoadFix._worldhalla != null)
			{
				if (RiverheimLoadFix._getState == null)
				{
					return "Worldhalla's code has changed since this fix was written";
				}
				worldState = RiverheimLoadFix._getState(gen);
				if (worldState != null && _stateBiome == null)
				{
					return "Worldhalla's map lookups have changed since this fix was written";
				}
			}
			bool customWorld = worldState != null;
			string text = OtherHooks(_getBiome, customWorld) ?? OtherHooks(_getBiomeHeight, customWorld) ?? OtherHooks(_generatePoints, customWorld: false, self: true);
			if (text != null)
			{
				return text + " also hooks the biome lookups";
			}
			return null;
		}

		private static string OtherHooks(MethodBase method, bool customWorld, bool self = false)
		{
			Patches patchInfo = Harmony.GetPatchInfo(method);
			if (patchInfo == null)
			{
				return null;
			}
			foreach (Patch prefix in patchInfo.Prefixes)
			{
				if (!Expected(prefix.owner, self, prefix: true))
				{
					return prefix.owner;
				}
			}
			ReadOnlyCollection<Patch>[] array = new ReadOnlyCollection<Patch>[2] { patchInfo.Postfixes, patchInfo.Finalizers };
			for (int i = 0; i < array.Length; i++)
			{
				foreach (Patch item in array[i])
				{
					if (!Expected(item.owner, self, prefix: false))
					{
						return item.owner;
					}
				}
			}
			if (self || !customWorld)
			{
				foreach (Patch transpiler in patchInfo.Transpilers)
				{
					if (!Expected(transpiler.owner, self: false, prefix: false))
					{
						return transpiler.owner;
					}
				}
			}
			return null;
		}

		private static bool Expected(string owner, bool self, bool prefix)
		{
			if (owner != null && owner.StartsWith("valheimmods.ValPerfMonitor", StringComparison.Ordinal))
			{
				return true;
			}
			if (self)
			{
				return owner == "valheimmods.ValPerfPatcher";
			}
			if (prefix)
			{
				return owner == "dev.gurebu.worldhalla";
			}
			return false;
		}

		private static bool GeneratePointsPrefix(World world)
		{
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Expected O, but got Unknown
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			WorldGenerator gen = WorldGenerator.instance;
			string text;
			object worldState;
			try
			{
				text = ParallelBlocker(gen, out worldState);
			}
			catch (Exception ex)
			{
				text = ex.GetType().Name + ": " + ex.Message;
				worldState = null;
			}
			if (text != null)
			{
				if (_reportedStandDown != text)
				{
					_log.LogInfo((object)("Biome map: filled the usual way (" + text + ")."));
				}
				_reportedStandDown = text;
				return true;
			}
			_reportedStandDown = null;
			BiomeAt biomeAt;
			HeightAt heightAt;
			try
			{
				if (worldState != null)
				{
					biomeAt = (BiomeAt)Delegate.CreateDelegate(typeof(BiomeAt), worldState, _stateBiome);
					StateHeightAt stateHeight = (StateHeightAt)Delegate.CreateDelegate(typeof(StateHeightAt), worldState, _stateHeight);
					heightAt = (Biome biome, float x, float y) => stateHeight(biome, x, y, out var _);
				}
				else
				{
					biomeAt = (float x, float y) => gen.GetBiome(x, y, 0.02f, false);
					Color val2 = default(Color);
					heightAt = (Biome biome, float x, float y) => gen.GetBiomeHeight(biome, x, y, ref val2, false, true);
				}
			}
			catch (Exception ex2)
			{
				_log.LogInfo((object)("Biome map: filled the usual way (map lookups: " + ex2.GetType().Name + ": " + ex2.Message + ")."));
				return true;
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			AltBiomeWorldData val = new AltBiomeWorldData(2048);
			val.dt = DateTime.Now;
			BiomeIndex[,] biomes = val.PointBiomes;
			float[,] heights = val.PointHeights;
			BiomeIndex ocean = BiomeHelpers.ToBiomeIndex((Biome)256);
			try
			{
				Parallel.For(0, 2048, delegate(int i)
				{
					//IL_0011: 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_002e: Unknown result type (might be due to invalid IL or missing references)
					//IL_006a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0070: Unknown result type (might be due to invalid IL or missing references)
					//IL_0076: Unknown result type (might be due to invalid IL or missing references)
					//IL_007b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0085: Unknown result type (might be due to invalid IL or missing references)
					//IL_0087: Unknown result type (might be due to invalid IL or missing references)
					//IL_008c: Unknown result type (might be due to invalid IL or missing references)
					//IL_009f: Unknown result type (might be due to invalid IL or missing references)
					//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
					//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
					//IL_0046: 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)
					float y = AltBiomeWorldData.MapSpaceToWorldSpace((float)i);
					for (int j = 0; j < 2048; j++)
					{
						Vector2 val2 = new Vector2
						{
							x = AltBiomeWorldData.MapSpaceToWorldSpace((float)j),
							y = y
						};
						if (((Vector2)(ref val2)).sqrMagnitude > 110250000f)
						{
							biomes[j, i] = ocean;
							heights[j, i] = -1000f;
						}
						else
						{
							Biome val3 = biomeAt(val2.x, val2.y);
							biomes[j, i] = BiomeHelpers.ToBiomeIndex(val3);
							heights[j, i] = heightAt(val3, val2.x, val2.y);
						}
					}
				});
			}
			catch (Exception ex3)
			{
				Exception ex4 = (ex3 as AggregateException)?.InnerException ?? ex3;
				_log.LogWarning((object)("Biome map: parallel fill failed (" + ex4.GetType().Name + ": " + ex4.Message + "); filling it the usual way."));
				return true;
			}
			double totalSeconds = stopwatch.Elapsed.TotalSeconds;
			val.PointsGenerated = true;
			world.m_biomeData = val;
			_dataWorld.Invoke(val) = world;
			_log.LogInfo((object)string.Format("Biome map: filled on {0} threads in {1:0.00} s ({2} lookups).", Environment.ProcessorCount, totalSeconds, (worldState != null) ? "Worldhalla" : "game"));
			return false;
		}
	}
	internal static class BundleCacheFix
	{
		private sealed class FileKey
		{
			public long Length;

			public DateTime Written;

			public string Key;
		}

		private const long MinBundleBytes = 262144L;

		private const int TailBytes = 1048576;

		private const string Extension = ".lz4bundle";

		private static string _dir;

		private static ManualLogSource _log;

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

		private static readonly Dictionary<string, FileKey> FileKeys = new Dictionary<string, FileKey>(StringComparer.OrdinalIgnoreCase);

		internal static int LoadedFromCopy;

		internal static int Queued;

		internal static int Converted;

		internal static int Failed;

		internal static double SourceMegabytes;

		public static string Apply(Harmony harmony, ManualLogSource log)
		{
			//IL_043e: Unknown result type (might be due to invalid IL or missing references)
			//IL_044c: Expected O, but got Unknown
			_log = log;
			_dir = Path.Combine(Path.Combine(Paths.CachePath, "ValPerfPatcher"), "bundles");
			Directory.CreateDirectory(_dir);
			CleanUp();
			Type typeFromHandle = typeof(AssetBundle);
			(string, Type[], string)[] obj = new(string, Type[], string)[16]
			{
				("LoadFromStream", new Type[1] { typeof(Stream) }, "Stream1"),
				("LoadFromStream", new Type[2]
				{
					typeof(Stream),
					typeof(uint)
				}, "Stream2"),
				("LoadFromStream", new Type[3]
				{
					typeof(Stream),
					typeof(uint),
					typeof(uint)
				}, "Stream2"),
				("LoadFromStreamAsync", new Type[1] { typeof(Stream) }, "StreamAsync1"),
				("LoadFromStreamAsync", new Type[2]
				{
					typeof(Stream),
					typeof(uint)
				}, "StreamAsync2"),
				("LoadFromStreamAsync", new Type[3]
				{
					typeof(Stream),
					typeof(uint),
					typeof(uint)
				}, "StreamAsync2"),
				("LoadFromMemory", new Type[1] { typeof(byte[]) }, "Memory1"),
				("LoadFromMemory", new Type[2]
				{
					typeof(byte[]),
					typeof(uint)
				}, "Memory2"),
				("LoadFromMemoryAsync", new Type[1] { typeof(byte[]) }, "MemoryAsync1"),
				("LoadFromMemoryAsync", new Type[2]
				{
					typeof(byte[]),
					typeof(uint)
				}, "MemoryAsync2"),
				("LoadFromFile", new Type[1] { typeof(string) }, "File1"),
				("LoadFromFile", new Type[2]
				{
					typeof(string),
					typeof(uint)
				}, "File2"),
				("LoadFromFile", new Type[3]
				{
					typeof(string),
					typeof(uint),
					typeof(ulong)
				}, "File3"),
				("LoadFromFileAsync", new Type[1] { typeof(string) }, "File1"),
				("LoadFromFileAsync", new Type[2]
				{
					typeof(string),
					typeof(uint)
				}, "File2"),
				("LoadFromFileAsync", new Type[3]
				{
					typeof(string),
					typeof(uint),
					typeof(ulong)
				}, "File3")
			};
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeFromHandle, "RecompressAssetBundleAsync", (Type[])null, (Type[])null);
			List<(MethodInfo, string)> list = new List<(MethodInfo, string)>();
			(string, Type[], string)[] array = obj;
			for (int i = 0; i < array.Length; i++)
			{
				(string, Type[], string) tuple = array[i];
				string item = tuple.Item1;
				Type[] item2 = tuple.Item2;
				string item3 = tuple.Item3;
				MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeFromHandle, item, item2, (Type[])null);
				if (methodInfo2 == null || methodInfo == null)
				{
					return "Unity's asset bundle loading has changed since this fix was written";
				}
				list.Add((methodInfo2, item3));
			}
			foreach (var (methodInfo3, text) in list)
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(BundleCacheFix), text, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			return null;
		}

		private static bool Stream1(Stream stream, ref AssetBundle __result)
		{
			return Replace(CopyFor(stream), ref __result);
		}

		private static bool Stream2(Stream stream, uint crc, ref AssetBundle __result)
		{
			if (crc == 0)
			{
				return Replace(CopyFor(stream), ref __result);
			}
			return true;
		}

		private static bool StreamAsync1(Stream stream, ref AssetBundleCreateRequest __result)
		{
			return ReplaceAsync(CopyFor(stream), ref __result);
		}

		private static bool StreamAsync2(Stream stream, uint crc, ref AssetBundleCreateRequest __result)
		{
			if (crc == 0)
			{
				return ReplaceAsync(CopyFor(stream), ref __result);
			}
			return true;
		}

		private static bool Memory1(byte[] binary, ref AssetBundle __result)
		{
			return Replace(CopyFor(binary), ref __result);
		}

		private static bool Memory2(byte[] binary, uint crc, ref AssetBundle __result)
		{
			if (crc == 0)
			{
				return Replace(CopyFor(binary), ref __result);
			}
			return true;
		}

		private static bool MemoryAsync1(byte[] binary, ref AssetBundleCreateRequest __result)
		{
			return ReplaceAsync(CopyFor(binary), ref __result);
		}

		private static bool MemoryAsync2(byte[] binary, uint crc, ref AssetBundleCreateRequest __result)
		{
			if (crc == 0)
			{
				return ReplaceAsync(CopyFor(binary), ref __result);
			}
			return true;
		}

		private static void File1(ref string path)
		{
			Redirect(ref path);
		}

		private static void File2(ref string path, uint crc)
		{
			if (crc == 0)
			{
				Redirect(ref path);
			}
		}

		private static void File3(ref string path, uint crc, ulong offset)
		{
			if (crc == 0 && offset == 0L)
			{
				Redirect(ref path);
			}
		}

		private static bool Replace(string copy, ref AssetBundle __result)
		{
			if (copy == null)
			{
				return true;
			}
			AssetBundle val = AssetBundle.LoadFromFile(copy);
			if ((Object)(object)val == (Object)null)
			{
				_log.LogWarning((object)("Asset bundle copy " + Path.GetFileName(copy) + " didn't load; using the mod's own bundle."));
				return true;
			}
			LoadedFromCopy++;
			__result = val;
			return false;
		}

		private static bool ReplaceAsync(string copy, ref AssetBundleCreateRequest __result)
		{
			if (copy == null)
			{
				return true;
			}
			AssetBundleCreateRequest val = AssetBundle.LoadFromFileAsync(copy);
			if (val == null)
			{
				return true;
			}
			LoadedFromCopy++;
			__result = val;
			return false;
		}

		private static void Redirect(ref string path)
		{
			string text = CopyFor(path);
			if (text != null)
			{
				LoadedFromCopy++;
				path = text;
			}
		}

		private static string CopyFor(byte[] binary)
		{
			if (binary == null || (long)binary.Length < 262144L)
			{
				return null;
			}
			using MemoryStream stream = new MemoryStream(binary, writable: false);
			return CopyFor(stream);
		}

		private static string CopyFor(Stream stream)
		{
			try
			{
				if (stream == null || !stream.CanRead || !stream.CanSeek)
				{
					return null;
				}
				long position = stream.Position;
				long num = stream.Length - position;
				if (num < 262144)
				{
					return null;
				}
				string text;
				try
				{
					text = SolidLzmaKey(stream, position, num);
				}
				finally
				{
					stream.Position = position;
				}
				if (text == null)
				{
					return null;
				}
				string text2 = Ready(text);
				if (text2 == null && Converting.Add(text))
				{
					string text3 = Path.Combine(_dir, text + ".src");
					try
					{
						using FileStream destination = File.Create(text3);
						stream.CopyTo(destination);
					}
					finally
					{
						stream.Position = position;
					}
					StartConversion(text, text3, deleteSource: true);
				}
				return text2;
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Asset bundle cache: " + ex.GetType().Name + ": " + ex.Message + "; using the usual load."));
				return null;
			}
		}

		private static string CopyFor(string path)
		{
			try
			{
				if (string.IsNullOrEmpty(path) || path.StartsWith(_dir, StringComparison.OrdinalIgnoreCase))
				{
					return null;
				}
				FileInfo fileInfo = new FileInfo(path);
				if (!fileInfo.Exists || fileInfo.Length < 262144)
				{
					return null;
				}
				if (!FileKeys.TryGetValue(path, out var value) || value.Length != fileInfo.Length || value.Written != fileInfo.LastWriteTimeUtc)
				{
					value = new FileKey
					{
						Length = fileInfo.Length,
						Written = fileInfo.LastWriteTimeUtc
					};
					using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
					{
						value.Key = SolidLzmaKey(stream, 0L, fileInfo.Length);
					}
					FileKeys[path] = value;
				}
				if (value.Key == null)
				{
					return null;
				}
				string text = Ready(value.Key);
				if (text == null && Converting.Add(value.Key))
				{
					StartConversion(value.Key, path, deleteSource: false);
				}
				return text;
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Asset bundle cache: " + ex.GetType().Name + ": " + ex.Message + "; using the usual load."));
				return null;
			}
		}

		private static string Ready(string key)
		{
			string text = Path.Combine(_dir, key + ".lz4bundle");
			if (!File.Exists(text))
			{
				return null;
			}
			try
			{
				File.SetLastWriteTimeUtc(text, DateTime.UtcNow);
			}
			catch
			{
			}
			return text;
		}

		private static void StartConversion(string key, string source, bool deleteSource)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			string temp = Path.Combine(_dir, key + ".tmp");
			string copy = Path.Combine(_dir, key + ".lz4bundle");
			SourceMegabytes += (double)new FileInfo(source).Length / 1000000.0;
			AssetBundleRecompressOperation op = AssetBundle.RecompressAssetBundleAsync(source, temp, BuildCompression.LZ4Runtime, 0u, (ThreadPriority)0);
			if (op == null)
			{
				if (deleteSource)
				{
					TryDelete(source);
				}
				Failed++;
				return;
			}
			Queued++;
			((AsyncOperation)op).completed += delegate
			{
				try
				{
					if (op.success && File.Exists(temp))
					{
						File.Move(temp, copy);
						Converted++;
						_log.LogInfo((object)$"Asset bundle {Path.GetFileName(source)}: fast-loading copy ready ({(double)new FileInfo(copy).Length / 1000000.0:F1} MB), used from the next load.");
					}
					else
					{
						Failed++;
						_log.LogWarning((object)("Asset bundle " + Path.GetFileName(source) + ": conversion failed (" + op.humanReadableResult + "); it keeps loading the usual way."));
					}
				}
				catch (Exception ex)
				{
					_log.LogWarning((object)("Asset bundle " + key + ": " + ex.Message));
				}
				finally
				{
					if (deleteSource)
					{
						TryDelete(source);
					}
					TryDelete(temp);
				}
			};
		}

		private static string SolidLzmaKey(Stream stream, long start, long length)
		{
			byte[] array = new byte[(int)Math.Min(length, 65536L)];
			ReadFully(stream, array, array.Length);
			if (!IsLzmaBundle(stream, start, length, array))
			{
				return null;
			}
			byte[] bytes = Encoding.UTF8.GetBytes(Application.unityVersion);
			ulong hash = Fnv(14695981039346656037uL, bytes, bytes.Length);
			hash = Fnv(hash, array, Math.Min(array.Length, 4096));
			int num = (int)Math.Min(length, 1048576L);
			byte[] array2 = new byte[num];
			stream.Position = start + length - num;
			ReadFully(stream, array2, num);
			hash = Fnv(hash, array2, num);
			return $"{length:x}-{hash:x16}";
		}

		private static bool IsLzmaBundle(Stream stream, long start, long length, byte[] head)
		{
			int i = 0;
			if (head.Length < 64 || ReadCString(head, ref i) != "UnityFS")
			{
				return false;
			}
			uint num = ReadU32(head, ref i);
			ReadCString(head, ref i);
			ReadCString(head, ref i);
			i += 8;
			int num2 = (int)ReadU32(head, ref i);
			int num3 = (int)ReadU32(head, ref i);
			uint num4 = ReadU32(head, ref i);
			if (num >= 7)
			{
				i = (i + 15) / 16 * 16;
			}
			if (num2 <= 0 || num3 <= 0 || num2 > length || num3 > 67108864)
			{
				return false;
			}
			byte[] array = new byte[num2];
			if ((num4 & 0x80) != 0)
			{
				stream.Position = start + length - num2;
				ReadFully(stream, array, num2);
			}
			else if (i + num2 <= head.Length)
			{
				Buffer.BlockCopy(head, i, array, 0, num2);
			}
			else
			{
				stream.Position = start + i;
				ReadFully(stream, array, num2);
			}
			switch (num4 & 0x3F)
			{
			case 2u:
			case 3u:
				array = Lz4Block(array, num3);
				break;
			default:
				return false;
			case 0u:
				break;
			}
			int num5 = 16;
			int num6 = ReadI32BE(array, num5);
			num5 += 4;
			if (num6 <= 0 || 20 + num6 * 10 > array.Length)
			{
				return false;
			}
			int num7 = 0;
			while (num7 < num6)
			{
				if ((((array[num5 + 8] << 8) | array[num5 + 9]) & 0x3F) == 1)
				{
					return true;
				}
				num7++;
				num5 += 10;
			}
			return false;
		}

		private static byte[] Lz4Block(byte[] src, int size)
		{
			byte[] array = new byte[size];
			int num = 0;
			int num2 = 0;
			while (num < src.Length && num2 < size)
			{
				int num3 = src[num++];
				int num4 = num3 >> 4;
				if (num4 == 15)
				{
					int num5;
					do
					{
						num5 = src[num++];
						num4 += num5;
					}
					while (num5 == 255);
				}
				Buffer.BlockCopy(src, num, array, num2, num4);
				num += num4;
				num2 += num4;
				if (num >= src.Length || num2 >= size)
				{
					break;
				}
				int num6 = src[num] | (src[num + 1] << 8);
				num += 2;
				int num7 = num3 & 0xF;
				if (num7 == 15)
				{
					int num8;
					do
					{
						num8 = src[num++];
						num7 += num8;
					}
					while (num8 == 255);
				}
				num7 += 4;
				int num9 = 0;
				while (num9 < num7)
				{
					array[num2] = array[num2 - num6];
					num9++;
					num2++;
				}
			}
			return array;
		}

		private static ulong Fnv(ulong hash, byte[] data, int count)
		{
			for (int i = 0; i < count; i++)
			{
				hash = (hash ^ data[i]) * 1099511628211L;
			}
			return hash;
		}

		private static string ReadCString(byte[] b, ref int i)
		{
			int num = i;
			while (i < b.Length && b[i] != 0)
			{
				i++;
			}
			string result = Encoding.ASCII.GetString(b, num, i - num);
			i++;
			return result;
		}

		private static uint ReadU32(byte[] b, ref int i)
		{
			int result = (b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3];
			i += 4;
			return (uint)result;
		}

		private static int ReadI32BE(byte[] b, int i)
		{
			return (b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3];
		}

		private static void ReadFully(Stream s, byte[] buffer, int count)
		{
			int num;
			for (int i = 0; i < count; i += num)
			{
				num = s.Read(buffer, i, count - i);
				if (num <= 0)
				{
					throw new EndOfStreamException();
				}
			}
		}

		private static void CleanUp()
		{
			string[] files = Directory.GetFiles(_dir);
			foreach (string text in files)
			{
				if (text.EndsWith(".src") || text.EndsWith(".tmp"))
				{
					TryDelete(text);
				}
				else if (text.EndsWith(".lz4bundle") && File.GetLastWriteTimeUtc(text) < DateTime.UtcNow.AddDays(-30.0))
				{
					TryDelete(text);
				}
			}
		}

		private static void TryDelete(string path)
		{
			try
			{
				if (File.Exists(path))
				{
					File.Delete(path);
				}
			}
			catch
			{
			}
		}
	}
	internal static class ChebyshevDistanceFix
	{
		internal const string VcpGuid = "MidnightsFX.ValheimCommunityPatch";

		public static string Apply(Harmony harmony)
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(Utils), "ChebyshevDistance", new Type[2]
			{
				typeof(Vector3),
				typeof(Vector3)
			}, (Type[])null);
			if (methodInfo == null || methodInfo.ReturnType != typeof(float))
			{
				return "Utils.ChebyshevDistance has changed since this fix was written";
			}
			if (!PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null).Any((CodeInstruction i) => i.opcode == OpCodes.Newarr))
			{
				return "Utils.ChebyshevDistance no longer allocates; nothing to fix";
			}
			Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
			if (patchInfo != null && patchInfo.Transpilers.Any((Patch p) => p.owner == "MidnightsFX.ValheimCommunityPatch"))
			{
				return "already done by ValheimCommunityPatch " + Plugin.VersionOf("MidnightsFX.ValheimCommunityPatch") + " (same result; it rewrites the method itself, a little cheaper)";
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ChebyshevDistanceFix), "Prefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool Prefix(Vector3 a, Vector3 b, ref float __result)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Abs(a.x - b.x);
			float num2 = Mathf.Abs(a.y - b.y);
			float num3 = Mathf.Abs(a.z - b.z);
			if (num2 > num)
			{
				num = num2;
			}
			if (num3 > num)
			{
				num = num3;
			}
			__result = num;
			return false;
		}
	}
	internal static class ConfigSaveHoldFix
	{
		private const float MaxWorldHoldSeconds = 180f;

		private static readonly object Lock = new object();

		private static readonly HashSet<ConfigFile> Held = new HashSet<ConfigFile>();

		private static bool _holding;

		private static bool _flushing;

		private static bool _worldLoad;

		private static bool _holdWorldLoads;

		private static DateTime _since;

		[ThreadStatic]
		private static bool _writeNow;

		private static ManualLogSource _log;

		private static int _savesHeld;

		private static int _filesWritten;

		public static string Apply(Harmony harmony, ManualLogSource log)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Expected O, but got Unknown
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Expected O, but got Unknown
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Expected O, but got Unknown
			_log = log;
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ConfigFile), "Save", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(FejdStartup), "Start", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.DeclaredMethod(typeof(Player), "OnSpawned", new Type[1] { typeof(bool) }, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.DeclaredMethod(typeof(ZNet), "OnNewConnection", new Type[1] { typeof(ZNetPeer) }, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				return "BepInEx's config saving or the game's main menu has changed since this fix was written";
			}
			Hold(worldLoad: false);
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ConfigSaveHoldFix), "SavePrefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo6 = AccessTools.DeclaredMethod(typeof(ConfigFile), "Reload", Type.EmptyTypes, (Type[])null);
			if (methodInfo6 != null)
			{
				harmony.Patch((MethodBase)methodInfo6, new HarmonyMethod(typeof(ConfigSaveHoldFix), "ReloadPrefix", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(ConfigSaveHoldFix), "Flush", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Application.quitting += Flush;
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(ConfigSaveHoldFix), "WorldLoadStart", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo3 == null || methodInfo4 == null || methodInfo5 == null)
			{
				log.LogWarning((object)"Mod config saves: the game's world loading has changed since this fix was written; saves are only held while mods start.");
			}
			else if (!Application.isBatchMode)
			{
				_holdWorldLoads = true;
				harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(typeof(ConfigSaveHoldFix), "Flush", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(ConfigSaveHoldFix), "Flush", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			return null;
		}

		private static void Hold(bool worldLoad)
		{
			lock (Lock)
			{
				if (!_holding)
				{
					_holding = true;
					_worldLoad = worldLoad;
					_since = DateTime.UtcNow;
					_savesHeld = (_filesWritten = 0);
				}
			}
		}

		private static void WorldLoadStart()
		{
			Flush();
			if (_holdWorldLoads)
			{
				Hold(worldLoad: true);
			}
		}

		private static void ReloadPrefix(ConfigFile __instance)
		{
			lock (Lock)
			{
				if (!Held.Remove(__instance))
				{
					return;
				}
			}
			_writeNow = true;
			try
			{
				__instance.Save();
				_filesWritten++;
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Mod config saves: could not write " + __instance.ConfigFilePath + ": " + ex.Message));
				}
			}
			finally
			{
				_writeNow = false;
			}
		}

		private static bool SavePrefix(ConfigFile __instance)
		{
			lock (Lock)
			{
				if (!_holding || _flushing || _writeNow)
				{
					return true;
				}
				if (!_worldLoad || !((DateTime.UtcNow - _since).TotalSeconds > 180.0))
				{
					Held.Add(__instance);
					_savesHeld++;
					return false;
				}
			}
			Flush();
			return true;
		}

		private static void Flush()
		{
			bool worldLoad;
			List<ConfigFile> list;
			lock (Lock)
			{
				if (!_holding)
				{
					return;
				}
				_holding = false;
				_flushing = true;
				worldLoad = _worldLoad;
				list = new List<ConfigFile>(Held);
				Held.Clear();
			}
			try
			{
				foreach (ConfigFile item in list)
				{
					try
					{
						item.Save();
						_filesWritten++;
					}
					catch (Exception ex)
					{
						ManualLogSource log = _log;
						if (log != null)
						{
							log.LogWarning((object)("Mod config saves: could not write " + item.ConfigFilePath + ": " + ex.Message));
						}
					}
				}
			}
			finally
			{
				lock (Lock)
				{
					_flushing = false;
				}
			}
			if (!worldLoad || _savesHeld > 0)
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogInfo((object)string.Format("Mod config saves: {0} saves while {1}, written as {2} file saves.", _savesHeld, worldLoad ? "the world loaded" : "mods started", _filesWritten));
				}
			}
		}
	}
	internal static class CreatureLevelItemDataFix
	{
		private static Type _data;

		private static MethodInfo _addComponent;

		private static MethodInfo _init;

		public static string Apply(Harmony harmony)
		{
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			_data = Plugin.ModType("org.bepinex.plugins.creaturelevelcontrol", "CreatureLevelControl.OriginalItemData");
			Type type = Plugin.ModType("org.bepinex.plugins.creaturelevelcontrol", "CreatureLevelControl.ItemControl");
			Type type2 = ((type == null) ? null : AccessTools.Inner(type, "PatchConfigReading"));
			MethodInfo methodInfo = ((type2 == null) ? null : AccessTools.DeclaredMethod(type2, "Postfix", (Type[])null, (Type[])null));
			_init = ((_data == null) ? null : AccessTools.DeclaredMethod(_data, "Init", Type.EmptyTypes, (Type[])null));
			MethodInfo methodInfo2 = AccessTools.Method(typeof(GameObject), "AddComponent", Type.EmptyTypes, (Type[])null);
			if (methodInfo == null || _init == null || methodInfo2 == null || !methodInfo2.IsGenericMethodDefinition)
			{
				return "Creature Level & Loot Control's item setup has changed since this fix was written";
			}
			_addComponent = methodInfo2.MakeGenericMethod(_data);
			List<CodeInstruction> originalInstructions;
			try
			{
				originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null);
			}
			catch (Exception ex)
			{
				return "could not read Creature Level & Loot Control's item setup (" + ex.Message + ")";
			}
			int num = 0;
			for (int i = 0; i + 1 < originalInstructions.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(originalInstructions[i], _addComponent) && CodeInstructionExtensions.Calls(originalInstructions[i + 1], _init))
				{
					num++;
				}
			}
			if (num != 1)
			{
				return "Creature Level & Loot Control's item setup no longer adds and sets up its item data in one step";
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CreatureLevelItemDataFix), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo addOnce = AccessTools.Method(typeof(CreatureLevelItemDataFix), "AddOnce", (Type[])null, (Type[])null);
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (i + 1 < list.Count && CodeInstructionExtensions.Calls(list[i], _addComponent) && CodeInstructionExtensions.Calls(list[i + 1], _init))
				{
					CodeInstruction val = CodeInstructionExtensions.MoveBlocksFrom(CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Call, (object)addOnce), list[i]), list[i]);
					val.labels.AddRange(list[i + 1].labels);
					val.blocks.AddRange(list[i + 1].blocks);
					yield return val;
					i++;
				}
				else
				{
					yield return list[i];
				}
			}
		}

		private static void AddOnce(GameObject item)
		{
			if (!((Object)(object)item.GetComponent(_data) != (Object)null))
			{
				Component obj = item.AddComponent(_data);
				_init.Invoke(obj, null);
			}
		}
	}
	internal static class CreatureLevelMapCirclesFix
	{
		private const string Circles = "CreatureLevelControl.WorldLevelMinimapCircles";

		private static FieldInfo _mapColors;

		private static FieldInfo _forestColors;

		private static FieldInfo _heightColors;

		private static ConfigEntryBase _factor;

		private static ConfigEntryBase _show;

		private static Action<Minimap> _draw;

		private static FieldRef<Minimap, Texture2D> _forestTexture;

		private static FieldRef<Minimap, Texture2D> _heightTexture;

		public static string Apply(Harmony harmony)
		{
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b2: Expected O, but got Unknown
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d8: Expected O, but got Unknown
			Type type = Plugin.ModType("org.bepinex.plugins.creaturelevelcontrol", "CreatureLevelControl.WorldLevelMinimapCircles");
			Type type2 = Plugin.ModType("org.bepinex.plugins.creaturelevelcontrol", "CreatureLevelControl.CreatureLevelControl");
			Type type3 = ((type == null) ? null : AccessTools.Inner(type, "PatchMinimapCircles"));
			MethodInfo methodInfo = ((type3 == null) ? null : AccessTools.DeclaredMethod(type3, "Postfix", new Type[1] { typeof(Minimap) }, (Type[])null));
			MethodInfo draw = ((type == null) ? null : AccessTools.DeclaredMethod(type, "DrawDistanceLevelCircles", new Type[1] { typeof(Minimap) }, (Type[])null));
			_mapColors = ((type == null) ? null : AccessTools.DeclaredField(type, "originalMapColors"));
			_forestColors = ((type == null) ? null : AccessTools.DeclaredField(type, "originalForestColors"));
			_heightColors = ((type == null) ? null : AccessTools.DeclaredField(type, "originalHeightColors"));
			FieldInfo factor = ((type2 == null) ? null : AccessTools.DeclaredField(type2, "difficultySecondFactor"));
			FieldInfo show = ((type2 == null) ? null : AccessTools.DeclaredField(type2, "displayDistanceFromSpawnCircles"));
			FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(Minimap), "m_forestMaskTexture");
			FieldInfo fieldInfo2 = AccessTools.DeclaredField(typeof(Minimap), "m_heightTexture");
			if (methodInfo == null || draw == null || !draw.IsStatic || factor == null || show == null || fieldInfo == null || fieldInfo.FieldType != typeof(Texture2D) || fieldInfo2 == null || fieldInfo2.FieldType != typeof(Texture2D) || new FieldInfo[3] { _mapColors, _forestColors, _heightColors }.Any((FieldInfo f) => f == null || !f.IsStatic || f.FieldType != typeof(Color[])))
			{
				return "Creature Level & Loot Control's map circles have changed since this fix was written";
			}
			object? value = factor.GetValue(null);
			_factor = (ConfigEntryBase)((value is ConfigEntryBase) ? value : null);
			object? value2 = show.GetValue(null);
			_show = (ConfigEntryBase)((value2 is ConfigEntryBase) ? value2 : null);
			if (_factor == null || _show == null || !Enum.IsDefined(_factor.SettingType, "Distance") || !Enum.IsDefined(_show.SettingType, "On"))
			{
				return "Creature Level & Loot Control's map circle settings have changed since this fix was written";
			}
			try
			{
				List<CodeInstruction> originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)draw, (ILGenerator)null);
				List<CodeInstruction> postfixCode = PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null);
				if (!originalInstructions.Any((CodeInstruction c) => CodeInstructionExtensions.LoadsField(c, factor, false)) || !originalInstructions.Any((CodeInstruction c) => CodeInstructionExtensions.LoadsField(c, show, false)) || !postfixCode.Any((CodeInstruction c) => CodeInstructionExtensions.Calls(c, draw)) || new FieldInfo[3] { _mapColors, _forestColors, _heightColors }.Any((FieldInfo f) => !postfixCode.Any((CodeInstruction c) => CodeInstructionExtensions.StoresField(c, f))))
				{
					return "Creature Level & Loot Control's map circles have changed since this fix was written";
				}
			}
			catch (Exception ex)
			{
				return "could not read Creature Level & Loot Control's map circles (" + ex.Message + ")";
			}
			_draw = AccessTools.MethodDelegate<Action<Minimap>>(draw, (object)null, true);
			_forestTexture = AccessTools.FieldRefAccess<Minimap, Texture2D>(fieldInfo);
			_heightTexture = AccessTools.FieldRefAccess<Minimap, Texture2D>(fieldInfo2);
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CreatureLevelMapCirclesFix), "PostfixPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)draw, new HarmonyMethod(typeof(CreatureLevelMapCirclesFix), "DrawPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool Shown()
		{
			if (_factor.BoxedValue?.ToString() == "Distance")
			{
				return _show.BoxedValue?.ToString() == "On";
			}
			return false;
		}

		private static bool PostfixPrefix(Minimap __0)
		{
			_mapColors.SetValue(null, null);
			_forestColors.SetValue(null, null);
			_heightColors.SetValue(null, null);
			_draw(__0);
			return false;
		}

		private static bool DrawPrefix(Minimap __0)
		{
			if (_mapColors.GetValue(null) != null)
			{
				return true;
			}
			if ((Object)(object)__0 == (Object)null || !Shown())
			{
				return false;
			}
			_mapColors.SetValue(null, __0.m_mapTexture.GetPixels());
			_forestColors.SetValue(null, _forestTexture.Invoke(__0).GetPixels());
			_heightColors.SetValue(null, _heightTexture.Invoke(__0).GetPixels());
			return true;
		}
	}
	internal static class CreatureLevelSectorTextFix
	{
		public const string TargetGuid = "org.bepinex.plugins.creaturelevelcontrol";

		public static float IntervalSeconds = 0.25f;

		private static FieldInfo _text;

		private static object _lastText;

		private static float _next;

		public static string Apply(Harmony harmony)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			Type type = Plugin.ModType("org.bepinex.plugins.creaturelevelcontrol", "CreatureLevelControl.CreatureSector");
			Type type2 = ((type == null) ? null : AccessTools.Inner(type, "PatchMinimapSectorUpdate"));
			MethodInfo methodInfo = ((type2 == null) ? null : AccessTools.Method(type2, "Postfix", Type.EmptyTypes, (Type[])null));
			_text = ((type == null) ? null : AccessTools.Field(type, "minimapSectorText"));
			if (methodInfo == null || methodInfo.ReturnType != typeof(void) || _text == null || !_text.IsStatic)
			{
				return "Creature Level & Loot Control's minimap level code has changed since this fix was written";
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CreatureLevelSectorTextFix), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool Prefix()
		{
			if (IntervalSeconds <= 0f)
			{
				return true;
			}
			object value = _text.GetValue(null);
			float unscaledTime = Time.unscaledTime;
			if (value != null && value == _lastText && unscaledTime < _next)
			{
				return false;
			}
			_lastText = value;
			_next = unscaledTime + IntervalSeconds;
			return true;
		}
	}
	internal static class CreatureLevelServerTimeFix
	{
		public static float IntervalSeconds = 10f;

		private static ZNetPeer _lastPeer;

		private static float _next;

		public static string Apply(Harmony harmony)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			Type type = Plugin.ModType("org.bepinex.plugins.creaturelevelcontrol", "CreatureLevelControl.Utils");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "RequestServerTime", Type.EmptyTypes, (Type[])null));
			if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(void) || !PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null).Any((CodeInstruction c) => c.opcode == OpCodes.Ldstr && c.operand as string == "CLLC GetServerTime"))
			{
				return "Creature Level & Loot Control's server time request has changed since this fix was written";
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CreatureLevelServerTimeFix), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool Prefix()
		{
			ZNet instance = ZNet.instance;
			if (IntervalSeconds <= 0f || (Object)(object)instance == (Object)null || instance.IsServer())
			{
				return true;
			}
			ZNetPeer serverPeer = instance.GetServerPeer();
			float unscaledTime = Time.unscaledTime;
			if (serverPeer == _lastPeer && unscaledTime < _next)
			{
				return false;
			}
			_lastPeer = serverPeer;
			_next = unscaledTime + IntervalSeconds;
			return true;
		}
	}
	internal static class CreatureManagerSpawnFix
	{
		private sealed class Copy
		{
			public FieldInfo LastField;

			public SpawnSystemList List;

			public HashSet<SpawnData> Entries;

			public bool Dirty = true;
		}

		private static readonly Dictionary<Type, Copy> Copies = new Dictionary<Type, Copy>();

		public static string Apply(Harmony harmony, ManualLogSource log)
		{
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Expected O, but got Unknown
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01c9: Expected O, but got Unknown
			int num = 0;
			int num2 = 0;
			HashSet<Assembly> hashSet = new HashSet<Assembly>();
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				BaseUnityPlugin instance = value.Instance;
				if ((Object)(object)instance == (Object)null || !hashSet.Add(((object)instance).GetType().Assembly))
				{
					continue;
				}
				Type type;
				try
				{
					type = ((object)instance).GetType().Assembly.GetType("CreatureManager.Creature", throwOnError: false);
				}
				catch
				{
					continue;
				}
				if (type == null)
				{
					continue;
				}
				MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "AddToSpawnSystem", new Type[1] { typeof(SpawnSystem) }, (Type[])null);
				FieldInfo fieldInfo = AccessTools.DeclaredField(type, "lastRegisteredSpawns");
				if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(void) || fieldInfo == null || !fieldInfo.IsStatic || fieldInfo.FieldType != typeof(List<SpawnData>))
				{
					num2++;
					log.LogInfo((object)("Creature spawn lists: " + value.Metadata.Name + "'s CreatureManager looks different; left alone."));
					continue;
				}
				Copy copy = new Copy
				{
					LastField = fieldInfo
				};
				Copies[type] = copy;
				instance.Config.SettingChanged += delegate
				{
					copy.Dirty = true;
				};
				instance.Config.ConfigReloaded += delegate
				{
					copy.Dirty = true;
				};
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CreatureManagerSpawnFix), "Prefix", (Type[])null), new HarmonyMethod(typeof(CreatureManagerSpawnFix), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num++;
				log.LogInfo((object)("Creature spawn lists: " + value.Metadata.Name + " reuses its spawn entries."));
			}
			if (num == 0)
			{
				if (num2 != 0)
				{
					return "the CreatureManager copies have changed since this fix was written";
				}
				return "no mod with CreatureManager is installed";
			}
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Game), "Shutdown", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(CreatureManagerSpawnFix), "Clear", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool Prefix(SpawnSystem __0, MethodBase __originalMethod, out bool __state)
		{
			__state = true;
			if (__originalMethod == null || !Copies.TryGetValue(__originalMethod.DeclaringType, out var value) || value.Dirty || (Object)(object)value.List == (Object)null)
			{
				return true;
			}
			if ((Object)(object)__0 == (Object)null || __0.m_spawnLists == null || __0.m_spawnLists.Count == 0)
			{
				return true;
			}
			SpawnSystemList val = __0.m_spawnLists[0];
			if ((Object)(object)val != (Object)(object)value.List || val.m_spawners == null)
			{
				return true;
			}
			if (!(value.LastField.GetValue(null) is List<SpawnData> list) || list.Count != value.Entries.Count)
			{
				return true;
			}
			int num = 0;
			foreach (SpawnData spawner in val.m_spawners)
			{
				if (spawner != null && value.Entries.Contains(spawner))
				{
					num++;
				}
			}
			if (num != value.Entries.Count)
			{
				return true;
			}
			__state = false;
			return false;
		}

		private static void Postfix(SpawnSystem __0, MethodBase __originalMethod, bool __state)
		{
			if (__state && !(__originalMethod == null) && Copies.TryGetValue(__originalMethod.DeclaringType, out var value))
			{
				List<SpawnData> list = value.LastField.GetValue(null) as List<SpawnData>;
				if ((Object)(object)__0 == (Object)null || __0.m_spawnLists == null || __0.m_spawnLists.Count == 0 || list == null)
				{
					value.Dirty = true;
					return;
				}
				value.List = __0.m_spawnLists[0];
				value.Entries = new HashSet<SpawnData>(list);
				value.Dirty = false;
			}
		}

		private static void Clear()
		{
			foreach (Copy value in Copies.Values)
			{
				value.Dirty = true;
				value.List = null;
			}
		}
	}
	internal static class DevcommandsPermissionFix
	{
		public const string TargetGuid = "server_devcommands";

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

		private static int _replaced;

		public static string Apply(Harmony harmony)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			Type type = Plugin.ModType("server_devcommands", "ServerDevcommands.PermissionManager");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "GetFeaturePermissionByHash", new Type[2]
			{
				typeof(string),
				typeof(int)
			}, (Type[])null));
			if (methodInfo == null)
			{
				return "Server Devcommands' permission check has changed since this fix was written";
			}
			_replaced = 0;
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(DevcommandsPermissionFix), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			if (_replaced != 1)
			{
				return "Server Devcommands' permission check has changed since this fix was written";
			}
			return null;
		}

		public static string LowerCached(string s)
		{
			if (s == null)
			{
				return null;
			}
			if (!Lower.TryGetValue(s, out var value))
			{
				value = s.ToLower();
				Lower[s] = value;
			}
			return value;
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo toLower = AccessTools.Method(typeof(string), "ToLower", new Type[0], (Type[])null);
			MethodInfo cached = AccessTools.Method(typeof(DevcommandsPermissionFix), "LowerCached", (Type[])null, (Type[])null);
			bool done = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!done && (instruction.opcode == OpCodes.Callvirt || instruction.opcode == OpCodes.Call) && object.Equals(instruction.operand, toLower))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = cached;
					done = true;
					_replaced++;
				}
				yield return instruction;
			}
		}
	}
	[BepInPlugin("__valheimmods.ValPerfPatcher.Early", "ValPerfPatcher (early start)", "1.0.32")]
	public sealed class EarlyPlugin : BaseUnityPlugin
	{
		public const string Guid = "__valheimmods.ValPerfPatcher.Early";

		public const string Name = "ValPerfPatcher (early start)";

		public const string VanillaFix = "Base game: read the translation table once";

		public const string LocalizerFix = "LocalizationManager mods: reuse loaded text";

		public const string BundleFix = "Mod asset bundles: keep a fast-loading copy";

		public const string ConfigFix = "Mod config saves: write each file once at startup";

		internal static string VanillaResult = "not started";

		internal static string LocalizerResult = "not started";

		internal static string BundleResult = "not started";

		internal static string ConfigResult = "not started";

		private void Awake()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			Harmony harmony = new Harmony("__valheimmods.ValPerfPatcher.Early");
			ConfigFile config = ReadOnlyMainConfig();
			VanillaResult = Run(config, "Base game: read the translation table once", () => TranslationLoadFix.ApplyVanilla(harmony));
			LocalizerResult = Run(config, "LocalizationManager mods: reuse loaded text", () => TranslationLoadFix.ApplyLocalizationManagers(harmony, ((BaseUnityPlugin)this).Logger));
			BundleResult = Run(config, "Mod asset bundles: keep a fast-loading copy", () => BundleCacheFix.Apply(harmony, ((BaseUnityPlugin)this).Logger));
			ConfigResult = Run(config, "Mod config saves: write each file once at startup", () => ConfigSaveHoldFix.Apply(harmony, ((BaseUnityPlugin)this).Logger));
		}

		private string Run(ConfigFile config, string name, Func<string> apply)
		{
			if (!config.Bind<bool>("Fixes", name, true, (ConfigDescription)null).Value)
			{
				return "off in config";
			}
			try
			{
				return apply();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)(name + ": " + ex.GetType().Name + ": " + ex.Message));
				return ex.GetType().Name + ": " + ex.Message;
			}
		}

		private static ConfigFile ReadOnlyMainConfig()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			return new ConfigFile(Path.Combine(Paths.ConfigPath, "valheimmods.ValPerfPatcher.cfg"), false)
			{
				SaveOnConfigSet = false
			};
		}
	}
	internal static class FarmingGhostPlantFix
	{
		public const string TargetGuid = "org.bepinex.plugins.farming";

		private static FieldRef<Plant, ZNetView> _nview;

		public static string Apply(Harmony harmony)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			Type type = Plugin.ModType("org.bepinex.plugins.farming", "Farming.Farming+SaveSkillLevel");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "Postfix", new Type[1] { typeof(Plant) }, (Type[])null));
			if (methodInfo == null || !methodInfo.IsStatic)
			{
				return "Farming's plant skill hook has changed since this fix was written";
			}
			if (AccessTools.DeclaredField(typeof(Plant), "m_nview")?.FieldType != typeof(ZNetView))
			{
				return "the game's plant code has changed since this fix was written";
			}
			_nview = AccessTools.FieldRefAccess<Plant, ZNetView>("m_nview");
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(FarmingGhostPlantFix), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool Prefix(Plant __instance)
		{
			ZNetView val = (((Object)(object)__instance == (Object)null) ? null : _nview.Invoke(__instance));
			if ((Object)(object)val != (Object)null)
			{
				return val.GetZDO() != null;
			}
			return false;
		}
	}
	internal static class FloatingSyncDeadbandFix
	{
		internal static float PositionStep = 0.05f;

		private const float VelocityStep = 0.1f;

		private const float AngleStep = 2f;

		private static readonly ConditionalWeakTable<ZSyncTransform, object> Floaters = new ConditionalWeakTable<ZSyncTransform, object>();

		private static readonly object Yes = new object();

		private static readonly object No = new object();

		private static FieldRef<ZSyncTransform, ZNetView> _nview;

		private static FieldRef<ZSyncTransform, Rigidbody> _body;

		private static FieldRef<ZSyncTransform, Character> _character;

		private static FieldRef<ZSyncTransform, Projectile> _projectile;

		private static FieldRef<ZSyncTransform, bool> _wasOwner;

		private static FieldRef<ZSyncTransform, Vector3> _positionCached;

		private static FieldRef<ZSyncTransform, Vector3> _velocityCached;

		private static int _skipped;

		private static int _sent;

		private static bool _reported;

		private static float _nextReport;

		private static ManualLogSource _log;

		public static string Apply(Harmony harmony, ManualLogSource log)
		{
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Expected O, but got Unknown
			_log = log;
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZSyncTransform), "OwnerSync", new Type[0], (Type[])null);
			if (methodInfo == null)
			{
				return "ZSyncTransform.OwnerSync has changed since this fix was written";
			}
			try
			{
				_nview = AccessTools.FieldRefAccess<ZSyncTransform, ZNetView>("m_nview");
				_body = AccessTools.FieldRefAccess<ZSyncTransform, Rigidbody>("m_body");
				_character = AccessTools.FieldRefAccess<ZSyncTransform, Character>("m_character");
				_projectile = AccessTools.FieldRefAccess<ZSyncTransform, Projectile>("m_projectile");
				_wasOwner = AccessTools.FieldRefAccess<ZSyncTransform, bool>("m_wasOwner");
				_positionCached = AccessTools.FieldRefAccess<ZSyncTransform, Vector3>("m_positionCached");
				_velocityCached = AccessTools.FieldRefAccess<ZSyncTransform, Vector3>("m_velocityCached");
			}
			catch (Exception)
			{
				return "ZSyncTransform's fields have changed since this fix was written";
			}
			List<CodeInstruction> originalInstructions = PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null);
			FieldInfo posField = AccessTools.Field(typeof(ZSyncTransform), "m_positionCached");
			FieldInfo velField = AccessTools.Field(typeof(ZSyncTransform), "m_velocityCached");
			MethodInfo hasChanged = AccessTools.PropertyGetter(typeof(Transform), "hasChanged");
			MethodInfo setRotation = AccessTools.Method(typeof(ZDO), "SetRotation", new Type[1] { typeof(Quaternion) }, (Type[])null);
			if (!originalInstructions.Any((CodeInstruction c) => CodeInstructionExtensions.LoadsField(c, posField, true)) || !originalInstructions.Any((CodeInstruction c) => CodeInstructionExtensions.LoadsField(c, velField, true)) || !originalInstructions.Any((CodeInstruction c) => CodeInstructionExtensions.Calls(c, hasChanged)) || !originalInstructions.Any((CodeInstruction c) => CodeInstructionExtensions.Calls(c, setRotation)))
			{
				return "ZSyncTransform.OwnerSync no longer looks as it did when this fix was written";
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(FloatingSyncDeadbandFix), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		private static bool IsFloater(ZSyncTransform sync)
		{
			if (!Floaters.TryGetValue(sync, out var value))
			{
				value = ((sync.m_syncPosition && !sync.m_characterParentSync && (Object)(object)_body.Invoke(sync) != (Object)null && (Object)(object)_character.Invoke(sync) == (Object)null && (Object)(object)_projectile.Invoke(sync) == (Object)null && (Object)(object)((Component)sync).GetComponent<Floating>() != (Object)null && (Object)(object)((Component)sync).GetComponent<Ship>() == (Object)null && (Object)(object)((Component)sync).GetComponent<Vagon>() == (Object)null && (Object)(object)((Component)sync).GetComponent<Fish>() == (Object)null) ? Yes : No);
				Floaters.Add(sync, value);
			}
			return value == Yes;
		}

		private static void Prefix(ZSyncTransform __instance)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			if (PositionStep <= 0f || !IsFloater(__instance))
			{
				return;
			}
			ZDO zDO = _nview.Invoke(__instance).GetZDO();
			if (zDO == null || !_wasOwner.Invoke(__instance) || !zDO.IsOwner())
			{
				return;
			}
			Rigidbody val = _body.Invoke(__instance);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Vector3 position = val.position;
			Vector3 val2 = position - zDO.GetPosition();
			if (((Vector3)(ref val2)).sqrMagnitude < PositionStep * PositionStep)
			{
				_positionCached.Invoke(__instance) = position;
				if (!_reported)
				{
					_skipped++;
				}
			}
			else if (!_reported)
			{
				_sent++;
			}
			Vector3 linearVelocity = val.linearVelocity;
			Vector3 val3 = ((((Vector3)(ref linearVelocity)).sqrMagnitude < 0.010000001f) ? Vector3.zero : linearVelocity);
			Vector3 vec = zDO.GetVec3(ZDOVars.s_velHash, Vector3.zero);
			val2 = val3 - vec;
			if (((Vector3)(ref val2)).sqrMagnitude < 0.010000001f)
			{
				_velocityCached.Invoke(__instance) = linearVelocity;
			}
			else if (val3 == Vector3.zero)
			{
				zDO.Set(ZDOVars.s_velHash, Vector3.zero);
				_velocityCached.Invoke(__instance) = linearVelocity;
			}
			if (__instance.m_syncRotation && !__instance.m_syncScale && ((Component)__instance).transform.hasChanged && Quaternion.Angle(val.rotation, zDO.GetRotation()) < 2f)
			{
				((Component)__instance).transform.hasChanged = false;
			}
			if (!_reported && Time.time >= _nextReport)
			{
				if (_nextReport > 0f && _skipped + _sent > 0)
				{
					_log.LogInfo((object)$"Floating objects: {_sent} position updates sent, {_skipped} skipped in the first minute with floating objects nearby.");
					_reported = true;
				}
				_skipped = (_sent = 0);
				_nextReport = Time.time + 60f;
			}
		}
	}
	internal static class FrozenSurfaces
	{
		private static readonly HashSet<Collider> Set = new HashSet<Collider>();

		private static readonly List<Collider> List = new List<Collider>();

		private static readonly Dictionary<WaterVolume, Collider> ByVolume = new Dictionary<WaterVolume, Collider>();

		private static FieldRef<object, MeshCollider> _surface;

		private static FieldRef<object, WaterVolume> _volume;

		private static string _problem;

		private static bool _patched;

		public static List<Collider> All => List;

		public static event Action<Collider> Added;

		public static bool Contains(Collider c)
		{
			if (c != null)
			{
				return Set.Contains(c);
			}
			return false;
		}

		public static bool IsFrozen(WaterVolume volume)
		{
			if (volume != null && ByVolume.TryGetValue(volume, out var value) && (Object)(object)value != (Object)null)
			{
				return value.enabled;
			}
			return false;
		}

		public static string Ensure(Harmony harmony)
		{
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			if (_patched || _problem != null)
			{
				return _problem;
			}
			Type type = Plugin.ModType("RustyMods.Seasonality",

patchers/ValPerfPatcher.Preloader.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ValPerfPatcher.Preloader")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0748580fd365b77f64b6e7279a486314c4bf5a5d")]
[assembly: AssemblyProduct("ValPerfPatcher.Preloader")]
[assembly: AssemblyTitle("ValPerfPatcher.Preloader")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ValPerfPatcher.Preloader
{
	public static class SoftReferenceNameAlias
	{
		public static IEnumerable<string> TargetDLLs { get; } = new string[1] { "SoftReferenceableAssets.dll" };

		public static void Patch(AssemblyDefinition assembly)
		{
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			ManualLogSource val = Logger.CreateLogSource("ValPerfPatcher.Preloader");
			try
			{
				ModuleDefinition mainModule = assembly.MainModule;
				TypeDefinition type = mainModule.GetType("SoftReferenceableAssets.SoftReference`1");
				if (type == null || ((TypeReference)type).GenericParameters.Count != 1)
				{
					val.LogWarning((object)"SoftReference.Name alias: the game's SoftReference has changed; nothing added.");
					return;
				}
				if (((IEnumerable<MethodDefinition>)type.Methods).Any((MethodDefinition m) => ((MemberReference)m).Name == "get_Name" && !m.IsStatic && !((MethodReference)m).HasParameters))
				{
					val.LogInfo((object)"SoftReference.Name alias: the game has Name itself; nothing added.");
					return;
				}
				MethodDefinition val2 = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "get_name" && !m.IsStatic && !((MethodReference)m).HasParameters && (int)((MethodReference)m).ReturnType.MetadataType == 14));
				if (val2 == null)
				{
					val.LogWarning((object)"SoftReference.Name alias: the game's SoftReference has no name getter; nothing added.");
					return;
				}
				GenericInstanceType val3 = new GenericInstanceType((TypeReference)(object)type);
				val3.GenericArguments.Add((TypeReference)(object)((TypeReference)type).GenericParameters[0]);
				MethodReference val4 = new MethodReference(((MemberReference)val2).Name, mainModule.TypeSystem.String, (TypeReference)(object)val3)
				{
					HasThis = true
				};
				MethodDefinition val5 = new MethodDefinition("get_Name", (MethodAttributes)2182, mainModule.TypeSystem.String);
				ILProcessor iLProcessor = val5.Body.GetILProcessor();
				iLProcessor.Emit(OpCodes.Ldarg_0);
				iLProcessor.Emit(OpCodes.Call, val4);
				iLProcessor.Emit(OpCodes.Ret);
				type.Methods.Add(val5);
				type.Properties.Add(new PropertyDefinition("Name", (PropertyAttributes)0, mainModule.TypeSystem.String)
				{
					GetMethod = val5
				});
				val.LogInfo((object)"SoftReference.Name alias: added (Valheim 1.0.30 renamed it to name; older mods still ask for Name).");
			}
			catch (Exception ex)
			{
				val.LogError((object)("SoftReference.Name alias: failed, nothing added: " + ex));
			}
			finally
			{
				Logger.Sources.Remove((ILogSource)(object)val);
			}
		}
	}
}