Decompiled source of Serverbound v0.1.28

BepInEx/plugins/Serverbound/Serverbound.dll

Decompiled 2 weeks ago
#define TRACE
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using Serverbound.Compatibility;
using Serverbound.FeatureModel;
using Serverbound.Features;
using Serverbound.Patching;
using Serverbound.Requirements;
using Serverbound.Settings;
using SoftReferenceableAssets;
using Steamworks;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("Serverbound.Tests")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: IgnoresAccessChecksTo("SoftReferenceableAssets")]
[assembly: AssemblyCompany("Serverbound")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Dedicated world simulation and optional client compatibility for Valheim.")]
[assembly: AssemblyFileVersion("0.1.28.0")]
[assembly: AssemblyInformationalVersion("0.1.28")]
[assembly: AssemblyProduct("Serverbound")]
[assembly: AssemblyTitle("Serverbound")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.28.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 Serverbound
{
	public static class AdminCommands
	{
		private static Dictionary<string, GameObject> s_items;

		public static ZNetPeer FindPlayer(string name, out string problem)
		{
			problem = null;
			List<ZNetPeer> list = (from p in ZNet.instance.GetPeers()
				where p.IsReady() && !string.IsNullOrEmpty(p.m_playerName)
				select p).ToList();
			ZNetPeer val = ((IEnumerable<ZNetPeer>)list).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => string.Equals(p.m_playerName, name, StringComparison.OrdinalIgnoreCase)));
			if (val != null)
			{
				return val;
			}
			List<ZNetPeer> list2 = list.Where((ZNetPeer p) => p.m_playerName.StartsWith(name, StringComparison.OrdinalIgnoreCase)).ToList();
			List<ZNetPeer> list3 = ((list2.Count > 0) ? list2 : list.Where((ZNetPeer p) => p.m_playerName.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0).ToList());
			if (list3.Count == 1)
			{
				return list3[0];
			}
			problem = ((list3.Count == 0) ? ("No player '" + name + "' online. Online: " + Names(list)) : ("'" + name + "' matches several players: " + Names(list3)));
			return null;
		}

		public static string Players()
		{
			List<ZNetPeer> list = (from p in ZNet.instance.GetPeers()
				where p.IsReady()
				select p).ToList();
			if (list.Count == 0)
			{
				return "No players online";
			}
			return string.Join("; ", list.Select(delegate(ZNetPeer p)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				Vector3 refPos = p.GetRefPos();
				return $"{p.m_playerName} ({p.m_socket.GetHostName()}) at {refPos.x:0},{refPos.z:0}";
			}));
		}

		public static string Give(ZNetPeer target, string itemName, int amount, string byWhom)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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_006b: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: 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_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = FindItem(itemName);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return "No item '" + itemName + "'." + Suggest(itemName);
			}
			amount = Mathf.Clamp(amount, 1, Mathf.Max(1, Configuration.maxGiveAmount.Value));
			ZDO zDO = ZDOMan.instance.GetZDO(target.m_characterID);
			Vector3 val2 = ((zDO != null) ? zDO.GetPosition() : target.GetRefPos()) + Vector3.up * 1.5f;
			int num = Mathf.Max(1, val.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxStackSize);
			int num2 = 0;
			for (int num3 = amount; num3 > 0; num3 -= num)
			{
				Vector2 val3 = Random.insideUnitCircle * 0.75f;
				Vector3 val4 = val2 + new Vector3(val3.x, 0.25f * (float)num2, val3.y);
				Object.Instantiate<GameObject>(val, val4, Quaternion.identity).GetComponent<ItemDrop>().SetStack(Mathf.Min(num3, num));
				num2++;
			}
			string text = $"{byWhom} gave {amount} x {((Object)val).name} to {target.m_playerName} in {num2} stack(s) at {val2.x:0},{val2.z:0}";
			Plugin.logger.LogInfo((object)("Admin: " + text));
			return text;
		}

		public static string Save(string byWhom)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer())
			{
				return "No world loaded, nothing to save";
			}
			bool flag = default(bool);
			if (!ZNet.instance.EnoughDiskSpaceAvailable(ref flag, false, (Action<bool>)null))
			{
				return "Not enough disk space, world not saved";
			}
			Plugin.logger.LogInfo((object)("Admin: " + byWhom + " requested a world save"));
			ZNet.instance.Save(false, true, true);
			return "Saving world";
		}

		public static string Broadcast(string text, string byWhom)
		{
			ZRoutedRpc.instance.InvokeRoutedRPC(0L, "ShowMessage", new object[2] { 2, text });
			Plugin.logger.LogInfo((object)("Admin: " + byWhom + " broadcast: " + text));
			return $"shown to {ZNet.instance.GetNrOfPlayers()} player(s): {text}";
		}

		public static string StartEvent(string name, ZNetPeer target, string byWhom)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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)
			if (!Object.op_Implicit((Object)(object)RandEventSystem.instance) || !RandEventSystem.instance.HaveEvent(name))
			{
				return "No event '" + name + "'. Events: " + Events();
			}
			ZDO zDO = ZDOMan.instance.GetZDO(target.m_characterID);
			Vector3 val = ((zDO != null) ? zDO.GetPosition() : target.GetRefPos());
			RandEventSystem.instance.SetRandomEventByName(name, val);
			string text = $"{byWhom} started event {name} at {target.m_playerName} ({val.x:0},{val.z:0})";
			Plugin.logger.LogInfo((object)("Admin: " + text));
			return text;
		}

		public static string Events()
		{
			if (!Object.op_Implicit((Object)(object)RandEventSystem.instance))
			{
				return "none (no world loaded)";
			}
			return string.Join(", ", RandEventSystem.instance.m_events.Select((RandomEvent e) => e.m_name));
		}

		public static bool TryParseAmount(string text, out int amount)
		{
			return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out amount);
		}

		private static string Names(List<ZNetPeer> peers)
		{
			if (peers.Count != 0)
			{
				return string.Join(", ", peers.Select((ZNetPeer p) => p.m_playerName));
			}
			return "nobody";
		}

		private static GameObject FindItem(string name)
		{
			if (s_items == null)
			{
				s_items = new Dictionary<string, GameObject>(StringComparer.OrdinalIgnoreCase);
				foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
				{
					if (Object.op_Implicit((Object)(object)prefab) && Object.op_Implicit((Object)(object)prefab.GetComponent<ItemDrop>()) && !s_items.ContainsKey(((Object)prefab).name))
					{
						s_items[((Object)prefab).name] = prefab;
					}
				}
			}
			if (!s_items.TryGetValue(name, out var value))
			{
				return null;
			}
			return value;
		}

		private static string Suggest(string name)
		{
			List<string> list = new List<string>();
			foreach (string key in s_items.Keys)
			{
				if (key.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					list.Add(key);
					if (list.Count == 8)
					{
						break;
					}
				}
			}
			if (list.Count <= 0)
			{
				return "";
			}
			return " Similar: " + string.Join(", ", list);
		}
	}
	public static class ConsoleInput
	{
		public delegate void LineHandler(string line, string notice);

		private static readonly UTF8Encoding s_utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

		private const string Cp1250 = "€\ufffd‚\ufffd„…†‡\ufffd‰Š‹ŚŤŽŹ\ufffd‘’“”•–—\ufffd™š›śťžź\u00a0ˇ\u02d8٤Ą¦§\u00a8©Ş«¬\u00ad®Ż°±\u02dbł\u00b4µ¶·\u00b8ąş»Ľ\u02ddľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ\u02d9";

		private const string Cp852 = "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ\u00b4\u00ad\u02dd\u02dbˇ\u02d8§÷\u00b8°\u00a8\u02d9űŘř■\u00a0";

		public static void ReadLines(Func<int> codePage, LineHandler handler)
		{
			bool noticed = false;
			using Stream stream = Console.OpenStandardInput();
			byte[] array = new byte[4096];
			List<byte> list = new List<byte>();
			int num;
			while ((num = stream.Read(array, 0, array.Length)) > 0)
			{
				for (int i = 0; i < num; i++)
				{
					if (array[i] == 10)
					{
						Emit(list, codePage(), handler, ref noticed);
						list.Clear();
					}
					else
					{
						list.Add(array[i]);
					}
				}
			}
			Emit(list, codePage(), handler, ref noticed);
		}

		private static void Emit(List<byte> line, int codePage, LineHandler handler, ref bool noticed)
		{
			if (line.Count > 0 && line[line.Count - 1] == 13)
			{
				line.RemoveAt(line.Count - 1);
			}
			if (line.Count != 0)
			{
				byte[] array = line.ToArray();
				string notice = null;
				bool fellBack;
				string line2 = Decode(array, codePage, out fellBack);
				if (fellBack && !noticed)
				{
					noticed = true;
					notice = string.Format("Console input is not UTF-8 (bytes: {0}); decoded with code page {1}.", BitConverter.ToString(array).Replace("-", " "), codePage) + " If accents come out wrong, set [Server] ConsoleInputCodePage to what the panel sends (1250, 852, 1252 or 65001).";
				}
				handler(line2, notice);
			}
		}

		public static string Decode(byte[] data, int codePage, out bool fellBack)
		{
			fellBack = false;
			bool flag = true;
			for (int i = 0; i < data.Length; i++)
			{
				if (data[i] >= 128)
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				return Encoding.ASCII.GetString(data);
			}
			if (codePage != 65001)
			{
				try
				{
					return s_utf8.GetString(data);
				}
				catch (DecoderFallbackException)
				{
					fellBack = true;
				}
			}
			return SingleByte(data, codePage);
		}

		private static string SingleByte(byte[] data, int codePage)
		{
			string text = codePage switch
			{
				1250 => "€\ufffd‚\ufffd„…†‡\ufffd‰Š‹ŚŤŽŹ\ufffd‘’“”•–—\ufffd™š›śťžź\u00a0ˇ\u02d8٤Ą¦§\u00a8©Ş«¬\u00ad®Ż°±\u02dbł\u00b4µ¶·\u00b8ąş»Ľ\u02ddľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ\u02d9", 
				852 => "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ\u00b4\u00ad\u02dd\u02dbˇ\u02d8§÷\u00b8°\u00a8\u02d9űŘř■\u00a0", 
				_ => null, 
			};
			char[] array = new char[data.Length];
			for (int i = 0; i < data.Length; i++)
			{
				byte b = data[i];
				array[i] = (char)((b < 128) ? b : (((int?)text?[b - 128]) ?? ((int)b)));
			}
			return new string(array);
		}
	}
	internal static class CoreVerification
	{
		private static readonly List<(MethodBase Target, MethodInfo Hook, HarmonyPatchType Kind)> hooks = new List<(MethodBase, MethodInfo, HarmonyPatchType)>();

		private static readonly Dictionary<MethodBase, bool> rewrites = new Dictionary<MethodBase, bool>();

		private static bool verified;

		internal static bool Failed { get; private set; }

		internal static bool Blocked
		{
			get
			{
				if (!Failed)
				{
					if (rewrites.Count != 0)
					{
						return !verified;
					}
					return false;
				}
				return true;
			}
		}

		internal static void Begin()
		{
			if (hooks.Count == 0)
			{
				Prepare();
			}
			rewrites.Clear();
			foreach (var item in hooks.Where<(MethodBase, MethodInfo, HarmonyPatchType)>(((MethodBase Target, MethodInfo Hook, HarmonyPatchType Kind) h) => (int)h.Kind == 3))
			{
				rewrites.Add(item.Item1, value: false);
			}
			Failed = false;
			verified = false;
		}

		private unsafe static void Prepare()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			Type[] nestedTypes = typeof(Core).GetNestedTypes();
			foreach (Type type in nestedTypes)
			{
				HarmonyMethod info = ((HarmonyAttribute)((MemberInfo)type).GetCustomAttributes<HarmonyPatch>().Single()).info;
				MethodInfo item = AccessTools.DeclaredMethod(info.declaringType, info.methodName, info.argumentTypes, (Type[])null) ?? throw new MissingMethodException(info.declaringType.FullName, info.methodName);
				HarmonyPatchType[] array = new HarmonyPatchType[4];
				RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
				HarmonyPatchType[] array2 = (HarmonyPatchType[])(object)array;
				for (int j = 0; j < array2.Length; j++)
				{
					HarmonyPatchType item2 = array2[j];
					MethodInfo method = type.GetMethod(((object)(*(HarmonyPatchType*)(&item2))/*cast due to .constrained prefix*/).ToString(), AccessTools.allDeclared);
					if (method != null)
					{
						hooks.Add((item, method, item2));
					}
				}
			}
		}

		internal static void Record(MethodBase method, bool matched)
		{
			if (rewrites.ContainsKey(method))
			{
				rewrites[method] = matched;
				if (!matched && !Failed)
				{
					Failed = true;
					SimulationPatch.Deactivate();
					Plugin.logger.LogError((object)("Core: " + (verified ? "NO LONGER APPLIED" : "NOT APPLIED") + "; required rewrite failed: " + method.DeclaringType.Name + "." + method.Name + "."));
				}
			}
		}

		internal static void Require(bool allowPending = false)
		{
			if (Failed || rewrites.Count == 0)
			{
				throw new NotSupportedException("Core: a required transpiler did not apply.");
			}
			MethodBase[] array = (from r in rewrites
				where !r.Value
				select r.Key).ToArray();
			if (array.Length != 0)
			{
				if (!allowPending)
				{
					throw new NotSupportedException("Core: required transpilers did not run: " + string.Join(", ", array.Select((MethodBase m) => m.DeclaringType.Name + "." + m.Name)));
				}
			}
			else
			{
				if (Harmony.GetAllPatchedMethods().SelectMany(SimulationPatch.All).Count((Patch p) => p.owner == "org.serverbound.valheim.Core") != hooks.Count || hooks.Any<(MethodBase, MethodInfo, HarmonyPatchType)>(((MethodBase Target, MethodInfo Hook, HarmonyPatchType Kind) h) => !Registered(h.Target, h.Hook, h.Kind)))
				{
					throw new NotSupportedException("Core: required Harmony registrations changed.");
				}
				verified = true;
			}
		}

		private static bool Registered(MethodBase target, MethodInfo hook, HarmonyPatchType kind)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			Patches patchInfo = Harmony.GetPatchInfo(target);
			if (patchInfo == null)
			{
				return false;
			}
			return (((int)kind == 1) ? patchInfo.Prefixes : (((int)kind == 2) ? patchInfo.Postfixes : (((int)kind == 3) ? patchInfo.Transpilers : patchInfo.Finalizers))).Count((Patch p) => p.owner == "org.serverbound.valheim.Core" && p.PatchMethod == hook) == 1;
		}
	}
	internal static class ILMatch
	{
		private static readonly OpCode[] localLoads = new OpCode[4]
		{
			OpCodes.Ldloc_0,
			OpCodes.Ldloc_1,
			OpCodes.Ldloc_2,
			OpCodes.Ldloc_3
		};

		internal static int Site(List<CodeInstruction> code, Func<int, bool> matches)
		{
			int[] array = Enumerable.Range(0, code.Count).Where(matches).ToArray();
			if (array.Length != 1 || !Plain(code[array[0]]))
			{
				return -1;
			}
			return array[0];
		}

		internal static bool Plain(CodeInstruction code)
		{
			if (code.labels.Count == 0)
			{
				return code.blocks.Count == 0;
			}
			return false;
		}

		internal static bool Shape(List<CodeInstruction> code, int start, params Func<CodeInstruction, bool>[] pattern)
		{
			if (start >= 0 && start + pattern.Length <= code.Count)
			{
				return Enumerable.Range(0, pattern.Length).All((int i) => pattern[i](code[start + i]));
			}
			return false;
		}

		internal static Func<CodeInstruction, bool> Is(params OpCode[] opcodes)
		{
			return (CodeInstruction code) => opcodes.Contains(code.opcode);
		}

		internal static Func<CodeInstruction, bool> Loads(FieldInfo field)
		{
			return (CodeInstruction code) => CodeInstructionExtensions.LoadsField(code, field, false);
		}

		internal static Func<CodeInstruction, bool> Calls(MethodInfo method)
		{
			return (CodeInstruction code) => CodeInstructionExtensions.Calls(code, method);
		}

		internal static Func<CodeInstruction, bool> Ldarg(int index)
		{
			return (CodeInstruction code) => CodeInstructionExtensions.IsLdarg(code, (int?)index);
		}

		internal static Func<CodeInstruction, bool> IsLoad(int index)
		{
			return (CodeInstruction code) => (index < localLoads.Length && code.opcode == localLoads[index]) || ((code.opcode == OpCodes.Ldloc || code.opcode == OpCodes.Ldloc_S) && Local(code) == index);
		}

		internal static Func<CodeInstruction, bool> IsAddress(int index)
		{
			return (CodeInstruction code) => (code.opcode == OpCodes.Ldloca || code.opcode == OpCodes.Ldloca_S) && Local(code) == index;
		}

		private static int Local(CodeInstruction code)
		{
			if (!(code.operand is LocalVariableInfo localVariableInfo))
			{
				return Convert.ToInt32(code.operand);
			}
			return localVariableInfo.LocalIndex;
		}

		internal static bool Locals(MethodBase method, int count, params (int Index, Type Type)[] expected)
		{
			IList<LocalVariableInfo> locals = method.GetMethodBody().LocalVariables;
			if (locals.Count == count)
			{
				return expected.All(((int Index, Type Type) local) => locals[local.Index].LocalType == local.Type);
			}
			return false;
		}

		internal static bool Targets(CodeInstruction branch, CodeInstruction destination)
		{
			if (branch.operand is Label item)
			{
				return destination.labels.Contains(item);
			}
			return false;
		}
	}
	[Harmony]
	[BepInPlugin("org.serverbound.valheim", "Serverbound", "0.1.28")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInIncompatibility("MVP.Valheim_Serverside_Simulations")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGUID = "org.serverbound.valheim";

		public const string PluginName = "Serverbound";

		public const string PluginVersion = "0.1.28";

		private static Plugin context;

		public static Configuration configuration;

		public static Harmony harmony;

		public const string ValheimPlusPluginId = "org.bepinex.plugins.valheim_plus";

		public static ManualLogSource logger;

		private static bool consoleStarted;

		private static bool installed;

		public static Plugin instance => context;

		private void Awake()
		{
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			context = this;
			logger = ((BaseUnityPlugin)this).Logger;
			Configuration.Load(((BaseUnityPlugin)this).Config);
			CompatibilityInstaller.Info = delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)message);
			};
			CompatibilityInstaller.Warning = delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)message);
			};
			CompatibilityInstaller.Error = delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)message);
			};
			try
			{
				CompatibilityInstaller.CheckInstallation(Resolve, VersionOf, IsDedicated());
				Guard.Build(typeof(ZNet).Assembly, IsDedicated() ? ExpectedBuilds.Server : ExpectedBuilds.Valheim);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Serverbound: REJECTED BUILD/INSTALLATION; no patches installed. " + ex));
				return;
			}
			if (!ModIsEnabled())
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Serverbound is disabled. (configuration)");
				return;
			}
			if (!IsDedicated())
			{
				bool value = ((BaseUnityPlugin)this).Config.Bind<bool>("Compatibility", "ClientSkills", true, "Publish ImpactfulSkills state only after a Serverbound server handshake. Dedicated simulation never runs on clients.").Value;
				CompatibilityInstaller.Install(Resolve, CompatibilityInstaller.Info, CompatibilityInstaller.Warning, CompatibilityInstaller.Error, value);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Serverbound client compatibility loaded; dedicated simulation is inactive on this client.");
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Installing Serverbound");
			LimitJobWorkers(Configuration.unityJobWorkers.Value);
			LimitPhysicsCatchUp(Configuration.maxCatchUpMs.Value);
			if (Configuration.consoleCommandsEnabled.Value)
			{
				ServerConsole.Start();
				consoleStarted = true;
			}
			harmony = new Harmony("org.serverbound.valheim");
			AvailableFeatures availableFeatures = new AvailableFeatures();
			availableFeatures.AddFeature(new Core());
			availableFeatures.AddFeature(new MaxObjectsPerFrame());
			availableFeatures.AddFeature(new Networking());
			availableFeatures.AddFeature(new Performance());
			availableFeatures.AddFeature(new Fixes());
			availableFeatures.AddFeature(new Debugging());
			availableFeatures.AddFeature(new VcpObjectPassPatch());
			availableFeatures.AddFeature(new DungeonLoadGuard());
			availableFeatures.AddFeature(new StationRange());
			availableFeatures.AddFeature(new ServerSmoke());
			availableFeatures.AddFeature(new HandedOverFires());
			PatchRequirements patchRequirements = new PatchRequirements();
			patchRequirements.AddRequirement(new PatchRequirement.DebugBuild());
			if (PatchFeatures(availableFeatures, new HarmonyFeaturesPatcher(patchRequirements)))
			{
				VanillaDrift.Check(((BaseUnityPlugin)this).Logger);
				installed = true;
				CompatibilityInstaller.Install(Resolve, CompatibilityInstaller.Info, CompatibilityInstaller.Warning, CompatibilityInstaller.Error, installOwnerSkills: true, dedicated: true);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Serverbound installed; deferred compatibility verification pending.");
			}
		}

		private static Assembly Resolve(string guid)
		{
			if (!Chainloader.PluginInfos.TryGetValue(guid, out var value))
			{
				return null;
			}
			return ((object)value.Instance)?.GetType().Assembly;
		}

		private static Version VersionOf(string guid)
		{
			if (!Chainloader.PluginInfos.TryGetValue(guid, out var value))
			{
				return null;
			}
			return value.Metadata.Version;
		}

		private void Start()
		{
			try
			{
				CompatibilityInstaller.CheckInstallation(Resolve, VersionOf, IsDedicated());
				if (installed)
				{
					CoreVerification.Require();
				}
				CompatibilityInstaller.Verify();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Serverbound: deferred compatibility gate failed. " + ex));
				DisableSimulation();
			}
		}

		internal static void DisableSimulation()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			installed = false;
			SimulationPatch.Deactivate();
			try
			{
				string[] array = (from p in Harmony.GetAllPatchedMethods().SelectMany(SimulationPatch.All)
					select p.owner).Where(IsSimulationOwner).Distinct().ToArray();
				for (int num = 0; num < array.Length; num++)
				{
					new Harmony(array[num]).UnpatchSelf();
				}
				if (Harmony.GetAllPatchedMethods().SelectMany(SimulationPatch.All).Any((Patch p) => IsSimulationOwner(p.owner)))
				{
					throw new InvalidOperationException("Serverbound hooks remain installed.");
				}
				SimulationPatch.RestoreVendors();
				CompatibilityInstaller.Error("Simulation: DISABLED; resolve the rejected integration before admitting players.");
			}
			catch (Exception ex)
			{
				CompatibilityInstaller.Error("Simulation: rollback could not disable Serverbound; stop the server before players join. " + ex);
			}
		}

		private static bool IsSimulationOwner(string owner)
		{
			if ((owner == "org.serverbound.valheim" || owner.StartsWith("org.serverbound.valheim.", StringComparison.Ordinal)) && owner != "org.serverbound.valheim.ServerConsole" && owner != "org.serverbound.valheim.OdinShip")
			{
				return owner != "org.serverbound.valheim.TerrainLimits";
			}
			return false;
		}

		private void Update()
		{
			if (installed && CoreVerification.Failed)
			{
				DisableSimulation();
			}
			OdinShipOwnershipPatch.Update();
			if (consoleStarted)
			{
				ServerConsole.ProcessPending();
			}
			if (installed)
			{
				PerformanceStats.Frame();
			}
		}

		private void FixedUpdate()
		{
			if (installed)
			{
				PerformanceStats.FixedStep();
			}
		}

		private void LimitJobWorkers(int limit)
		{
			int jobWorkerCount = JobsUtility.JobWorkerCount;
			if (limit > 0 && limit < jobWorkerCount)
			{
				JobsUtility.JobWorkerCount = limit;
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Unity job worker threads: {jobWorkerCount} -> {JobsUtility.JobWorkerCount}");
			}
		}

		private void LimitPhysicsCatchUp(int milliseconds)
		{
			if (milliseconds > 0)
			{
				float maximumDeltaTime = Time.maximumDeltaTime;
				Time.maximumDeltaTime = Mathf.Max((float)milliseconds / 1000f, Time.fixedDeltaTime);
				((BaseUnityPlugin)this).Logger.LogInfo((object)($"Physics catch-up: at most {Mathf.RoundToInt(Time.maximumDeltaTime / Time.fixedDeltaTime)} fixed steps per frame " + $"(fixed step {1000f * Time.fixedDeltaTime:0} ms, longest frame counted {1000f * maximumDeltaTime:0} -> {1000f * Time.maximumDeltaTime:0} ms)"));
			}
		}

		private bool PatchFeatures(AvailableFeatures availableFeatures, HarmonyFeaturesPatcher patcher)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			List<Harmony> list = new List<Harmony>();
			foreach (IFeature item in availableFeatures.EnabledFeatures())
			{
				string name = item.GetType().Name;
				Harmony val = new Harmony("org.serverbound.valheim." + name);
				try
				{
					if (item is Core)
					{
						CoreVerification.Begin();
					}
					patcher.PatchAll(item.GetType().GetNestedTypes(), val);
					if (item is Core)
					{
						CoreVerification.Require(allowPending: true);
					}
					list.Add(val);
				}
				catch (Exception arg)
				{
					val.UnpatchSelf();
					if (item is Core)
					{
						((BaseUnityPlugin)this).Logger.LogError((object)string.Format("Core patches failed to apply; {0} is disabled and the server runs vanilla. {1}", "Serverbound", arg));
						foreach (Harmony item2 in list)
						{
							item2.UnpatchSelf();
						}
						harmony.UnpatchSelf();
						return false;
					}
					((BaseUnityPlugin)this).Logger.LogError((object)$"Feature {name} failed to apply and is disabled. {arg}");
				}
			}
			return true;
		}

		public bool ModIsEnabled()
		{
			return Configuration.modEnabled.Value;
		}

		public static bool IsDedicated()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return new ZNet().IsDedicated();
		}
	}
	public static class ServerConsole
	{
		private const string Commands = "save | stop | players | give <item> <amount> <player> | broadcast <text> | event <name> <player> | events | help -- anything else goes to the game console: kick, ban, unban, banned, stopevent, devcommands, skiptime ...";

		private static readonly ConcurrentQueue<string> s_commands = new ConcurrentQueue<string>();

		private static bool s_capturing;

		private static int s_captured;

		private static Harmony s_capture;

		public static void Start()
		{
			Thread thread = new Thread(ReadLoop);
			thread.IsBackground = true;
			thread.Name = "Serverbound console";
			thread.Start();
			Plugin.logger.LogInfo((object)"Console commands enabled on standard input: save | stop | players | give <item> <amount> <player> | broadcast <text> | event <name> <player> | events | help -- anything else goes to the game console: kick, ban, unban, banned, stopevent, devcommands, skiptime ...");
		}

		private static void ReadLoop()
		{
			try
			{
				ConsoleInput.ReadLines(() => Configuration.consoleInputCodePage.Value, delegate(string line, string notice)
				{
					if (notice != null)
					{
						s_commands.Enqueue("\u0001" + notice);
					}
					line = line.Trim();
					if (line.Length > 0)
					{
						s_commands.Enqueue(line);
					}
				});
			}
			catch (Exception ex)
			{
				s_commands.Enqueue("\0" + ex.Message);
			}
		}

		private static void Reply(string text)
		{
			Plugin.logger.LogInfo((object)("Console: " + text));
			WriteOut(text);
		}

		private static void WriteOut(string text)
		{
			try
			{
				Console.Out.WriteLine("Console: " + text);
				Console.Out.Flush();
			}
			catch (Exception)
			{
			}
		}

		public static void ProcessPending()
		{
			string result;
			while (s_commands.TryDequeue(out result))
			{
				Execute(result);
			}
		}

		private static void Execute(string command)
		{
			if (command[0] == '\0')
			{
				Plugin.logger.LogWarning((object)("Console commands unavailable, cannot read standard input: " + command.Substring(1)));
				return;
			}
			if (command[0] == '\u0001')
			{
				Plugin.logger.LogWarning((object)command.Substring(1));
				WriteOut(command.Substring(1));
				return;
			}
			string[] array = command.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			bool flag = Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer();
			try
			{
				switch (array[0].ToLowerInvariant())
				{
				case "save":
					Reply(AdminCommands.Save("console"));
					break;
				case "stop":
				case "quit":
				case "shutdown":
					Reply("saving world and shutting down");
					Application.Quit();
					break;
				case "players":
					Reply(flag ? AdminCommands.Players() : "no world loaded");
					break;
				case "give":
				{
					if (!flag)
					{
						Reply("no world loaded");
						break;
					}
					if (array.Length < 4 || !AdminCommands.TryParseAmount(array[2], out var amount))
					{
						Reply("usage: give <item> <amount> <player>, e.g. give Copper 120 Ulf");
						break;
					}
					string problem;
					ZNetPeer val = AdminCommands.FindPlayer(string.Join(" ", array, 3, array.Length - 3), out problem);
					Reply((val == null) ? problem : AdminCommands.Give(val, array[1], amount, "console"));
					break;
				}
				case "broadcast":
				case "say":
					if (!flag)
					{
						Reply("no world loaded");
					}
					else if (array.Length < 2)
					{
						Reply("usage: broadcast <text>");
					}
					else
					{
						Reply(AdminCommands.Broadcast(command.Substring(array[0].Length).Trim(), "console"));
					}
					break;
				case "event":
				{
					if (!flag)
					{
						Reply("no world loaded");
						break;
					}
					if (array.Length < 3)
					{
						Reply("usage: event <name> <player>, e.g. event army_eikthyr Ulf; `events` lists the names");
						break;
					}
					string problem2;
					ZNetPeer val2 = AdminCommands.FindPlayer(string.Join(" ", array, 2, array.Length - 2), out problem2);
					Reply((val2 == null) ? problem2 : AdminCommands.StartEvent(array[1], val2, "console"));
					break;
				}
				case "events":
					Reply(flag ? ("events: " + AdminCommands.Events()) : "no world loaded");
					break;
				case "help":
					Reply("commands: save | stop | players | give <item> <amount> <player> | broadcast <text> | event <name> <player> | events | help -- anything else goes to the game console: kick, ban, unban, banned, stopevent, devcommands, skiptime ...");
					break;
				default:
					RunGameCommand(command, array[0]);
					break;
				}
			}
			catch (Exception ex)
			{
				Plugin.logger.LogWarning((object)$"Console: '{command}' failed: {ex}");
				Reply("'" + command + "' failed: " + ex.Message);
			}
		}

		private static void RunGameCommand(string command, string word)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)Console.instance))
			{
				Reply("'" + word + "' is not one of ours and the game console is not up yet. Commands: save | stop | players | give <item> <amount> <player> | broadcast <text> | event <name> <player> | events | help -- anything else goes to the game console: kick, ban, unban, banned, stopevent, devcommands, skiptime ...");
				return;
			}
			if (s_capture == null)
			{
				s_capture = new Harmony("org.serverbound.valheim.ServerConsole");
				s_capture.Patch((MethodBase)AccessTools.Method(typeof(Terminal), "AddString", new Type[1] { typeof(string) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(ServerConsole), "AddStringPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			s_capturing = true;
			s_captured = 0;
			try
			{
				((Terminal)Console.instance).TryRunCommand(command, false, true);
			}
			finally
			{
				s_capturing = false;
			}
			if (s_captured == 0)
			{
				Reply("game console ran '" + word + "' without output");
			}
		}

		public static void AddStringPostfix(Terminal __instance, string text)
		{
			if (s_capturing && (Object)(object)__instance == (Object)(object)Console.instance)
			{
				s_captured++;
				WriteOut(text);
			}
		}
	}
	public static class ServerSafe
	{
		private static readonly Dictionary<string, MethodInfo> Replacements = new Dictionary<string, MethodInfo>
		{
			{
				"GetZDOID",
				AccessTools.Method(typeof(ServerSafe), "LocalPlayerZDOID", (Type[])null, (Type[])null)
			},
			{
				"GetPlayerID",
				AccessTools.Method(typeof(ServerSafe), "LocalPlayerID", (Type[])null, (Type[])null)
			},
			{
				"GetPlayerName",
				AccessTools.Method(typeof(ServerSafe), "LocalPlayerName", (Type[])null, (Type[])null)
			}
		};

		private static readonly FieldInfo localPlayer = AccessTools.Field(typeof(Player), "m_localPlayer");

		public static ZDOID LocalPlayerZDOID()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return ZDOID.None;
			}
			return ((Character)Player.m_localPlayer).GetZDOID();
		}

		public static long LocalPlayerID()
		{
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return 0L;
			}
			return Player.m_localPlayer.GetPlayerID();
		}

		public static string LocalPlayerName()
		{
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return "";
			}
			return Player.m_localPlayer.GetPlayerName();
		}

		private static bool Replacement(CodeInstruction code)
		{
			if (code.opcode == OpCodes.Callvirt && code.operand is MethodInfo methodInfo && methodInfo.DeclaringType.IsAssignableFrom(typeof(Player)))
			{
				return Replacements.ContainsKey(methodInfo.Name);
			}
			return false;
		}

		public static IEnumerable<CodeInstruction> NullSafeLocalPlayer(IEnumerable<CodeInstruction> instructions, MethodBase original, int expected)
		{
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			List<CodeInstruction> codes = instructions.Select((Func<CodeInstruction, CodeInstruction>)((CodeInstruction i) => new CodeInstruction(i))).ToList();
			int[] array = (from i in Enumerable.Range(0, codes.Count)
				where ILMatch.Shape(codes, i, ILMatch.Loads(localPlayer), Replacement)
				select i).ToArray();
			bool flag = array.Length == expected && array.All((int i) => ILMatch.Plain(codes[i + 1]));
			CoreVerification.Record(original, flag);
			if (!flag)
			{
				Plugin.logger.LogWarning((object)$"{original.DeclaringType.Name}.{original.Name}: found {array.Length} Player.m_localPlayer call(s), expected {expected}. The game changed this method; it was left unchanged and the patch needs reviewing.");
				return codes;
			}
			for (int num = array.Length - 1; num >= 0; num--)
			{
				int num2 = array[num];
				CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)Replacements[((MethodInfo)codes[num2 + 1].operand).Name]);
				val.labels.AddRange(codes[num2].labels);
				val.blocks.AddRange(codes[num2].blocks);
				codes[num2] = val;
				codes.RemoveAt(num2 + 1);
			}
			return codes;
		}
	}
	public class Utilities
	{
		public static bool IsDebugBuild()
		{
			return false;
		}
	}
	public static class VanillaDrift
	{
		public const string ReviewedForGameVersion = "1.0.15";

		private static readonly Dictionary<MethodBase, string[]> Expected = new Dictionary<MethodBase, string[]>
		{
			{
				AccessTools.Method(typeof(ZoneSystem), "Update", (Type[])null, (Type[])null),
				new string[15]
				{
					"CinematicsManager::IsPlaying", "TextViewer::IsShowingIntro", "Utils::GetTimeBudgetForTargetFrameRate", "ZNet::GetConnectionStatus", "ZNet::GetPeers", "ZNet::GetReferencePosition", "ZNet::IsServer", "ZNet::get_instance", "ZNetPeer::GetRefPos", "ZoneSystem::CreateGhostZones",
					"ZoneSystem::CreateLocalZones", "ZoneSystem::TimeSinceStart", "ZoneSystem::UpdatePrefabLifetimes", "ZoneSystem::UpdateTTL", "ZoneSystem::get_LocationsGenerated"
				}
			},
			{
				AccessTools.Method(typeof(ZoneSystem), "IsActiveAreaLoaded", (Type[])null, (Type[])null),
				new string[7] { "SimulationDistance::get_IsClassic", "SimulationDistance::get_NearSimulationDistance", "Vector2s::.ctor", "ZNet::GetReferencePosition", "ZNet::get_instance", "ZoneSystem::GetZone", "ZoneSystem::ZonesWithinRadius" }
			},
			{
				AccessTools.Method(typeof(ZNetScene), "CreateDestroyObjects", (Type[])null, (Type[])null),
				new string[8] { "ZDOMan::FindSectorObjects", "ZDOMan::get_instance", "ZNet::GetReferencePosition", "ZNet::GetSyncedSimulationDistance", "ZNet::get_instance", "ZNetScene::CreateObjects", "ZNetScene::RemoveObjects", "ZoneSystem::GetZone" }
			},
			{
				AccessTools.Method(typeof(ZDOMan), "ReleaseNearbyZDOS", (Type[])null, (Type[])null),
				new string[14]
				{
					"SimulationDistance::.ctor", "SimulationDistance::get_IsClassic", "SimulationDistance::get_NearSimulationDistance", "ZDO::GetOwner", "ZDO::GetPosition", "ZDO::HasOwner", "ZDO::SetOwner", "ZDO::get_Persistent", "ZDOMan::FindSectorObjects", "ZDOMan::IsInPeerActiveArea",
					"ZNet::GetSyncedSimulationDistance", "ZNet::get_instance", "ZNetScene::InActiveArea", "ZoneSystem::GetZone"
				}
			},
			{
				AccessTools.Method(typeof(ZDOMan), "SendZDOToPeers2", (Type[])null, (Type[])null),
				new string[1] { "ZDOMan::SendZDOs" }
			},
			{
				AccessTools.Method(typeof(ZNetScene), "OutsideActiveArea", new Type[2]
				{
					typeof(Vector3),
					typeof(Vector2s)
				}, (Type[])null),
				new string[1] { "ZNetScene::PointInsideActiveArea" }
			},
			{
				AccessTools.Method(typeof(Ship), "UpdateOwner", (Type[])null, (Type[])null),
				new string[8] { "Ship::GetNewOwnerID", "Ship::IsPlayerInBoat", "Ship::RefreshPlayerList", "ZDO::SetOwner", "ZLog::Log", "ZNetView::GetZDO", "ZNetView::IsOwner", "ZNetView::IsValid" }
			}
		};

		public static void Check(ManualLogSource logger)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			string text = ((object)Version.CurrentVersion/*cast due to .constrained prefix*/).ToString();
			int num = 0;
			foreach (KeyValuePair<MethodBase, string[]> item in Expected)
			{
				if (item.Key == null)
				{
					logger.LogError((object)"Vanilla drift check: a replaced method no longer exists in this game version.");
					num++;
					continue;
				}
				HashSet<string> hashSet = GameCalls(item.Key);
				List<string> list = (from s in hashSet.Except(item.Value)
					orderby s
					select s).ToList();
				List<string> list2 = (from s in item.Value.Except(hashSet)
					orderby s
					select s).ToList();
				if (list.Count != 0 || list2.Count != 0)
				{
					num++;
					logger.LogWarning((object)("Vanilla " + item.Key.DeclaringType.Name + "." + item.Key.Name + " changed since this mod's replacement was reviewed (game 1.0.15, running " + text + "). Now calls: [" + string.Join(", ", list) + "]. No longer calls: [" + string.Join(", ", list2) + "]. The replacement may be dropping new vanilla behaviour."));
				}
			}
			if (num == 0)
			{
				logger.LogInfo((object)string.Format("Vanilla drift check passed ({0} replaced methods, reviewed for {1}, running {2}).", Expected.Count, "1.0.15", text));
			}
		}

		private static HashSet<string> GameCalls(MethodBase method)
		{
			HashSet<string> hashSet = new HashSet<string>();
			foreach (CodeInstruction originalInstruction in PatchProcessor.GetOriginalInstructions(method, (ILGenerator)null))
			{
				if ((originalInstruction.opcode == OpCodes.Call || originalInstruction.opcode == OpCodes.Callvirt || originalInstruction.opcode == OpCodes.Newobj) && originalInstruction.operand is MethodBase methodBase && methodBase.DeclaringType != null)
				{
					string name = methodBase.DeclaringType.Assembly.GetName().Name;
					if (name == "assembly_valheim" || name == "assembly_utils")
					{
						hashSet.Add(methodBase.DeclaringType.Name + "::" + methodBase.Name);
					}
				}
			}
			return hashSet;
		}
	}
}
namespace Serverbound.Requirements
{
	public class PatchRequirement
	{
		public class DebugBuild : IPatchRequirement
		{
			public const string name = "DebugBuild";

