Decompiled source of InteropFixes v1.0.4

InteropFixes.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using InteropFixes.Modules.EpicLootCraftyBoxes;
using InteropFixes.Modules.PathOfValheimanLookup;
using InteropFixes.Modules.Vnei;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("InteropFixes")]
[assembly: AssemblyDescription("Runtime compatibility fixes for Valheim mods")]
[assembly: AssemblyCompany("sighsorry")]
[assembly: AssemblyProduct("InteropFixes")]
[assembly: ComVisible(false)]
[assembly: Guid("D710223A-7033-4535-B9A8-C3E2D98D20DF")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("1.0.4.0")]
[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 InteropFixes
{
	[BepInPlugin("sighsorry.InteropFixes", "InteropFixes", "1.0.4")]
	[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.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class InteropFixesPlugin : BaseUnityPlugin
	{
		internal const string ModGuid = "sighsorry.InteropFixes";

		internal const string ModName = "InteropFixes";

		internal const string ModVersion = "1.0.4";

		internal const string MagicPluginGuid = "blacks7ar.MagicPlugin";

		internal const string VneiGuid = "com.maxsch.valheim.vnei";

		internal const string PathOfValheimanGuid = "treextr.pathofvalheiman";

		internal const string EpicLootGuid = "randyknapp.mods.epicloot";

		internal const string CraftyBoxesGuid = "Azumatt.AzuCraftyBoxes";

		internal const string BlastedGuid = "sighsorry.blastedswimmingtarredbugfix";

		internal const string LegacyVneiGuid = "sighsorry.VneiItemLookupFix";

		internal const string LegacyBridgeGuid = "sighsorry.EpicLootCraftyBoxesBridge";

		private static InteropFixesPlugin? _instance;

		private Harmony? _cosmeticNetworkHarmony;

		private Harmony? _magicHarmony;

		private Harmony? _vneiHarmony;

		private Harmony? _povLookupHarmony;

		private Harmony? _bridgeHarmony;

		private bool _stopping;

		internal static ManualLogSource ModLogger { get; private set; }

		internal static bool CosmeticRuntimeActive
		{
			get
			{
				if ((Object)(object)_instance != (Object)null)
				{
					return !_instance._stopping;
				}
				return false;
			}
		}

		private void Awake()
		{
			ModLogger = ((BaseUnityPlugin)this).Logger;
			_instance = this;
			TryInitialize("PoV / VNEI optional lookup", delegate
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Expected O, but got Unknown
				if (ModuleIsolation.CanInstall("PoV / VNEI optional lookup", new string[2] { "com.maxsch.valheim.vnei", "treextr.pathofvalheiman" }, null))
				{
					_povLookupHarmony = new Harmony("sighsorry.InteropFixes.PovOptionalLookup");
					if (!PathOfValheimanLookupModule.TryInstall(_povLookupHarmony))
					{
						StopPovLookup();
					}
				}
			}, StopPovLookup);
			TryInitialize("Cosmetic network coordination", delegate
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Expected O, but got Unknown
				_cosmeticNetworkHarmony = new Harmony("sighsorry.InteropFixes.CosmeticNetwork");
				CosmeticNetworkCoordinator.Install(_cosmeticNetworkHarmony);
			}, StopCosmeticNetwork);
		}

		private IEnumerator Start()
		{
			yield return null;
			if (_stopping)
			{
				yield break;
			}
			bool num = Application.isBatchMode || (int)SystemInfo.graphicsDeviceType == 4;
			TryInitialize("MagicPlugin", delegate
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Expected O, but got Unknown
				if (ModuleIsolation.CanInstall("MagicPlugin", new string[1] { "blacks7ar.MagicPlugin" }, null, checkOldBlasted: true))
				{
					_magicHarmony = new Harmony("sighsorry.InteropFixes.MagicPlugin");
					MagicPluginCompatibility.TryInstall(_magicHarmony, enableNetworkCosmetics: true);
				}
			}, StopMagic);
			if (!num)
			{
				TryInitialize("VNEI item lookup", delegate
				{
					//IL_0027: Unknown result type (might be due to invalid IL or missing references)
					//IL_0031: Expected O, but got Unknown
					if (ModuleIsolation.CanInstall("VNEI item lookup", new string[1] { "com.maxsch.valheim.vnei" }, "sighsorry.VneiItemLookupFix"))
					{
						_vneiHarmony = new Harmony("sighsorry.InteropFixes.VneiItemLookup");
						if (!VneiItemLookupModule.TryInstall(_vneiHarmony))
						{
							StopVnei();
						}
					}
				}, StopVnei);
				TryInitialize("EpicLoot / CraftyBoxes", delegate
				{
					//IL_002f: Unknown result type (might be due to invalid IL or missing references)
					//IL_0039: Expected O, but got Unknown
					if (ModuleIsolation.CanInstall("EpicLoot / CraftyBoxes", new string[2] { "randyknapp.mods.epicloot", "Azumatt.AzuCraftyBoxes" }, "sighsorry.EpicLootCraftyBoxesBridge"))
					{
						_bridgeHarmony = new Harmony("sighsorry.InteropFixes.EpicLootCraftyBoxes");
						if (!EpicLootCraftyBoxesModule.TryInstall(_bridgeHarmony))
						{
							StopBridge();
						}
					}
				}, StopBridge);
			}
			ModLogger.LogInfo((object)"InteropFixes 1.0.4: optional integration initialization finished.");
		}

		private static void TryInitialize(string name, Action install, Action rollback)
		{
			try
			{
				install();
			}
			catch (Exception arg)
			{
				ModLogger.LogError((object)$"{name} initialization failed; rolling back only this integration: {arg}");
				try
				{
					rollback();
				}
				catch (Exception arg2)
				{
					ModLogger.LogError((object)$"{name} rollback failed: {arg2}");
				}
			}
		}

		private void OnDestroy()
		{
			_stopping = true;
			StopSafely("Cosmetic network coordination", StopCosmeticNetwork);
			StopSafely("EpicLoot / CraftyBoxes", StopBridge);
			StopSafely("VNEI item lookup", StopVnei);
			StopSafely("PoV / VNEI optional lookup", StopPovLookup);
			StopSafely("MagicPlugin", StopMagic);
			if (_instance == this)
			{
				_instance = null;
			}
		}

		private static void StopSafely(string name, Action stop)
		{
			try
			{
				stop();
			}
			catch (Exception arg)
			{
				ModLogger.LogError((object)$"{name} shutdown failed: {arg}");
			}
		}

		private void StopVnei()
		{
			if (_vneiHarmony == null)
			{
				return;
			}
			try
			{
				VneiItemLookupModule.Stop();
			}
			finally
			{
				if (TryUnpatch(_vneiHarmony, "VNEI item lookup"))
				{
					_vneiHarmony = null;
				}
			}
		}

		private void StopPovLookup()
		{
			if (_povLookupHarmony == null)
			{
				return;
			}
			try
			{
				PathOfValheimanLookupModule.Stop();
			}
			finally
			{
				if (TryUnpatch(_povLookupHarmony, "PoV / VNEI optional lookup"))
				{
					_povLookupHarmony = null;
				}
			}
		}

		private void StopBridge()
		{
			if (_bridgeHarmony == null)
			{
				return;
			}
			try
			{
				EpicLootCraftyBoxesModule.Stop();
			}
			finally
			{
				if (TryUnpatch(_bridgeHarmony, "EpicLoot / CraftyBoxes"))
				{
					_bridgeHarmony = null;
				}
			}
		}

		private void StopMagic()
		{
			if (_magicHarmony != null && TryUnpatch(_magicHarmony, "MagicPlugin") && MagicPluginCompatibility.RestoreExternalPatchesAndReset())
			{
				_magicHarmony = null;
			}
		}

		private void StopCosmeticNetwork()
		{
			if (_cosmeticNetworkHarmony == null)
			{
				return;
			}
			try
			{
				CosmeticNetworkCoordinator.Stop();
			}
			finally
			{
				if (TryUnpatch(_cosmeticNetworkHarmony, "Cosmetic network coordination"))
				{
					_cosmeticNetworkHarmony = null;
				}
			}
		}

		internal static bool TryUnpatch(Harmony harmony, string capability)
		{
			return ModuleIsolation.TryUnpatch(harmony, capability);
		}
	}
	internal static class ModuleIsolation
	{
		internal static bool CanInstall(string name, string[] required, string? legacyGuid, bool checkOldBlasted = false)
		{
			foreach (string key in required)
			{
				if (!Chainloader.PluginInfos.ContainsKey(key))
				{
					return false;
				}
			}
			if (legacyGuid == null && !checkOldBlasted)
			{
				return true;
			}
			if (legacyGuid != null && Chainloader.PluginInfos.ContainsKey(legacyGuid))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)(name + " integration skipped: " + legacyGuid + " is installed. Remove its standalone DLL to use the integrated module."));
				return false;
			}
			foreach (MethodBase allPatchedMethod in Harmony.GetAllPatchedMethods())
			{
				Patches patchInfo = Harmony.GetPatchInfo(allPatchedMethod);
				if (patchInfo == null)
				{
					continue;
				}
				foreach (Patch item in Enumerate(patchInfo))
				{
					if (IsLegacyPatch(item.owner, item.PatchMethod?.DeclaringType?.FullName, legacyGuid, checkOldBlasted))
					{
						InteropFixesPlugin.ModLogger.LogWarning((object)(name + " integration skipped: existing legacy hook on " + allPatchedMethod.DeclaringType?.FullName + "." + allPatchedMethod.Name + " (owner " + item.owner + "). Update/remove that legacy module first; other integrations remain available."));
						return false;
					}
				}
			}
			return true;
		}

		internal static bool IsLegacyPatch(string owner, string? patchType, string? legacyGuid, bool checkOldBlasted)
		{
			if (legacyGuid != null && (owner == legacyGuid || owner.StartsWith(legacyGuid + ".", StringComparison.Ordinal)))
			{
				return true;
			}
			if (checkOldBlasted)
			{
				if (!(owner == "sighsorry.blastedswimmingtarredbugfix.MagicPlugin"))
				{
					return patchType?.StartsWith("BlastedSwimmingTarredBugFix.MagicPlugin", StringComparison.Ordinal) ?? false;
				}
				return true;
			}
			return false;
		}

		private static IEnumerable<Patch> Enumerate(Patches patches)
		{
			foreach (Patch prefix in patches.Prefixes)
			{
				yield return prefix;
			}
			foreach (Patch postfix in patches.Postfixes)
			{
				yield return postfix;
			}
			foreach (Patch transpiler in patches.Transpilers)
			{
				yield return transpiler;
			}
			foreach (Patch finalizer in patches.Finalizers)
			{
				yield return finalizer;
			}
		}

		internal static bool TryUnpatch(Harmony harmony, string capability)
		{
			Exception ex = null;
			try
			{
				harmony.UnpatchSelf();
			}
			catch (Exception ex2)
			{
				ex = ex2;
			}
			try
			{
				using IEnumerator<MethodBase> enumerator = harmony.GetPatchedMethods().GetEnumerator();
				if (enumerator.MoveNext())
				{
					MethodBase current = enumerator.Current;
					InteropFixesPlugin.ModLogger.LogError((object)$"{capability}: could not remove owned hook on {current.DeclaringType?.FullName}.{current.Name}. External replacements will not be restored. {ex}");
					return false;
				}
			}
			catch (Exception arg)
			{
				InteropFixesPlugin.ModLogger.LogError((object)$"{capability}: could not verify removal of owned hooks: {arg}. {ex}");
				return false;
			}
			if (ex != null)
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)(capability + ": removal reported an error, but no owned hooks remain: " + ex.Message));
			}
			return true;
		}
	}
	internal sealed class CosmeticAgreement
	{
		private sealed class Peer
		{
			internal long ReportRevision;

			internal int Mask;

			internal bool Ready;
		}

		internal const int AllMask = 127;

		private readonly Dictionary<long, Peer> _peers = new Dictionary<long, Peer>();

		internal long Session { get; private set; }

		internal long Revision { get; private set; }

		internal int LocalMask { get; private set; }

		internal bool LocalReady { get; private set; }

		internal int Mask { get; private set; }

		internal void Reset(long session)
		{
			if (session <= 0)
			{
				throw new ArgumentOutOfRangeException("session");
			}
			long revision = ((Session == session) ? checked(Revision + 1) : 1);
			Session = session;
			Revision = revision;
			_peers.Clear();
			LocalMask = 0;
			LocalReady = false;
			Mask = 0;
		}

		internal void SetLocal(int mask, bool ready)
		{
			if (!IsValidMask(mask))
			{
				mask = 0;
				ready = false;
			}
			if (LocalMask != mask || LocalReady != ready)
			{
				LocalMask = mask;
				LocalReady = ready;
				Recompute();
			}
		}

		internal void AddPeer(long token)
		{
			if (token > 0 && !_peers.ContainsKey(token))
			{
				_peers.Add(token, new Peer());
				Recompute();
			}
		}

		internal void RemovePeer(long token)
		{
			if (_peers.Remove(token))
			{
				Recompute();
			}
		}

		internal bool Report(long token, long session, long reportRevision, int mask, bool ready)
		{
			if (session <= 0 || session != Session || reportRevision <= 0 || !IsValidMask(mask) || !_peers.TryGetValue(token, out Peer value) || reportRevision <= value.ReportRevision)
			{
				return false;
			}
			value.ReportRevision = reportRevision;
			value.Mask = mask;
			value.Ready = ready;
			Recompute();
			return true;
		}

		private void Recompute()
		{
			int num = ((Session > 0 && LocalReady) ? LocalMask : 0);
			foreach (Peer value in _peers.Values)
			{
				if (value.ReportRevision == 0L || !value.Ready)
				{
					num = 0;
					break;
				}
				num &= value.Mask;
			}
			Mask = num;
			checked
			{
				Revision++;
			}
		}

		internal static bool IsValidMask(int mask)
		{
			if (mask >= 0)
			{
				return (mask & -128) == 0;
			}
			return false;
		}
	}
	internal static class CosmeticNetworkCoordinator
	{
		private sealed class Connection
		{
			internal readonly ZNetPeer Peer;

			internal readonly Dictionary<string, object> Handlers = new Dictionary<string, object>();

			internal long Nonce;

			internal long ReportRevision;

			internal int LastReportMask = -1;

			internal bool LastReportReady;

			internal long PendingRevision;

			internal int PendingMask;

			internal bool PendingReady;

			internal Connection(ZNetPeer peer)
			{
				Peer = peer;
			}
		}

		internal const int Protocol = 2;

		private const int MaxParticipants = 128;

		private const string HelloRpc = "sighsorry.InteropFixes.Cosmetics.Hello.v2";

		private const string ReportRpc = "sighsorry.InteropFixes.Cosmetics.Report.v2";

		private const string GrantRpc = "sighsorry.InteropFixes.Cosmetics.Grant.v2";

		private static readonly CosmeticAgreement Agreement = new CosmeticAgreement();

		private static readonly Dictionary<ZRpc, Connection> Connections = new Dictionary<ZRpc, Connection>();

		private static readonly HashSet<long> Participants = new HashSet<long>();

		private static readonly Dictionary<long, float> RecentlyLeft = new Dictionary<long, float>();

		private static FieldInfo? _rpcFunctions;

		private static Harmony? _harmony;

		private static ZNet? _net;

		private static ZNetScene? _scene;

		private static bool _installed;

		private static bool _sceneReady;

		private static int _localMask;

		private static int _clientGrant;

		private static long _session;

		private static long _lastGrantRevision;

		private static long _wireRevision;

		private static bool _warned;

		private static bool _transmissionFailed;

		internal static long SessionToken
		{
			get
			{
				if (!_installed)
				{
					return 0L;
				}
				return _session;
			}
		}

		internal static void Install(Harmony harmony)
		{
			if (_installed)
			{
				return;
			}
			_harmony = harmony;
			try
			{
				_rpcFunctions = AccessTools.DeclaredField(typeof(ZRpc), "m_functions");
				if (_rpcFunctions == null || !typeof(IDictionary).IsAssignableFrom(_rpcFunctions.FieldType))
				{
					throw new MissingFieldException("ZRpc.m_functions");
				}
				Patch(typeof(ZNet), "Awake", Type.EmptyTypes, null, "NetworkAwake");
				Patch(typeof(ZNet), "OnNewConnection", new Type[1] { typeof(ZNetPeer) }, "BeforeNewConnection", "AfterNewConnection");
				Patch(typeof(ZNet), "RPC_PeerInfo", new Type[2]
				{
					typeof(ZRpc),
					typeof(ZPackage)
				}, null, "AfterPeerInfo");
				Patch(typeof(ZNet), "Disconnect", new Type[1] { typeof(ZNetPeer) }, "BeforeDisconnect", null);
				Patch(typeof(ZNet), "StopAll", new Type[1] { typeof(bool) }, "NetworkStopping", null);
				Patch(typeof(ZNetScene), "Awake", Type.EmptyTypes, "SceneStarting", "SceneReady");
				Patch(typeof(ZNetScene), "OnDestroy", Type.EmptyTypes, "SceneDestroying", null);
				_installed = true;
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					NetworkAwake(ZNet.instance);
				}
				if ((Object)(object)ZNetScene.instance != (Object)null)
				{
					SceneReady(ZNetScene.instance);
				}
			}
			catch (Exception ex)
			{
				Stop();
				InteropFixesPlugin.ModLogger.LogWarning((object)("Cosmetic capability negotiation is unavailable; original FX creation is retained. " + ex));
			}
		}

		private static void Patch(Type type, string name, Type[] parameters, string? prefix, string? postfix)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: 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)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, name, parameters, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
			if (methodInfo.IsStatic || methodInfo.ReturnType != typeof(void))
			{
				throw new NotSupportedException(methodInfo.ToString());
			}
			_harmony.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(CosmeticNetworkCoordinator), prefix, (Type[])null)
			{
				priority = 800
			}, (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(CosmeticNetworkCoordinator), postfix, (Type[])null)
			{
				priority = 0
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static bool CanOptimize(int mask)
		{
			if (!_installed || _transmissionFailed || mask == 0 || !CosmeticAgreement.IsValidMask(mask) || (Object)(object)_net == (Object)null || _net != ZNet.instance || !_sceneReady || _scene != ZNetScene.instance || (_localMask & mask) != mask || !InteropFixesPlugin.CosmeticRuntimeActive)
			{
				return false;
			}
			if (_net.IsServer())
			{
				if (Connections.Count < 128)
				{
					return (Agreement.Mask & mask) == mask;
				}
				return false;
			}
			if (_session != 0L)
			{
				return (_clientGrant & mask) == mask;
			}
			return false;
		}

		internal static bool IsParticipant(long sender)
		{
			if (!_installed || (Object)(object)_net == (Object)null || _session == 0L || sender == 0L)
			{
				return false;
			}
			if (sender == ZNet.GetUID() || Participants.Contains(sender))
			{
				return true;
			}
			if (!RecentlyLeft.TryGetValue(sender, out var value))
			{
				return false;
			}
			if (Time.realtimeSinceStartup <= value)
			{
				return true;
			}
			RecentlyLeft.Remove(sender);
			return false;
		}

		internal static void SetLocalCapabilities(int mask)
		{
			_localMask = (CosmeticAgreement.IsValidMask(mask) ? mask : 0);
			RefreshReadiness();
		}

		internal static void RefreshReadiness()
		{
			if (!_installed || (Object)(object)_net == (Object)null)
			{
				return;
			}
			try
			{
				if (_net.IsServer())
				{
					Agreement.SetLocal(_localMask, !_transmissionFailed && _sceneReady && InteropFixesPlugin.CosmeticRuntimeActive);
					Publish();
				}
				else
				{
					Report();
				}
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static void NetworkAwake(ZNet __instance)
		{
			if (!_installed)
			{
				return;
			}
			try
			{
				ResetSession();
				_net = __instance;
				if (__instance.IsServer())
				{
					_session = NewNonce();
					Agreement.Reset(_session);
				}
				_scene = ZNetScene.instance;
				_sceneReady = (Object)(object)_scene != (Object)null;
				foreach (ZNetPeer peer in __instance.GetPeers())
				{
					BeforeNewConnection(__instance, peer);
					AfterNewConnection(peer);
				}
				RefreshReadiness();
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static void BeforeNewConnection(ZNet __instance, ZNetPeer peer)
		{
			if (!_installed || peer?.m_rpc == null || Connections.ContainsKey(peer.m_rpc))
			{
				return;
			}
			try
			{
				if (_net != __instance)
				{
					NetworkAwake(__instance);
				}
				if (!Connections.ContainsKey(peer.m_rpc))
				{
					Connection connection = new Connection(peer);
					Connections.Add(peer.m_rpc, connection);
					Register(connection, "sighsorry.InteropFixes.Cosmetics.Hello.v2", ReceiveHello);
					Register(connection, "sighsorry.InteropFixes.Cosmetics.Report.v2", ReceiveReport);
					Register(connection, "sighsorry.InteropFixes.Cosmetics.Grant.v2", ReceiveGrant);
					if (__instance.IsServer())
					{
						connection.Nonce = NewNonce();
						Agreement.AddPeer(connection.Nonce);
						Publish();
					}
					else
					{
						ClearSessionGrant();
					}
				}
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static void AfterNewConnection(ZNetPeer peer)
		{
			if (!_installed || (Object)(object)_net == (Object)null || !_net.IsServer() || !Connections.TryGetValue(peer.m_rpc, out Connection value))
			{
				return;
			}
			try
			{
				ZPackage val = Header(value);
				peer.m_rpc.Invoke("sighsorry.InteropFixes.Cosmetics.Hello.v2", new object[1] { val });
				Publish();
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static void AfterPeerInfo(ZRpc rpc)
		{
			if (!_installed || (Object)(object)_net == (Object)null || !Connections.TryGetValue(rpc, out Connection value) || !value.Peer.IsReady())
			{
				return;
			}
			try
			{
				if (_net.IsServer() && value.PendingRevision > 0)
				{
					Agreement.Report(value.Nonce, _session, value.PendingRevision, value.PendingMask, value.PendingReady);
					value.PendingRevision = 0L;
				}
				RefreshReadiness();
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static void BeforeDisconnect(ZNetPeer peer)
		{
			if (!_installed || peer?.m_rpc == null || !Connections.TryGetValue(peer.m_rpc, out Connection value))
			{
				return;
			}
			Connections.Remove(peer.m_rpc);
			try
			{
				Unregister(value);
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
			try
			{
				if ((Object)(object)_net != (Object)null && _net.IsServer())
				{
					Agreement.RemovePeer(value.Nonce);
					Publish();
				}
				else
				{
					ClearSessionGrant();
				}
			}
			catch (Exception error2)
			{
				DisableTransmission(error2);
			}
		}

		private static void NetworkStopping()
		{
			if (_installed)
			{
				ResetSession();
			}
		}

		private static void SceneStarting(ZNetScene __instance)
		{
			if (_installed)
			{
				_scene = __instance;
				_sceneReady = false;
				_localMask = 0;
				RefreshReadiness();
			}
		}

		private static void SceneReady(ZNetScene __instance)
		{
			if (_installed)
			{
				_scene = __instance;
				_sceneReady = true;
				RefreshReadiness();
			}
		}

		private static void SceneDestroying(ZNetScene __instance)
		{
			if (_installed && _scene == __instance)
			{
				_sceneReady = false;
				_localMask = 0;
				RefreshReadiness();
				_scene = null;
			}
		}

		private static void ReceiveHello(ZRpc rpc, ZPackage message)
		{
			if (!_installed || (Object)(object)_net == (Object)null || _net.IsServer() || !Connections.TryGetValue(rpc, out Connection value) || !value.Peer.m_server)
			{
				return;
			}
			try
			{
				int num = message.ReadInt();
				long num2 = message.ReadLong();
				long num3 = message.ReadLong();
				if (num == 2 && num2 > 0 && num3 > 0 && message.GetPos() == message.Size() && (value.Nonce == 0L || (value.Nonce == num3 && _session == num2)))
				{
					_session = num2;
					value.Nonce = num3;
					Report();
				}
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static void Report()
		{
			if (_session == 0L || (Object)(object)_net == (Object)null || _net.IsServer())
			{
				return;
			}
			foreach (Connection value in Connections.Values)
			{
				if (value.Peer.m_server && value.Nonce != 0L)
				{
					bool flag = !_transmissionFailed && _sceneReady && value.Peer.IsReady() && InteropFixesPlugin.CosmeticRuntimeActive;
					int num = (flag ? _localMask : 0);
					if (value.LastReportMask != num || value.LastReportReady != flag)
					{
						_clientGrant &= num;
						value.LastReportMask = num;
						value.LastReportReady = flag;
						ZPackage val = Header(value);
						val.Write(++value.ReportRevision);
						val.Write(num);
						val.Write(flag);
						value.Peer.m_rpc.Invoke("sighsorry.InteropFixes.Cosmetics.Report.v2", new object[1] { val });
					}
				}
			}
		}

		private static void ReceiveReport(ZRpc rpc, ZPackage message)
		{
			if (!_installed || (Object)(object)_net == (Object)null || !_net.IsServer() || !Connections.TryGetValue(rpc, out Connection value))
			{
				return;
			}
			try
			{
				if (!ReadHeader(message, value))
				{
					return;
				}
				long num = message.ReadLong();
				int num2 = message.ReadInt();
				bool flag = message.ReadBool();
				if (message.GetPos() != message.Size() || num <= value.ReportRevision || !CosmeticAgreement.IsValidMask(num2))
				{
					return;
				}
				value.ReportRevision = num;
				if (!value.Peer.IsReady())
				{
					if (num > value.PendingRevision)
					{
						value.PendingRevision = num;
						value.PendingMask = num2;
						value.PendingReady = flag;
					}
				}
				else if (Agreement.Report(value.Nonce, _session, num, num2, flag))
				{
					Publish();
				}
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static void ReceiveGrant(ZRpc rpc, ZPackage message)
		{
			if (!_installed || (Object)(object)_net == (Object)null || _net.IsServer() || !Connections.TryGetValue(rpc, out Connection value) || !value.Peer.m_server)
			{
				return;
			}
			try
			{
				if (!ReadHeader(message, value))
				{
					return;
				}
				long num = message.ReadLong();
				int num2 = message.ReadInt();
				int num3 = message.ReadInt();
				if (num <= _lastGrantRevision || num <= 0 || !CosmeticAgreement.IsValidMask(num2) || num3 < 1 || num3 > 128)
				{
					return;
				}
				HashSet<long> hashSet = new HashSet<long>();
				for (int i = 0; i < num3; i++)
				{
					long num4 = message.ReadLong();
					if (num4 == 0L || !hashSet.Add(num4))
					{
						return;
					}
				}
				if (message.GetPos() == message.Size())
				{
					_lastGrantRevision = num;
					_clientGrant = ((!_transmissionFailed && value.Peer.IsReady()) ? (num2 & _localMask) : 0);
					UpdateParticipants(hashSet);
				}
			}
			catch (Exception error)
			{
				DisableTransmission(error);
			}
		}

		private static bool ReadHeader(ZPackage message, Connection connection)
		{
			if (message.ReadInt() == 2 && message.ReadLong() == _session && message.ReadLong() == connection.Nonce && _session != 0L)
			{
				return connection.Nonce != 0;
			}
			return false;
		}

		private static ZPackage Header(Connection connection)
		{
			//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)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(2);
			val.Write(_session);
			val.Write(connection.Nonce);
			return val;
		}

		private static void Publish()
		{
			if ((Object)(object)_net == (Object)null || !_net.IsServer() || _session == 0L)
			{
				return;
			}
			HashSet<long> hashSet = new HashSet<long> { ZNet.GetUID() };
			foreach (Connection value in Connections.Values)
			{
				if (value.Peer.IsReady())
				{
					hashSet.Add(value.Peer.m_uid);
				}
			}
			UpdateParticipants(hashSet);
			int num = ((hashSet.Count <= 128) ? Agreement.Mask : 0);
			if (hashSet.Count > 128)
			{
				hashSet.Clear();
				hashSet.Add(ZNet.GetUID());
			}
			long num2 = ++_wireRevision;
			Exception ex = null;
			foreach (Connection value2 in Connections.Values)
			{
				if (value2.Nonce == 0L || value2.ReportRevision == 0L || !value2.Peer.IsReady())
				{
					continue;
				}
				try
				{
					ZPackage val = Header(value2);
					val.Write(num2);
					val.Write(num);
					val.Write(hashSet.Count);
					foreach (long item in hashSet)
					{
						val.Write(item);
					}
					value2.Peer.m_rpc.Invoke("sighsorry.InteropFixes.Cosmetics.Grant.v2", new object[1] { val });
				}
				catch (Exception ex2)
				{
					if (ex == null)
					{
						ex = ex2;
					}
				}
			}
			if (ex == null)
			{
				return;
			}
			throw new InvalidOperationException("A cosmetic grant could not be sent.", ex);
		}

		private static void UpdateParticipants(HashSet<long> current)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			foreach (long participant in Participants)
			{
				if (!current.Contains(participant))
				{
					RecentlyLeft[participant] = realtimeSinceStartup + 30f;
				}
			}
			if (RecentlyLeft.Count > 256)
			{
				RecentlyLeft.Clear();
			}
			Participants.Clear();
			foreach (long item in current)
			{
				Participants.Add(item);
			}
		}

		private static void Register(Connection connection, string name, Action<ZRpc, ZPackage> callback)
		{
			IDictionary dictionary = (IDictionary)_rpcFunctions.GetValue(connection.Peer.m_rpc);
			int num = StableHash(name);
			if (dictionary.Contains(num))
			{
				throw new InvalidOperationException("Cosmetic RPC identifier already registered: " + name);
			}
			connection.Peer.m_rpc.Register<ZPackage>(name, callback);
			connection.Handlers.Add(name, dictionary[num]);
		}

		private static void Unregister(Connection connection)
		{
			if (_rpcFunctions == null)
			{
				return;
			}
			IDictionary dictionary = (IDictionary)_rpcFunctions.GetValue(connection.Peer.m_rpc);
			foreach (KeyValuePair<string, object> handler in connection.Handlers)
			{
				if (dictionary[StableHash(handler.Key)] == handler.Value)
				{
					connection.Peer.m_rpc.Unregister(handler.Key);
				}
			}
			connection.Handlers.Clear();
		}

		private static void ResetSession()
		{
			foreach (Connection value in Connections.Values)
			{
				try
				{
					Unregister(value);
				}
				catch (Exception ex)
				{
					InteropFixesPlugin.ModLogger.LogWarning((object)("Could not remove own cosmetic RPC: " + ex.Message));
				}
			}
			Connections.Clear();
			_net = null;
			ClearSessionGrant();
			_wireRevision = 0L;
			_warned = false;
			_transmissionFailed = false;
		}

		private static void ClearSessionGrant()
		{
			_session = 0L;
			_clientGrant = 0;
			_lastGrantRevision = 0L;
			Participants.Clear();
			RecentlyLeft.Clear();
		}

		private static void DisableTransmission(Exception error)
		{
			_transmissionFailed = true;
			_clientGrant = 0;
			try
			{
				if ((Object)(object)_net != (Object)null && _net.IsServer())
				{
					Agreement.SetLocal(0, ready: false);
					Publish();
				}
				else if ((Object)(object)_net != (Object)null)
				{
					Report();
				}
			}
			catch
			{
			}
			if (!_warned)
			{
				_warned = true;
				InteropFixesPlugin.ModLogger.LogWarning((object)("Cosmetic negotiation failed; new local FX optimization is disabled. " + error));
			}
		}

		internal static void Stop()
		{
			_installed = false;
			ResetSession();
			_scene = null;
			_sceneReady = false;
			_localMask = 0;
			if (_harmony != null && ModuleIsolation.TryUnpatch(_harmony, "Cosmetic capability agreement"))
			{
				_harmony = null;
			}
		}

		private static long NewNonce()
		{
			long num = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0) & 0x7FFFFFFFFFFFFFFFL;
			if (num != 0L)
			{
				return num;
			}
			return 1L;
		}

		private static int StableHash(string text)
		{
			int num = 5381;
			int num2 = num;
			for (int i = 0; i < text.Length && text[i] != 0; i += 2)
			{
				num = ((num << 5) + num) ^ text[i];
				if (i == text.Length - 1 || text[i + 1] == '\0')
				{
					break;
				}
				num2 = ((num2 << 5) + num2) ^ text[i + 1];
			}
			return num + num2 * 1566083941;
		}
	}
	internal static class MagicPatchContract
	{
		internal const string ProjectileContract = "17BAA2C31BB6E9DD4DA2F3B85E3726AAB53FD4AC8CD7D9F2835E4EBC91A97538";

		internal const string TeleportContract = "21E126B35A09509ADAEE71DB5440E8B20306EEC82EAB236D25ED38564C200AAF";

		internal static bool Matches(MethodInfo method, string expected, out string failure)
		{
			try
			{
				string text = Fingerprint(method);
				if (string.Equals(text, expected, StringComparison.Ordinal))
				{
					failure = string.Empty;
					return true;
				}
				failure = "the " + method.Name + " body/helper contract changed (" + text + "); its original MagicPlugin patch is retained";
			}
			catch (Exception ex)
			{
				failure = "the " + method.Name + " body/helper contract could not be read (" + ex.Message + "); its original MagicPlugin patch is retained";
			}
			return false;
		}

		internal static string Fingerprint(MethodBase root)
		{
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			Queue<MethodBase> queue = new Queue<MethodBase>();
			HashSet<MethodBase> hashSet = new HashSet<MethodBase>();
			StringBuilder stringBuilder = new StringBuilder();
			queue.Enqueue(root);
			while (queue.Count != 0)
			{
				MethodBase methodBase = queue.Dequeue();
				if (!hashSet.Add(methodBase))
				{
					continue;
				}
				if (hashSet.Count > 128)
				{
					throw new InvalidOperationException("Helper graph exceeds its bounded contract scope");
				}
				Patches patchInfo = Harmony.GetPatchInfo(methodBase);
				if (patchInfo != null && patchInfo.Owners.Count > 0)
				{
					throw new InvalidOperationException("The replaced method or a reachable helper already has Harmony hooks");
				}
				MethodBody methodBody = methodBase.GetMethodBody() ?? throw new InvalidOperationException("Missing method body");
				stringBuilder.Append("METHOD ").Append(MethodName(methodBase)).Append('|')
					.Append(methodBase.IsStatic)
					.Append('|')
					.Append(methodBody.InitLocals)
					.Append('\n');
				foreach (LocalVariableInfo localVariable in methodBody.LocalVariables)
				{
					stringBuilder.Append("LOCAL ").Append(localVariable.LocalIndex).Append(':')
						.Append(TypeName(localVariable.LocalType))
						.Append(':')
						.Append(localVariable.IsPinned)
						.Append('\n');
				}
				List<CodeInstruction> originalInstructions = PatchProcessor.GetOriginalInstructions(methodBase, (ILGenerator)null);
				if (originalInstructions.Count > 8192)
				{
					throw new InvalidOperationException("Method exceeds its bounded contract scope");
				}
				Dictionary<Label, int> dictionary = new Dictionary<Label, int>();
				int num = 0;
				foreach (CodeInstruction item in originalInstructions)
				{
					foreach (Label label in item.labels)
					{
						dictionary[label] = num;
					}
					if (item.opcode != OpCodes.Nop)
					{
						num++;
					}
				}
				foreach (CodeInstruction item2 in originalInstructions)
				{
					foreach (ExceptionBlock block in item2.blocks)
					{
						stringBuilder.Append("EH ").Append(block.blockType).Append(':')
							.Append((block.catchType == null) ? string.Empty : TypeName(block.catchType))
							.Append('\n');
					}
					if (item2.opcode == OpCodes.Nop)
					{
						continue;
					}
					string opcode = item2.opcode.Name;
					object operand = item2.operand;
					NormalizeShortForms(ref opcode, ref operand);
					stringBuilder.Append(opcode).Append('|');
					if (!(operand is MethodBase methodBase2))
					{
						if (!(operand is FieldInfo fieldInfo))
						{
							if (!(operand is Type type))
							{
								if (!(operand is Label key))
								{
									if (!(operand is Label[] array))
									{
										if (!(operand is LocalVariableInfo localVariableInfo))
										{
											if (!(operand is string text))
											{
												if (!(operand is float value))
												{
													if (!(operand is double value2))
													{
														if (operand != null)
														{
															if (!(operand is IFormattable formattable))
															{
																throw new InvalidOperationException("Unsupported IL operand " + operand.GetType().FullName);
															}
															stringBuilder.Append(formattable.ToString(null, CultureInfo.InvariantCulture));
														}
													}
													else
													{
														stringBuilder.Append(BitConverter.DoubleToInt64Bits(value2).ToString("X16", CultureInfo.InvariantCulture));
													}
												}
												else
												{
													stringBuilder.Append(BitConverter.ToInt32(BitConverter.GetBytes(value), 0).ToString("X8", CultureInfo.InvariantCulture));
												}
											}
											else
											{
												stringBuilder.Append(text.Length).Append(':').Append(text);
											}
										}
										else
										{
											stringBuilder.Append(localVariableInfo.LocalIndex);
										}
									}
									else
									{
										Label[] array2 = array;
										foreach (Label key2 in array2)
										{
											stringBuilder.Append('@').Append(dictionary[key2]).Append(',');
										}
									}
								}
								else
								{
									stringBuilder.Append('@').Append(dictionary[key]);
								}
							}
							else
							{
								stringBuilder.Append(TypeName(type));
							}
						}
						else
						{
							stringBuilder.Append(TypeName(fieldInfo.DeclaringType)).Append("::").Append(GeneratedName(fieldInfo.Name))
								.Append(':')
								.Append(TypeName(fieldInfo.FieldType))
								.Append(':')
								.Append(fieldInfo.IsStatic);
						}
					}
					else
					{
						stringBuilder.Append(MethodName(methodBase2));
						if (methodBase2.Module == root.Module)
						{
							queue.Enqueue(methodBase2);
						}
					}
					stringBuilder.Append('\n');
				}
			}
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString()))).Replace("-", string.Empty);
		}

		private static string MethodName(MethodBase method)
		{
			string text = string.Join(",", from parameter in method.GetParameters()
				select TypeName(parameter.ParameterType));
			string text2 = (method.IsGenericMethod ? ("<" + string.Join(",", method.GetGenericArguments().Select(TypeName)) + ">") : string.Empty);
			string text3 = ((method is MethodInfo methodInfo) ? TypeName(methodInfo.ReturnType) : "ctor");
			return TypeName(method.DeclaringType) + "::" + GeneratedName(method.Name) + text2 + "(" + text + ")->" + text3;
		}

		private static string TypeName(Type type)
		{
			if (type.IsGenericParameter)
			{
				return ((type.DeclaringMethod == null) ? "!" : "!!") + type.GenericParameterPosition;
			}
			if (type.IsByRef)
			{
				return TypeName(type.GetElementType()) + "&";
			}
			if (type.IsPointer)
			{
				return TypeName(type.GetElementType()) + "*";
			}
			if (type.IsArray)
			{
				return TypeName(type.GetElementType()) + "[" + new string(',', type.GetArrayRank() - 1) + "]";
			}
			if (type.IsGenericType)
			{
				return GeneratedName(type.GetGenericTypeDefinition().FullName) + "<" + string.Join(",", type.GetGenericArguments().Select(TypeName)) + ">";
			}
			return GeneratedName(type.FullName ?? type.Name);
		}

		private static string GeneratedName(string value)
		{
			value = Regex.Replace(value, "(<>c__DisplayClass)\\d+_\\d+", "$1*", RegexOptions.CultureInvariant);
			value = Regex.Replace(value, "(<>f__AnonymousType)\\d+", "$1*", RegexOptions.CultureInvariant);
			return Regex.Replace(value, "(<>9__|b__)\\d+_(\\d+)", "$1*_$2", RegexOptions.CultureInvariant);
		}

		private static void NormalizeShortForms(ref string opcode, ref object? operand)
		{
			string[] array = new string[3] { "ldarg.", "ldloc.", "stloc." };
			int i;
			for (i = 0; i < array.Length; i++)
			{
				string text = array[i];
				if (opcode.StartsWith(text, StringComparison.Ordinal) && int.TryParse(opcode.Substring(text.Length), out var result))
				{
					opcode = text.TrimEnd('.');
					operand = result;
					return;
				}
			}
			if (opcode.StartsWith("ldc.i4.", StringComparison.Ordinal))
			{
				string text2 = opcode.Substring("ldc.i4.".Length);
				if (text2 == "m1" || int.TryParse(text2, out i))
				{
					opcode = "ldc.i4";
					operand = ((text2 == "m1") ? (-1) : int.Parse(text2, CultureInfo.InvariantCulture));
					return;
				}
			}
			if (opcode.EndsWith(".s", StringComparison.Ordinal))
			{
				opcode = opcode.Substring(0, opcode.Length - 2);
			}
		}
	}
	internal static class MagicPluginCompatibility
	{
		private sealed class ProjectileConfiguration
		{
			internal ConfigEntry<float> MagicVelocity { get; }

			internal ConfigEntry<float> MagicAccuracy { get; }

			internal ConfigEntry<float> SurtlingStaffAoe { get; }

			internal ConfigEntry<float> EikthyrStaffAoe { get; }

			internal ConfigEntry<float> LightningStaffAoe { get; }

			internal ConfigEntry<float> PoisonStaffAoe { get; }

			internal ConfigEntry<float> ArcticStaffAoe { get; }

			internal ConfigEntry<float> ModersAoeRange { get; }

			internal ConfigEntry<float> ModersChopDamage { get; }

			internal ConfigEntry<float> ModersFrostDamage { get; }

			internal ConfigEntry<float> ModersPickaxeDamage { get; }

			internal ConfigEntry<float> ModersPierceDamage { get; }

			internal ConfigEntry<float> YagluthAoeRange { get; }

			internal ConfigEntry<float> YagluthBluntDamage { get; }

			internal ConfigEntry<float> YagluthChopDamage { get; }

			internal ConfigEntry<float> YagluthFireDamage { get; }

			internal ConfigEntry<float> YagluthPickaxeDamage { get; }

			private ProjectileConfiguration(ConfigEntry<float> magicVelocity, ConfigEntry<float> magicAccuracy, ConfigEntry<float> surtlingStaffAoe, ConfigEntry<float> eikthyrStaffAoe, ConfigEntry<float> lightningStaffAoe, ConfigEntry<float> poisonStaffAoe, ConfigEntry<float> arcticStaffAoe, ConfigEntry<float> modersAoeRange, ConfigEntry<float> modersChopDamage, ConfigEntry<float> modersFrostDamage, ConfigEntry<float> modersPickaxeDamage, ConfigEntry<float> modersPierceDamage, ConfigEntry<float> yagluthAoeRange, ConfigEntry<float> yagluthBluntDamage, ConfigEntry<float> yagluthChopDamage, ConfigEntry<float> yagluthFireDamage, ConfigEntry<float> yagluthPickaxeDamage)
			{
				MagicVelocity = magicVelocity;
				MagicAccuracy = magicAccuracy;
				SurtlingStaffAoe = surtlingStaffAoe;
				EikthyrStaffAoe = eikthyrStaffAoe;
				LightningStaffAoe = lightningStaffAoe;
				PoisonStaffAoe = poisonStaffAoe;
				ArcticStaffAoe = arcticStaffAoe;
				ModersAoeRange = modersAoeRange;
				ModersChopDamage = modersChopDamage;
				ModersFrostDamage = modersFrostDamage;
				ModersPickaxeDamage = modersPickaxeDamage;
				ModersPierceDamage = modersPierceDamage;
				YagluthAoeRange = yagluthAoeRange;
				YagluthBluntDamage = yagluthBluntDamage;
				YagluthChopDamage = yagluthChopDamage;
				YagluthFireDamage = yagluthFireDamage;
				YagluthPickaxeDamage = yagluthPickaxeDamage;
			}

			internal static bool TryCreate(Type? pluginType, Type? configType, out ProjectileConfiguration? configuration, out string missingField)
			{
				configuration = null;
				missingField = "MagicPlugin.Plugin";
				if (pluginType == null)
				{
					return false;
				}
				missingField = "MagicPlugin.Functions.ConfigSetup";
				if (configType == null)
				{
					return false;
				}
				if (!TryGetFloatConfig(pluginType, "_magicVelocity", out ConfigEntry<float> entry, out missingField) || !TryGetFloatConfig(pluginType, "_magciAccuracy", out ConfigEntry<float> entry2, out missingField) || !TryGetFloatConfig(configType, "_surtlingStaffAOE", out ConfigEntry<float> entry3, out missingField) || !TryGetFloatConfig(configType, "_eikthyrStaffAOE", out ConfigEntry<float> entry4, out missingField) || !TryGetFloatConfig(configType, "_lightningStaffAOE", out ConfigEntry<float> entry5, out missingField) || !TryGetFloatConfig(configType, "_poisonStaffAOE", out ConfigEntry<float> entry6, out missingField) || !TryGetFloatConfig(configType, "_arcticStaffAOE", out ConfigEntry<float> entry7, out missingField) || !TryGetFloatConfig(configType, "_modersAoeRange", out ConfigEntry<float> entry8, out missingField) || !TryGetFloatConfig(configType, "_modersChopDamage", out ConfigEntry<float> entry9, out missingField) || !TryGetFloatConfig(configType, "_modersFrostDamage", out ConfigEntry<float> entry10, out missingField) || !TryGetFloatConfig(configType, "_modersPickaxeDamage", out ConfigEntry<float> entry11, out missingField) || !TryGetFloatConfig(configType, "_modersPierceDamage", out ConfigEntry<float> entry12, out missingField) || !TryGetFloatConfig(configType, "_yagluthAoeRange", out ConfigEntry<float> entry13, out missingField) || !TryGetFloatConfig(configType, "_yagluthBluntDamage", out ConfigEntry<float> entry14, out missingField) || !TryGetFloatConfig(configType, "_yagluthChopDamage", out ConfigEntry<float> entry15, out missingField) || !TryGetFloatConfig(configType, "_yagluthFireDamage", out ConfigEntry<float> entry16, out missingField) || !TryGetFloatConfig(configType, "_yagluthPickaxeDamage", out ConfigEntry<float> entry17, out missingField))
				{
					return false;
				}
				configuration = new ProjectileConfiguration(entry, entry2, entry3, entry4, entry5, entry6, entry7, entry8, entry9, entry10, entry11, entry12, entry13, entry14, entry15, entry16, entry17);
				return true;
			}

			private static bool TryGetFloatConfig(Type ownerType, string fieldName, out ConfigEntry<float> entry, out string missingField)
			{
				missingField = ownerType.FullName + "." + fieldName;
				FieldInfo fieldInfo = AccessTools.Field(ownerType, fieldName);
				if (fieldInfo == null || !fieldInfo.IsStatic || fieldInfo.FieldType != typeof(ConfigEntry<float>) || !(fieldInfo.GetValue(null) is ConfigEntry<float> val))
				{
					entry = null;
					return false;
				}
				entry = val;
				return true;
			}
		}

		private sealed class PatchReplacement
		{
			internal MethodInfo Original { get; }

			internal Patch ExternalPatch { get; }

			internal HarmonyPatchType PatchType { get; }

			internal PatchReplacement(MethodInfo original, Patch externalPatch, HarmonyPatchType patchType)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				Original = original;
				ExternalPatch = externalPatch;
				PatchType = patchType;
			}
		}

		private const string PluginTypeName = "MagicPlugin.Plugin";

		private const string ConfigTypeName = "MagicPlugin.Functions.ConfigSetup";

		private const string AttackPatchTypeName = "MagicPlugin.Patches.AttackPatch";

		private const string PlayerPatchTypeName = "MagicPlugin.Patches.PlayerPatch";

		private static ProjectileConfiguration? _projectileConfiguration;

		private static bool _registryGuardInstalled;

		private static bool _reportedProjectileRuntimeError;

		private static bool _reportedTeleportRuntimeError;

		private static bool _reportedRegistryRuntimeError;

		private static PatchReplacement? _projectileReplacement;

		private static PatchReplacement? _teleportReplacement;

		private static FieldRef<Character, ZNetView>? _characterNViewAccessor;

		private static FieldRef<Tameable, MonsterAI>? _tameableMonsterAiAccessor;

		internal static void TryInstall(Harmony harmony, bool enableNetworkCosmetics = false)
		{
			if (!Chainloader.PluginInfos.TryGetValue("blacks7ar.MagicPlugin", out var value))
			{
				InteropFixesPlugin.ModLogger.LogDebug((object)"MagicPlugin is not loaded; MagicPlugin-specific compatibility fixes are inactive.");
				return;
			}
			Assembly magicAssembly = ((object)value.Instance)?.GetType().Assembly ?? FindAssemblyWithType("MagicPlugin.Plugin");
			if (magicAssembly == null)
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)"MagicPlugin compatibility skipped: the plugin assembly could not be resolved.");
				return;
			}
			string version = value.Metadata.Version?.ToString() ?? "unknown";
			TryInstallCapability("projectile compatibility", delegate
			{
				TryInstallProjectilePatch(harmony, magicAssembly, version);
			});
			TryInstallCapability("teleport compatibility", delegate
			{
				TryInstallTeleportPatch(harmony, magicAssembly, version);
			});
			TryInstallCapability("Character registry guard", delegate
			{
				TryInstallRegistryGuard(harmony, magicAssembly, version);
			});
			if (enableNetworkCosmetics)
			{
				TryInstallCapability("cosmetic peer-ZDO prevention", delegate
				{
					MagicPluginCosmeticZdoPrevention.TryInstall(harmony, version);
				});
			}
			else
			{
				InteropFixesPlugin.ModLogger.LogDebug((object)"MagicPlugin cosmetic network optimization is off; original network effects are preserved.");
			}
		}

		internal static bool RestoreExternalPatchesAndReset()
		{
			if (RestoreExternalPatch(_projectileReplacement))
			{
				_projectileReplacement = null;
			}
			if (RestoreExternalPatch(_teleportReplacement))
			{
				_teleportReplacement = null;
			}
			_projectileConfiguration = null;
			_characterNViewAccessor = null;
			_tameableMonsterAiAccessor = null;
			_registryGuardInstalled = false;
			_reportedProjectileRuntimeError = false;
			_reportedTeleportRuntimeError = false;
			_reportedRegistryRuntimeError = false;
			MagicPluginCosmeticZdoPrevention.Reset();
			if (_projectileReplacement == null)
			{
				return _teleportReplacement == null;
			}
			return false;
		}

		private static void TryInstallProjectilePatch(Harmony harmony, Assembly magicAssembly, string version)
		{
			if (_projectileReplacement != null)
			{
				return;
			}
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Attack), "FireProjectileBurst", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = magicAssembly.GetType("MagicPlugin.Patches.AttackPatch", throwOnError: false)?.GetMethod("FireProjectileBurst_Prefix", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Attack) }, null);
			if (methodInfo == null || methodInfo2 == null || methodInfo2.ReturnType != typeof(bool))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)"MagicPlugin projectile compatibility skipped: the expected FireProjectileBurst patch structure was not found.");
				return;
			}
			Patch val = FindOwnedPatch(methodInfo, (HarmonyPatchType)1, methodInfo2);
			if (val == null || !HasExpectedOwnedPatchSet(methodInfo, (HarmonyPatchType)1, methodInfo2))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)"MagicPlugin projectile compatibility skipped: the complete MagicPlugin FireProjectileBurst patch set did not match.");
				return;
			}
			if (!MagicPatchContract.Matches(methodInfo2, "17BAA2C31BB6E9DD4DA2F3B85E3726AAB53FD4AC8CD7D9F2835E4EBC91A97538", out string failure))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin projectile compatibility skipped: " + failure));
				return;
			}
			Type? type = magicAssembly.GetType("MagicPlugin.Plugin", throwOnError: false);
			Type type2 = magicAssembly.GetType("MagicPlugin.Functions.ConfigSetup", throwOnError: false);
			if (!ProjectileConfiguration.TryCreate(type, type2, out ProjectileConfiguration configuration, out string missingField))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin projectile compatibility skipped: required float config '" + missingField + "' was not found."));
				return;
			}
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(typeof(MagicPluginCompatibility), "FireProjectileBurstPrefix", (Type[])null, (Type[])null);
			string failure2 = "the InteropFixes replacement prefix was not found.";
			if (methodInfo3 == null || !TryReplacePatch(harmony, methodInfo, val, methodInfo3, (HarmonyPatchType)1, out failure2))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin projectile compatibility skipped: " + failure2));
				return;
			}
			_projectileConfiguration = configuration;
			_projectileReplacement = new PatchReplacement(methodInfo, val, (HarmonyPatchType)1);
			InteropFixesPlugin.ModLogger.LogInfo((object)("Installed MagicPlugin FireProjectileBurst compatibility for MagicPlugin " + version + "."));
		}

		private static void TryInstallTeleportPatch(Harmony harmony, Assembly magicAssembly, string version)
		{
			if (_teleportReplacement != null)
			{
				return;
			}
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Player), "TeleportTo", new Type[3]
			{
				typeof(Vector3),
				typeof(Quaternion),
				typeof(bool)
			}, (Type[])null);
			MethodInfo methodInfo2 = magicAssembly.GetType("MagicPlugin.Patches.PlayerPatch", throwOnError: false)?.GetMethod("TeleportTo_Postfix", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3]
			{
				typeof(Player),
				typeof(Vector3).MakeByRefType(),
				typeof(Quaternion).MakeByRefType()
			}, null);
			if (methodInfo == null || methodInfo2 == null || methodInfo2.ReturnType != typeof(void))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)"MagicPlugin teleport compatibility skipped: the expected Player.TeleportTo patch structure was not found.");
				return;
			}
			Patch val = FindOwnedPatch(methodInfo, (HarmonyPatchType)2, methodInfo2);
			if (val == null || !HasExpectedOwnedPatchSet(methodInfo, (HarmonyPatchType)2, methodInfo2))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)"MagicPlugin teleport compatibility skipped: the complete MagicPlugin TeleportTo patch set did not match.");
				return;
			}
			if (!MagicPatchContract.Matches(methodInfo2, "21E126B35A09509ADAEE71DB5440E8B20306EEC82EAB236D25ED38564C200AAF", out string failure))
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin teleport compatibility skipped: " + failure));
				return;
			}
			FieldRef<Character, ZNetView> characterNViewAccessor;
			FieldRef<Tameable, MonsterAI> tameableMonsterAiAccessor;
			try
			{
				characterNViewAccessor = AccessTools.FieldRefAccess<Character, ZNetView>("m_nview");
				tameableMonsterAiAccessor = AccessTools.FieldRefAccess<Tameable, MonsterAI>("m_monsterAI");
			}
			catch (Exception ex)
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin teleport compatibility skipped: required Valheim field accessors could not be created (" + ex.Message + ")."));
				return;
			}
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(typeof(MagicPluginCompatibility), "TeleportToPostfix", (Type[])null, (Type[])null);
			string failure2 = "the InteropFixes replacement postfix was not found.";
			_characterNViewAccessor = characterNViewAccessor;
			_tameableMonsterAiAccessor = tameableMonsterAiAccessor;
			if (methodInfo3 == null || !TryReplacePatch(harmony, methodInfo, val, methodInfo3, (HarmonyPatchType)2, out failure2))
			{
				_characterNViewAccessor = null;
				_tameableMonsterAiAccessor = null;
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin teleport compatibility skipped: " + failure2));
			}
			else
			{
				_teleportReplacement = new PatchReplacement(methodInfo, val, (HarmonyPatchType)2);
				InteropFixesPlugin.ModLogger.LogInfo((object)("Installed MagicPlugin safe teleport compatibility for MagicPlugin " + version + "."));
			}
		}

		private static void TryInstallRegistryGuard(Harmony harmony, Assembly magicAssembly, string version)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			if (_registryGuardInstalled)
			{
				return;
			}
			MethodInfo methodInfo = magicAssembly.GetType("MagicPlugin.Plugin", throwOnError: false)?.GetMethod("Update", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(MagicPluginCompatibility), "MagicPluginUpdatePrefix", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo.ReturnType != typeof(void) || methodInfo2 == null)
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)"MagicPlugin Character registry guard skipped: MagicPlugin.Plugin.Update did not match the expected structure.");
				return;
			}
			try
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_registryGuardInstalled = true;
				InteropFixesPlugin.ModLogger.LogInfo((object)("Installed MagicPlugin Character registry guard for MagicPlugin " + version + "."));
			}
			catch (Exception ex)
			{
				harmony.Unpatch((MethodBase)methodInfo, methodInfo2);
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin Character registry guard skipped after a patching failure: " + ex.Message));
			}
		}

		private static bool FireProjectileBurstPrefix(Attack __instance, Humanoid ___m_character, ItemData ___m_weapon)
		{
			try
			{
				ProjectileConfiguration projectileConfiguration = _projectileConfiguration;
				if (projectileConfiguration != null)
				{
					ApplyFireProjectileBurstAdjustments(__instance, ___m_character, ___m_weapon, projectileConfiguration);
				}
			}
			catch (Exception ex)
			{
				if (!_reportedProjectileRuntimeError)
				{
					_reportedProjectileRuntimeError = true;
					InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin projectile compatibility failed while applying an adjustment: " + ex.Message));
				}
			}
			return true;
		}

		private static void ApplyFireProjectileBurstAdjustments(Attack attack, Humanoid character, ItemData weapon, ProjectileConfiguration configuration)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			if (attack == null)
			{
				return;
			}
			Player val = (Player)(object)((character is Player) ? character : null);
			if (val == null)
			{
				return;
			}
			SharedData val2 = weapon?.m_shared;
			if (val2 == null || (int)val2.m_skillType != 9)
			{
				return;
			}
			string text = val2.m_name ?? "";
			if (text.EndsWith("scepter", StringComparison.Ordinal) || text.Contains("flamestaff") || text.Contains("thunderstaff"))
			{
				return;
			}
			string ammoType = val2.m_ammoType;
			if ((ammoType != null && ammoType.Contains("ammo_spells")) || ((Object)(object)val2.m_secondaryAttack?.m_attackProjectile != (Object)null && ((Object)val2.m_secondaryAttack.m_attackProjectile).name == "BDS_DvergerStaffFire_clusterbomb_projectile"))
			{
				return;
			}
			if (text == "$bmp_arcticstaff" || text == "$item_stafficeshards")
			{
				attack.m_projectileVel *= 1.2f;
				attack.m_projectileVelMin *= 1.2f;
				attack.m_projectileAccuracy *= 0f;
				attack.m_projectileAccuracyMin *= 0f;
			}
			else
			{
				attack.m_projectileVel *= configuration.MagicVelocity.Value;
				attack.m_projectileVelMin *= configuration.MagicVelocity.Value;
				attack.m_projectileAccuracy *= configuration.MagicAccuracy.Value;
				attack.m_projectileAccuracyMin *= configuration.MagicAccuracy.Value;
			}
			GameObject attackProjectile = attack.m_attackProjectile;
			if (Object.op_Implicit((Object)(object)attackProjectile))
			{
				string obj = ((Object)attackProjectile).name ?? "";
				string text2 = obj.ToLowerInvariant();
				float skillFactor = ((Character)val).GetSkillFactor((SkillType)9);
				if (text2.Contains("surtlingstaff"))
				{
					ApplyProjectileAoe(attackProjectile, configuration.SurtlingStaffAoe, skillFactor);
				}
				if (text2.Contains("eikthyrsstaff"))
				{
					ApplyProjectileAoe(attackProjectile, configuration.EikthyrStaffAoe, skillFactor);
				}
				if (text2.Contains("lightningstaff"))
				{
					ApplyProjectileAoe(attackProjectile, configuration.LightningStaffAoe, skillFactor);
				}
				if (text2.Contains("poisonstaff"))
				{
					ApplyProjectileAoe(attackProjectile, configuration.PoisonStaffAoe, skillFactor);
				}
				if (text2.Contains("arcticstaff"))
				{
					ApplyProjectileAoe(attackProjectile, configuration.ArcticStaffAoe, skillFactor);
				}
				if (obj == "bmp_modersheritage_projectile")
				{
					ApplyModersHeritage(attackProjectile, skillFactor, configuration);
				}
				if (obj == "bmp_yagluthsheritage_projectile")
				{
					ApplyYagluthsHeritage(attackProjectile, skillFactor, configuration);
				}
			}
		}

		private static void ApplyProjectileAoe(GameObject projectilePrefab, ConfigEntry<float> aoeConfig, float elementalSkillFactor)
		{
			Projectile component = projectilePrefab.GetComponent<Projectile>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.m_aoe = aoeConfig.Value + 2f * elementalSkillFactor;
			}
		}

		private static void ApplyModersHeritage(GameObject projectilePrefab, float elementalSkillFactor, ProjectileConfiguration configuration)
		{
			Projectile val = TryGetSpawnedProjectile(projectilePrefab);
			if (Object.op_Implicit((Object)(object)val))
			{
				val.m_aoe = configuration.ModersAoeRange.Value + 2f * elementalSkillFactor;
				val.m_damage.m_chop = configuration.ModersChopDamage.Value;
				val.m_damage.m_frost = configuration.ModersFrostDamage.Value * (1f + elementalSkillFactor);
				val.m_damage.m_pickaxe = configuration.ModersPickaxeDamage.Value;
				val.m_damage.m_pierce = configuration.ModersPierceDamage.Value;
			}
		}

		private static void ApplyYagluthsHeritage(GameObject projectilePrefab, float elementalSkillFactor, ProjectileConfiguration configuration)
		{
			Projectile val = TryGetSpawnedProjectile(projectilePrefab);
			if (Object.op_Implicit((Object)(object)val))
			{
				val.m_aoe = configuration.YagluthAoeRange.Value + 2f * elementalSkillFactor;
				val.m_damage.m_blunt = configuration.YagluthBluntDamage.Value;
				val.m_damage.m_chop = configuration.YagluthChopDamage.Value;
				val.m_damage.m_fire = configuration.YagluthFireDamage.Value * (1f + elementalSkillFactor);
				val.m_damage.m_pickaxe = configuration.YagluthPickaxeDamage.Value;
			}
		}

		private static Projectile? TryGetSpawnedProjectile(GameObject projectilePrefab)
		{
			GameObject obj = projectilePrefab.GetComponent<Projectile>()?.m_spawnOnHit;
			SpawnAbility val = ((obj != null) ? obj.GetComponent<SpawnAbility>() : null);
			if (val?.m_spawnPrefab == null || val.m_spawnPrefab.Length == 0)
			{
				return null;
			}
			GameObject obj2 = val.m_spawnPrefab[0];
			if (obj2 == null)
			{
				return null;
			}
			return obj2.GetComponent<Projectile>();
		}

		private static void TeleportToPostfix(Player __instance, ref Vector3 pos, ref Quaternion rot, bool __result)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (!__result)
			{
				return;
			}
			try
			{
				TeleportFollowingMagicSummons(__instance, pos, rot);
			}
			catch (Exception ex)
			{
				if (!_reportedTeleportRuntimeError)
				{
					_reportedTeleportRuntimeError = true;
					InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin teleport compatibility failed while moving followed summons: " + ex.Message));
				}
			}
		}

		private static void TeleportFollowingMagicSummons(Player player, Vector3 position, Quaternion rotation)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)player))
			{
				return;
			}
			GameObject gameObject = ((Component)player).gameObject;
			if (!Object.op_Implicit((Object)(object)gameObject))
			{
				return;
			}
			Vector3 position2 = position + ((Component)player).transform.forward;
			List<Character> allCharacters = Character.GetAllCharacters();
			for (int i = 0; i < allCharacters.Count; i++)
			{
				Character val = allCharacters[i];
				if (IsFollowedMagicSummon(val, gameObject))
				{
					Transform transform = ((Component)val).transform;
					transform.position = position2;
					transform.rotation = rotation;
				}
			}
		}

		private static bool IsFollowedMagicSummon(Character character, GameObject owner)
		{
			if (!Object.op_Implicit((Object)(object)character) || !Object.op_Implicit((Object)(object)((Component)character).gameObject))
			{
				return false;
			}
			FieldRef<Character, ZNetView> characterNViewAccessor = _characterNViewAccessor;
			if (characterNViewAccessor == null)
			{
				return false;
			}
			ZNetView val = characterNViewAccessor.Invoke(character);
			if (!Object.op_Implicit((Object)(object)val) || !val.IsValid())
			{
				return false;
			}
			if (!(((Object)((Component)character).gameObject).name ?? "").StartsWith("BMP_", StringComparison.Ordinal) || !character.IsTamed())
			{
				return false;
			}
			Tameable component = ((Component)character).GetComponent<Tameable>();
			FieldRef<Tameable, MonsterAI> tameableMonsterAiAccessor = _tameableMonsterAiAccessor;
			MonsterAI val2 = ((Object.op_Implicit((Object)(object)component) && tameableMonsterAiAccessor != null) ? tameableMonsterAiAccessor.Invoke(component) : null);
			return (Object)(object)(Object.op_Implicit((Object)(object)val2) ? val2.GetFollowTarget() : null) == (Object)(object)owner;
		}

		private static void MagicPluginUpdatePrefix()
		{
			try
			{
				List<Character> allCharacters = Character.GetAllCharacters();
				for (int num = allCharacters.Count - 1; num >= 0; num--)
				{
					Character val = allCharacters[num];
					if (val == null || !Object.op_Implicit((Object)(object)val))
					{
						allCharacters.RemoveAt(num);
						if (val != null)
						{
							TryRemoveCharacterHud(val);
						}
					}
				}
			}
			catch (Exception ex)
			{
				ReportRegistryRuntimeError(ex);
			}
		}

		private static void TryRemoveCharacterHud(Character character)
		{
			try
			{
				if (Object.op_Implicit((Object)(object)EnemyHud.instance))
				{
					EnemyHud.instance.RemoveCharacterHud(character);
				}
			}
			catch (Exception ex)
			{
				InteropFixesPlugin.ModLogger.LogDebug((object)("Failed to repair a removed MagicPlugin Character HUD reference: " + ex.Message));
			}
		}

		private static void ReportRegistryRuntimeError(Exception ex)
		{
			if (!_reportedRegistryRuntimeError)
			{
				_reportedRegistryRuntimeError = true;
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin Character registry guard failed while pruning stale references: " + ex.Message));
			}
		}

		private static bool HasExpectedOwnedPatchSet(MethodBase original, HarmonyPatchType expectedType, MethodInfo expectedMethod)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			Patches patchInfo = Harmony.GetPatchInfo(original);
			if (patchInfo == null)
			{
				return false;
			}
			int num = 0;
			(HarmonyPatchType, ReadOnlyCollection<Patch>)[] array = new(HarmonyPatchType, ReadOnlyCollection<Patch>)[4]
			{
				((HarmonyPatchType)1, patchInfo.Prefixes),
				((HarmonyPatchType)2, patchInfo.Postfixes),
				((HarmonyPatchType)3, patchInfo.Transpilers),
				((HarmonyPatchType)4, patchInfo.Finalizers)
			};
			for (int i = 0; i < array.Length; i++)
			{
				(HarmonyPatchType, ReadOnlyCollection<Patch>) tuple = array[i];
				foreach (Patch item in tuple.Item2)
				{
					if (!(item.owner != "blacks7ar.MagicPlugin"))
					{
						if (tuple.Item1 != expectedType || !IsSameMethod(item.PatchMethod, expectedMethod))
						{
							return false;
						}
						num++;
					}
				}
			}
			return num == 1;
		}

		private static Patch? FindOwnedPatch(MethodBase original, HarmonyPatchType patchType, MethodInfo expectedMethod)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			Patches patchInfo = Harmony.GetPatchInfo(original);
			if (patchInfo == null)
			{
				return null;
			}
			foreach (Patch item in (IEnumerable<Patch>)(((int)patchType == 1) ? patchInfo.Prefixes : patchInfo.Postfixes))
			{
				if (item.owner == "blacks7ar.MagicPlugin" && IsSameMethod(item.PatchMethod, expectedMethod))
				{
					return item;
				}
			}
			return null;
		}

		private static bool TryReplacePatch(Harmony harmony, MethodInfo original, Patch externalPatch, MethodInfo replacement, HarmonyPatchType patchType, out string failure)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			try
			{
				harmony.Unpatch((MethodBase)original, externalPatch.PatchMethod);
				flag = FindOwnedPatch(original, patchType, externalPatch.PatchMethod) == null;
				if (!flag)
				{
					failure = $"the exact external {patchType} could not be removed.";
					return false;
				}
				HarmonyMethod val = new HarmonyMethod(replacement)
				{
					priority = externalPatch.priority,
					before = externalPatch.before,
					after = externalPatch.after
				};
				if ((int)patchType == 1)
				{
					harmony.Patch((MethodBase)original, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					harmony.Patch((MethodBase)original, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				failure = "";
				return true;
			}
			catch (Exception ex)
			{
				try
				{
					harmony.Unpatch((MethodBase)original, replacement);
				}
				catch
				{
				}
				bool num = !flag || TryRestoreExternalPatch(original, externalPatch, patchType);
				failure = "patch replacement failed (" + ex.Message + ").";
				if (!num)
				{
					failure += " The original MagicPlugin patch could not be restored.";
				}
				return false;
			}
		}

		private static bool TryRestoreExternalPatch(MethodInfo original, Patch externalPatch, HarmonyPatchType patchType)
		{
			//IL_00b3: 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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			Exception ex = null;
			try
			{
				HarmonyMethod val = new HarmonyMethod(externalPatch.PatchMethod)
				{
					priority = externalPatch.priority,
					before = externalPatch.before,
					after = externalPatch.after
				};
				Harmony val2 = new Harmony(externalPatch.owner);
				if ((int)patchType == 1)
				{
					val2.Patch((MethodBase)original, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					val2.Patch((MethodBase)original, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex2)
			{
				ex = ex2;
			}
			try
			{
				if (FindOwnedPatch(original, patchType, externalPatch.PatchMethod) != null)
				{
					if (ex != null)
					{
						InteropFixesPlugin.ModLogger.LogWarning((object)$"MagicPlugin patch restoration reported an error, but the exact {patchType} was found in the Harmony patch inventory: {ex.Message}");
					}
					return true;
				}
			}
			catch (Exception ex3)
			{
				InteropFixesPlugin.ModLogger.LogError((object)$"Could not verify the restored MagicPlugin {patchType} on {original.DeclaringType?.FullName}.{original.Name}: {ex3}");
				return false;
			}
			InteropFixesPlugin.ModLogger.LogError((object)($"The restored MagicPlugin {patchType} on {original.DeclaringType?.FullName}.{original.Name} was not found in the Harmony patch inventory." + ((ex == null) ? string.Empty : $" Restoration also reported: {ex}")));
			return false;
		}

		private static bool RestoreExternalPatch(PatchReplacement? replacement)
		{
			//IL_000d: 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)
			if (replacement == null)
			{
				return true;
			}
			try
			{
				if (FindOwnedPatch(replacement.Original, replacement.PatchType, replacement.ExternalPatch.PatchMethod) == null)
				{
					return TryRestoreExternalPatch(replacement.Original, replacement.ExternalPatch, replacement.PatchType);
				}
				return true;
			}
			catch (Exception arg)
			{
				InteropFixesPlugin.ModLogger.LogError((object)$"Failed to restore a replaced MagicPlugin patch while InteropFixes was shutting down: {arg}");
			}
			return false;
		}

		private static void TryInstallCapability(string capability, Action install)
		{
			try
			{
				install();
			}
			catch (Exception ex)
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin " + capability + " skipped after a structural probe failed: " + ex.Message));
			}
		}

		private static bool IsSameMethod(MethodInfo left, MethodInfo right)
		{
			if ((object)left == right || left.Equals(right))
			{
				return true;
			}
			try
			{
				return left.Module.Equals(right.Module) && left.MetadataToken == right.MetadataToken;
			}
			catch
			{
				return false;
			}
		}

		private static Assembly? FindAssemblyWithType(string fullTypeName)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (assembly.GetType(fullTypeName, throwOnError: false) != null)
				{
					return assembly;
				}
			}
			return null;
		}
	}
	internal static class MagicPluginCosmeticZdoPrevention
	{
		private enum LocalizedEffectKind
		{
			None,
			DefaultLifetime,
			ExplicitLifetime
		}

		[Flags]
		private enum CosmeticFeature
		{
			None = 0,
			FlameLaunch = 1,
			ThunderLaunch = 2,
			ThunderHit = 4,
			ArcticLaunch = 8,
			ArcticHit = 0x10,
			ArcticIceblockDestroyed = 0x20,
			IceScepterNovaRing = 0x40,
			All = 0x7F
		}

		[Flags]
		private enum CosmeticCarrierKind
		{
			None = 0,
			FlameStaffLaunch = 1,
			ThunderStaffLaunch = 2,
			ArcticStaffLaunch = 4,
			IceScepterNovaRing = 8,
			ArcticIceblockDestroyed = 0x10
		}

		private readonly struct CosmeticEffectState
		{
			internal LocalizedEffectKind Kind { get; }

			internal CosmeticEvent? Replay { get; }

			internal CosmeticEffectState(LocalizedEffectKind kind, CosmeticEvent? replay)
			{
				Kind = kind;
				Replay = replay;
			}
		}

		private readonly struct CosmeticEvent
		{
			internal long Session { get; }

			internal ZDOID Source { get; }

			internal CosmeticFeature Feature { get; }

			internal Vector3 Position { get; }

			internal Quaternion Rotation { get; }

			internal CosmeticEvent(long session, ZDOID source, CosmeticFeature feature, Vector3 position, Quaternion rotation)
			{
				//IL_0008: 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)
				//IL_0016: 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_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				Session = session;
				Source = source;
				Feature = feature;
				Position = position;
				Rotation = rotation;
			}
		}

		private sealed class CosmeticReplayHistory
		{
			private readonly int _capacity;

			private readonly HashSet<(ZDOID Source, int Feature)> _seen = new HashSet<(ZDOID, int)>();

			private readonly Queue<(ZDOID Source, int Feature)> _order = new Queue<(ZDOID, int)>();

			private long _session = long.MinValue;

			internal int Count => _seen.Count;

			internal CosmeticReplayHistory(int capacity)
			{
				if (capacity <= 0)
				{
					throw new ArgumentOutOfRangeException("capacity");
				}
				_capacity = capacity;
			}

			internal bool TryRecord(long session, ZDOID source, int feature)
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				if (_session != session)
				{
					Clear();
					_session = session;
				}
				(ZDOID, int) item = (source, feature);
				if (!_seen.Add(item))
				{
					return false;
				}
				_order.Enqueue(item);
				if (_order.Count > _capacity)
				{
					_seen.Remove(_order.Dequeue());
				}
				return true;
			}

			internal void Clear()
			{
				_seen.Clear();
				_order.Clear();
				_session = long.MinValue;
			}
		}

		private readonly struct CosmeticProjectileBurstState
		{
			internal bool WasInside { get; }

			internal CosmeticCarrierKind PreviousMarker { get; }

			internal CosmeticProjectileBurstState(bool wasInside, CosmeticCarrierKind previousMarker)
			{
				WasInside = wasInside;
				PreviousMarker = previousMarker;
			}
		}

		private readonly struct CosmeticProjectileHitState
		{
			internal CosmeticFeature PreviousContext { get; }

			internal ZNetView? PreviousView { get; }

			internal CosmeticProjectileHitState(CosmeticFeature previousContext, ZNetView? previousView)
			{
				PreviousContext = previousContext;
				PreviousView = previousView;
			}
		}

		private const string FlameStaffName = "BMP_FlameStaff";

		private const string ThunderStaffName = "BMP_ThunderStaff";

		private const string ArcticStaffName = "BMP_ArcticStaff";

		private const string IceScepterName = "BMP_IceScepter";

		private const string FlameProjectileName = "bmp_flamewand_projectile";

		private const string ThunderProjectileName = "bmp_lightningwand_projectile";

		private const string ArcticProjectileName = "BMP_ArcticStaff_Ice_Projectile";

		private const string ArcticIceblockerName = "BMP_ArcticStaff_Iceblocker";

		private const string IceScepterNovaAoeName = "BMP_DvergerStaffNova_aoe";

		private const string FlameLaunchEffectName = "BMP_Fx_FlameStaff_Launch";

		private const string ThunderLaunchEffectName = "BMP_Fx_ThunderStaff_Launch";

		private const string ArcticLaunchEffectName = "BMP_Fx_ArcticStaff_Iceshard_Launch";

		private const string ThunderExplosionEffectName = "bmp_lightningwand_explosion";

		private const string ArcticHitEffectName = "BMP_Vfx_ArcticStaff_Ice_Hit";

		private const string ColdHitSoundName = "BMP_Sfx_Dragon_Coldball_Explode";

		private const string ArcticDestroyedEffectName = "BMP_Vfx_ArcticStaff_Iceblocker_Destroyed";

		private const string ArcticDestroyedSoundName = "BMP_Sfx_ArcticStaff_Ice_Destroyed";

		private const string IceScepterNovaRingName = "bmp_fx_DvergerMage_Nova_ring";

		private const float LaunchEffectLifetime = 8f;

		private const float ArcticHitEffectLifetime = 8f;

		private const float ColdHitSoundLifetime = 3f;

		private const float ArcticDestroyedEffectLifetime = 5f;

		private const float ArcticDestroyedSoundLifetime = 4f;

		private const float MaximumExplicitCosmeticLifetime = 30f;

		private const float NovaSuppressionTokenLifetime = 3f;

		private const string CosmeticEventRpc = "sighsorry.InteropFixes.MagicCosmeticEvent.v1";

		private const int CosmeticEventPacketSize = 52;

		private static readonly Version MinimumCosmeticPatchVersion = new Version(2, 1, 9);

		private static readonly int FlameProjectileHash = "bmp_flamewand_projectile".GetStableHashCode();

		private static readonly int ThunderProjectileHash = "bmp_lightningwand_projectile".GetStableHashCode();

		private static readonly int ArcticProjectileHash = "BMP_ArcticStaff_Ice_Projectile".GetStableHashCode();

		private static readonly int ArcticIceblockerHash = "BMP_ArcticStaff_Iceblocker".GetStableHashCode();

		private static readonly int IceScepterNovaAoeHash = "BMP_DvergerStaffNova_aoe".GetStableHashCode();

		private static readonly int CosmeticCarrierMarkerHash = "BlastedSwimmingTarredBugFix_MagicCosmeticCarrier".GetStableHashCode();

		private static bool _cosmeticZdoPatchInstalled;

		private static bool _reportedCosmeticRuntimeError;

		private static ZNetScene? _probedCosmeticScene;

		private static CosmeticFeature _cosmeticFeatures;

		private static SharedData? _flameStaffSharedData;

		private static SharedData? _thunderStaffSharedData;

		private static SharedData? _arcticStaffSharedData;

		private static SharedData? _iceScepterSharedData;

		private static EffectList? _flameLaunchEffects;

		private static EffectList? _thunderLaunchEffects;

		private static EffectList? _arcticLaunchEffects;

		private static EffectList? _iceScepterNovaEffects;

		private static GameObject? _flameLaunchEffectPrefab;

		private static GameObject? _thunderLaunchEffectPrefab;

		private static GameObject? _arcticLaunchEffectPrefab;

		private static GameObject? _thunderExplosionEffectPrefab;

		private static GameObject? _arcticHitEffectPrefab;

		private static GameObject? _coldHitSoundPrefab;

		private static GameObject? _arcticDestroyedEffectPrefab;

		private static GameObject? _arcticDestroyedSoundPrefab;

		private static GameObject? _iceScepterNovaRingPrefab;

		private static float _iceScepterNovaRingLifetime;

		private static readonly Dictionary<Character, float> PendingNovaSuppressions = new Dictionary<Character, float>();

		private static readonly CosmeticReplayHistory ReplayHistory = new CosmeticReplayHistory(4096);

		private static ZRoutedRpc? _registeredRpc;

		private static object? _registeredHandler;

		private static FieldInfo? _rpcFunctions;

		[ThreadStatic]
		private static CosmeticFeature _projectileHitContext;

		[ThreadStatic]
		private static ZNetView? _projectileHitView;

		[ThreadStatic]
		private static bool _insideCosmeticProjectileBurst;

		[ThreadStatic]
		private static CosmeticCarrierKind _suppressedLaunchMarker;

		private static bool EventReceiverReady
		{
			get
			{
				if (_registeredHandler != null)
				{
					return _registeredRpc == ZRoutedRpc.instance;
				}
				return false;
			}
		}

		private static int GetStableHashCode(this string value)
		{
			int num = 5381;
			int num2 = num;
			for (int i = 0; i < value.Length && value[i] != 0; i += 2)
			{
				num = ((num << 5) + num) ^ value[i];
				if (i == value.Length - 1 || value[i + 1] == '\0')
				{
					break;
				}
				num2 = ((num2 << 5) + num2) ^ value[i + 1];
			}
			return num + num2 * 1566083941;
		}

		internal static void Reset()
		{
			_cosmeticZdoPatchInstalled = false;
			DetachEventReceiver();
			_reportedCosmeticRuntimeError = false;
			_probedCosmeticScene = null;
			ClearCosmeticFeatureState();
			_projectileHitContext = CosmeticFeature.None;
			_projectileHitView = null;
			_insideCosmeticProjectileBurst = false;
			_suppressedLaunchMarker = CosmeticCarrierKind.None;
		}

		internal static void TryInstall(Harmony harmony, string version)
		{
			//IL_04df: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ec: Expected O, but got Unknown
			//IL_04ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_051f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0526: Expected O, but got Unknown
			//IL_055d: Expected O, but got Unknown
			//IL_0570: Unknown result type (might be due to invalid IL or missing references)
			//IL_0575: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0591: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c3: Expected O, but got Unknown
			//IL_05c3: Expected O, but got Unknown
			//IL_05c3: Expected O, but got Unknown
			//IL_05d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Expected O, but got Unknown
			//IL_0600: Unknown result type (might be due to invalid IL or missing references)
			//IL_0605: Unknown result type (might be due to invalid IL or missing references)
			//IL_0622: Unknown result type (might be due to invalid IL or missing references)
			//IL_0627: Unknown result type (might be due to invalid IL or missing references)
			//IL_0634: Expected O, but got Unknown
			//IL_0634: Expected O, but got Unknown
			//IL_0649: Unknown result type (might be due to invalid IL or missing references)
			//IL_064e: Unknown result type (might be due to invalid IL or missing references)
			//IL_065d: Expected O, but got Unknown
			//IL_0672: Unknown result type (might be due to invalid IL or missing references)
			//IL_0677: Unknown result type (might be due to invalid IL or missing references)
			//IL_0686: Expected O, but got Unknown
			//IL_0699: Unknown result type (might be due to invalid IL or missing references)
			//IL_069e: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06cd: Expected O, but got Unknown
			//IL_06cd: Expected O, but got Unknown
			if (_cosmeticZdoPatchInstalled)
			{
				return;
			}
			if (!TryParseVersion(version, out Version version2) || version2.CompareTo(MinimumCosmeticPatchVersion) < 0)
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)($"MagicPlugin cosmetic peer-ZDO prevention requires MagicPlugin {MinimumCosmeticPatchVersion} or later; " + "MagicPlugin " + version + " keeps its original cosmetic ZDO behavior."));
				return;
			}
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Attack), "FireProjectileBurst", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(typeof(EffectList), "Create", new Type[6]
			{
				typeof(Vector3),
				typeof(Quaternion),
				typeof(Transform),
				typeof(float),
				typeof(int),
				typeof(ZDOID)
			}, (Type[])null);
			ConstructorInfo constructorInfo = AccessTools.Constructor(typeof(ZRoutedRpc), new Type[1] { typeof(bool) }, false);
			MethodInfo methodInfo4 = AccessTools.DeclaredMethod(typeof(ZNetScene), "CreateObject", new Type[1] { typeof(ZDO) }, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.DeclaredMethod(typeof(Projectile), "OnHit", new Type[4]
			{
				typeof(Collider),
				typeof(Vector3),
				typeof(bool),
				typeof(Vector3)
			}, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.DeclaredMethod(typeof(Projectile), "Setup", new Type[6]
			{
				typeof(Character),
				typeof(Vector3),
				typeof(float),
				typeof(HitData),
				typeof(ItemData),
				typeof(ItemData)
			}, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.DeclaredMethod(typeof(Aoe), "Setup", new Type[6]
			{
				typeof(Character),
				typeof(Vector3),
				typeof(float),
				typeof(HitData),
				typeof(ItemData),
				typeof(ItemData)
			}, (Type[])null);
			FieldInfo fieldInfo = AccessTools.Field(typeof(ZNetView), "m_forceDisableInit");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(Projectile), "m_nview");
			FieldInfo fieldInfo3 = AccessTools.Field(typeof(Aoe), "m_nview");
			FieldInfo fieldInfo4 = AccessTools.Field(typeof(ZRoutedRpc), "m_functions");
			if (methodInfo?.ReturnType != typeof(void) || methodInfo2?.ReturnType != typeof(void) || methodInfo3?.ReturnType != typeof(GameObject[]) || constructorInfo == null || methodInfo4?.ReturnType != typeof(GameObject) || methodInfo5?.ReturnType != typeof(void) || methodInfo6?.ReturnType != typeof(void) || methodInfo7?.ReturnType != typeof(void) || fieldInfo == null || !fieldInfo.IsStatic || fieldInfo.FieldType != typeof(bool) || fieldInfo2?.FieldType != typeof(ZNetView) || fieldInfo3?.FieldType != typeof(ZNetView) || fieldInfo4 == null || !typeof(IDictionary).IsAssignableFrom(fieldInfo4.FieldType) || !fieldInfo4.FieldType.IsGenericType || fieldInfo4.FieldType.GetGenericTypeDefinition() != typeof(Dictionary<, >) || fieldInfo4.FieldType.GetGenericArguments()[0] != typeof(int) || fieldInfo4.FieldType.GetGenericArguments()[1].FullName != "RoutedMethodBase")
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)"MagicPlugin cosmetic peer-ZDO prevention skipped: the expected Valheim effect, scene, or projectile structure was not found.");
				return;
			}
			try
			{
				_rpcFunctions = fieldInfo4;
				harmony.Patch((MethodBase)constructorInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "RoutedRpcCreatedPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				HarmonyMethod val = new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticProbeZNetSceneAwakePrefix", (Type[])null)
				{
					priority = 800
				};
				HarmonyMethod val2 = new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticProbeZNetSceneAwakePostfix", (Type[])null);
				val2.priority = 0;
				val2.after = new string[3] { "org.bepinex.helpers.ItemManager", "com.jotunn.jotunn", "blacks7ar.MagicPlugin" };
				harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticEffectListCreatePrefix", (Type[])null)
				{
					priority = 0
				}, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticEffectListCreatePostfix", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticEffectListCreateCleanup", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticNetworkObjectCreatePostfix", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticProjectileHitContextPrefix", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticProjectileHitContextFinalizer", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticProjectileSetupPostfix", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticAoeSetupPostfix", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticProjectileBurstContextPrefix", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(MagicPluginCosmeticZdoPrevention), "CosmeticProjectileBurstContextFinalizer", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null);
				_cosmeticZdoPatchInstalled = true;
				if (ZRoutedRpc.instance != null)
				{
					AttachEventReceiver(ZRoutedRpc.instance);
				}
				InteropFixesPlugin.ModLogger.LogInfo((object)("Installed structurally gated MagicPlugin cosmetic peer-ZDO prevention for MagicPlugin " + version + "."));
				ZNetScene instance = ZNetScene.instance;
				if (Object.op_Implicit((Object)(object)instance))
				{
					TryProbeCosmeticFeatures(instance);
				}
			}
			catch (Exception ex)
			{
				_cosmeticZdoPatchInstalled = false;
				DetachEventReceiver();
				_probedCosmeticScene = null;
				ClearCosmeticFeatureState();
				TryUnpatchCosmeticBurstContext(harmony, methodInfo2);
				TryUnpatchCosmeticMethods(harmony, methodInfo, methodInfo3, constructorInfo, methodInfo4, methodInfo5, methodInfo6, methodInfo7);
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin cosmetic peer-ZDO prevention skipped after a patching failure: " + ex.Message));
			}
		}

		private static bool TryParseVersion(string value, out Version version)
		{
			int num = value.IndexOfAny(new char[2] { '-', '+' });
			if (Version.TryParse((num >= 0) ? value.Substring(0, num) : value, out Version result))
			{
				version = result;
				return true;
			}
			version = null;
			return false;
		}

		private static void CosmeticProbeZNetSceneAwakePrefix()
		{
			_probedCosmeticScene = null;
			ClearCosmeticFeatureState();
		}

		private static void CosmeticProbeZNetSceneAwakePostfix(ZNetScene __instance)
		{
			TryProbeCosmeticFeatures(__instance);
		}

		private static void TryProbeCosmeticFeatures(ZNetScene scene)
		{
			if (_cosmeticZdoPatchInstalled && Object.op_Implicit((Object)(object)scene) && _probedCosmeticScene != scene)
			{
				_probedCosmeticScene = scene;
				ClearCosmeticFeatureState();
				CosmeticFeature cosmeticFeature = CosmeticFeature.None;
				if (ProbeCosmeticFeature(CosmeticFeature.FlameLaunch, () => TryProbeLaunchFeature(scene, "BMP_FlameStaff", "bmp_flamewand_projectile", FlameProjectileHash, "BMP_Fx_FlameStaff_Launch", ref _flameStaffSharedData, ref _flameLaunchEffects, ref _flameLaunchEffectPrefab)))
				{
					cosmeticFeature |= CosmeticFeature.FlameLaunch;
				}
				if (ProbeCosmeticFeature(CosmeticFeature.ThunderLaunch, () => TryProbeLaunchFeature(scene, "BMP_ThunderStaff", "bmp_lightningwand_projectile", ThunderProjectileHash, "BMP_Fx_ThunderStaff_Launch", ref _thunderStaffSharedData, ref _thunderLaunchEffects, ref _thunderLaunchEffectPrefab)))
				{
					cosmeticFeature |= CosmeticFeature.ThunderLaunch;
				}
				if (ProbeCosmeticFeature(CosmeticFeature.ThunderHit, () => TryProbeThunderHitFeature(scene)))
				{
					cosmeticFeature |= CosmeticFeature.ThunderHit;
				}
				if (ProbeCosmeticFeature(CosmeticFeature.ArcticLaunch, () => TryProbeLaunchFeature(scene, "BMP_ArcticStaff", "BMP_ArcticStaff_Ice_Projectile", ArcticProjectileHash, "BMP_Fx_ArcticStaff_Iceshard_Launch", ref _arcticStaffSharedData, ref _arcticLaunchEffects, ref _arcticLaunchEffectPrefab)))
				{
					cosmeticFeature |= CosmeticFeature.ArcticLaunch;
				}
				if (ProbeCosmeticFeature(CosmeticFeature.ArcticHit, () => TryProbeArcticHitFeature(scene)))
				{
					cosmeticFeature |= CosmeticFeature.ArcticHit;
				}
				if (ProbeCosmeticFeature(CosmeticFeature.ArcticIceblockDestroyed, () => TryProbeArcticIceblockDestroyedFeature(scene)))
				{
					cosmeticFeature |= CosmeticFeature.ArcticIceblockDestroyed;
				}
				if (ProbeCosmeticFeature(CosmeticFeature.IceScepterNovaRing, () => TryProbeIceScepterNovaFeature(scene)))
				{
					cosmeticFeature |= CosmeticFeature.IceScepterNovaRing;
				}
				_cosmeticFeatures = cosmeticFeature;
				PublishLocalCapabilities();
				if (cosmeticFeature != CosmeticFeature.None)
				{
					InteropFixesPlugin.ModLogger.LogInfo((object)("MagicPlugin cosmetic structural probe enabled: " + FormatCosmeticFeatures(cosmeticFeature) + "."));
				}
				CosmeticFeature cosmeticFeature2 = CosmeticFeature.All & ~cosmeticFeature;
				if (cosmeticFeature2 != CosmeticFeature.None)
				{
					InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin cosmetic structural probe kept original behavior for: " + FormatCosmeticFeatures(cosmeticFeature2) + "."));
				}
			}
		}

		private static bool ProbeCosmeticFeature(CosmeticFeature feature, Func<bool> probe)
		{
			try
			{
				return probe();
			}
			catch (Exception ex)
			{
				InteropFixesPlugin.ModLogger.LogWarning((object)("MagicPlugin cosmetic structural probe rejected " + FormatCosmeticFeatures(feature) + ": " + ex.Message));
				return false;
			}
		}

		private static void ClearCosmeticFeatureState()
		{
			_cosmeticFeatures = CosmeticFeature.None;
			CosmeticNetworkCoordinator.SetLocalCapabilities(0);
			_flameStaffSharedData = null;
			_thunderStaffSharedData = null;
			_arcticStaffSharedData = null;
			_iceScepterSharedData = null;
			_flameLaunchEffects = null;
			_thunderLaunchEffects = null;
			_arcticLaunchEffects = null;
			_iceScepterNovaEffects = null;
			_flameLaunchEffectPrefab = null;
			_thunderLaunchEffectPrefab = null;
			_arcticLaunchEffectPrefab = null;
			_thunderExplosionEffectPrefab = null;
			_arcticHitEffectPrefab = null;
			_coldHitSoundPrefab = null;
			_arcticDestroyedEffectPrefab = null;
			_arcticDestroyedSoundPrefab = null;
			_iceScepterNovaRingPrefab = null;
			_iceScepterNovaRingLifetime = 0f;
			PendingNovaSuppressions.Clear();
			ReplayHistory.Clear();
		}

		private static bool TryProbeLaunchFeature(ZNetScene scene, string itemName, string projectileName, int projectileHash, string effectName, ref SharedData? cachedSharedData, ref EffectList? cachedEffects, ref GameObject? cachedEffectPrefab)
		{
			if (!TryResolveAttackGraph(scene, itemName, secondaryAttack: false, projectileName, projectileHash, out SharedData sharedData, out Attack attack, out GameObject projectilePrefab) || !TryGetSafeNetworkProjectile(projectilePrefab, out Projectile _) || attack.m_projectileBursts <= 0)
			{
				return false;
			}
			GameObject val = TryResolveExactScenePrefab(scene, effectName);
			if (!Object.op_Implicit((Object)(object)val) || !IsExactSingleEffectList(attack.m_burstEffect, val, effectName, 0) || !IsSafeNetworkCosmetic(val, effectName, 8f, requireAudio: false))
			{
				return false;
			}
			cachedSharedData = sharedData;
			cachedEffects = attack.m_burstEffect;
			cachedEffectPrefab = val;
			return true;
		}

		private static bool TryProbeThunderHitFeature(ZNetScene scene)
		{
			GameObject? prefab = TryResolveExactScenePrefab(scene, "bmp_lightningwand_projectile", ThunderProjectileHash);
			GameObject val = TryResolveExactScenePrefab(scene, "bmp_lightningwand_explosion");
			GameObject val2 = TryResolveExactScenePrefab(scene, "BMP_Sfx_Dragon_Coldball_Explode");
			if (!TryGetSafeNetworkProje