			string IPatchRequirement.Name => "DebugBuild";

			Func<bool> IPatchRequirement.Checker => Utilities.IsDebugBuild;
		}
	}
}
namespace Serverbound.Patching
{
	public interface IPatchRequirement
	{
		string Name { get; }

		Func<bool> Checker { get; }
	}
	public class PatchRequirements
	{
		private readonly Dictionary<string, Func<bool>> _requirements;

		public PatchRequirements()
		{
			_requirements = new Dictionary<string, Func<bool>>();
		}

		public PatchRequirements(Dictionary<string, Func<bool>> requirements)
		{
			_requirements = requirements;
		}

		public PatchRequirements AddRequirement(IPatchRequirement patchRequirement)
		{
			_requirements.Add(patchRequirement.Name, patchRequirement.Checker);
			return this;
		}

		public bool IsAllowed(string requirement_name)
		{
			_requirements.TryGetValue(requirement_name, out var value);
			return value?.Invoke() ?? false;
		}
	}
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
	public class PatchRequiresAttribute : Attribute
	{
		public readonly string requirement_name;

		public PatchRequiresAttribute(string requirement_name)
		{
			this.requirement_name = requirement_name;
		}
	}
	public class HarmonyFeaturesPatcher
	{
		private readonly PatchRequirements _patchRequirements;

		public HarmonyFeaturesPatcher(PatchRequirements availableFeatures)
		{
			_patchRequirements = availableFeatures;
		}

		public void PatchAll(Type[] types, Harmony harmony_instance)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			foreach (Type type in types)
			{
				if (!type.GetCustomAttributes<PatchRequiresAttribute>().ToList().Any((PatchRequiresAttribute attribute) => !_patchRequirements.IsAllowed(attribute.requirement_name)))
				{
					ZLog.Log((object)("Patching: " + type.ToString()));
					new PatchClassProcessor(harmony_instance, type).Patch();
				}
				else
				{
					ZLog.Log((object)("Patch disabled: " + type.ToString()));
				}
			}
		}
	}
}
namespace Serverbound.Features
{
	public class Core : IFeature
	{
		[HarmonyPatch(typeof(Pickable), "RPC_Pick")]
		public static class Pickable_RPC_Pick_Patch
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				return ServerSafe.NullSafeLocalPlayer(instructions, __originalMethod, 1);
			}
		}

		[HarmonyPatch(typeof(Ship), "UpdateSailSize")]
		public static class Ship_UpdateSailSize_Patch
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				return ServerSafe.NullSafeLocalPlayer(instructions, __originalMethod, 2);
			}
		}

		[HarmonyPatch(typeof(CookingStation), "SpawnItem")]
		public static class CookingStation_SpawnItem_Patch
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				return ServerSafe.NullSafeLocalPlayer(instructions, __originalMethod, 2);
			}
		}

		[HarmonyPatch(typeof(Leviathan), "RPC_Left")]
		public static class Leviathan_RPC_Left_Patch
		{
			private static bool Prefix()
			{
				return (Object)(object)Player.m_localPlayer != (Object)null;
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "CreateDestroyObjects")]
		public class CreateDestroyObjects_Patch
		{
			private static readonly HashSet<ZDO> s_seen = new HashSet<ZDO>();

			private static readonly HashSet<Vector2s> s_queriedZones = new HashSet<Vector2s>();

			private static bool Prefix(ZNetScene __instance)
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Blocked)
				{
					return true;
				}
				List<ZDO> tempCurrentObjects = __instance.m_tempCurrentObjects;
				List<ZDO> tempCurrentDistantObjects = __instance.m_tempCurrentDistantObjects;
				tempCurrentObjects.Clear();
				tempCurrentDistantObjects.Clear();
				s_queriedZones.Clear();
				SimulationDistance syncedSimulationDistance = ZNet.instance.GetSyncedSimulationDistance();
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer.IsReady())
					{
						Vector2s zone = ZoneSystem.GetZone(peer.GetRefPos());
						if (s_queriedZones.Add(zone))
						{
							ZDOMan.instance.FindSectorObjects(zone, syncedSimulationDistance, tempCurrentObjects, tempCurrentDistantObjects);
						}
					}
				}
				RemoveDuplicates(tempCurrentObjects);
				RemoveDuplicates(tempCurrentDistantObjects);
				if (VcpObjectPassPatch.UnloadKept)
				{
					tempCurrentObjects.Reverse(0, 0);
					tempCurrentDistantObjects.Reverse(0, 0);
				}
				__instance.CreateObjects(tempCurrentObjects, tempCurrentDistantObjects);
				__instance.RemoveObjects(tempCurrentObjects, tempCurrentDistantObjects);
				return false;
			}

			private static void RemoveDuplicates(List<ZDO> zdos)
			{
				s_seen.Clear();
				zdos.RemoveAll((ZDO zdo) => !s_seen.Add(zdo));
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "CreateObjectsSorted")]
		public static class ZNetScene_CreateObjectsSorted_Patch
		{
			private static readonly List<Vector3> s_peerPositions;

			private static int s_peerPositionsFrame;

			private static readonly HashSet<Vector2s> s_checkedCenters;

			private static readonly HashSet<Vector2s> s_readySectors;

			private static readonly List<Vector2s> s_area;

			private static MethodInfo distanceSqrMethod;

			private static MethodInfo nearestPeerMethod;

			private static MethodInfo activeAreaMethod;

			private static MethodInfo prepareAreasMethod;

			private static MethodInfo createdGetter;

			private static MethodInfo skipPendingMethod;

			private static MethodInfo zoneInstanceGetter;

			private static MethodInfo positionMethod;

			private static MethodInfo addMethod;

			private static MethodInfo moveNextMethod;

			private static FieldInfo sortValueField;

			private static FieldInfo pendingObjectsField;

			static ZNetScene_CreateObjectsSorted_Patch()
			{
				s_peerPositions = new List<Vector3>();
				s_peerPositionsFrame = -1;
				s_checkedCenters = new HashSet<Vector2s>();
				s_readySectors = new HashSet<Vector2s>();
				s_area = new List<Vector2s>();
				Prepare();
			}

			private static void Prepare()
			{
				if (!(distanceSqrMethod != null))
				{
					distanceSqrMethod = Method(typeof(Utils), "DistanceSqr", typeof(Vector3), typeof(Vector3));
					nearestPeerMethod = Method(typeof(ZNetScene_CreateObjectsSorted_Patch), "NearestPeerDistanceSqr", typeof(Vector3), typeof(Vector3));
					activeAreaMethod = Method(typeof(ZoneSystem), "IsActiveAreaLoaded");
					prepareAreasMethod = Method(typeof(ZNetScene_CreateObjectsSorted_Patch), "PrepareReadyAreas", typeof(ZoneSystem));
					createdGetter = AccessTools.PropertyGetter(typeof(ZDO), "Created") ?? throw new MissingMemberException(typeof(ZDO).FullName, "Created");
					skipPendingMethod = Method(typeof(ZNetScene_CreateObjectsSorted_Patch), "CreatedOrAreaPending", typeof(ZDO));
					zoneInstanceGetter = AccessTools.PropertyGetter(typeof(ZoneSystem), "instance") ?? throw new MissingMemberException(typeof(ZoneSystem).FullName, "instance");
					positionMethod = Method(typeof(ZDO), "GetPosition");
					addMethod = Method(typeof(List<ZDO>), "Add", typeof(ZDO));
					moveNextMethod = Method(typeof(List<ZDO>.Enumerator), "MoveNext");
					sortValueField = AccessTools.Field(typeof(ZDO), "m_tempSortValue") ?? throw new MissingFieldException(typeof(ZDO).FullName, "m_tempSortValue");
					pendingObjectsField = AccessTools.Field(typeof(ZNetScene), "m_tempCurrentObjects2") ?? throw new MissingFieldException(typeof(ZNetScene).FullName, "m_tempCurrentObjects2");
				}
			}

			private static MethodInfo Method(Type type, string name, params Type[] arguments)
			{
				return AccessTools.DeclaredMethod(type, name, arguments, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				List<CodeInstruction> list = instructions.ToList();
				List<CodeInstruction> code = ((IEnumerable<CodeInstruction>)list).Select((Func<CodeInstruction, CodeInstruction>)((CodeInstruction i) => new CodeInstruction(i))).ToList();
				int num = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], activeAreaMethod));
				int num2 = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], createdGetter));
				int num3 = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], distanceSqrMethod));
				int addSite = ILMatch.Site(code, (int i) => CodeInstructionExtensions.Calls(code[i], addMethod));
				bool flag = ILMatch.Locals(__originalMethod, 6, (0, typeof(Vector3)), (2, typeof(List<ZDO>.Enumerator)), (3, typeof(ZDO))) && MatchesReadiness(code, num) && MatchesCandidates(code, num2, num3, addSite);
				CoreVerification.Record(__originalMethod, flag);
				if (!flag)
				{
					Plugin.logger.LogWarning((object)(__originalMethod.DeclaringType.Name + "." + __originalMethod.Name + ": readiness or sort anchors changed; left unchanged. Core requires review."));
					return list;
				}
				code[num].opcode = OpCodes.Call;
				code[num].operand = prepareAreasMethod;
				code[num2].opcode = OpCodes.Call;
				code[num2].operand = skipPendingMethod;
				code[num3].operand = nearestPeerMethod;
				return code;
			}

			private static bool MatchesReadiness(List<CodeInstruction> code, int areaSite)
			{
				if (ILMatch.Shape(code, areaSite - 1, ILMatch.Calls(zoneInstanceGetter), ILMatch.Calls(activeAreaMethod), ILMatch.Is(OpCodes.Brtrue, OpCodes.Brtrue_S), ILMatch.Is(OpCodes.Ret), ILMatch.Ldarg(0)))
				{
					return ILMatch.Targets(code[areaSite + 1], code[areaSite + 3]);
				}
				return false;
			}

			private static bool MatchesCandidates(List<CodeInstruction> code, int createdSite, int distanceSite, int addSite)
			{
				if (ILMatch.Shape(code, createdSite - 1, ILMatch.IsLoad(3), ILMatch.Calls(createdGetter), ILMatch.Is(OpCodes.Brtrue, OpCodes.Brtrue_S), ILMatch.IsLoad(3), ILMatch.IsLoad(0), ILMatch.IsLoad(3), ILMatch.Calls(positionMethod), ILMatch.Calls(distanceSqrMethod), (CodeInstruction i) => CodeInstructionExtensions.StoresField(i, sortValueField)) && ILMatch.Shape(code, addSite - 3, ILMatch.Ldarg(0), ILMatch.Loads(pendingObjectsField), ILMatch.IsLoad(3), ILMatch.Calls(addMethod), ILMatch.IsAddress(2), ILMatch.Calls(moveNextMethod)) && distanceSite == createdSite + 6)
				{
					return ILMatch.Targets(code[createdSite + 1], code[addSite + 1]);
				}
				return false;
			}

			private static bool PrepareReadyAreas(ZoneSystem zones)
			{
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Blocked)
				{
					return zones.IsActiveAreaLoaded();
				}
				s_checkedCenters.Clear();
				s_readySectors.Clear();
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer.IsReady())
					{
						Vector2s zone = ZoneSystem.GetZone(peer.GetRefPos());
						if (s_checkedCenters.Add(zone) && ZoneSystem_IsActiveAreaLoaded_Patch.IsAreaLoaded(zones, zone, s_area))
						{
							s_readySectors.UnionWith(s_area);
						}
					}
				}
				return s_readySectors.Count != 0;
			}

			private static bool CreatedOrAreaPending(ZDO zdo)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				if (!zdo.Created)
				{
					if (!CoreVerification.Blocked)
					{
						return !s_readySectors.Contains(zdo.GetSector());
					}
					return false;
				}
				return true;
			}

			public static float NearestPeerDistanceSqr(Vector3 referencePosition, Vector3 position)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0086: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Blocked)
				{
					return Utils.DistanceSqr(referencePosition, position);
				}
				if (s_peerPositionsFrame != Time.frameCount)
				{
					s_peerPositionsFrame = Time.frameCount;
					s_peerPositions.Clear();
					foreach (ZNetPeer peer in ZNet.instance.GetPeers())
					{
						if (peer.IsReady())
						{
							s_peerPositions.Add(peer.GetRefPos());
						}
					}
				}
				if (s_peerPositions.Count == 0)
				{
					return Utils.DistanceSqr(referencePosition, position);
				}
				float num = float.MaxValue;
				foreach (Vector3 s_peerPosition in s_peerPositions)
				{
					num = Mathf.Min(num, Utils.DistanceSqr(s_peerPosition, position));
				}
				return num;
			}
		}

		[HarmonyPatch(typeof(ZoneSystem), "IsActiveAreaLoaded")]
		public static class ZoneSystem_IsActiveAreaLoaded_Patch
		{
			private static bool Prefix(ZoneSystem __instance, ref bool __result)
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Blocked)
				{
					return true;
				}
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer.IsReady() && !IsAreaLoaded(__instance, ZoneSystem.GetZone(peer.GetRefPos())))
					{
						__result = false;
						return false;
					}
				}
				__result = true;
				return false;
			}

			internal static bool IsAreaLoaded(ZoneSystem zones, Vector2s center, List<Vector2s> sectors = null)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_0062: Unknown result type (might be due to invalid IL or missing references)
				sectors?.Clear();
				SimulationDistance simulationDistance = zones.m_simulationDistance;
				int nearSimulationDistance = ((SimulationDistance)(ref simulationDistance)).NearSimulationDistance;
				Vector2s val = default(Vector2s);
				for (int i = center.y - nearSimulationDistance; i <= center.y + nearSimulationDistance; i++)
				{
					for (int j = center.x - nearSimulationDistance; j <= center.x + nearSimulationDistance; j++)
					{
						((Vector2s)(ref val))..ctor(j, i);
						if (((SimulationDistance)(ref simulationDistance)).IsClassic || zones.ZonesWithinRadius(center, val, nearSimulationDistance, false))
						{
							if (!zones.m_zones.ContainsKey(val))
							{
								return false;
							}
							sectors?.Add(val);
						}
					}
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(ZoneSystem), "Update")]
		public static class ZoneSystem_Update_Patch
		{
			private static int s_nextPeer;

			private static bool Prefix(ZoneSystem __instance)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Invalid comparison between Unknown and I4
				if (CoreVerification.Blocked)
				{
					return true;
				}
				if ((int)ZNet.GetConnectionStatus() != 2 || (ZNet.instance.IsServer() && !__instance.LocationsGenerated))
				{
					return true;
				}
				__instance.m_lastFixedTime = Time.fixedTime;
				__instance.m_updateTimer += Time.deltaTime;
				if (__instance.m_updateTimer > 0.1f)
				{
					__instance.m_updateTimer = 0f;
					__instance.UpdateTTL(0.1f);
					if (ZNet.instance.IsServer())
					{
						long timestamp = Stopwatch.GetTimestamp();
						List<ZNetPeer> peers = ZNet.instance.GetPeers();
						int num = SpawnZones(__instance, peers, ghost: false);
						int ghost = ((num == 0) ? SpawnZones(__instance, peers, ghost: true) : 0);
						PerformanceStats.Zones(num, ghost, timestamp);
					}
					__instance.UpdatePrefabLifetimes();
				}
				return false;
			}

			private static int SpawnZones(ZoneSystem zoneSystem, List<ZNetPeer> peers, bool ghost)
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				int num = ((Configuration.maxZonesPerTick.Value > 0) ? Configuration.maxZonesPerTick.Value : int.MaxValue);
				int count = peers.Count;
				int num2 = s_nextPeer;
				int num3 = 0;
				for (int i = 0; i < count; i++)
				{
					if (num3 >= num)
					{
						break;
					}
					int num4 = (num2 + i) % count;
					if (peers[num4].IsReady())
					{
						Vector3 refPos = peers[num4].GetRefPos();
						if (ghost ? zoneSystem.CreateGhostZones(refPos) : zoneSystem.CreateLocalZones(refPos))
						{
							num3++;
							s_nextPeer = (num4 + 1) % count;
						}
					}
				}
				return num3;
			}
		}

		[HarmonyPatch(typeof(ZDOMan), "ReleaseNearbyZDOS")]
		public static class ZDOMan_ReleaseNearbyZDOS_Patch
		{
			private static bool Prefix(ZDOMan __instance, Vector3 refPosition, long uid)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Blocked)
				{
					return true;
				}
				Vector2s zone = ZoneSystem.GetZone(refPosition);
				List<ZDO> tempNearObjects = __instance.m_tempNearObjects;
				tempNearObjects.Clear();
				SimulationDistance syncedSimulationDistance = ZNet.instance.GetSyncedSimulationDistance();
				__instance.FindSectorObjects(zone, new SimulationDistance(((SimulationDistance)(ref syncedSimulationDistance)).NearSimulationDistance, 0, ((SimulationDistance)(ref syncedSimulationDistance)).IsClassic), tempNearObjects, (List<ZDO>)null);
				long uID = ZNet.GetUID();
				foreach (ZDO item in tempNearObjects)
				{
					if (!item.Persistent)
					{
						continue;
					}
					Vector3 position = item.GetPosition();
					bool flag = false;
					foreach (ZNetPeer peer in ZNet.instance.GetPeers())
					{
						if (peer.IsReady() && ZNetScene.InActiveArea(position, ZoneSystem.GetZone(peer.GetRefPos())))
						{
							flag = true;
							break;
						}
					}
					long owner = item.GetOwner();
					if (owner == uid || owner == uID)
					{
						if (!flag)
						{
							item.SetOwner(0L);
						}
					}
					else if ((owner == 0L || !__instance.IsInPeerActiveArea(position, owner)) && flag)
					{
						item.SetOwner(uID);
					}
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(RandEventSystem), "FixedUpdate")]
		public static class RandEventSystem_FixedUpdate_Patch
		{
			private static readonly MethodInfo isAnyPlayerInEventArea = AccessTools.Method(typeof(RandEventSystem), "IsAnyPlayerInEventArea", (Type[])null, (Type[])null);

			private static readonly MethodInfo isInsideRandomEventArea = AccessTools.Method(typeof(RandEventSystem), "IsInsideRandomEventArea", (Type[])null, (Type[])null);

			private static readonly MethodInfo opImplicit = AccessTools.Method(typeof(Object), "op_Implicit", (Type[])null, (Type[])null);

			private static readonly MethodInfo getTransform = AccessTools.PropertyGetter(typeof(Component), "transform");

			private static readonly MethodInfo getPosition = AccessTools.PropertyGetter(typeof(Transform), "position");

			private static readonly FieldInfo localPlayer = AccessTools.Field(typeof(Player), "m_localPlayer");

			private static readonly FieldInfo randomEvent = AccessTools.Field(typeof(RandEventSystem), "m_randomEvent");

			private static bool Prefix()
			{
				return !CoreVerification.Blocked;
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				//IL_0222: Unknown result type (might be due to invalid IL or missing references)
				//IL_0227: Unknown result type (might be due to invalid IL or missing references)
				//IL_0257: Expected O, but got Unknown
				List<CodeInstruction> list = instructions.ToList();
				List<CodeInstruction> list2 = ((IEnumerable<CodeInstruction>)list).Select((Func<CodeInstruction, CodeInstruction>)((CodeInstruction i) => new CodeInstruction(i))).ToList();
				int num = list2.FindIndex((CodeInstruction code) => CodeInstructionExtensions.Calls(code, isAnyPlayerInEventArea));
				CodeInstruction val = ((num >= 0 && num + 1 < list2.Count) ? LoadOf(list2[num + 1]) : null);
				int num2 = -1;
				for (int num3 = Math.Max(num, 0); num3 < list2.Count; num3++)
				{
					if (val == null)
					{
						break;
					}
					if (ILMatch.Shape(list2, num3, ILMatch.Loads(localPlayer), ILMatch.Calls(opImplicit), ILMatch.Is(OpCodes.Brfalse, OpCodes.Brfalse_S)))
					{
						num2 = num3 + 2;
						break;
					}
				}
				int num4 = ((num2 >= 0) ? list2.FindIndex(num2, (CodeInstruction code) => CodeInstructionExtensions.Calls(code, isInsideRandomEventArea)) : (-1));
				int num5 = num4 - 6;
				bool flag = num5 > num2 && ILMatch.Shape(list2, num5, ILMatch.Ldarg(0), ILMatch.Ldarg(0), ILMatch.Loads(randomEvent), ILMatch.Loads(localPlayer), ILMatch.Calls(getTransform), ILMatch.Calls(getPosition), ILMatch.Calls(isInsideRandomEventArea));
				if (val == null || num2 < 0 || !flag)
				{
					CoreVerification.Record(__originalMethod, matched: false);
					string text = ((val == null) ? "the IsAnyPlayerInEventArea result" : ((num2 < 0) ? "the local player check" : "the IsInsideRandomEventArea call for the local player"));
					Plugin.logger.LogWarning((object)(__originalMethod.DeclaringType.Name + "." + __originalMethod.Name + ": " + text + " not found; left unchanged, so random events will not become active on the server. The game changed this method; the patch needs reviewing."));
					return list;
				}
				CoreVerification.Record(__originalMethod, matched: true);
				list2[num2] = new CodeInstruction(list2[num2])
				{
					opcode = ((list2[num2].opcode == OpCodes.Brfalse_S) ? OpCodes.Brtrue_S : OpCodes.Brtrue)
				};
				for (int num6 = num5; num6 <= num4; num6++)
				{
					val.labels.AddRange(list2[num6].labels);
					val.blocks.AddRange(list2[num6].blocks);
				}
				list2.RemoveRange(num5, num4 - num5 + 1);
				list2.Insert(num5, val);
				return list2;
			}

			private static CodeInstruction LoadOf(CodeInstruction store)
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Expected O, but got Unknown
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Expected O, but got Unknown
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Expected O, but got Unknown
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Expected O, but got Unknown
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: Expected O, but got Unknown
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00be: Expected O, but got Unknown
				if (store.opcode == OpCodes.Stloc_0)
				{
					return new CodeInstruction(OpCodes.Ldloc_0, (object)null);
				}
				if (store.opcode == OpCodes.Stloc_1)
				{
					return new CodeInstruction(OpCodes.Ldloc_1, (object)null);
				}
				if (store.opcode == OpCodes.Stloc_2)
				{
					return new CodeInstruction(OpCodes.Ldloc_2, (object)null);
				}
				if (store.opcode == OpCodes.Stloc_3)
				{
					return new CodeInstruction(OpCodes.Ldloc_3, (object)null);
				}
				if (store.opcode == OpCodes.Stloc_S)
				{
					return new CodeInstruction(OpCodes.Ldloc_S, store.operand);
				}
				if (store.opcode == OpCodes.Stloc)
				{
					return new CodeInstruction(OpCodes.Ldloc, store.operand);
				}
				return null;
			}
		}

		[HarmonyPatch(typeof(SpawnSystem), "UpdateSpawning")]
		public static class SpawnSystem_UpdateSpawning_Patch
		{
			private static readonly FieldInfo localPlayer = AccessTools.Field(typeof(Player), "m_localPlayer");

			private static readonly MethodInfo ownerEquality = AccessTools.Method(typeof(Object), "op_Equality", (Type[])null, (Type[])null);

			private static readonly MethodInfo currentSpawners = AccessTools.Method(typeof(RandEventSystem), "GetCurrentSpawners", (Type[])null, (Type[])null);

			private static readonly MethodInfo serverSpawners = AccessTools.Method(typeof(Core), "GetCurrentSpawners", (Type[])null, (Type[])null);

			private static bool Prefix()
			{
				return !CoreVerification.Blocked;
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Expected O, but got Unknown
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Expected O, but got Unknown
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Expected O, but got Unknown
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Expected O, but got Unknown
				//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00df: Expected O, but got Unknown
				//IL_019f: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a5: Expected O, but got Unknown
				List<CodeInstruction> list = instructions.ToList();
				CodeMatcher val = new CodeMatcher((IEnumerable<CodeInstruction>)list, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[4]
				{
					new CodeMatch((OpCode?)OpCodes.Ldsfld, (object)localPlayer, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldnull, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Call, (object)ownerEquality, (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction instruction) => instruction.opcode == OpCodes.Brfalse || instruction.opcode == OpCodes.Brfalse_S), (string)null)
				});
				bool isValid = val.IsValid;
				if (isValid)
				{
					val.Opcode = ((val.Opcode == OpCodes.Brfalse_S) ? OpCodes.Brtrue_S : OpCodes.Brtrue);
					val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
					{
						new CodeMatch((OpCode?)OpCodes.Callvirt, (object)currentSpawners, (string)null)
					});
				}
				if (!isValid || !val.IsValid || !ILMatch.Plain(val.Instruction))
				{
					CoreVerification.Record(__originalMethod, matched: false);
					string text = ((!isValid) ? "the local player check not found" : ((!val.IsValid) ? "the RandEventSystem.GetCurrentSpawners call not found" : "the RandEventSystem.GetCurrentSpawners call carries a branch label"));
					Plugin.logger.LogWarning((object)(__originalMethod.DeclaringType.Name + "." + __originalMethod.Name + ": " + text + "; left unchanged, so the server will not spawn creatures. The game changed this method; the patch needs reviewing."));
					return list;
				}
				CoreVerification.Record(__originalMethod, matched: true);
				val.Opcode = OpCodes.Call;
				val.Operand = serverSpawners;
				val.Insert((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null)
				});
				return val.InstructionEnumeration();
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "OutsideActiveArea", new Type[]
		{
			typeof(Vector3),
			typeof(Vector2s)
		})]
		public static class ZNetScene_OutsideActiveArea_Patch
		{
			private static bool Prefix(ref bool __result, Vector3 point)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Blocked)
				{
					return true;
				}
				__result = true;
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer.IsReady() && ZNetScene.InActiveArea(point, ZoneSystem.GetZone(peer.GetRefPos())))
					{
						__result = false;
						break;
					}
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(ZRoutedRpc), "RPC_RoutedRPC")]
		public static class ZRoutedRpc_RPC_RoutedRPC_Patch
		{
			private static bool Prefix(ZRoutedRpc __instance, ZRpc rpc, ZPackage pkg)
			{
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Failed || !__instance.m_server)
				{
					return true;
				}
				int pos = pkg.GetPos();
				try
				{
					pkg.ReadLong();
					long sender = pkg.ReadLong();
					pkg.ReadLong();
					pkg.ReadZDOID();
					if (pkg.ReadInt() != RequestResponsHash)
					{
						return true;
					}
					return __instance.m_peers.Any((ZNetPeer peer) => peer.m_rpc == rpc && peer.IsReady() && peer.m_uid == sender);
				}
				finally
				{
					pkg.SetPos(pos);
				}
			}
		}

		[HarmonyPatch(typeof(ZRoutedRpc), "RouteRPC")]
		public static class ZRoutedRpc_RouteRPC_Patch
		{
			private static void Prefix(ZRoutedRpc __instance, RoutedRPCData rpcData)
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				if (CoreVerification.Blocked || rpcData.m_methodHash != RequestResponsHash)
				{
					return;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(rpcData.m_targetZDO);
				if (zDO == null || zDO.GetOwner() != rpcData.m_senderPeerID || zDO.GetInt("InUse", 0) != 0 || !__instance.m_peers.Any((ZNetPeer peer) => peer.m_uid == rpcData.m_targetPeerID && peer.IsReady()))
				{
					return;
				}
				ZNetView val = ZNetScene.instance.FindInstance(zDO);
				Ship val2 = (Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent<Ship>() : null);
				if (!Object.op_Implicit((Object)(object)val2) || (Object)(object)val2.m_nview != (Object)(object)val || !val2.m_players.Any((Player player) => Object.op_Implicit((Object)(object)player) && ((Character)player).GetOwner() == rpcData.m_targetPeerID))
				{
					return;
				}
				ZPackage parameters = rpcData.m_parameters;
				if (parameters.Size() != 1)
				{
					return;
				}
				int pos = parameters.GetPos();
				try
				{
					parameters.SetPos(0);
					if (parameters.ReadBool())
					{
						Plugin.logger.LogDebug((object)$"RequestRespons: Setting ship's owner to {rpcData.m_targetPeerID}");
						zDO.SetOwner(rpcData.m_targetPeerID);
					}
				}
				finally
				{
					parameters.SetPos(pos);
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "UpdateAttack")]
		public static class Humanoid_UpdateAttack_Patch
		{
			private static void Prefix(ref Humanoid __instance)
			{
				if (__instance.m_currentAttack != null && (Object)(object)__instance.m_currentAttack.m_character == (Object)null)
				{
					__instance.m_currentAttack = null;
				}
			}
		}

		[HarmonyPatch(typeof(Ship), "UpdateOwner")]
		public static class Ship_UpdateOwner_Patch
		{
			private static bool Prefix(ref Ship __instance)
			{
				if (CoreVerification.Blocked)
				{
					return true;
				}
				if (!__instance.m_nview.IsValid())
				{
					return false;
				}
				ZDO zDO = __instance.m_nview.GetZDO();
				if (zDO.GetInt("InUse", 0) == 0)
				{
					if (!__instance.m_shipControlls.HaveValidUser())
					{
						__instance.m_lastWaterImpactTime = Time.time;
						zDO.SetOwner(ZNet.GetUID());
						return false;
					}
					long user = __instance.m_shipControlls.GetUser();
					Player val = ((user != 0L) ? Player.GetPlayer(user) : null);
					if ((Object)(object)val != (Object)null)
					{
						long owner = ((Character)val).GetOwner();
						Plugin.logger.LogDebug((object)$"UpdateOwner: Setting ship's owner to {owner}");
						zDO.SetOwner(owner);
					}
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(AudioMan), "Update")]
		public static class AudioMan_Update_Patch
		{
			private static bool Prefix()
			{
				return false;
			}
		}

		[HarmonyPatch(typeof(ShieldDomeImageEffect), "GetDomeColor")]
		public static class ShieldDomeImageEffect_GetDomeColor_Patch
		{
			private static bool Prefix(ref Color __result)
			{
				//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)
				__result = new Color(1f, 1f, 1f);
				return false;
			}
		}

		private static readonly int RequestResponsHash = StringExtensionMethods.GetStableHashCode("RequestRespons");

		public bool FeatureEnabled()
		{
			return true;
		}

		public static bool IsServer()
		{
			if (Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return ZNet.instance.IsServer();
			}
			return false;
		}

		public static void PrintLog(string text)
		{
			Trace.WriteLine(text);
		}

		public static void PrintLog(object[] obj)
		{
			Trace.WriteLine(string.Concat(obj));
		}

		public static List<SpawnData> GetCurrentSpawners(RandEventSystem instance, SpawnSystem spawnSystem)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			RandomEvent activeEvent = instance.m_activeEvent;
			if (activeEvent == null)
			{
				return null;
			}
			Vector3 position = spawnSystem.m_nview.GetZDO().GetPosition();
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (ZNetScene.InActiveArea(position, ZoneSystem.GetZone(((Component)allPlayer).transform.position)) && instance.IsInsideRandomEventArea(activeEvent, ((Component)allPlayer).transform.position))
				{
					return instance.GetCurrentSpawners();
				}
			}
			return null;
		}
	}
	[Harmony]
	internal class Debugging : IFeature
	{
		[PatchRequires("DebugBuild")]
		[HarmonyPatch(typeof(Chat), "RPC_ChatMessage")]
		public static class Chat_RPC_ChatMessage_Patch
		{
			private static void Prefix(ref long sender, ref string text)
			{
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				ZNetPeer peer = ZNet.instance.GetPeer(sender);
				if (peer == null)
				{
					return;
				}
				if (text == "startevent")
				{
					RandEventSystem.instance.SetRandomEventByName("army_theelder", peer.GetRefPos());
				}
				else if (text == "stopevent")
				{
					RandEventSystem.instance.ResetRandomEvent();
				}
				else if (text.StartsWith("maxobjects"))
				{
					string[] array = text.Split(new char[1] { ' ' });
					if (array.Length > 1 && int.TryParse(array[1], out var result))
					{
						Configuration.maxObjectsPerFrame.Value = result;
					}
				}
			}
		}

		public bool FeatureEnabled()
		{
			return Utilities.IsDebugBuild();
		}
	}
	public class DungeonLoadGuard : IFeature
	{
		[HarmonyPatch(typeof(BundleLoader), "OnLoadAsyncCompleted", new Type[] { })]
		public static class BundleLoader_OnLoadAsyncCompleted_Patch
		{
			private static bool Prefix(ref BundleLoader __instance)
			{
				AssetBundleCreateRequestWrapper asyncLoadRequest = __instance.m_asyncLoadRequest;
				if (asyncLoadRequest == null || (Object)(object)asyncLoadRequest.AssetBundle != (Object)null)
				{
					return true;
				}
				__instance.m_bundle = null;
				__instance.m_asyncLoadRequest = null;
				LogOnce("bundle " + __instance.m_bundleName, "Unity returned no bundle for " + __instance.m_bundleName + "; reporting its assets as failed.");
				if (__instance.m_shouldBeLoaded)
				{
					((BundleLoader)(ref __instance)).InvokeCallbacks((LoadResult)1);
				}
				else if (BundleLoader.s_tickOnAsyncOperationComplete)
				{
					((BundleLoader)(ref __instance)).TickAsync();
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(AssetLoader), "LoadAssetFromBundleAsync")]
		public static class AssetLoader_LoadAssetFromBundleAsync_Patch
		{
			private unsafe static bool Prefix(ref AssetLoader __instance)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				AssetBundleLoader instance = AssetBundleLoader.Instance;
				if (instance == null || (Object)(object)((BundleLoader)(ref instance.m_bundleLoaders[__instance.m_bundleLoaderIndex])).Bundle != (Object)null)
				{
					return true;
				}
				AssetID assetID = __instance.m_assetID;
				LogOnce("asset " + ((object)(*(AssetID*)(&assetID))/*cast due to .constrained prefix*/).ToString(), $"Asset {__instance.m_assetID} ({__instance.m_assetPathInBundle}) has no bundle to load from; reporting it as failed.");
				((AssetLoader)(ref __instance)).InvokeCallbacks((LoadResult)1);
				return false;
			}
		}

		[HarmonyPatch(typeof(DungeonGenerator), "OnRoomLoaded")]
		[HarmonyAfter(new string[] { "MidnightsFX.ValheimCommunityPatch" })]
		public static class DungeonGenerator_OnRoomLoaded_Patch
		{
			private static bool Prefix(DungeonGenerator __instance, LoadResult result, bool __runOriginal)
			{
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: Invalid comparison between Unknown and I4
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: 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)
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				if (!__runOriginal || (int)result != 1 || (Object)(object)__instance == (Object)null || !Object.op_Implicit((Object)(object)__instance))
				{
					return true;
				}
				Vector3 position = ((Component)__instance).transform.position;
				LogOnce("dungeon " + ((object)ZoneSystem.GetZone(position)/*cast due to .constrained prefix*/).ToString(), $"Dungeon {((Object)__instance).name} at {position:F0}: a room failed to load ({result}). Letting it go so its zone keeps working; it is tried again the next time it is created.");
				__instance.m_roomsToLoad = int.MaxValue;
				__instance.ReleaseHeldReferences();
				return false;
			}
		}

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

		public bool FeatureEnabled()
		{
			return Configuration.fixDungeonLoadGuard.Value;
		}

		private static void LogOnce(string key, string text)
		{
			if (s_logged.Add(key))
			{
				Plugin.logger.LogWarning((object)text);
			}
		}
	}
	public class Fixes : IFeature
	{
		[HarmonyPatch(typeof(ZDOMan), "SetDirtySector")]
		public static class ZDOMan_SetDirtySector_Patch
		{
			private static bool Prefix(ZDOMan __instance, ZDO zdo)
			{
				if (!zdo.Persistent || !IsPortal(zdo))
				{
					return true;
				}
				__instance.SetDirtyPortals();
				return false;
			}
		}

		[HarmonyPatch(typeof(ZDO), "Deserialize")]
		public static class ZDO_Deserialize_Patch
		{
			private static void Postfix(ZDO __instance)
			{
				if (Configuration.fixSaveClientChanges.Value && __instance.Persistent && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer() && ZDOMan.instance != null)
				{
					ZDOMan.instance.SetDirtySector(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(ZDO), "InternalSetPosition")]
		public static class ZDO_InternalSetPosition_Patch
		{
			private static void Prefix(ZDO __instance, out SectorIndex __state)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				__state = FiledSector(__instance);
			}

			private static void Postfix(ZDO __instance, SectorIndex __state)
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				if (Configuration.fixTeleportGhosts.Value && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer() && ZDOMan.instance != null && !(FiledSector(__instance) == __state) && !IsPortal(__instance))
				{
					ZDOMan.instance.ZDOSectorInvalidated(__instance);
				}
			}

			private static SectorIndex FiledSector(ZDO zdo)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				if (!zdo.OutsideZones)
				{
					return zdo.GetSectorIndex();
				}
				return ZoneSystem.SectorZero;
			}
		}

		public bool FeatureEnabled()
		{
			return true;
		}

		private static bool IsPortal(ZDO zdo)
		{
			if (Object.op_Implicit((Object)(object)Game.instance))
			{
				return Game.instance.PortalPrefabHash.Contains(zdo.GetPrefab());
			}
			return false;
		}
	}
	public class HandedOverFires : IFeature
	{
		[HarmonyPatch(typeof(Fire), "UpdateFire")]
		public static class Fire_UpdateFire_Patch
		{
			private static void Postfix(Fire __instance)
			{
				if (!__instance.m_nview.IsOwner())
				{
					return;
				}
				CinderSpawner component = ((Component)__instance).GetComponent<CinderSpawner>();
				if (!((Object)(object)component == (Object)null) && !component.m_hasAttachObj && !s_searched.TryGetValue(component, out var _))
				{
					s_searched.Add(component, null);
					Collider val = BurningOn(((Component)__instance).transform);
					if ((Object)(object)val != (Object)null)
					{
						component.m_attachObj = ((Component)val).gameObject;
						component.m_hasAttachObj = true;
					}
				}
			}
		}

		private const float TouchRadius = 0.5f;

		private const int TouchSteps = 10;

		private static readonly ConditionalWeakTable<CinderSpawner, object> s_searched = new ConditionalWeakTable<CinderSpawner, object>();

		private static readonly Collider[] s_touching = (Collider[])(object)new Collider[32];

		private static int s_burnableMask;

		public bool FeatureEnabled()
		{
			return Configuration.fixHandedOverFires.Value;
		}

		private static Collider BurningOn(Transform fire)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (s_burnableMask == 0)
			{
				s_burnableMask = LayerMask.GetMask(new string[6] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "vehicle" });
			}
			Vector3 position = fire.position;
			for (int i = 1; i <= 10; i++)
			{
				int num = Physics.OverlapSphereNonAlloc(position, 0.5f * (float)i / 10f, s_touching, s_burnableMask, (QueryTriggerInteraction)1);
				for (int j = 0; j < num; j++)
				{
					Collider val = s_touching[j];
					if (!((Component)val).transform.IsChildOf(fire) && Burnable(val))
					{
						return val;
					}
				}
			}
			return null;
		}

		private static bool Burnable(Collider collider)
		{
			WearNTear componentInParent = ((Component)collider).GetComponentInParent<WearNTear>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				return componentInParent.m_burnable;
			}
			if (!((Object)(object)((Component)collider).GetComponentInParent<TreeBase>() != (Object)null))
			{
				return (Object)(object)((Component)collider).GetComponentInParent<TreeLog>() != (Object)null;
			}
			return true;
		}
	}
	public class MaxObjectsPerFrame : IFeature
	{
		[HarmonyPatch(typeof(ZNetScene), "CreateObjects")]
		public class CreateObjects_Patch
		{
			private static readonly MethodInfo maxCreated = AccessTools.Method(typeof(MaxObjectsPerFrame), "GetMaxCreatedPerFrame", (Type[])null, (Type[])null);

			public static void ILManipulator(ILContext il)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
				new ILCursor(il).GotoNext((MoveType)0, new Func<Instruction, bool>[5]
				{
					(Instruction i) => ILPatternMatchingExt.MatchLdarg(i, 0),
					(Instruction i) => ILPatternMatchingExt.MatchLdarg(i, 1),
					(Instruction i) => ILPatternMatchingExt.MatchLdloc(i, 0),
					(Instruction i) => ILPatternMatchingExt.MatchLdloca(i, 1),
					(Instruction i) => ILPatternMatchingExt.MatchCall<ZNetScene>(i, "CreateObjectsSorted")
				}).Emit(OpCodes.Call, (MethodBase)maxCreated).Emit(OpCodes.Stloc_0);
			}
		}

		public bool FeatureEnabled()
		{
			return Configuration.maxObjectsPerFrameEnabled.Value;
		}

		public static int GetMaxCreatedPerFrame()
		{
			return Configuration.maxObjectsPerFrame.Value;
		}
	}
	public class Networking : IFeature
	{
		[HarmonyPatch(typeof(ZDOMan), "SendZDOs")]
		public static class ZDOMan_SendZDOs_Patch
		{
			private static readonly MethodInfo queueSize = AccessTools.Method(typeof(Networking), "QueueSize", (Type[])null, (Type[])null);

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0086: Expected O, but got Unknown
				List<CodeInstruction> list = new List<CodeInstruction>(instructions);
				int num = list.Count((CodeInstruction code) => CodeInstructionExtensions.LoadsConstant(code, 10240L));
				if (num != 2)
				{
					Plugin.logger.LogWarning((object)$"{__originalMethod.DeclaringType.Name}.{__originalMethod.Name}: found {num} send queue limit(s), expected 2. The game changed this method; it was left unchanged and the patch needs reviewing.");
					return list;
				}
				for (int num2 = 0; num2 < list.Count; num2++)
				{
					if (CodeInstructionExtensions.LoadsConstant(list[num2], 10240L))
					{
						CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)queueSize);
						val.labels.AddRange(list[num2].labels);
						val.blocks.AddRange(list[num2].blocks);
						list[num2] = val;
					}
				}
				return list;
			}

			private static void Prefix(ZDOPeer peer, bool flush)
			{
				Stats.Record(peer.m_peer, flush);
			}
		}

		[HarmonyPatch(typeof(ZSteamSocket), "RegisterGlobalCallbacks")]
		public static class ZSteamSocket_RegisterGlobalCallbacks_Patch
		{
			private static void Postfix()
			{
				int num = Configuration.networkSendRateMaxKB.Value * 1024;
				int num2 = Math.Min(Configuration.networkSendRateMinKB.Value * 1024, num);
				SetSteamConfig((ESteamNetworkingConfigValue)10, num2);
				SetSteamConfig((ESteamNetworkingConfigValue)11, num);
				Plugin.logger.LogInfo((object)$"Networking: Steam send rate {num2 / 1024}-{num / 1024} KB/s, send queue {QueueSize() / 1024} KB per player");
			}

			private static void SetSteamConfig(ESteamNetworkingConfigValue key, int value)
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				GCHandle gCHandle = GCHandle.Alloc(value, GCHandleType.Pinned);
				try
				{
					SteamGameServerNetworkingUtils.SetConfigValue(key, (ESteamNetworkingConfigScope)1, IntPtr.Zero, (ESteamNetworkingConfigDataType)1, gCHandle.AddrOfPinnedObject());
				}
				finally
				{
					gCHandle.Free();
				}
			}
		}

		private static class Stats
		{
			private class PeerStats
			{
				public string name;

				public int ticks;

				public int full;

				public int maxQueued;
			}

			private static readonly Dictionary<long, PeerStats> s_peers = new Dictionary<long, PeerStats>();

			private static float s_nextReport = -1f;

			public static void Record(ZNetPeer peer, bool flush)
			{
				int value = Configuration.networkStatsMinutes.Value;
				if (!(value <= 0 || flush) && peer != null && peer.m_socket != null)
				{
					int sendQueueSize = peer.m_socket.GetSendQueueSize();
					if (!s_peers.TryGetValue(peer.m_uid, out var value2))
					{
						value2 = new PeerStats();
						s_peers[peer.m_uid] = value2;
					}
					value2.name = peer.m_playerName;
					value2.ticks++;
					if (QueueSize() - sendQueueSize < 2048)
					{
						value2.full++;
					}
					value2.maxQueued = Math.Max(value2.maxQueued, sendQueueSize);
					float realtimeSinceStartup = Time.realtimeSinceStartup;
					if (s_nextReport < 0f)
					{
						s_nextReport = realtimeSinceStartup + (float)value * 60f;
					}
					else if (realtimeSinceStartup >= s_nextReport)
					{
						Report();
						s_nextReport = realtimeSinceStartup + (float)value * 60f;
					}
				}
			}

			private static void Report()
			{
				foreach (PeerStats value in s_peers.Values)
				{
					Plugin.logger.LogInfo((object)$"Networking {value.name}: send queue full in {100f * (float)value.full / (float)value.ticks:0.0}% of {value.ticks} send ticks, at most {value.maxQueued / 1024} of {QueueSize() / 1024} KB queued");
				}
				s_peers.Clear();
			}
		}

		private const int VanillaQueueSize = 10240;

		public bool FeatureEnabled()
		{
			return Configuration.networkingEnabled.Value;
		}

		public static int QueueSize()
		{
			return Mathf.Clamp(Configuration.networkQueueSizeKB.Value, 10, 80) * 1024;
		}
	}
	public class Performance : IFeature
	{
		[HarmonyPatch(typeof(ZDOMan), "SendZDOToPeers2")]
		public static class ZDOMan_SendZDOToPeers2_Patch
		{
			private static double s_owed;

			private static int s_next;

			private static double s_last = -1.0;

			private static bool Prefix(ZDOMan __instance)
			{
				float num = (float)Configuration.sendIntervalMs.Value / 1000f;
				if (num <= 0f)
				{
					return true;
				}
				double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
				double num2 = ((s_last < 0.0) ? 0.0 : (realtimeSinceStartupAsDouble - s_last));
				s_last = realtimeSinceStartupAsDouble;
				List<ZDOPeer> peers = __instance.m_peers;
				int count = peers.Count;
				if (count == 0)
				{
					s_owed = 0.0;
					return false;
				}
				s_owed = Math.Min(s_owed + (double)count * num2 / (double)num, count);
				int num3 = (int)s_owed;
				s_owed -= num3;
				for (int i = 0; i < num3; i++)
				{
					if (s_next >= count)
					{
						s_next = 0;
					}
					__instance.SendZDOs(peers[s_next++], false);
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(ZDOMan), "SendZDOs")]
		public static class ZDOMan_SendZDOs_Timing
		{
			private static void Prefix()
			{
				PerformanceStats.SendStarted();
			}

			private static void Postfix()
			{
				PerformanceStats.SendFinished();
			}
		}

		[HarmonyPatch]
		public static class PresentManager_RequestTargetFrameRate_Patch
		{
			private static int s_logged;

			private static int s_forced;

			private static bool s_looked;

			private static FieldRef<PresentManager, int> s_refreshRate;

			private static Action<PresentManager> s_apply;

			private static IEnumerable<MethodBase> TargetMethods()
			{
				List<MethodBase> list = new List<MethodBase>();
				foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(typeof(PresentManager)))
				{
					ParameterInfo[] parameters = declaredMethod.GetParameters();
					if (declaredMethod.Name == "RequestTargetFrameRate" && parameters.Length >= 1 && parameters[0].ParameterType == typeof(int))
					{
						list.Add(declaredMethod);
					}
				}
				if (list.Count == 0)
				{
					Plugin.logger.LogWarning((object)"PresentManager.RequestTargetFrameRate(int, ...) is gone from this game version: the server keeps the frame rate the game asks for.");
				}
				return list;
			}

			private static void Prefix(ref int __0)
			{
				int num = __0;
				int value = Configuration.serverTargetFps.Value;
				if (value <= 0 || !Plugin.IsDedicated())
				{
					s_forced = 0;
					return;
				}
				int num2 = Mathf.Clamp(value, 30, 240);
				if (s_logged++ == 0 || num2 != num)
				{
					Plugin.logger.LogInfo((object)$"Server target frame rate: {num} -> {num2}");
				}
				__0 = num2;
				s_forced = num2;
			}

			private static void Postfix(PresentManager __instance)
			{
				if (s_forced <= 0 || __instance == null)
				{
					return;
				}
				if (!s_looked)
				{
					s_looked = true;
					FieldInfo field = typeof(PresentManager).GetField("m_requestedRefreshRate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					MethodInfo method = typeof(Pre